blob: 1eb5f6204ba37f24581d11ce81e201beaec59afa [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Execute compiled code */
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003
Guido van Rossum681d79a1995-07-18 14:51:37 +00004/* XXX TO DO:
Guido van Rossum681d79a1995-07-18 14:51:37 +00005 XXX speed up searching for keywords by using a dictionary
Guido van Rossum681d79a1995-07-18 14:51:37 +00006 XXX document it!
7 */
8
Thomas Wouters477c8d52006-05-27 19:21:47 +00009/* enable more aggressive intra-module optimizations, where available */
10#define PY_LOCAL_AGGRESSIVE
11
Guido van Rossumb209a111997-04-29 18:18:01 +000012#include "Python.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000013
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000015#include "frameobject.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000016#include "eval.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000017#include "opcode.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +000018#include "structmember.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000019
Guido van Rossumc6004111993-11-05 10:22:19 +000020#include <ctype.h>
21
Thomas Wouters477c8d52006-05-27 19:21:47 +000022#ifndef WITH_TSC
Michael W. Hudson75eabd22005-01-18 15:56:11 +000023
24#define READ_TIMESTAMP(var)
25
26#else
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000027
28typedef unsigned long long uint64;
29
Michael W. Hudson800ba232004-08-12 18:19:17 +000030#if defined(__ppc__) /* <- Don't know if this is the correct symbol; this
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 section should work for GCC on any PowerPC
32 platform, irrespective of OS.
33 POWER? Who knows :-) */
Michael W. Hudson800ba232004-08-12 18:19:17 +000034
Michael W. Hudson75eabd22005-01-18 15:56:11 +000035#define READ_TIMESTAMP(var) ppc_getcounter(&var)
Michael W. Hudson800ba232004-08-12 18:19:17 +000036
37static void
38ppc_getcounter(uint64 *v)
39{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 register unsigned long tbu, tb, tbu2;
Michael W. Hudson800ba232004-08-12 18:19:17 +000041
42 loop:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 asm volatile ("mftbu %0" : "=r" (tbu) );
44 asm volatile ("mftb %0" : "=r" (tb) );
45 asm volatile ("mftbu %0" : "=r" (tbu2));
46 if (__builtin_expect(tbu != tbu2, 0)) goto loop;
Michael W. Hudson800ba232004-08-12 18:19:17 +000047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 /* The slightly peculiar way of writing the next lines is
49 compiled better by GCC than any other way I tried. */
50 ((long*)(v))[0] = tbu;
51 ((long*)(v))[1] = tb;
Michael W. Hudson800ba232004-08-12 18:19:17 +000052}
53
Mark Dickinsona25b1312009-10-31 10:18:44 +000054#elif defined(__i386__)
55
56/* this is for linux/x86 (and probably any other GCC/x86 combo) */
Michael W. Hudson800ba232004-08-12 18:19:17 +000057
Michael W. Hudson75eabd22005-01-18 15:56:11 +000058#define READ_TIMESTAMP(val) \
59 __asm__ __volatile__("rdtsc" : "=A" (val))
Michael W. Hudson800ba232004-08-12 18:19:17 +000060
Mark Dickinsona25b1312009-10-31 10:18:44 +000061#elif defined(__x86_64__)
62
63/* for gcc/x86_64, the "A" constraint in DI mode means *either* rax *or* rdx;
64 not edx:eax as it does for i386. Since rdtsc puts its result in edx:eax
65 even in 64-bit mode, we need to use "a" and "d" for the lower and upper
66 32-bit pieces of the result. */
67
68#define READ_TIMESTAMP(val) \
69 __asm__ __volatile__("rdtsc" : \
70 "=a" (((int*)&(val))[0]), "=d" (((int*)&(val))[1]));
71
72
73#else
74
75#error "Don't know how to implement timestamp counter for this architecture"
76
Michael W. Hudson800ba232004-08-12 18:19:17 +000077#endif
78
Thomas Wouters477c8d52006-05-27 19:21:47 +000079void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1)
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 uint64 intr, inst, loop;
83 PyThreadState *tstate = PyThreadState_Get();
84 if (!tstate->interp->tscdump)
85 return;
86 intr = intr1 - intr0;
87 inst = inst1 - inst0 - intr;
88 loop = loop1 - loop0 - intr;
89 fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
Stefan Krahb7e10102010-06-23 18:42:39 +000090 opcode, ticked, inst, loop);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000091}
Michael W. Hudson800ba232004-08-12 18:19:17 +000092
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000093#endif
94
Guido van Rossum04691fc1992-08-12 15:35:34 +000095/* Turn this on if your compiler chokes on the big switch: */
Guido van Rossum1ae940a1995-01-02 19:04:15 +000096/* #define CASE_TOO_BIG 1 */
Guido van Rossum04691fc1992-08-12 15:35:34 +000097
Guido van Rossum408027e1996-12-30 16:17:54 +000098#ifdef Py_DEBUG
Guido van Rossum96a42c81992-01-12 02:29:51 +000099/* For debugging the interpreter: */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100#define LLTRACE 1 /* Low-level trace feature */
101#define CHECKEXC 1 /* Double-check exception checking */
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000102#endif
103
Jeremy Hylton52820442001-01-03 23:52:36 +0000104typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *);
Guido van Rossum5b722181993-03-30 17:46:03 +0000105
Guido van Rossum374a9221991-04-04 10:40:29 +0000106/* Forward declarations */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000107#ifdef WITH_TSC
Thomas Wouters477c8d52006-05-27 19:21:47 +0000108static PyObject * call_function(PyObject ***, int, uint64*, uint64*);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000109#else
Thomas Wouters477c8d52006-05-27 19:21:47 +0000110static PyObject * call_function(PyObject ***, int);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000111#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000112static PyObject * fast_function(PyObject *, PyObject ***, int, int, int);
113static PyObject * do_call(PyObject *, PyObject ***, int, int);
114static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int);
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000115static PyObject * update_keyword_args(PyObject *, int, PyObject ***,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 PyObject *);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117static PyObject * update_star_args(int, int, PyObject *, PyObject ***);
118static PyObject * load_args(PyObject ***, int);
Jeremy Hylton52820442001-01-03 23:52:36 +0000119#define CALL_FLAG_VAR 1
120#define CALL_FLAG_KW 2
121
Guido van Rossum0a066c01992-03-27 17:29:15 +0000122#ifdef LLTRACE
Guido van Rossumc2e20742006-02-27 22:32:47 +0000123static int lltrace;
Tim Petersdbd9ba62000-07-09 03:09:57 +0000124static int prtrace(PyObject *, char *);
Guido van Rossum0a066c01992-03-27 17:29:15 +0000125#endif
Fred Drake5755ce62001-06-27 19:19:46 +0000126static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 int, PyObject *);
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +0000128static int call_trace_protected(Py_tracefunc, PyObject *,
Stefan Krahb7e10102010-06-23 18:42:39 +0000129 PyFrameObject *, int, PyObject *);
Fred Drake5755ce62001-06-27 19:19:46 +0000130static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *);
Tim Peters8a5c3c72004-04-05 19:36:21 +0000131static int maybe_call_line_trace(Py_tracefunc, PyObject *,
Stefan Krahb7e10102010-06-23 18:42:39 +0000132 PyFrameObject *, int *, int *, int *);
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000133
Thomas Wouters477c8d52006-05-27 19:21:47 +0000134static PyObject * cmp_outcome(int, PyObject *, PyObject *);
135static PyObject * import_from(PyObject *, PyObject *);
Thomas Wouters52152252000-08-17 22:55:00 +0000136static int import_all_from(PyObject *, PyObject *);
Neal Norwitzda059e32007-08-26 05:33:45 +0000137static void format_exc_check_arg(PyObject *, const char *, PyObject *);
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000138static void format_exc_unbound(PyCodeObject *co, int oparg);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000139static PyObject * unicode_concatenate(PyObject *, PyObject *,
140 PyFrameObject *, unsigned char *);
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000141static PyObject * special_lookup(PyObject *, char *, PyObject **);
Guido van Rossum374a9221991-04-04 10:40:29 +0000142
Paul Prescode68140d2000-08-30 20:25:01 +0000143#define NAME_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 "name '%.200s' is not defined"
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000145#define GLOBAL_NAME_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 "global name '%.200s' is not defined"
Paul Prescode68140d2000-08-30 20:25:01 +0000147#define UNBOUNDLOCAL_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 "local variable '%.200s' referenced before assignment"
Jeremy Hyltonc76770c2001-04-13 16:51:46 +0000149#define UNBOUNDFREE_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 "free variable '%.200s' referenced before assignment" \
151 " in enclosing scope"
Guido van Rossum374a9221991-04-04 10:40:29 +0000152
Guido van Rossum950361c1997-01-24 13:49:28 +0000153/* Dynamic execution profile */
154#ifdef DYNAMIC_EXECUTION_PROFILE
155#ifdef DXPAIRS
156static long dxpairs[257][256];
157#define dxp dxpairs[256]
158#else
159static long dxp[256];
160#endif
161#endif
162
Jeremy Hylton985eba52003-02-05 23:13:00 +0000163/* Function call profile */
164#ifdef CALL_PROFILE
165#define PCALL_NUM 11
166static int pcall[PCALL_NUM];
167
168#define PCALL_ALL 0
169#define PCALL_FUNCTION 1
170#define PCALL_FAST_FUNCTION 2
171#define PCALL_FASTER_FUNCTION 3
172#define PCALL_METHOD 4
173#define PCALL_BOUND_METHOD 5
174#define PCALL_CFUNCTION 6
175#define PCALL_TYPE 7
176#define PCALL_GENERATOR 8
177#define PCALL_OTHER 9
178#define PCALL_POP 10
179
180/* Notes about the statistics
181
182 PCALL_FAST stats
183
184 FAST_FUNCTION means no argument tuple needs to be created.
185 FASTER_FUNCTION means that the fast-path frame setup code is used.
186
187 If there is a method call where the call can be optimized by changing
188 the argument tuple and calling the function directly, it gets recorded
189 twice.
190
191 As a result, the relationship among the statistics appears to be
192 PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
193 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
194 PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
195 PCALL_METHOD > PCALL_BOUND_METHOD
196*/
197
198#define PCALL(POS) pcall[POS]++
199
200PyObject *
201PyEval_GetCallStats(PyObject *self)
202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 return Py_BuildValue("iiiiiiiiiii",
204 pcall[0], pcall[1], pcall[2], pcall[3],
205 pcall[4], pcall[5], pcall[6], pcall[7],
206 pcall[8], pcall[9], pcall[10]);
Jeremy Hylton985eba52003-02-05 23:13:00 +0000207}
208#else
209#define PCALL(O)
210
211PyObject *
212PyEval_GetCallStats(PyObject *self)
213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_INCREF(Py_None);
215 return Py_None;
Jeremy Hylton985eba52003-02-05 23:13:00 +0000216}
217#endif
218
Tim Peters5ca576e2001-06-18 22:08:13 +0000219
Benjamin Petersond2be5b42010-09-10 22:47:02 +0000220#ifdef WITH_THREAD
221#define GIL_REQUEST _Py_atomic_load_relaxed(&gil_drop_request)
222#else
223#define GIL_REQUEST 0
224#endif
225
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000226/* This can set eval_breaker to 0 even though gil_drop_request became
227 1. We believe this is all right because the eval loop will release
228 the GIL eventually anyway. */
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000229#define COMPUTE_EVAL_BREAKER() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 _Py_atomic_store_relaxed( \
231 &eval_breaker, \
Benjamin Petersond2be5b42010-09-10 22:47:02 +0000232 GIL_REQUEST | \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 _Py_atomic_load_relaxed(&pendingcalls_to_do) | \
234 pending_async_exc)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000235
Benjamin Petersond2be5b42010-09-10 22:47:02 +0000236#ifdef WITH_THREAD
237
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000238#define SET_GIL_DROP_REQUEST() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 do { \
240 _Py_atomic_store_relaxed(&gil_drop_request, 1); \
241 _Py_atomic_store_relaxed(&eval_breaker, 1); \
242 } while (0)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000243
244#define RESET_GIL_DROP_REQUEST() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 do { \
246 _Py_atomic_store_relaxed(&gil_drop_request, 0); \
247 COMPUTE_EVAL_BREAKER(); \
248 } while (0)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000249
Benjamin Petersond2be5b42010-09-10 22:47:02 +0000250#endif
251
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000252/* Pending calls are only modified under pending_lock */
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000253#define SIGNAL_PENDING_CALLS() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 do { \
255 _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \
256 _Py_atomic_store_relaxed(&eval_breaker, 1); \
257 } while (0)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000258
259#define UNSIGNAL_PENDING_CALLS() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 do { \
261 _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \
262 COMPUTE_EVAL_BREAKER(); \
263 } while (0)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000264
265#define SIGNAL_ASYNC_EXC() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 do { \
267 pending_async_exc = 1; \
268 _Py_atomic_store_relaxed(&eval_breaker, 1); \
269 } while (0)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000270
271#define UNSIGNAL_ASYNC_EXC() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000273
274
Guido van Rossume59214e1994-08-30 08:01:59 +0000275#ifdef WITH_THREAD
Guido van Rossumff4949e1992-08-05 19:58:53 +0000276
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000277#ifdef HAVE_ERRNO_H
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000278#include <errno.h>
Guido van Rossum2571cc81999-04-07 16:07:23 +0000279#endif
Guido van Rossum49b56061998-10-01 20:42:43 +0000280#include "pythread.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +0000281
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000282static PyThread_type_lock pending_lock = 0; /* for pending calls */
Guido van Rossuma9672091994-09-14 13:31:22 +0000283static long main_thread = 0;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000284/* This single variable consolidates all requests to break out of the fast path
285 in the eval loop. */
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000286static _Py_atomic_int eval_breaker = {0};
287/* Request for dropping the GIL */
288static _Py_atomic_int gil_drop_request = {0};
289/* Request for running pending calls. */
290static _Py_atomic_int pendingcalls_to_do = {0};
291/* Request for looking at the `async_exc` field of the current thread state.
292 Guarded by the GIL. */
293static int pending_async_exc = 0;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000294
295#include "ceval_gil.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000296
Tim Peters7f468f22004-10-11 02:40:51 +0000297int
298PyEval_ThreadsInitialized(void)
299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 return gil_created();
Tim Peters7f468f22004-10-11 02:40:51 +0000301}
302
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000303void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000304PyEval_InitThreads(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (gil_created())
307 return;
308 create_gil();
309 take_gil(PyThreadState_GET());
310 main_thread = PyThread_get_thread_ident();
311 if (!pending_lock)
312 pending_lock = PyThread_allocate_lock();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000313}
Guido van Rossumff4949e1992-08-05 19:58:53 +0000314
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000315void
Antoine Pitrou1df15362010-09-13 14:16:46 +0000316_PyEval_FiniThreads(void)
317{
318 if (!gil_created())
319 return;
320 destroy_gil();
321 assert(!gil_created());
322}
323
324void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000325PyEval_AcquireLock(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 PyThreadState *tstate = PyThreadState_GET();
328 if (tstate == NULL)
329 Py_FatalError("PyEval_AcquireLock: current thread state is NULL");
330 take_gil(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000331}
332
333void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000334PyEval_ReleaseLock(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* This function must succeed when the current thread state is NULL.
337 We therefore avoid PyThreadState_GET() which dumps a fatal error
338 in debug mode.
339 */
340 drop_gil((PyThreadState*)_Py_atomic_load_relaxed(
341 &_PyThreadState_Current));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000342}
343
344void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000345PyEval_AcquireThread(PyThreadState *tstate)
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (tstate == NULL)
348 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
349 /* Check someone has called PyEval_InitThreads() to create the lock */
350 assert(gil_created());
351 take_gil(tstate);
352 if (PyThreadState_Swap(tstate) != NULL)
353 Py_FatalError(
354 "PyEval_AcquireThread: non-NULL old thread state");
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000355}
356
357void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000358PyEval_ReleaseThread(PyThreadState *tstate)
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (tstate == NULL)
361 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
362 if (PyThreadState_Swap(NULL) != tstate)
363 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
364 drop_gil(tstate);
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000365}
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000366
367/* This function is called from PyOS_AfterFork to ensure that newly
368 created child processes don't hold locks referring to threads which
369 are not running in the child process. (This could also be done using
370 pthread_atfork mechanism, at least for the pthreads implementation.) */
371
372void
373PyEval_ReInitThreads(void)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyObject *threading, *result;
376 PyThreadState *tstate = PyThreadState_GET();
Jesse Nollera8513972008-07-17 16:49:17 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (!gil_created())
379 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 recreate_gil();
381 pending_lock = PyThread_allocate_lock();
382 take_gil(tstate);
383 main_thread = PyThread_get_thread_ident();
Jesse Nollera8513972008-07-17 16:49:17 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* Update the threading module with the new state.
386 */
387 tstate = PyThreadState_GET();
388 threading = PyMapping_GetItemString(tstate->interp->modules,
389 "threading");
390 if (threading == NULL) {
391 /* threading not imported */
392 PyErr_Clear();
393 return;
394 }
395 result = PyObject_CallMethod(threading, "_after_fork", NULL);
396 if (result == NULL)
397 PyErr_WriteUnraisable(threading);
398 else
399 Py_DECREF(result);
400 Py_DECREF(threading);
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000401}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000402
403#else
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000404static _Py_atomic_int eval_breaker = {0};
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000405static int pending_async_exc = 0;
406#endif /* WITH_THREAD */
407
408/* This function is used to signal that async exceptions are waiting to be
409 raised, therefore it is also useful in non-threaded builds. */
410
411void
412_PyEval_SignalAsyncExc(void)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 SIGNAL_ASYNC_EXC();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000415}
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000416
Guido van Rossumff4949e1992-08-05 19:58:53 +0000417/* Functions save_thread and restore_thread are always defined so
418 dynamically loaded modules needn't be compiled separately for use
419 with and without threads: */
420
Guido van Rossum2fca21f71997-07-18 23:56:58 +0000421PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000422PyEval_SaveThread(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 PyThreadState *tstate = PyThreadState_Swap(NULL);
425 if (tstate == NULL)
426 Py_FatalError("PyEval_SaveThread: NULL tstate");
Guido van Rossume59214e1994-08-30 08:01:59 +0000427#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (gil_created())
429 drop_gil(tstate);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000430#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 return tstate;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000432}
433
434void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000435PyEval_RestoreThread(PyThreadState *tstate)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (tstate == NULL)
438 Py_FatalError("PyEval_RestoreThread: NULL tstate");
Guido van Rossume59214e1994-08-30 08:01:59 +0000439#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (gil_created()) {
441 int err = errno;
442 take_gil(tstate);
443 errno = err;
444 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000445#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 PyThreadState_Swap(tstate);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000447}
448
449
Guido van Rossuma9672091994-09-14 13:31:22 +0000450/* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
451 signal handlers or Mac I/O completion routines) can schedule calls
452 to a function to be called synchronously.
453 The synchronous function is called with one void* argument.
454 It should return 0 for success or -1 for failure -- failure should
455 be accompanied by an exception.
456
457 If registry succeeds, the registry function returns 0; if it fails
458 (e.g. due to too many pending calls) it returns -1 (without setting
459 an exception condition).
460
461 Note that because registry may occur from within signal handlers,
462 or other asynchronous events, calling malloc() is unsafe!
463
464#ifdef WITH_THREAD
465 Any thread can schedule pending calls, but only the main thread
466 will execute them.
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000467 There is no facility to schedule calls to a particular thread, but
468 that should be easy to change, should that ever be required. In
469 that case, the static variables here should go into the python
470 threadstate.
Guido van Rossuma9672091994-09-14 13:31:22 +0000471#endif
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000472*/
Guido van Rossuma9672091994-09-14 13:31:22 +0000473
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000474#ifdef WITH_THREAD
475
476/* The WITH_THREAD implementation is thread-safe. It allows
477 scheduling to be made from any thread, and even from an executing
478 callback.
479 */
480
481#define NPENDINGCALLS 32
482static struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 int (*func)(void *);
484 void *arg;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000485} pendingcalls[NPENDINGCALLS];
486static int pendingfirst = 0;
487static int pendinglast = 0;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000488static char pendingbusy = 0;
489
490int
491Py_AddPendingCall(int (*func)(void *), void *arg)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 int i, j, result=0;
494 PyThread_type_lock lock = pending_lock;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* try a few times for the lock. Since this mechanism is used
497 * for signal handling (on the main thread), there is a (slim)
498 * chance that a signal is delivered on the same thread while we
499 * hold the lock during the Py_MakePendingCalls() function.
500 * This avoids a deadlock in that case.
501 * Note that signals can be delivered on any thread. In particular,
502 * on Windows, a SIGINT is delivered on a system-created worker
503 * thread.
504 * We also check for lock being NULL, in the unlikely case that
505 * this function is called before any bytecode evaluation takes place.
506 */
507 if (lock != NULL) {
508 for (i = 0; i<100; i++) {
509 if (PyThread_acquire_lock(lock, NOWAIT_LOCK))
510 break;
511 }
512 if (i == 100)
513 return -1;
514 }
515
516 i = pendinglast;
517 j = (i + 1) % NPENDINGCALLS;
518 if (j == pendingfirst) {
519 result = -1; /* Queue full */
520 } else {
521 pendingcalls[i].func = func;
522 pendingcalls[i].arg = arg;
523 pendinglast = j;
524 }
525 /* signal main loop */
526 SIGNAL_PENDING_CALLS();
527 if (lock != NULL)
528 PyThread_release_lock(lock);
529 return result;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000530}
531
532int
533Py_MakePendingCalls(void)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 int i;
536 int r = 0;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (!pending_lock) {
539 /* initial allocation of the lock */
540 pending_lock = PyThread_allocate_lock();
541 if (pending_lock == NULL)
542 return -1;
543 }
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* only service pending calls on main thread */
546 if (main_thread && PyThread_get_thread_ident() != main_thread)
547 return 0;
548 /* don't perform recursive pending calls */
549 if (pendingbusy)
550 return 0;
551 pendingbusy = 1;
552 /* perform a bounded number of calls, in case of recursion */
553 for (i=0; i<NPENDINGCALLS; i++) {
554 int j;
555 int (*func)(void *);
556 void *arg = NULL;
557
558 /* pop one item off the queue while holding the lock */
559 PyThread_acquire_lock(pending_lock, WAIT_LOCK);
560 j = pendingfirst;
561 if (j == pendinglast) {
562 func = NULL; /* Queue empty */
563 } else {
564 func = pendingcalls[j].func;
565 arg = pendingcalls[j].arg;
566 pendingfirst = (j + 1) % NPENDINGCALLS;
567 }
568 if (pendingfirst != pendinglast)
569 SIGNAL_PENDING_CALLS();
570 else
571 UNSIGNAL_PENDING_CALLS();
572 PyThread_release_lock(pending_lock);
573 /* having released the lock, perform the callback */
574 if (func == NULL)
575 break;
576 r = func(arg);
577 if (r)
578 break;
579 }
580 pendingbusy = 0;
581 return r;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000582}
583
584#else /* if ! defined WITH_THREAD */
585
586/*
587 WARNING! ASYNCHRONOUSLY EXECUTING CODE!
588 This code is used for signal handling in python that isn't built
589 with WITH_THREAD.
590 Don't use this implementation when Py_AddPendingCalls() can happen
591 on a different thread!
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592
Guido van Rossuma9672091994-09-14 13:31:22 +0000593 There are two possible race conditions:
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000594 (1) nested asynchronous calls to Py_AddPendingCall()
595 (2) AddPendingCall() calls made while pending calls are being processed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000597 (1) is very unlikely because typically signal delivery
598 is blocked during signal handling. So it should be impossible.
599 (2) is a real possibility.
Guido van Rossuma9672091994-09-14 13:31:22 +0000600 The current code is safe against (2), but not against (1).
601 The safety against (2) is derived from the fact that only one
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000602 thread is present, interrupted by signals, and that the critical
603 section is protected with the "busy" variable. On Windows, which
604 delivers SIGINT on a system thread, this does not hold and therefore
605 Windows really shouldn't use this version.
606 The two threads could theoretically wiggle around the "busy" variable.
Guido van Rossuma027efa1997-05-05 20:56:21 +0000607*/
Guido van Rossum8861b741996-07-30 16:49:37 +0000608
Guido van Rossuma9672091994-09-14 13:31:22 +0000609#define NPENDINGCALLS 32
610static struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 int (*func)(void *);
612 void *arg;
Guido van Rossuma9672091994-09-14 13:31:22 +0000613} pendingcalls[NPENDINGCALLS];
614static volatile int pendingfirst = 0;
615static volatile int pendinglast = 0;
Benjamin Peterson08ec84c2010-05-30 14:49:32 +0000616static _Py_atomic_int pendingcalls_to_do = {0};
Guido van Rossuma9672091994-09-14 13:31:22 +0000617
618int
Thomas Wouters334fb892000-07-25 12:56:38 +0000619Py_AddPendingCall(int (*func)(void *), void *arg)
Guido van Rossuma9672091994-09-14 13:31:22 +0000620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 static volatile int busy = 0;
622 int i, j;
623 /* XXX Begin critical section */
624 if (busy)
625 return -1;
626 busy = 1;
627 i = pendinglast;
628 j = (i + 1) % NPENDINGCALLS;
629 if (j == pendingfirst) {
630 busy = 0;
631 return -1; /* Queue full */
632 }
633 pendingcalls[i].func = func;
634 pendingcalls[i].arg = arg;
635 pendinglast = j;
Skip Montanarod581d772002-09-03 20:10:45 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 SIGNAL_PENDING_CALLS();
638 busy = 0;
639 /* XXX End critical section */
640 return 0;
Guido van Rossuma9672091994-09-14 13:31:22 +0000641}
642
Guido van Rossum180d7b41994-09-29 09:45:57 +0000643int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644Py_MakePendingCalls(void)
Guido van Rossuma9672091994-09-14 13:31:22 +0000645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 static int busy = 0;
647 if (busy)
648 return 0;
649 busy = 1;
650 UNSIGNAL_PENDING_CALLS();
651 for (;;) {
652 int i;
653 int (*func)(void *);
654 void *arg;
655 i = pendingfirst;
656 if (i == pendinglast)
657 break; /* Queue empty */
658 func = pendingcalls[i].func;
659 arg = pendingcalls[i].arg;
660 pendingfirst = (i + 1) % NPENDINGCALLS;
661 if (func(arg) < 0) {
662 busy = 0;
663 SIGNAL_PENDING_CALLS(); /* We're not done yet */
664 return -1;
665 }
666 }
667 busy = 0;
668 return 0;
Guido van Rossuma9672091994-09-14 13:31:22 +0000669}
670
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000671#endif /* WITH_THREAD */
672
Guido van Rossuma9672091994-09-14 13:31:22 +0000673
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000674/* The interpreter's recursion limit */
675
Hye-Shik Changb6fa2812005-04-04 15:49:02 +0000676#ifndef Py_DEFAULT_RECURSION_LIMIT
677#define Py_DEFAULT_RECURSION_LIMIT 1000
678#endif
679static int recursion_limit = Py_DEFAULT_RECURSION_LIMIT;
680int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000681
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000682int
683Py_GetRecursionLimit(void)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return recursion_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000686}
687
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000688void
689Py_SetRecursionLimit(int new_limit)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 recursion_limit = new_limit;
692 _Py_CheckRecursionLimit = recursion_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000693}
694
Armin Rigo2b3eb402003-10-28 12:05:48 +0000695/* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
696 if the recursion_depth reaches _Py_CheckRecursionLimit.
697 If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
698 to guarantee that _Py_CheckRecursiveCall() is regularly called.
699 Without USE_STACKCHECK, there is no need for this. */
700int
701_Py_CheckRecursiveCall(char *where)
702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyThreadState *tstate = PyThreadState_GET();
Armin Rigo2b3eb402003-10-28 12:05:48 +0000704
705#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (PyOS_CheckStack()) {
707 --tstate->recursion_depth;
708 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
709 return -1;
710 }
Armin Rigo2b3eb402003-10-28 12:05:48 +0000711#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 _Py_CheckRecursionLimit = recursion_limit;
713 if (tstate->recursion_critical)
714 /* Somebody asked that we don't check for recursion. */
715 return 0;
716 if (tstate->overflowed) {
717 if (tstate->recursion_depth > recursion_limit + 50) {
718 /* Overflowing while handling an overflow. Give up. */
719 Py_FatalError("Cannot recover from stack overflow.");
720 }
721 return 0;
722 }
723 if (tstate->recursion_depth > recursion_limit) {
724 --tstate->recursion_depth;
725 tstate->overflowed = 1;
726 PyErr_Format(PyExc_RuntimeError,
727 "maximum recursion depth exceeded%s",
728 where);
729 return -1;
730 }
731 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000732}
733
Guido van Rossum374a9221991-04-04 10:40:29 +0000734/* Status code for main loop (reason for stack unwind) */
Raymond Hettinger7c958652004-04-06 10:11:10 +0000735enum why_code {
Stefan Krahb7e10102010-06-23 18:42:39 +0000736 WHY_NOT = 0x0001, /* No error */
737 WHY_EXCEPTION = 0x0002, /* Exception occurred */
738 WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */
739 WHY_RETURN = 0x0008, /* 'return' statement */
740 WHY_BREAK = 0x0010, /* 'break' statement */
741 WHY_CONTINUE = 0x0020, /* 'continue' statement */
742 WHY_YIELD = 0x0040, /* 'yield' operator */
743 WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */
Raymond Hettinger7c958652004-04-06 10:11:10 +0000744};
Guido van Rossum374a9221991-04-04 10:40:29 +0000745
Collin Winter828f04a2007-08-31 00:04:24 +0000746static enum why_code do_raise(PyObject *, PyObject *);
Guido van Rossum0368b722007-05-11 16:50:42 +0000747static int unpack_iterable(PyObject *, int, int, PyObject **);
Guido van Rossum1aa14831997-01-21 05:34:20 +0000748
Jeffrey Yasskin008d8ef2008-12-06 17:09:27 +0000749/* Records whether tracing is on for any thread. Counts the number of
750 threads for which tstate->c_tracefunc is non-NULL, so if the value
751 is 0, we know we don't have to check this thread's c_tracefunc.
752 This speeds up the if statement in PyEval_EvalFrameEx() after
753 fast_next_opcode*/
754static int _Py_TracingPossible = 0;
755
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000756
Guido van Rossum374a9221991-04-04 10:40:29 +0000757
Guido van Rossumb209a111997-04-29 18:18:01 +0000758PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000759PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
Guido van Rossum681d79a1995-07-18 14:51:37 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 return PyEval_EvalCodeEx(co,
762 globals, locals,
763 (PyObject **)NULL, 0,
764 (PyObject **)NULL, 0,
765 (PyObject **)NULL, 0,
766 NULL, NULL);
Guido van Rossum681d79a1995-07-18 14:51:37 +0000767}
768
769
770/* Interpreter main loop */
771
Martin v. Löwis8d97e332004-06-27 15:43:12 +0000772PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000773PyEval_EvalFrame(PyFrameObject *f) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 /* This is for backward compatibility with extension modules that
775 used this API; core interpreter code should call
776 PyEval_EvalFrameEx() */
777 return PyEval_EvalFrameEx(f, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000778}
779
780PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000781PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Guido van Rossum374a9221991-04-04 10:40:29 +0000782{
Guido van Rossum950361c1997-01-24 13:49:28 +0000783#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 int lastopcode = 0;
Guido van Rossum950361c1997-01-24 13:49:28 +0000785#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 register PyObject **stack_pointer; /* Next free slot in value stack */
787 register unsigned char *next_instr;
788 register int opcode; /* Current opcode */
789 register int oparg; /* Current opcode argument, if any */
790 register enum why_code why; /* Reason for block stack unwind */
791 register int err; /* Error status -- nonzero if error */
792 register PyObject *x; /* Result object -- NULL if error */
793 register PyObject *v; /* Temporary objects popped off stack */
794 register PyObject *w;
795 register PyObject *u;
796 register PyObject *t;
797 register PyObject **fastlocals, **freevars;
798 PyObject *retval = NULL; /* Return value */
799 PyThreadState *tstate = PyThreadState_GET();
800 PyCodeObject *co;
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 /* when tracing we set things up so that
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 not (instr_lb <= current_bytecode_offset < instr_ub)
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 is true when the line being executed has changed. The
807 initial values are such as to make this false the first
808 time it is tested. */
809 int instr_ub = -1, instr_lb = 0, instr_prev = -1;
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 unsigned char *first_instr;
812 PyObject *names;
813 PyObject *consts;
Neal Norwitz5f5153e2005-10-21 04:28:38 +0000814#if defined(Py_DEBUG) || defined(LLTRACE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 /* Make it easier to find out where we are with a debugger */
816 char *filename;
Guido van Rossum99bec951992-09-03 20:29:45 +0000817#endif
Guido van Rossum374a9221991-04-04 10:40:29 +0000818
Antoine Pitroub52ec782009-01-25 16:34:23 +0000819/* Computed GOTOs, or
820 the-optimization-commonly-but-improperly-known-as-"threaded code"
821 using gcc's labels-as-values extension
822 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
823
824 The traditional bytecode evaluation loop uses a "switch" statement, which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 decent compilers will optimize as a single indirect branch instruction
Antoine Pitroub52ec782009-01-25 16:34:23 +0000826 combined with a lookup table of jump addresses. However, since the
827 indirect jump instruction is shared by all opcodes, the CPU will have a
828 hard time making the right prediction for where to jump next (actually,
829 it will be always wrong except in the uncommon case of a sequence of
830 several identical opcodes).
831
832 "Threaded code" in contrast, uses an explicit jump table and an explicit
833 indirect jump instruction at the end of each opcode. Since the jump
834 instruction is at a different address for each opcode, the CPU will make a
835 separate prediction for each of these instructions, which is equivalent to
836 predicting the second opcode of each opcode pair. These predictions have
837 a much better chance to turn out valid, especially in small bytecode loops.
838
839 A mispredicted branch on a modern CPU flushes the whole pipeline and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 can cost several CPU cycles (depending on the pipeline depth),
Antoine Pitroub52ec782009-01-25 16:34:23 +0000841 and potentially many more instructions (depending on the pipeline width).
842 A correctly predicted branch, however, is nearly free.
843
844 At the time of this writing, the "threaded code" version is up to 15-20%
845 faster than the normal "switch" version, depending on the compiler and the
846 CPU architecture.
847
848 We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined,
849 because it would render the measurements invalid.
850
851
852 NOTE: care must be taken that the compiler doesn't try to "optimize" the
853 indirect jumps by sharing them between all opcodes. Such optimizations
854 can be disabled on gcc by using the -fno-gcse flag (or possibly
855 -fno-crossjumping).
856*/
857
Antoine Pitrou042b1282010-08-13 21:15:58 +0000858#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitroub52ec782009-01-25 16:34:23 +0000859#undef USE_COMPUTED_GOTOS
Antoine Pitrou042b1282010-08-13 21:15:58 +0000860#define USE_COMPUTED_GOTOS 0
Antoine Pitroub52ec782009-01-25 16:34:23 +0000861#endif
862
Antoine Pitrou042b1282010-08-13 21:15:58 +0000863#ifdef HAVE_COMPUTED_GOTOS
864 #ifndef USE_COMPUTED_GOTOS
865 #define USE_COMPUTED_GOTOS 1
866 #endif
867#else
868 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
869 #error "Computed gotos are not supported on this compiler."
870 #endif
871 #undef USE_COMPUTED_GOTOS
872 #define USE_COMPUTED_GOTOS 0
873#endif
874
875#if USE_COMPUTED_GOTOS
Antoine Pitroub52ec782009-01-25 16:34:23 +0000876/* Import the static jump table */
877#include "opcode_targets.h"
878
879/* This macro is used when several opcodes defer to the same implementation
880 (e.g. SETUP_LOOP, SETUP_FINALLY) */
881#define TARGET_WITH_IMPL(op, impl) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 TARGET_##op: \
883 opcode = op; \
884 if (HAS_ARG(op)) \
885 oparg = NEXTARG(); \
886 case op: \
887 goto impl; \
Antoine Pitroub52ec782009-01-25 16:34:23 +0000888
889#define TARGET(op) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 TARGET_##op: \
891 opcode = op; \
892 if (HAS_ARG(op)) \
893 oparg = NEXTARG(); \
894 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000895
896
897#define DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 { \
899 if (!_Py_atomic_load_relaxed(&eval_breaker)) { \
900 FAST_DISPATCH(); \
901 } \
902 continue; \
903 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000904
905#ifdef LLTRACE
906#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 { \
908 if (!lltrace && !_Py_TracingPossible) { \
909 f->f_lasti = INSTR_OFFSET(); \
910 goto *opcode_targets[*next_instr++]; \
911 } \
912 goto fast_next_opcode; \
913 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000914#else
915#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 { \
917 if (!_Py_TracingPossible) { \
918 f->f_lasti = INSTR_OFFSET(); \
919 goto *opcode_targets[*next_instr++]; \
920 } \
921 goto fast_next_opcode; \
922 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000923#endif
924
925#else
926#define TARGET(op) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000928#define TARGET_WITH_IMPL(op, impl) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* silence compiler warnings about `impl` unused */ \
930 if (0) goto impl; \
931 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000932#define DISPATCH() continue
933#define FAST_DISPATCH() goto fast_next_opcode
934#endif
935
936
Neal Norwitza81d2202002-07-14 00:27:26 +0000937/* Tuple access macros */
938
939#ifndef Py_DEBUG
940#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
941#else
942#define GETITEM(v, i) PyTuple_GetItem((v), (i))
943#endif
944
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000945#ifdef WITH_TSC
946/* Use Pentium timestamp counter to mark certain events:
947 inst0 -- beginning of switch statement for opcode dispatch
948 inst1 -- end of switch statement (may be skipped)
949 loop0 -- the top of the mainloop
Thomas Wouters477c8d52006-05-27 19:21:47 +0000950 loop1 -- place where control returns again to top of mainloop
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000951 (may be skipped)
952 intr1 -- beginning of long interruption
953 intr2 -- end of long interruption
954
955 Many opcodes call out to helper C functions. In some cases, the
956 time in those functions should be counted towards the time for the
957 opcode, but not in all cases. For example, a CALL_FUNCTION opcode
958 calls another Python function; there's no point in charge all the
959 bytecode executed by the called function to the caller.
960
961 It's hard to make a useful judgement statically. In the presence
962 of operator overloading, it's impossible to tell if a call will
963 execute new Python code or not.
964
965 It's a case-by-case judgement. I'll use intr1 for the following
966 cases:
967
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000968 IMPORT_STAR
969 IMPORT_FROM
970 CALL_FUNCTION (and friends)
971
972 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0;
974 int ticked = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 READ_TIMESTAMP(inst0);
977 READ_TIMESTAMP(inst1);
978 READ_TIMESTAMP(loop0);
979 READ_TIMESTAMP(loop1);
Michael W. Hudson800ba232004-08-12 18:19:17 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* shut up the compiler */
982 opcode = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000983#endif
984
Guido van Rossum374a9221991-04-04 10:40:29 +0000985/* Code access macros */
986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987#define INSTR_OFFSET() ((int)(next_instr - first_instr))
988#define NEXTOP() (*next_instr++)
989#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
990#define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
991#define JUMPTO(x) (next_instr = first_instr + (x))
992#define JUMPBY(x) (next_instr += (x))
Guido van Rossum374a9221991-04-04 10:40:29 +0000993
Raymond Hettingerf606f872003-03-16 03:11:04 +0000994/* OpCode prediction macros
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 Some opcodes tend to come in pairs thus making it possible to
996 predict the second code when the first is run. For example,
997 COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And,
998 those opcodes are often followed by a POP_TOP.
Raymond Hettingerf606f872003-03-16 03:11:04 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Verifying the prediction costs a single high-speed test of a register
1001 variable against a constant. If the pairing was good, then the
1002 processor's own internal branch predication has a high likelihood of
1003 success, resulting in a nearly zero-overhead transition to the
1004 next opcode. A successful prediction saves a trip through the eval-loop
1005 including its two unpredictable branches, the HAS_ARG test and the
1006 switch-case. Combined with the processor's internal branch prediction,
1007 a successful PREDICT has the effect of making the two opcodes run as if
1008 they were a single new opcode with the bodies combined.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001009
Georg Brandl86b2fb92008-07-16 03:43:04 +00001010 If collecting opcode statistics, your choices are to either keep the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 predictions turned-on and interpret the results as if some opcodes
1012 had been combined or turn-off predictions so that the opcode frequency
1013 counter updates for both opcodes.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001014
1015 Opcode prediction is disabled with threaded code, since the latter allows
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 the CPU to record separate branch prediction information for each
1017 opcode.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001018
Raymond Hettingerf606f872003-03-16 03:11:04 +00001019*/
1020
Antoine Pitrou042b1282010-08-13 21:15:58 +00001021#if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022#define PREDICT(op) if (0) goto PRED_##op
1023#define PREDICTED(op) PRED_##op:
1024#define PREDICTED_WITH_ARG(op) PRED_##op:
Raymond Hettingera7216982004-02-08 19:59:27 +00001025#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026#define PREDICT(op) if (*next_instr == op) goto PRED_##op
1027#define PREDICTED(op) PRED_##op: next_instr++
1028#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
Antoine Pitroub52ec782009-01-25 16:34:23 +00001029#endif
1030
Raymond Hettingerf606f872003-03-16 03:11:04 +00001031
Guido van Rossum374a9221991-04-04 10:40:29 +00001032/* Stack manipulation macros */
1033
Martin v. Löwis18e16552006-02-15 17:27:45 +00001034/* The stack can grow at most MAXINT deep, as co_nlocals and
1035 co_stacksize are ints. */
Stefan Krahb7e10102010-06-23 18:42:39 +00001036#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
1037#define EMPTY() (STACK_LEVEL() == 0)
1038#define TOP() (stack_pointer[-1])
1039#define SECOND() (stack_pointer[-2])
1040#define THIRD() (stack_pointer[-3])
1041#define FOURTH() (stack_pointer[-4])
1042#define PEEK(n) (stack_pointer[-(n)])
1043#define SET_TOP(v) (stack_pointer[-1] = (v))
1044#define SET_SECOND(v) (stack_pointer[-2] = (v))
1045#define SET_THIRD(v) (stack_pointer[-3] = (v))
1046#define SET_FOURTH(v) (stack_pointer[-4] = (v))
1047#define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
1048#define BASIC_STACKADJ(n) (stack_pointer += n)
1049#define BASIC_PUSH(v) (*stack_pointer++ = (v))
1050#define BASIC_POP() (*--stack_pointer)
Guido van Rossum374a9221991-04-04 10:40:29 +00001051
Guido van Rossum96a42c81992-01-12 02:29:51 +00001052#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053#define PUSH(v) { (void)(BASIC_PUSH(v), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001054 lltrace && prtrace(TOP(), "push")); \
1055 assert(STACK_LEVEL() <= co->co_stacksize); }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001057 BASIC_POP())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001059 lltrace && prtrace(TOP(), "stackadj")); \
1060 assert(STACK_LEVEL() <= co->co_stacksize); }
Christian Heimes0449f632007-12-15 01:27:15 +00001061#define EXT_POP(STACK_POINTER) ((void)(lltrace && \
Stefan Krahb7e10102010-06-23 18:42:39 +00001062 prtrace((STACK_POINTER)[-1], "ext_pop")), \
1063 *--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001064#else
Stefan Krahb7e10102010-06-23 18:42:39 +00001065#define PUSH(v) BASIC_PUSH(v)
1066#define POP() BASIC_POP()
1067#define STACKADJ(n) BASIC_STACKADJ(n)
Guido van Rossumc2e20742006-02-27 22:32:47 +00001068#define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001069#endif
1070
Guido van Rossum681d79a1995-07-18 14:51:37 +00001071/* Local variable macros */
1072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073#define GETLOCAL(i) (fastlocals[i])
Guido van Rossumcfbf1a32002-03-28 20:17:52 +00001074
1075/* The SETLOCAL() macro must not DECREF the local variable in-place and
1076 then store the new value; it must copy the old value to a temporary
1077 value, then store the new value, and then DECREF the temporary value.
1078 This is because it is possible that during the DECREF the frame is
1079 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1080 variable would be pointing to already-freed memory. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001082 GETLOCAL(i) = value; \
1083 Py_XDECREF(tmp); } while (0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001084
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001085
1086#define UNWIND_BLOCK(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 while (STACK_LEVEL() > (b)->b_level) { \
1088 PyObject *v = POP(); \
1089 Py_XDECREF(v); \
1090 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001091
1092#define UNWIND_EXCEPT_HANDLER(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 { \
1094 PyObject *type, *value, *traceback; \
1095 assert(STACK_LEVEL() >= (b)->b_level + 3); \
1096 while (STACK_LEVEL() > (b)->b_level + 3) { \
1097 value = POP(); \
1098 Py_XDECREF(value); \
1099 } \
1100 type = tstate->exc_type; \
1101 value = tstate->exc_value; \
1102 traceback = tstate->exc_traceback; \
1103 tstate->exc_type = POP(); \
1104 tstate->exc_value = POP(); \
1105 tstate->exc_traceback = POP(); \
1106 Py_XDECREF(type); \
1107 Py_XDECREF(value); \
1108 Py_XDECREF(traceback); \
1109 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001110
1111#define SAVE_EXC_STATE() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 { \
1113 PyObject *type, *value, *traceback; \
1114 Py_XINCREF(tstate->exc_type); \
1115 Py_XINCREF(tstate->exc_value); \
1116 Py_XINCREF(tstate->exc_traceback); \
1117 type = f->f_exc_type; \
1118 value = f->f_exc_value; \
1119 traceback = f->f_exc_traceback; \
1120 f->f_exc_type = tstate->exc_type; \
1121 f->f_exc_value = tstate->exc_value; \
1122 f->f_exc_traceback = tstate->exc_traceback; \
1123 Py_XDECREF(type); \
1124 Py_XDECREF(value); \
1125 Py_XDECREF(traceback); \
1126 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001127
1128#define SWAP_EXC_STATE() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 { \
1130 PyObject *tmp; \
1131 tmp = tstate->exc_type; \
1132 tstate->exc_type = f->f_exc_type; \
1133 f->f_exc_type = tmp; \
1134 tmp = tstate->exc_value; \
1135 tstate->exc_value = f->f_exc_value; \
1136 f->f_exc_value = tmp; \
1137 tmp = tstate->exc_traceback; \
1138 tstate->exc_traceback = f->f_exc_traceback; \
1139 f->f_exc_traceback = tmp; \
1140 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001141
Guido van Rossuma027efa1997-05-05 20:56:21 +00001142/* Start of code */
1143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (f == NULL)
1145 return NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 /* push frame */
1148 if (Py_EnterRecursiveCall(""))
1149 return NULL;
Guido van Rossum8861b741996-07-30 16:49:37 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 tstate->frame = f;
Tim Peters5ca576e2001-06-18 22:08:13 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (tstate->use_tracing) {
1154 if (tstate->c_tracefunc != NULL) {
1155 /* tstate->c_tracefunc, if defined, is a
1156 function that will be called on *every* entry
1157 to a code block. Its return value, if not
1158 None, is a function that will be called at
1159 the start of each executed line of code.
1160 (Actually, the function must return itself
1161 in order to continue tracing.) The trace
1162 functions are called with three arguments:
1163 a pointer to the current frame, a string
1164 indicating why the function is called, and
1165 an argument which depends on the situation.
1166 The global trace function is also called
1167 whenever an exception is detected. */
1168 if (call_trace_protected(tstate->c_tracefunc,
1169 tstate->c_traceobj,
1170 f, PyTrace_CALL, Py_None)) {
1171 /* Trace function raised an error */
1172 goto exit_eval_frame;
1173 }
1174 }
1175 if (tstate->c_profilefunc != NULL) {
1176 /* Similar for c_profilefunc, except it needn't
1177 return itself and isn't called for "line" events */
1178 if (call_trace_protected(tstate->c_profilefunc,
1179 tstate->c_profileobj,
1180 f, PyTrace_CALL, Py_None)) {
1181 /* Profile function raised an error */
1182 goto exit_eval_frame;
1183 }
1184 }
1185 }
Neil Schemenauer6c0f2002001-09-04 19:03:35 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 co = f->f_code;
1188 names = co->co_names;
1189 consts = co->co_consts;
1190 fastlocals = f->f_localsplus;
1191 freevars = f->f_localsplus + co->co_nlocals;
1192 first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code);
1193 /* An explanation is in order for the next line.
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 f->f_lasti now refers to the index of the last instruction
1196 executed. You might think this was obvious from the name, but
1197 this wasn't always true before 2.3! PyFrame_New now sets
1198 f->f_lasti to -1 (i.e. the index *before* the first instruction)
1199 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
1200 does work. Promise.
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 When the PREDICT() macros are enabled, some opcode pairs follow in
1203 direct succession without updating f->f_lasti. A successful
1204 prediction effectively links the two codes together as if they
1205 were a single new opcode; accordingly,f->f_lasti will point to
1206 the first code in the pair (for instance, GET_ITER followed by
1207 FOR_ITER is effectively a single opcode and f->f_lasti will point
1208 at to the beginning of the combined pair.)
1209 */
1210 next_instr = first_instr + f->f_lasti + 1;
1211 stack_pointer = f->f_stacktop;
1212 assert(stack_pointer != NULL);
1213 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (co->co_flags & CO_GENERATOR && !throwflag) {
1216 if (f->f_exc_type != NULL && f->f_exc_type != Py_None) {
1217 /* We were in an except handler when we left,
1218 restore the exception state which was put aside
1219 (see YIELD_VALUE). */
1220 SWAP_EXC_STATE();
1221 }
1222 else {
1223 SAVE_EXC_STATE();
1224 }
1225 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001226
Tim Peters5ca576e2001-06-18 22:08:13 +00001227#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00001229#endif
Neal Norwitz5f5153e2005-10-21 04:28:38 +00001230#if defined(Py_DEBUG) || defined(LLTRACE)
Victor Stinner4a3733d2010-08-17 00:39:57 +00001231 {
1232 PyObject *error_type, *error_value, *error_traceback;
1233 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1234 filename = _PyUnicode_AsString(co->co_filename);
Victor Stinnera0006452010-10-13 10:48:55 +00001235 if (filename == NULL && tstate->overflowed) {
1236 /* maximum recursion depth exceeded */
1237 goto exit_eval_frame;
1238 }
Victor Stinner4a3733d2010-08-17 00:39:57 +00001239 PyErr_Restore(error_type, error_value, error_traceback);
1240 }
Tim Peters5ca576e2001-06-18 22:08:13 +00001241#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 why = WHY_NOT;
1244 err = 0;
1245 x = Py_None; /* Not a reference, just anything non-NULL */
1246 w = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (throwflag) { /* support for generator.throw() */
1249 why = WHY_EXCEPTION;
1250 goto on_error;
1251 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 for (;;) {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001254#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (inst1 == 0) {
1256 /* Almost surely, the opcode executed a break
1257 or a continue, preventing inst1 from being set
1258 on the way out of the loop.
1259 */
1260 READ_TIMESTAMP(inst1);
1261 loop1 = inst1;
1262 }
1263 dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1,
1264 intr0, intr1);
1265 ticked = 0;
1266 inst1 = 0;
1267 intr0 = 0;
1268 intr1 = 0;
1269 READ_TIMESTAMP(loop0);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001270#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1272 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 /* Do periodic things. Doing this every time through
1275 the loop would add too much overhead, so we do it
1276 only every Nth instruction. We also do it if
1277 ``pendingcalls_to_do'' is set, i.e. when an asynchronous
1278 event needs attention (e.g. a signal handler or
1279 async I/O handler); see Py_AddPendingCall() and
1280 Py_MakePendingCalls() above. */
Guido van Rossumac7be682001-01-17 15:42:30 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (_Py_atomic_load_relaxed(&eval_breaker)) {
1283 if (*next_instr == SETUP_FINALLY) {
1284 /* Make the last opcode before
1285 a try: finally: block uninterruptable. */
1286 goto fast_next_opcode;
1287 }
1288 tstate->tick_counter++;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001289#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 ticked = 1;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001291#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) {
1293 if (Py_MakePendingCalls() < 0) {
1294 why = WHY_EXCEPTION;
1295 goto on_error;
1296 }
1297 }
Guido van Rossume59214e1994-08-30 08:01:59 +00001298#ifdef WITH_THREAD
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001299 if (_Py_atomic_load_relaxed(&gil_drop_request)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 /* Give another thread a chance */
1301 if (PyThreadState_Swap(NULL) != tstate)
1302 Py_FatalError("ceval: tstate mix-up");
1303 drop_gil(tstate);
1304
1305 /* Other threads may run now */
1306
1307 take_gil(tstate);
1308 if (PyThreadState_Swap(tstate) != NULL)
1309 Py_FatalError("ceval: orphan tstate");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 }
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001311#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 /* Check for asynchronous exceptions. */
1313 if (tstate->async_exc != NULL) {
1314 x = tstate->async_exc;
1315 tstate->async_exc = NULL;
1316 UNSIGNAL_ASYNC_EXC();
1317 PyErr_SetNone(x);
1318 Py_DECREF(x);
1319 why = WHY_EXCEPTION;
1320 goto on_error;
1321 }
1322 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 fast_next_opcode:
1325 f->f_lasti = INSTR_OFFSET();
Guido van Rossumac7be682001-01-17 15:42:30 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 /* line-by-line tracing support */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (_Py_TracingPossible &&
1330 tstate->c_tracefunc != NULL && !tstate->tracing) {
1331 /* see maybe_call_line_trace
1332 for expository comments */
1333 f->f_stacktop = stack_pointer;
Tim Peters8a5c3c72004-04-05 19:36:21 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 err = maybe_call_line_trace(tstate->c_tracefunc,
1336 tstate->c_traceobj,
1337 f, &instr_lb, &instr_ub,
1338 &instr_prev);
1339 /* Reload possibly changed frame fields */
1340 JUMPTO(f->f_lasti);
1341 if (f->f_stacktop != NULL) {
1342 stack_pointer = f->f_stacktop;
1343 f->f_stacktop = NULL;
1344 }
1345 if (err) {
1346 /* trace function raised an exception */
1347 goto on_error;
1348 }
1349 }
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 /* Extract opcode and argument */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 opcode = NEXTOP();
1354 oparg = 0; /* allows oparg to be stored in a register because
1355 it doesn't have to be remembered across a full loop */
1356 if (HAS_ARG(opcode))
1357 oparg = NEXTARG();
Stefan Krahb7e10102010-06-23 18:42:39 +00001358 dispatch_opcode:
Guido van Rossum950361c1997-01-24 13:49:28 +00001359#ifdef DYNAMIC_EXECUTION_PROFILE
1360#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 dxpairs[lastopcode][opcode]++;
1362 lastopcode = opcode;
Guido van Rossum950361c1997-01-24 13:49:28 +00001363#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 dxp[opcode]++;
Guido van Rossum950361c1997-01-24 13:49:28 +00001365#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00001366
Guido van Rossum96a42c81992-01-12 02:29:51 +00001367#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* Instruction tracing */
Guido van Rossumac7be682001-01-17 15:42:30 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 if (lltrace) {
1371 if (HAS_ARG(opcode)) {
1372 printf("%d: %d, %d\n",
1373 f->f_lasti, opcode, oparg);
1374 }
1375 else {
1376 printf("%d: %d\n",
1377 f->f_lasti, opcode);
1378 }
1379 }
Guido van Rossum374a9221991-04-04 10:40:29 +00001380#endif
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 /* Main switch on opcode */
1383 READ_TIMESTAMP(inst0);
Jeremy Hylton52820442001-01-03 23:52:36 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 switch (opcode) {
Guido van Rossumac7be682001-01-17 15:42:30 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 /* BEWARE!
1388 It is essential that any operation that fails sets either
1389 x to NULL, err to nonzero, or why to anything but WHY_NOT,
1390 and that no operation that succeeds does this! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* case STOP_CODE: this is an error! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 TARGET(NOP)
1395 FAST_DISPATCH();
Raymond Hettinger9c18e812004-06-21 16:31:15 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 TARGET(LOAD_FAST)
1398 x = GETLOCAL(oparg);
1399 if (x != NULL) {
1400 Py_INCREF(x);
1401 PUSH(x);
1402 FAST_DISPATCH();
1403 }
1404 format_exc_check_arg(PyExc_UnboundLocalError,
1405 UNBOUNDLOCAL_ERROR_MSG,
1406 PyTuple_GetItem(co->co_varnames, oparg));
1407 break;
Neil Schemenauer63543862002-02-17 19:10:14 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 TARGET(LOAD_CONST)
1410 x = GETITEM(consts, oparg);
1411 Py_INCREF(x);
1412 PUSH(x);
1413 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PREDICTED_WITH_ARG(STORE_FAST);
1416 TARGET(STORE_FAST)
1417 v = POP();
1418 SETLOCAL(oparg, v);
1419 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 TARGET(POP_TOP)
1422 v = POP();
1423 Py_DECREF(v);
1424 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 TARGET(ROT_TWO)
1427 v = TOP();
1428 w = SECOND();
1429 SET_TOP(w);
1430 SET_SECOND(v);
1431 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 TARGET(ROT_THREE)
1434 v = TOP();
1435 w = SECOND();
1436 x = THIRD();
1437 SET_TOP(w);
1438 SET_SECOND(x);
1439 SET_THIRD(v);
1440 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 TARGET(DUP_TOP)
1443 v = TOP();
1444 Py_INCREF(v);
1445 PUSH(v);
1446 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001447
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00001448 TARGET(DUP_TOP_TWO)
1449 x = TOP();
1450 Py_INCREF(x);
1451 w = SECOND();
1452 Py_INCREF(w);
1453 STACKADJ(2);
1454 SET_TOP(x);
1455 SET_SECOND(w);
1456 FAST_DISPATCH();
Thomas Wouters434d0822000-08-24 20:11:32 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 TARGET(UNARY_POSITIVE)
1459 v = TOP();
1460 x = PyNumber_Positive(v);
1461 Py_DECREF(v);
1462 SET_TOP(x);
1463 if (x != NULL) DISPATCH();
1464 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 TARGET(UNARY_NEGATIVE)
1467 v = TOP();
1468 x = PyNumber_Negative(v);
1469 Py_DECREF(v);
1470 SET_TOP(x);
1471 if (x != NULL) DISPATCH();
1472 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 TARGET(UNARY_NOT)
1475 v = TOP();
1476 err = PyObject_IsTrue(v);
1477 Py_DECREF(v);
1478 if (err == 0) {
1479 Py_INCREF(Py_True);
1480 SET_TOP(Py_True);
1481 DISPATCH();
1482 }
1483 else if (err > 0) {
1484 Py_INCREF(Py_False);
1485 SET_TOP(Py_False);
1486 err = 0;
1487 DISPATCH();
1488 }
1489 STACKADJ(-1);
1490 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 TARGET(UNARY_INVERT)
1493 v = TOP();
1494 x = PyNumber_Invert(v);
1495 Py_DECREF(v);
1496 SET_TOP(x);
1497 if (x != NULL) DISPATCH();
1498 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 TARGET(BINARY_POWER)
1501 w = POP();
1502 v = TOP();
1503 x = PyNumber_Power(v, w, Py_None);
1504 Py_DECREF(v);
1505 Py_DECREF(w);
1506 SET_TOP(x);
1507 if (x != NULL) DISPATCH();
1508 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 TARGET(BINARY_MULTIPLY)
1511 w = POP();
1512 v = TOP();
1513 x = PyNumber_Multiply(v, w);
1514 Py_DECREF(v);
1515 Py_DECREF(w);
1516 SET_TOP(x);
1517 if (x != NULL) DISPATCH();
1518 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 TARGET(BINARY_TRUE_DIVIDE)
1521 w = POP();
1522 v = TOP();
1523 x = PyNumber_TrueDivide(v, w);
1524 Py_DECREF(v);
1525 Py_DECREF(w);
1526 SET_TOP(x);
1527 if (x != NULL) DISPATCH();
1528 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 TARGET(BINARY_FLOOR_DIVIDE)
1531 w = POP();
1532 v = TOP();
1533 x = PyNumber_FloorDivide(v, w);
1534 Py_DECREF(v);
1535 Py_DECREF(w);
1536 SET_TOP(x);
1537 if (x != NULL) DISPATCH();
1538 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 TARGET(BINARY_MODULO)
1541 w = POP();
1542 v = TOP();
1543 if (PyUnicode_CheckExact(v))
1544 x = PyUnicode_Format(v, w);
1545 else
1546 x = PyNumber_Remainder(v, w);
1547 Py_DECREF(v);
1548 Py_DECREF(w);
1549 SET_TOP(x);
1550 if (x != NULL) DISPATCH();
1551 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 TARGET(BINARY_ADD)
1554 w = POP();
1555 v = TOP();
1556 if (PyUnicode_CheckExact(v) &&
1557 PyUnicode_CheckExact(w)) {
1558 x = unicode_concatenate(v, w, f, next_instr);
1559 /* unicode_concatenate consumed the ref to v */
1560 goto skip_decref_vx;
1561 }
1562 else {
1563 x = PyNumber_Add(v, w);
1564 }
1565 Py_DECREF(v);
1566 skip_decref_vx:
1567 Py_DECREF(w);
1568 SET_TOP(x);
1569 if (x != NULL) DISPATCH();
1570 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 TARGET(BINARY_SUBTRACT)
1573 w = POP();
1574 v = TOP();
1575 x = PyNumber_Subtract(v, w);
1576 Py_DECREF(v);
1577 Py_DECREF(w);
1578 SET_TOP(x);
1579 if (x != NULL) DISPATCH();
1580 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 TARGET(BINARY_SUBSCR)
1583 w = POP();
1584 v = TOP();
1585 x = PyObject_GetItem(v, w);
1586 Py_DECREF(v);
1587 Py_DECREF(w);
1588 SET_TOP(x);
1589 if (x != NULL) DISPATCH();
1590 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 TARGET(BINARY_LSHIFT)
1593 w = POP();
1594 v = TOP();
1595 x = PyNumber_Lshift(v, w);
1596 Py_DECREF(v);
1597 Py_DECREF(w);
1598 SET_TOP(x);
1599 if (x != NULL) DISPATCH();
1600 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 TARGET(BINARY_RSHIFT)
1603 w = POP();
1604 v = TOP();
1605 x = PyNumber_Rshift(v, w);
1606 Py_DECREF(v);
1607 Py_DECREF(w);
1608 SET_TOP(x);
1609 if (x != NULL) DISPATCH();
1610 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 TARGET(BINARY_AND)
1613 w = POP();
1614 v = TOP();
1615 x = PyNumber_And(v, w);
1616 Py_DECREF(v);
1617 Py_DECREF(w);
1618 SET_TOP(x);
1619 if (x != NULL) DISPATCH();
1620 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 TARGET(BINARY_XOR)
1623 w = POP();
1624 v = TOP();
1625 x = PyNumber_Xor(v, w);
1626 Py_DECREF(v);
1627 Py_DECREF(w);
1628 SET_TOP(x);
1629 if (x != NULL) DISPATCH();
1630 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 TARGET(BINARY_OR)
1633 w = POP();
1634 v = TOP();
1635 x = PyNumber_Or(v, w);
1636 Py_DECREF(v);
1637 Py_DECREF(w);
1638 SET_TOP(x);
1639 if (x != NULL) DISPATCH();
1640 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 TARGET(LIST_APPEND)
1643 w = POP();
1644 v = PEEK(oparg);
1645 err = PyList_Append(v, w);
1646 Py_DECREF(w);
1647 if (err == 0) {
1648 PREDICT(JUMP_ABSOLUTE);
1649 DISPATCH();
1650 }
1651 break;
Raymond Hettingerdd80f762004-03-07 07:31:06 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 TARGET(SET_ADD)
1654 w = POP();
1655 v = stack_pointer[-oparg];
1656 err = PySet_Add(v, w);
1657 Py_DECREF(w);
1658 if (err == 0) {
1659 PREDICT(JUMP_ABSOLUTE);
1660 DISPATCH();
1661 }
1662 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 TARGET(INPLACE_POWER)
1665 w = POP();
1666 v = TOP();
1667 x = PyNumber_InPlacePower(v, w, Py_None);
1668 Py_DECREF(v);
1669 Py_DECREF(w);
1670 SET_TOP(x);
1671 if (x != NULL) DISPATCH();
1672 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 TARGET(INPLACE_MULTIPLY)
1675 w = POP();
1676 v = TOP();
1677 x = PyNumber_InPlaceMultiply(v, w);
1678 Py_DECREF(v);
1679 Py_DECREF(w);
1680 SET_TOP(x);
1681 if (x != NULL) DISPATCH();
1682 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 TARGET(INPLACE_TRUE_DIVIDE)
1685 w = POP();
1686 v = TOP();
1687 x = PyNumber_InPlaceTrueDivide(v, w);
1688 Py_DECREF(v);
1689 Py_DECREF(w);
1690 SET_TOP(x);
1691 if (x != NULL) DISPATCH();
1692 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 TARGET(INPLACE_FLOOR_DIVIDE)
1695 w = POP();
1696 v = TOP();
1697 x = PyNumber_InPlaceFloorDivide(v, w);
1698 Py_DECREF(v);
1699 Py_DECREF(w);
1700 SET_TOP(x);
1701 if (x != NULL) DISPATCH();
1702 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 TARGET(INPLACE_MODULO)
1705 w = POP();
1706 v = TOP();
1707 x = PyNumber_InPlaceRemainder(v, w);
1708 Py_DECREF(v);
1709 Py_DECREF(w);
1710 SET_TOP(x);
1711 if (x != NULL) DISPATCH();
1712 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 TARGET(INPLACE_ADD)
1715 w = POP();
1716 v = TOP();
1717 if (PyUnicode_CheckExact(v) &&
1718 PyUnicode_CheckExact(w)) {
1719 x = unicode_concatenate(v, w, f, next_instr);
1720 /* unicode_concatenate consumed the ref to v */
1721 goto skip_decref_v;
1722 }
1723 else {
1724 x = PyNumber_InPlaceAdd(v, w);
1725 }
1726 Py_DECREF(v);
1727 skip_decref_v:
1728 Py_DECREF(w);
1729 SET_TOP(x);
1730 if (x != NULL) DISPATCH();
1731 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 TARGET(INPLACE_SUBTRACT)
1734 w = POP();
1735 v = TOP();
1736 x = PyNumber_InPlaceSubtract(v, w);
1737 Py_DECREF(v);
1738 Py_DECREF(w);
1739 SET_TOP(x);
1740 if (x != NULL) DISPATCH();
1741 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 TARGET(INPLACE_LSHIFT)
1744 w = POP();
1745 v = TOP();
1746 x = PyNumber_InPlaceLshift(v, w);
1747 Py_DECREF(v);
1748 Py_DECREF(w);
1749 SET_TOP(x);
1750 if (x != NULL) DISPATCH();
1751 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 TARGET(INPLACE_RSHIFT)
1754 w = POP();
1755 v = TOP();
1756 x = PyNumber_InPlaceRshift(v, w);
1757 Py_DECREF(v);
1758 Py_DECREF(w);
1759 SET_TOP(x);
1760 if (x != NULL) DISPATCH();
1761 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 TARGET(INPLACE_AND)
1764 w = POP();
1765 v = TOP();
1766 x = PyNumber_InPlaceAnd(v, w);
1767 Py_DECREF(v);
1768 Py_DECREF(w);
1769 SET_TOP(x);
1770 if (x != NULL) DISPATCH();
1771 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 TARGET(INPLACE_XOR)
1774 w = POP();
1775 v = TOP();
1776 x = PyNumber_InPlaceXor(v, w);
1777 Py_DECREF(v);
1778 Py_DECREF(w);
1779 SET_TOP(x);
1780 if (x != NULL) DISPATCH();
1781 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 TARGET(INPLACE_OR)
1784 w = POP();
1785 v = TOP();
1786 x = PyNumber_InPlaceOr(v, w);
1787 Py_DECREF(v);
1788 Py_DECREF(w);
1789 SET_TOP(x);
1790 if (x != NULL) DISPATCH();
1791 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 TARGET(STORE_SUBSCR)
1794 w = TOP();
1795 v = SECOND();
1796 u = THIRD();
1797 STACKADJ(-3);
1798 /* v[w] = u */
1799 err = PyObject_SetItem(v, w, u);
1800 Py_DECREF(u);
1801 Py_DECREF(v);
1802 Py_DECREF(w);
1803 if (err == 0) DISPATCH();
1804 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 TARGET(DELETE_SUBSCR)
1807 w = TOP();
1808 v = SECOND();
1809 STACKADJ(-2);
1810 /* del v[w] */
1811 err = PyObject_DelItem(v, w);
1812 Py_DECREF(v);
1813 Py_DECREF(w);
1814 if (err == 0) DISPATCH();
1815 break;
Barry Warsaw23c9ec82000-08-21 15:44:01 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 TARGET(PRINT_EXPR)
1818 v = POP();
1819 w = PySys_GetObject("displayhook");
1820 if (w == NULL) {
1821 PyErr_SetString(PyExc_RuntimeError,
1822 "lost sys.displayhook");
1823 err = -1;
1824 x = NULL;
1825 }
1826 if (err == 0) {
1827 x = PyTuple_Pack(1, v);
1828 if (x == NULL)
1829 err = -1;
1830 }
1831 if (err == 0) {
1832 w = PyEval_CallObject(w, x);
1833 Py_XDECREF(w);
1834 if (w == NULL)
1835 err = -1;
1836 }
1837 Py_DECREF(v);
1838 Py_XDECREF(x);
1839 break;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +00001840
Thomas Wouters434d0822000-08-24 20:11:32 +00001841#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 default: switch (opcode) {
Thomas Wouters434d0822000-08-24 20:11:32 +00001843#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 TARGET(RAISE_VARARGS)
1845 v = w = NULL;
1846 switch (oparg) {
1847 case 2:
1848 v = POP(); /* cause */
1849 case 1:
1850 w = POP(); /* exc */
1851 case 0: /* Fallthrough */
1852 why = do_raise(w, v);
1853 break;
1854 default:
1855 PyErr_SetString(PyExc_SystemError,
1856 "bad RAISE_VARARGS oparg");
1857 why = WHY_EXCEPTION;
1858 break;
1859 }
1860 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 TARGET(STORE_LOCALS)
1863 x = POP();
1864 v = f->f_locals;
1865 Py_XDECREF(v);
1866 f->f_locals = x;
1867 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 TARGET(RETURN_VALUE)
1870 retval = POP();
1871 why = WHY_RETURN;
1872 goto fast_block_end;
Guido van Rossumdb3165e1993-10-18 17:06:59 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 TARGET(YIELD_VALUE)
1875 retval = POP();
1876 f->f_stacktop = stack_pointer;
1877 why = WHY_YIELD;
1878 /* Put aside the current exception state and restore
1879 that of the calling frame. This only serves when
1880 "yield" is used inside an except handler. */
1881 SWAP_EXC_STATE();
1882 goto fast_yield;
Tim Peters5ca576e2001-06-18 22:08:13 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 TARGET(POP_EXCEPT)
1885 {
1886 PyTryBlock *b = PyFrame_BlockPop(f);
1887 if (b->b_type != EXCEPT_HANDLER) {
1888 PyErr_SetString(PyExc_SystemError,
1889 "popped block is not an except handler");
1890 why = WHY_EXCEPTION;
1891 break;
1892 }
1893 UNWIND_EXCEPT_HANDLER(b);
1894 }
1895 DISPATCH();
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 TARGET(POP_BLOCK)
1898 {
1899 PyTryBlock *b = PyFrame_BlockPop(f);
1900 UNWIND_BLOCK(b);
1901 }
1902 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 PREDICTED(END_FINALLY);
1905 TARGET(END_FINALLY)
1906 v = POP();
1907 if (PyLong_Check(v)) {
1908 why = (enum why_code) PyLong_AS_LONG(v);
1909 assert(why != WHY_YIELD);
1910 if (why == WHY_RETURN ||
1911 why == WHY_CONTINUE)
1912 retval = POP();
1913 if (why == WHY_SILENCED) {
1914 /* An exception was silenced by 'with', we must
1915 manually unwind the EXCEPT_HANDLER block which was
1916 created when the exception was caught, otherwise
1917 the stack will be in an inconsistent state. */
1918 PyTryBlock *b = PyFrame_BlockPop(f);
1919 assert(b->b_type == EXCEPT_HANDLER);
1920 UNWIND_EXCEPT_HANDLER(b);
1921 why = WHY_NOT;
1922 }
1923 }
1924 else if (PyExceptionClass_Check(v)) {
1925 w = POP();
1926 u = POP();
1927 PyErr_Restore(v, w, u);
1928 why = WHY_RERAISE;
1929 break;
1930 }
1931 else if (v != Py_None) {
1932 PyErr_SetString(PyExc_SystemError,
1933 "'finally' pops bad exception");
1934 why = WHY_EXCEPTION;
1935 }
1936 Py_DECREF(v);
1937 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 TARGET(LOAD_BUILD_CLASS)
1940 x = PyDict_GetItemString(f->f_builtins,
1941 "__build_class__");
1942 if (x == NULL) {
1943 PyErr_SetString(PyExc_ImportError,
1944 "__build_class__ not found");
1945 break;
1946 }
1947 Py_INCREF(x);
1948 PUSH(x);
1949 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 TARGET(STORE_NAME)
1952 w = GETITEM(names, oparg);
1953 v = POP();
1954 if ((x = f->f_locals) != NULL) {
1955 if (PyDict_CheckExact(x))
1956 err = PyDict_SetItem(x, w, v);
1957 else
1958 err = PyObject_SetItem(x, w, v);
1959 Py_DECREF(v);
1960 if (err == 0) DISPATCH();
1961 break;
1962 }
1963 PyErr_Format(PyExc_SystemError,
1964 "no locals found when storing %R", w);
1965 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 TARGET(DELETE_NAME)
1968 w = GETITEM(names, oparg);
1969 if ((x = f->f_locals) != NULL) {
1970 if ((err = PyObject_DelItem(x, w)) != 0)
1971 format_exc_check_arg(PyExc_NameError,
1972 NAME_ERROR_MSG,
1973 w);
1974 break;
1975 }
1976 PyErr_Format(PyExc_SystemError,
1977 "no locals when deleting %R", w);
1978 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
1981 TARGET(UNPACK_SEQUENCE)
1982 v = POP();
1983 if (PyTuple_CheckExact(v) &&
1984 PyTuple_GET_SIZE(v) == oparg) {
1985 PyObject **items = \
1986 ((PyTupleObject *)v)->ob_item;
1987 while (oparg--) {
1988 w = items[oparg];
1989 Py_INCREF(w);
1990 PUSH(w);
1991 }
1992 Py_DECREF(v);
1993 DISPATCH();
1994 } else if (PyList_CheckExact(v) &&
1995 PyList_GET_SIZE(v) == oparg) {
1996 PyObject **items = \
1997 ((PyListObject *)v)->ob_item;
1998 while (oparg--) {
1999 w = items[oparg];
2000 Py_INCREF(w);
2001 PUSH(w);
2002 }
2003 } else if (unpack_iterable(v, oparg, -1,
2004 stack_pointer + oparg)) {
2005 STACKADJ(oparg);
2006 } else {
2007 /* unpack_iterable() raised an exception */
2008 why = WHY_EXCEPTION;
2009 }
2010 Py_DECREF(v);
2011 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 TARGET(UNPACK_EX)
2014 {
2015 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
2016 v = POP();
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (unpack_iterable(v, oparg & 0xFF, oparg >> 8,
2019 stack_pointer + totalargs)) {
2020 stack_pointer += totalargs;
2021 } else {
2022 why = WHY_EXCEPTION;
2023 }
2024 Py_DECREF(v);
2025 break;
2026 }
Guido van Rossum0368b722007-05-11 16:50:42 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 TARGET(STORE_ATTR)
2029 w = GETITEM(names, oparg);
2030 v = TOP();
2031 u = SECOND();
2032 STACKADJ(-2);
2033 err = PyObject_SetAttr(v, w, u); /* v.w = u */
2034 Py_DECREF(v);
2035 Py_DECREF(u);
2036 if (err == 0) DISPATCH();
2037 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 TARGET(DELETE_ATTR)
2040 w = GETITEM(names, oparg);
2041 v = POP();
2042 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
2043 /* del v.w */
2044 Py_DECREF(v);
2045 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 TARGET(STORE_GLOBAL)
2048 w = GETITEM(names, oparg);
2049 v = POP();
2050 err = PyDict_SetItem(f->f_globals, w, v);
2051 Py_DECREF(v);
2052 if (err == 0) DISPATCH();
2053 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 TARGET(DELETE_GLOBAL)
2056 w = GETITEM(names, oparg);
2057 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
2058 format_exc_check_arg(
2059 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
2060 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 TARGET(LOAD_NAME)
2063 w = GETITEM(names, oparg);
2064 if ((v = f->f_locals) == NULL) {
2065 PyErr_Format(PyExc_SystemError,
2066 "no locals when loading %R", w);
2067 why = WHY_EXCEPTION;
2068 break;
2069 }
2070 if (PyDict_CheckExact(v)) {
2071 x = PyDict_GetItem(v, w);
2072 Py_XINCREF(x);
2073 }
2074 else {
2075 x = PyObject_GetItem(v, w);
2076 if (x == NULL && PyErr_Occurred()) {
2077 if (!PyErr_ExceptionMatches(
2078 PyExc_KeyError))
2079 break;
2080 PyErr_Clear();
2081 }
2082 }
2083 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002084 x = PyDict_GetItem(f->f_globals, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002086 x = PyDict_GetItem(f->f_builtins, w);
2087 if (x == NULL) {
2088 format_exc_check_arg(
2089 PyExc_NameError,
2090 NAME_ERROR_MSG, w);
2091 break;
2092 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 }
2094 Py_INCREF(x);
2095 }
2096 PUSH(x);
2097 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 TARGET(LOAD_GLOBAL)
2100 w = GETITEM(names, oparg);
2101 if (PyUnicode_CheckExact(w)) {
2102 /* Inline the PyDict_GetItem() calls.
2103 WARNING: this is an extreme speed hack.
2104 Do not try this at home. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002105 Py_hash_t hash = ((PyUnicodeObject *)w)->hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (hash != -1) {
2107 PyDictObject *d;
2108 PyDictEntry *e;
2109 d = (PyDictObject *)(f->f_globals);
2110 e = d->ma_lookup(d, w, hash);
2111 if (e == NULL) {
2112 x = NULL;
2113 break;
2114 }
2115 x = e->me_value;
2116 if (x != NULL) {
2117 Py_INCREF(x);
2118 PUSH(x);
2119 DISPATCH();
2120 }
2121 d = (PyDictObject *)(f->f_builtins);
2122 e = d->ma_lookup(d, w, hash);
2123 if (e == NULL) {
2124 x = NULL;
2125 break;
2126 }
2127 x = e->me_value;
2128 if (x != NULL) {
2129 Py_INCREF(x);
2130 PUSH(x);
2131 DISPATCH();
2132 }
2133 goto load_global_error;
2134 }
2135 }
2136 /* This is the un-inlined version of the code above */
2137 x = PyDict_GetItem(f->f_globals, w);
2138 if (x == NULL) {
2139 x = PyDict_GetItem(f->f_builtins, w);
2140 if (x == NULL) {
2141 load_global_error:
2142 format_exc_check_arg(
2143 PyExc_NameError,
2144 GLOBAL_NAME_ERROR_MSG, w);
2145 break;
2146 }
2147 }
2148 Py_INCREF(x);
2149 PUSH(x);
2150 DISPATCH();
Guido van Rossum681d79a1995-07-18 14:51:37 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 TARGET(DELETE_FAST)
2153 x = GETLOCAL(oparg);
2154 if (x != NULL) {
2155 SETLOCAL(oparg, NULL);
2156 DISPATCH();
2157 }
2158 format_exc_check_arg(
2159 PyExc_UnboundLocalError,
2160 UNBOUNDLOCAL_ERROR_MSG,
2161 PyTuple_GetItem(co->co_varnames, oparg)
2162 );
2163 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002164
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002165 TARGET(DELETE_DEREF)
2166 x = freevars[oparg];
2167 if (PyCell_GET(x) != NULL) {
2168 PyCell_Set(x, NULL);
Benjamin Peterson00ebe2c2010-09-10 22:02:31 +00002169 DISPATCH();
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002170 }
2171 err = -1;
2172 format_exc_unbound(co, oparg);
2173 break;
2174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 TARGET(LOAD_CLOSURE)
2176 x = freevars[oparg];
2177 Py_INCREF(x);
2178 PUSH(x);
2179 if (x != NULL) DISPATCH();
2180 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 TARGET(LOAD_DEREF)
2183 x = freevars[oparg];
2184 w = PyCell_Get(x);
2185 if (w != NULL) {
2186 PUSH(w);
2187 DISPATCH();
2188 }
2189 err = -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002190 format_exc_unbound(co, oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 TARGET(STORE_DEREF)
2194 w = POP();
2195 x = freevars[oparg];
2196 PyCell_Set(x, w);
2197 Py_DECREF(w);
2198 DISPATCH();
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 TARGET(BUILD_TUPLE)
2201 x = PyTuple_New(oparg);
2202 if (x != NULL) {
2203 for (; --oparg >= 0;) {
2204 w = POP();
2205 PyTuple_SET_ITEM(x, oparg, w);
2206 }
2207 PUSH(x);
2208 DISPATCH();
2209 }
2210 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 TARGET(BUILD_LIST)
2213 x = PyList_New(oparg);
2214 if (x != NULL) {
2215 for (; --oparg >= 0;) {
2216 w = POP();
2217 PyList_SET_ITEM(x, oparg, w);
2218 }
2219 PUSH(x);
2220 DISPATCH();
2221 }
2222 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 TARGET(BUILD_SET)
2225 x = PySet_New(NULL);
2226 if (x != NULL) {
2227 for (; --oparg >= 0;) {
2228 w = POP();
2229 if (err == 0)
2230 err = PySet_Add(x, w);
2231 Py_DECREF(w);
2232 }
2233 if (err != 0) {
2234 Py_DECREF(x);
2235 break;
2236 }
2237 PUSH(x);
2238 DISPATCH();
2239 }
2240 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 TARGET(BUILD_MAP)
2243 x = _PyDict_NewPresized((Py_ssize_t)oparg);
2244 PUSH(x);
2245 if (x != NULL) DISPATCH();
2246 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 TARGET(STORE_MAP)
2249 w = TOP(); /* key */
2250 u = SECOND(); /* value */
2251 v = THIRD(); /* dict */
2252 STACKADJ(-2);
2253 assert (PyDict_CheckExact(v));
2254 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2255 Py_DECREF(u);
2256 Py_DECREF(w);
2257 if (err == 0) DISPATCH();
2258 break;
Christian Heimes99170a52007-12-19 02:07:34 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 TARGET(MAP_ADD)
2261 w = TOP(); /* key */
2262 u = SECOND(); /* value */
2263 STACKADJ(-2);
2264 v = stack_pointer[-oparg]; /* dict */
2265 assert (PyDict_CheckExact(v));
2266 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2267 Py_DECREF(u);
2268 Py_DECREF(w);
2269 if (err == 0) {
2270 PREDICT(JUMP_ABSOLUTE);
2271 DISPATCH();
2272 }
2273 break;
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 TARGET(LOAD_ATTR)
2276 w = GETITEM(names, oparg);
2277 v = TOP();
2278 x = PyObject_GetAttr(v, w);
2279 Py_DECREF(v);
2280 SET_TOP(x);
2281 if (x != NULL) DISPATCH();
2282 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 TARGET(COMPARE_OP)
2285 w = POP();
2286 v = TOP();
2287 x = cmp_outcome(oparg, v, w);
2288 Py_DECREF(v);
2289 Py_DECREF(w);
2290 SET_TOP(x);
2291 if (x == NULL) break;
2292 PREDICT(POP_JUMP_IF_FALSE);
2293 PREDICT(POP_JUMP_IF_TRUE);
2294 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 TARGET(IMPORT_NAME)
2297 w = GETITEM(names, oparg);
2298 x = PyDict_GetItemString(f->f_builtins, "__import__");
2299 if (x == NULL) {
2300 PyErr_SetString(PyExc_ImportError,
2301 "__import__ not found");
2302 break;
2303 }
2304 Py_INCREF(x);
2305 v = POP();
2306 u = TOP();
2307 if (PyLong_AsLong(u) != -1 || PyErr_Occurred())
2308 w = PyTuple_Pack(5,
2309 w,
2310 f->f_globals,
2311 f->f_locals == NULL ?
2312 Py_None : f->f_locals,
2313 v,
2314 u);
2315 else
2316 w = PyTuple_Pack(4,
2317 w,
2318 f->f_globals,
2319 f->f_locals == NULL ?
2320 Py_None : f->f_locals,
2321 v);
2322 Py_DECREF(v);
2323 Py_DECREF(u);
2324 if (w == NULL) {
2325 u = POP();
2326 Py_DECREF(x);
2327 x = NULL;
2328 break;
2329 }
2330 READ_TIMESTAMP(intr0);
2331 v = x;
2332 x = PyEval_CallObject(v, w);
2333 Py_DECREF(v);
2334 READ_TIMESTAMP(intr1);
2335 Py_DECREF(w);
2336 SET_TOP(x);
2337 if (x != NULL) DISPATCH();
2338 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 TARGET(IMPORT_STAR)
2341 v = POP();
2342 PyFrame_FastToLocals(f);
2343 if ((x = f->f_locals) == NULL) {
2344 PyErr_SetString(PyExc_SystemError,
2345 "no locals found during 'import *'");
2346 break;
2347 }
2348 READ_TIMESTAMP(intr0);
2349 err = import_all_from(x, v);
2350 READ_TIMESTAMP(intr1);
2351 PyFrame_LocalsToFast(f, 0);
2352 Py_DECREF(v);
2353 if (err == 0) DISPATCH();
2354 break;
Guido van Rossum25831651993-05-19 14:50:45 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 TARGET(IMPORT_FROM)
2357 w = GETITEM(names, oparg);
2358 v = TOP();
2359 READ_TIMESTAMP(intr0);
2360 x = import_from(v, w);
2361 READ_TIMESTAMP(intr1);
2362 PUSH(x);
2363 if (x != NULL) DISPATCH();
2364 break;
Thomas Wouters52152252000-08-17 22:55:00 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 TARGET(JUMP_FORWARD)
2367 JUMPBY(oparg);
2368 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE);
2371 TARGET(POP_JUMP_IF_FALSE)
2372 w = POP();
2373 if (w == Py_True) {
2374 Py_DECREF(w);
2375 FAST_DISPATCH();
2376 }
2377 if (w == Py_False) {
2378 Py_DECREF(w);
2379 JUMPTO(oparg);
2380 FAST_DISPATCH();
2381 }
2382 err = PyObject_IsTrue(w);
2383 Py_DECREF(w);
2384 if (err > 0)
2385 err = 0;
2386 else if (err == 0)
2387 JUMPTO(oparg);
2388 else
2389 break;
2390 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE);
2393 TARGET(POP_JUMP_IF_TRUE)
2394 w = POP();
2395 if (w == Py_False) {
2396 Py_DECREF(w);
2397 FAST_DISPATCH();
2398 }
2399 if (w == Py_True) {
2400 Py_DECREF(w);
2401 JUMPTO(oparg);
2402 FAST_DISPATCH();
2403 }
2404 err = PyObject_IsTrue(w);
2405 Py_DECREF(w);
2406 if (err > 0) {
2407 err = 0;
2408 JUMPTO(oparg);
2409 }
2410 else if (err == 0)
2411 ;
2412 else
2413 break;
2414 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 TARGET(JUMP_IF_FALSE_OR_POP)
2417 w = TOP();
2418 if (w == Py_True) {
2419 STACKADJ(-1);
2420 Py_DECREF(w);
2421 FAST_DISPATCH();
2422 }
2423 if (w == Py_False) {
2424 JUMPTO(oparg);
2425 FAST_DISPATCH();
2426 }
2427 err = PyObject_IsTrue(w);
2428 if (err > 0) {
2429 STACKADJ(-1);
2430 Py_DECREF(w);
2431 err = 0;
2432 }
2433 else if (err == 0)
2434 JUMPTO(oparg);
2435 else
2436 break;
2437 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 TARGET(JUMP_IF_TRUE_OR_POP)
2440 w = TOP();
2441 if (w == Py_False) {
2442 STACKADJ(-1);
2443 Py_DECREF(w);
2444 FAST_DISPATCH();
2445 }
2446 if (w == Py_True) {
2447 JUMPTO(oparg);
2448 FAST_DISPATCH();
2449 }
2450 err = PyObject_IsTrue(w);
2451 if (err > 0) {
2452 err = 0;
2453 JUMPTO(oparg);
2454 }
2455 else if (err == 0) {
2456 STACKADJ(-1);
2457 Py_DECREF(w);
2458 }
2459 else
2460 break;
2461 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 PREDICTED_WITH_ARG(JUMP_ABSOLUTE);
2464 TARGET(JUMP_ABSOLUTE)
2465 JUMPTO(oparg);
Guido van Rossum58da9312007-11-10 23:39:45 +00002466#if FAST_LOOPS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 /* Enabling this path speeds-up all while and for-loops by bypassing
2468 the per-loop checks for signals. By default, this should be turned-off
2469 because it prevents detection of a control-break in tight loops like
2470 "while 1: pass". Compile with this option turned-on when you need
2471 the speed-up and do not need break checking inside tight loops (ones
2472 that contain only instructions ending with FAST_DISPATCH).
2473 */
2474 FAST_DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002475#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002477#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 TARGET(GET_ITER)
2480 /* before: [obj]; after [getiter(obj)] */
2481 v = TOP();
2482 x = PyObject_GetIter(v);
2483 Py_DECREF(v);
2484 if (x != NULL) {
2485 SET_TOP(x);
2486 PREDICT(FOR_ITER);
2487 DISPATCH();
2488 }
2489 STACKADJ(-1);
2490 break;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 PREDICTED_WITH_ARG(FOR_ITER);
2493 TARGET(FOR_ITER)
2494 /* before: [iter]; after: [iter, iter()] *or* [] */
2495 v = TOP();
2496 x = (*v->ob_type->tp_iternext)(v);
2497 if (x != NULL) {
2498 PUSH(x);
2499 PREDICT(STORE_FAST);
2500 PREDICT(UNPACK_SEQUENCE);
2501 DISPATCH();
2502 }
2503 if (PyErr_Occurred()) {
2504 if (!PyErr_ExceptionMatches(
2505 PyExc_StopIteration))
2506 break;
2507 PyErr_Clear();
2508 }
2509 /* iterator ended normally */
2510 x = v = POP();
2511 Py_DECREF(v);
2512 JUMPBY(oparg);
2513 DISPATCH();
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 TARGET(BREAK_LOOP)
2516 why = WHY_BREAK;
2517 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 TARGET(CONTINUE_LOOP)
2520 retval = PyLong_FromLong(oparg);
2521 if (!retval) {
2522 x = NULL;
2523 break;
2524 }
2525 why = WHY_CONTINUE;
2526 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally)
2529 TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally)
2530 TARGET(SETUP_FINALLY)
2531 _setup_finally:
2532 /* NOTE: If you add any new block-setup opcodes that
2533 are not try/except/finally handlers, you may need
2534 to update the PyGen_NeedsFinalizing() function.
2535 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
2538 STACK_LEVEL());
2539 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 TARGET(SETUP_WITH)
2542 {
2543 static PyObject *exit, *enter;
2544 w = TOP();
2545 x = special_lookup(w, "__exit__", &exit);
2546 if (!x)
2547 break;
2548 SET_TOP(x);
2549 u = special_lookup(w, "__enter__", &enter);
2550 Py_DECREF(w);
2551 if (!u) {
2552 x = NULL;
2553 break;
2554 }
2555 x = PyObject_CallFunctionObjArgs(u, NULL);
2556 Py_DECREF(u);
2557 if (!x)
2558 break;
2559 /* Setup the finally block before pushing the result
2560 of __enter__ on the stack. */
2561 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
2562 STACK_LEVEL());
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 PUSH(x);
2565 DISPATCH();
2566 }
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 TARGET(WITH_CLEANUP)
2569 {
2570 /* At the top of the stack are 1-3 values indicating
2571 how/why we entered the finally clause:
2572 - TOP = None
2573 - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
2574 - TOP = WHY_*; no retval below it
2575 - (TOP, SECOND, THIRD) = exc_info()
2576 (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER
2577 Below them is EXIT, the context.__exit__ bound method.
2578 In the last case, we must call
2579 EXIT(TOP, SECOND, THIRD)
2580 otherwise we must call
2581 EXIT(None, None, None)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 In the first two cases, we remove EXIT from the
2584 stack, leaving the rest in the same order. In the
2585 third case, we shift the bottom 3 values of the
2586 stack down, and replace the empty spot with NULL.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 In addition, if the stack represents an exception,
2589 *and* the function call returns a 'true' value, we
2590 push WHY_SILENCED onto the stack. END_FINALLY will
2591 then not re-raise the exception. (But non-local
2592 gotos should still be resumed.)
2593 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 PyObject *exit_func;
2596 u = TOP();
2597 if (u == Py_None) {
2598 (void)POP();
2599 exit_func = TOP();
2600 SET_TOP(u);
2601 v = w = Py_None;
2602 }
2603 else if (PyLong_Check(u)) {
2604 (void)POP();
2605 switch(PyLong_AsLong(u)) {
2606 case WHY_RETURN:
2607 case WHY_CONTINUE:
2608 /* Retval in TOP. */
2609 exit_func = SECOND();
2610 SET_SECOND(TOP());
2611 SET_TOP(u);
2612 break;
2613 default:
2614 exit_func = TOP();
2615 SET_TOP(u);
2616 break;
2617 }
2618 u = v = w = Py_None;
2619 }
2620 else {
2621 PyObject *tp, *exc, *tb;
2622 PyTryBlock *block;
2623 v = SECOND();
2624 w = THIRD();
2625 tp = FOURTH();
2626 exc = PEEK(5);
2627 tb = PEEK(6);
2628 exit_func = PEEK(7);
2629 SET_VALUE(7, tb);
2630 SET_VALUE(6, exc);
2631 SET_VALUE(5, tp);
2632 /* UNWIND_EXCEPT_HANDLER will pop this off. */
2633 SET_FOURTH(NULL);
2634 /* We just shifted the stack down, so we have
2635 to tell the except handler block that the
2636 values are lower than it expects. */
2637 block = &f->f_blockstack[f->f_iblock - 1];
2638 assert(block->b_type == EXCEPT_HANDLER);
2639 block->b_level--;
2640 }
2641 /* XXX Not the fastest way to call it... */
2642 x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
2643 NULL);
2644 Py_DECREF(exit_func);
2645 if (x == NULL)
2646 break; /* Go to error exit */
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 if (u != Py_None)
2649 err = PyObject_IsTrue(x);
2650 else
2651 err = 0;
2652 Py_DECREF(x);
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (err < 0)
2655 break; /* Go to error exit */
2656 else if (err > 0) {
2657 err = 0;
2658 /* There was an exception and a True return */
2659 PUSH(PyLong_FromLong((long) WHY_SILENCED));
2660 }
2661 PREDICT(END_FINALLY);
2662 break;
2663 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 TARGET(CALL_FUNCTION)
2666 {
2667 PyObject **sp;
2668 PCALL(PCALL_ALL);
2669 sp = stack_pointer;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002670#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 x = call_function(&sp, oparg, &intr0, &intr1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002672#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 x = call_function(&sp, oparg);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002674#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 stack_pointer = sp;
2676 PUSH(x);
2677 if (x != NULL)
2678 DISPATCH();
2679 break;
2680 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw)
2683 TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw)
2684 TARGET(CALL_FUNCTION_VAR_KW)
2685 _call_function_var_kw:
2686 {
2687 int na = oparg & 0xff;
2688 int nk = (oparg>>8) & 0xff;
2689 int flags = (opcode - CALL_FUNCTION) & 3;
2690 int n = na + 2 * nk;
2691 PyObject **pfunc, *func, **sp;
2692 PCALL(PCALL_ALL);
2693 if (flags & CALL_FLAG_VAR)
2694 n++;
2695 if (flags & CALL_FLAG_KW)
2696 n++;
2697 pfunc = stack_pointer - n - 1;
2698 func = *pfunc;
Jeremy Hylton52820442001-01-03 23:52:36 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 if (PyMethod_Check(func)
Stefan Krahb7e10102010-06-23 18:42:39 +00002701 && PyMethod_GET_SELF(func) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 PyObject *self = PyMethod_GET_SELF(func);
2703 Py_INCREF(self);
2704 func = PyMethod_GET_FUNCTION(func);
2705 Py_INCREF(func);
2706 Py_DECREF(*pfunc);
2707 *pfunc = self;
2708 na++;
2709 n++;
2710 } else
2711 Py_INCREF(func);
2712 sp = stack_pointer;
2713 READ_TIMESTAMP(intr0);
2714 x = ext_do_call(func, &sp, flags, na, nk);
2715 READ_TIMESTAMP(intr1);
2716 stack_pointer = sp;
2717 Py_DECREF(func);
Jeremy Hylton52820442001-01-03 23:52:36 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 while (stack_pointer > pfunc) {
2720 w = POP();
2721 Py_DECREF(w);
2722 }
2723 PUSH(x);
2724 if (x != NULL)
2725 DISPATCH();
2726 break;
2727 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function)
2730 TARGET(MAKE_FUNCTION)
2731 _make_function:
2732 {
2733 int posdefaults = oparg & 0xff;
2734 int kwdefaults = (oparg>>8) & 0xff;
2735 int num_annotations = (oparg >> 16) & 0x7fff;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 v = POP(); /* code object */
2738 x = PyFunction_New(v, f->f_globals);
2739 Py_DECREF(v);
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 if (x != NULL && opcode == MAKE_CLOSURE) {
2742 v = POP();
2743 if (PyFunction_SetClosure(x, v) != 0) {
2744 /* Can't happen unless bytecode is corrupt. */
2745 why = WHY_EXCEPTION;
2746 }
2747 Py_DECREF(v);
2748 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 if (x != NULL && num_annotations > 0) {
2751 Py_ssize_t name_ix;
2752 u = POP(); /* names of args with annotations */
2753 v = PyDict_New();
2754 if (v == NULL) {
2755 Py_DECREF(x);
2756 x = NULL;
2757 break;
2758 }
2759 name_ix = PyTuple_Size(u);
2760 assert(num_annotations == name_ix+1);
2761 while (name_ix > 0) {
2762 --name_ix;
2763 t = PyTuple_GET_ITEM(u, name_ix);
2764 w = POP();
2765 /* XXX(nnorwitz): check for errors */
2766 PyDict_SetItem(v, t, w);
2767 Py_DECREF(w);
2768 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 if (PyFunction_SetAnnotations(x, v) != 0) {
2771 /* Can't happen unless
2772 PyFunction_SetAnnotations changes. */
2773 why = WHY_EXCEPTION;
2774 }
2775 Py_DECREF(v);
2776 Py_DECREF(u);
2777 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 /* XXX Maybe this should be a separate opcode? */
2780 if (x != NULL && posdefaults > 0) {
2781 v = PyTuple_New(posdefaults);
2782 if (v == NULL) {
2783 Py_DECREF(x);
2784 x = NULL;
2785 break;
2786 }
2787 while (--posdefaults >= 0) {
2788 w = POP();
2789 PyTuple_SET_ITEM(v, posdefaults, w);
2790 }
2791 if (PyFunction_SetDefaults(x, v) != 0) {
2792 /* Can't happen unless
2793 PyFunction_SetDefaults changes. */
2794 why = WHY_EXCEPTION;
2795 }
2796 Py_DECREF(v);
2797 }
2798 if (x != NULL && kwdefaults > 0) {
2799 v = PyDict_New();
2800 if (v == NULL) {
2801 Py_DECREF(x);
2802 x = NULL;
2803 break;
2804 }
2805 while (--kwdefaults >= 0) {
2806 w = POP(); /* default value */
2807 u = POP(); /* kw only arg name */
2808 /* XXX(nnorwitz): check for errors */
2809 PyDict_SetItem(v, u, w);
2810 Py_DECREF(w);
2811 Py_DECREF(u);
2812 }
2813 if (PyFunction_SetKwDefaults(x, v) != 0) {
2814 /* Can't happen unless
2815 PyFunction_SetKwDefaults changes. */
2816 why = WHY_EXCEPTION;
2817 }
2818 Py_DECREF(v);
2819 }
2820 PUSH(x);
2821 break;
2822 }
Guido van Rossum8861b741996-07-30 16:49:37 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 TARGET(BUILD_SLICE)
2825 if (oparg == 3)
2826 w = POP();
2827 else
2828 w = NULL;
2829 v = POP();
2830 u = TOP();
2831 x = PySlice_New(u, v, w);
2832 Py_DECREF(u);
2833 Py_DECREF(v);
2834 Py_XDECREF(w);
2835 SET_TOP(x);
2836 if (x != NULL) DISPATCH();
2837 break;
Guido van Rossum8861b741996-07-30 16:49:37 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 TARGET(EXTENDED_ARG)
2840 opcode = NEXTOP();
2841 oparg = oparg<<16 | NEXTARG();
2842 goto dispatch_opcode;
Guido van Rossum8861b741996-07-30 16:49:37 +00002843
Antoine Pitrou042b1282010-08-13 21:15:58 +00002844#if USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 _unknown_opcode:
Antoine Pitroub52ec782009-01-25 16:34:23 +00002846#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 default:
2848 fprintf(stderr,
2849 "XXX lineno: %d, opcode: %d\n",
2850 PyFrame_GetLineNumber(f),
2851 opcode);
2852 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2853 why = WHY_EXCEPTION;
2854 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00002855
2856#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 }
Guido van Rossum04691fc1992-08-12 15:35:34 +00002858#endif
2859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 } /* switch */
Guido van Rossum374a9221991-04-04 10:40:29 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 on_error:
Guido van Rossumac7be682001-01-17 15:42:30 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 READ_TIMESTAMP(inst1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 /* Quickly continue if no error occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 if (why == WHY_NOT) {
2869 if (err == 0 && x != NULL) {
Guido van Rossum681d79a1995-07-18 14:51:37 +00002870#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 /* This check is expensive! */
2872 if (PyErr_Occurred())
2873 fprintf(stderr,
2874 "XXX undetected error\n");
2875 else {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002876#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 READ_TIMESTAMP(loop1);
2878 continue; /* Normal, fast path */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002879#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 }
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002881#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 }
2883 why = WHY_EXCEPTION;
2884 x = Py_None;
2885 err = 0;
2886 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 /* Double-check exception status */
Guido van Rossumac7be682001-01-17 15:42:30 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2891 if (!PyErr_Occurred()) {
2892 PyErr_SetString(PyExc_SystemError,
2893 "error return without exception set");
2894 why = WHY_EXCEPTION;
2895 }
2896 }
Guido van Rossumeb894eb1999-03-09 16:16:45 +00002897#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 else {
2899 /* This check is expensive! */
2900 if (PyErr_Occurred()) {
2901 char buf[128];
2902 sprintf(buf, "Stack unwind with exception "
2903 "set and why=%d", why);
2904 Py_FatalError(buf);
2905 }
2906 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002907#endif
2908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 /* Log traceback info if this is a real exception */
Guido van Rossumac7be682001-01-17 15:42:30 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 if (why == WHY_EXCEPTION) {
2912 PyTraceBack_Here(f);
Guido van Rossum96a42c81992-01-12 02:29:51 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 if (tstate->c_tracefunc != NULL)
2915 call_exc_trace(tstate->c_tracefunc,
2916 tstate->c_traceobj, f);
2917 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
Guido van Rossumac7be682001-01-17 15:42:30 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 if (why == WHY_RERAISE)
2922 why = WHY_EXCEPTION;
Guido van Rossum374a9221991-04-04 10:40:29 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 /* Unwind stacks if a (pseudo) exception occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002925
Raymond Hettinger1dd83092004-02-06 18:32:33 +00002926fast_block_end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 while (why != WHY_NOT && f->f_iblock > 0) {
2928 /* Peek at the current block. */
2929 PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1];
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 assert(why != WHY_YIELD);
2932 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
2933 why = WHY_NOT;
2934 JUMPTO(PyLong_AS_LONG(retval));
2935 Py_DECREF(retval);
2936 break;
2937 }
2938 /* Now we have to pop the block. */
2939 f->f_iblock--;
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 if (b->b_type == EXCEPT_HANDLER) {
2942 UNWIND_EXCEPT_HANDLER(b);
2943 continue;
2944 }
2945 UNWIND_BLOCK(b);
2946 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2947 why = WHY_NOT;
2948 JUMPTO(b->b_handler);
2949 break;
2950 }
2951 if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT
2952 || b->b_type == SETUP_FINALLY)) {
2953 PyObject *exc, *val, *tb;
2954 int handler = b->b_handler;
2955 /* Beware, this invalidates all b->b_* fields */
2956 PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL());
2957 PUSH(tstate->exc_traceback);
2958 PUSH(tstate->exc_value);
2959 if (tstate->exc_type != NULL) {
2960 PUSH(tstate->exc_type);
2961 }
2962 else {
2963 Py_INCREF(Py_None);
2964 PUSH(Py_None);
2965 }
2966 PyErr_Fetch(&exc, &val, &tb);
2967 /* Make the raw exception data
2968 available to the handler,
2969 so a program can emulate the
2970 Python main loop. */
2971 PyErr_NormalizeException(
2972 &exc, &val, &tb);
2973 PyException_SetTraceback(val, tb);
2974 Py_INCREF(exc);
2975 tstate->exc_type = exc;
2976 Py_INCREF(val);
2977 tstate->exc_value = val;
2978 tstate->exc_traceback = tb;
2979 if (tb == NULL)
2980 tb = Py_None;
2981 Py_INCREF(tb);
2982 PUSH(tb);
2983 PUSH(val);
2984 PUSH(exc);
2985 why = WHY_NOT;
2986 JUMPTO(handler);
2987 break;
2988 }
2989 if (b->b_type == SETUP_FINALLY) {
2990 if (why & (WHY_RETURN | WHY_CONTINUE))
2991 PUSH(retval);
2992 PUSH(PyLong_FromLong((long)why));
2993 why = WHY_NOT;
2994 JUMPTO(b->b_handler);
2995 break;
2996 }
2997 } /* unwind stack */
Guido van Rossum374a9221991-04-04 10:40:29 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 /* End the loop if we still have an error (or return) */
Guido van Rossumac7be682001-01-17 15:42:30 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 if (why != WHY_NOT)
3002 break;
3003 READ_TIMESTAMP(loop1);
Guido van Rossumac7be682001-01-17 15:42:30 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 } /* main loop */
Guido van Rossumac7be682001-01-17 15:42:30 +00003006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 assert(why != WHY_YIELD);
3008 /* Pop remaining stack entries. */
3009 while (!EMPTY()) {
3010 v = POP();
3011 Py_XDECREF(v);
3012 }
Guido van Rossum35974fb2001-12-06 21:28:18 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 if (why != WHY_RETURN)
3015 retval = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00003016
Raymond Hettinger1dd83092004-02-06 18:32:33 +00003017fast_yield:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 if (tstate->use_tracing) {
3019 if (tstate->c_tracefunc) {
3020 if (why == WHY_RETURN || why == WHY_YIELD) {
3021 if (call_trace(tstate->c_tracefunc,
3022 tstate->c_traceobj, f,
3023 PyTrace_RETURN, retval)) {
3024 Py_XDECREF(retval);
3025 retval = NULL;
3026 why = WHY_EXCEPTION;
3027 }
3028 }
3029 else if (why == WHY_EXCEPTION) {
3030 call_trace_protected(tstate->c_tracefunc,
3031 tstate->c_traceobj, f,
3032 PyTrace_RETURN, NULL);
3033 }
3034 }
3035 if (tstate->c_profilefunc) {
3036 if (why == WHY_EXCEPTION)
3037 call_trace_protected(tstate->c_profilefunc,
3038 tstate->c_profileobj, f,
3039 PyTrace_RETURN, NULL);
3040 else if (call_trace(tstate->c_profilefunc,
3041 tstate->c_profileobj, f,
3042 PyTrace_RETURN, retval)) {
3043 Py_XDECREF(retval);
3044 retval = NULL;
3045 why = WHY_EXCEPTION;
3046 }
3047 }
3048 }
Guido van Rossuma4240131997-01-21 21:18:36 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 /* pop frame */
Thomas Woutersce272b62007-09-19 21:19:28 +00003051exit_eval_frame:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 Py_LeaveRecursiveCall();
3053 tstate->frame = f->f_back;
Guido van Rossumac7be682001-01-17 15:42:30 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 return retval;
Guido van Rossum374a9221991-04-04 10:40:29 +00003056}
3057
Guido van Rossumc2e20742006-02-27 22:32:47 +00003058/* This is gonna seem *real weird*, but if you put some other code between
Martin v. Löwis8d97e332004-06-27 15:43:12 +00003059 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
Guido van Rossumc2e20742006-02-27 22:32:47 +00003060 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
Skip Montanaro786ea6b2004-03-01 15:44:05 +00003061
Tim Peters6d6c1a32001-08-02 04:15:00 +00003062PyObject *
3063PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 PyObject **args, int argcount, PyObject **kws, int kwcount,
3065 PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure)
Tim Peters5ca576e2001-06-18 22:08:13 +00003066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 register PyFrameObject *f;
3068 register PyObject *retval = NULL;
3069 register PyObject **fastlocals, **freevars;
3070 PyThreadState *tstate = PyThreadState_GET();
3071 PyObject *x, *u;
3072 int total_args = co->co_argcount + co->co_kwonlyargcount;
Tim Peters5ca576e2001-06-18 22:08:13 +00003073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 if (globals == NULL) {
3075 PyErr_SetString(PyExc_SystemError,
3076 "PyEval_EvalCodeEx: NULL globals");
3077 return NULL;
3078 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 assert(tstate != NULL);
3081 assert(globals != NULL);
3082 f = PyFrame_New(tstate, co, globals, locals);
3083 if (f == NULL)
3084 return NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 fastlocals = f->f_localsplus;
3087 freevars = f->f_localsplus + co->co_nlocals;
Tim Peters5ca576e2001-06-18 22:08:13 +00003088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 if (total_args || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
3090 int i;
3091 int n = argcount;
3092 PyObject *kwdict = NULL;
3093 if (co->co_flags & CO_VARKEYWORDS) {
3094 kwdict = PyDict_New();
3095 if (kwdict == NULL)
3096 goto fail;
3097 i = total_args;
3098 if (co->co_flags & CO_VARARGS)
3099 i++;
3100 SETLOCAL(i, kwdict);
3101 }
3102 if (argcount > co->co_argcount) {
3103 if (!(co->co_flags & CO_VARARGS)) {
3104 PyErr_Format(PyExc_TypeError,
3105 "%U() takes %s %d "
Benjamin Peterson88968ad2010-06-25 19:30:21 +00003106 "positional argument%s (%d given)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 co->co_name,
3108 defcount ? "at most" : "exactly",
Benjamin Peterson88968ad2010-06-25 19:30:21 +00003109 co->co_argcount,
3110 co->co_argcount == 1 ? "" : "s",
Benjamin Petersonaa7fbd92010-09-25 03:25:42 +00003111 argcount + kwcount);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 goto fail;
3113 }
3114 n = co->co_argcount;
3115 }
3116 for (i = 0; i < n; i++) {
3117 x = args[i];
3118 Py_INCREF(x);
3119 SETLOCAL(i, x);
3120 }
3121 if (co->co_flags & CO_VARARGS) {
3122 u = PyTuple_New(argcount - n);
3123 if (u == NULL)
3124 goto fail;
3125 SETLOCAL(total_args, u);
3126 for (i = n; i < argcount; i++) {
3127 x = args[i];
3128 Py_INCREF(x);
3129 PyTuple_SET_ITEM(u, i-n, x);
3130 }
3131 }
3132 for (i = 0; i < kwcount; i++) {
3133 PyObject **co_varnames;
3134 PyObject *keyword = kws[2*i];
3135 PyObject *value = kws[2*i + 1];
3136 int j;
3137 if (keyword == NULL || !PyUnicode_Check(keyword)) {
3138 PyErr_Format(PyExc_TypeError,
3139 "%U() keywords must be strings",
3140 co->co_name);
3141 goto fail;
3142 }
3143 /* Speed hack: do raw pointer compares. As names are
3144 normally interned this should almost always hit. */
3145 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
3146 for (j = 0; j < total_args; j++) {
3147 PyObject *nm = co_varnames[j];
3148 if (nm == keyword)
3149 goto kw_found;
3150 }
3151 /* Slow fallback, just in case */
3152 for (j = 0; j < total_args; j++) {
3153 PyObject *nm = co_varnames[j];
3154 int cmp = PyObject_RichCompareBool(
3155 keyword, nm, Py_EQ);
3156 if (cmp > 0)
3157 goto kw_found;
3158 else if (cmp < 0)
3159 goto fail;
3160 }
3161 if (j >= total_args && kwdict == NULL) {
3162 PyErr_Format(PyExc_TypeError,
3163 "%U() got an unexpected "
3164 "keyword argument '%S'",
3165 co->co_name,
3166 keyword);
3167 goto fail;
3168 }
3169 PyDict_SetItem(kwdict, keyword, value);
3170 continue;
3171 kw_found:
3172 if (GETLOCAL(j) != NULL) {
3173 PyErr_Format(PyExc_TypeError,
3174 "%U() got multiple "
3175 "values for keyword "
3176 "argument '%S'",
3177 co->co_name,
3178 keyword);
3179 goto fail;
3180 }
3181 Py_INCREF(value);
3182 SETLOCAL(j, value);
3183 }
3184 if (co->co_kwonlyargcount > 0) {
3185 for (i = co->co_argcount; i < total_args; i++) {
3186 PyObject *name;
3187 if (GETLOCAL(i) != NULL)
3188 continue;
3189 name = PyTuple_GET_ITEM(co->co_varnames, i);
3190 if (kwdefs != NULL) {
3191 PyObject *def = PyDict_GetItem(kwdefs, name);
3192 if (def) {
3193 Py_INCREF(def);
3194 SETLOCAL(i, def);
3195 continue;
3196 }
3197 }
3198 PyErr_Format(PyExc_TypeError,
3199 "%U() needs keyword-only argument %S",
3200 co->co_name, name);
3201 goto fail;
3202 }
3203 }
3204 if (argcount < co->co_argcount) {
3205 int m = co->co_argcount - defcount;
3206 for (i = argcount; i < m; i++) {
3207 if (GETLOCAL(i) == NULL) {
3208 int j, given = 0;
3209 for (j = 0; j < co->co_argcount; j++)
3210 if (GETLOCAL(j))
3211 given++;
3212 PyErr_Format(PyExc_TypeError,
3213 "%U() takes %s %d "
3214 "argument%s "
3215 "(%d given)",
3216 co->co_name,
3217 ((co->co_flags & CO_VARARGS) ||
3218 defcount) ? "at least"
3219 : "exactly",
3220 m, m == 1 ? "" : "s", given);
3221 goto fail;
3222 }
3223 }
3224 if (n > m)
3225 i = n - m;
3226 else
3227 i = 0;
3228 for (; i < defcount; i++) {
3229 if (GETLOCAL(m+i) == NULL) {
3230 PyObject *def = defs[i];
3231 Py_INCREF(def);
3232 SETLOCAL(m+i, def);
3233 }
3234 }
3235 }
3236 }
3237 else if (argcount > 0 || kwcount > 0) {
3238 PyErr_Format(PyExc_TypeError,
3239 "%U() takes no arguments (%d given)",
3240 co->co_name,
3241 argcount + kwcount);
3242 goto fail;
3243 }
3244 /* Allocate and initialize storage for cell vars, and copy free
3245 vars into frame. This isn't too efficient right now. */
3246 if (PyTuple_GET_SIZE(co->co_cellvars)) {
3247 int i, j, nargs, found;
3248 Py_UNICODE *cellname, *argname;
3249 PyObject *c;
Tim Peters5ca576e2001-06-18 22:08:13 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 nargs = total_args;
3252 if (co->co_flags & CO_VARARGS)
3253 nargs++;
3254 if (co->co_flags & CO_VARKEYWORDS)
3255 nargs++;
Tim Peters5ca576e2001-06-18 22:08:13 +00003256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 /* Initialize each cell var, taking into account
3258 cell vars that are initialized from arguments.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 Should arrange for the compiler to put cellvars
3261 that are arguments at the beginning of the cellvars
3262 list so that we can march over it more efficiently?
3263 */
3264 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
3265 cellname = PyUnicode_AS_UNICODE(
3266 PyTuple_GET_ITEM(co->co_cellvars, i));
3267 found = 0;
3268 for (j = 0; j < nargs; j++) {
3269 argname = PyUnicode_AS_UNICODE(
3270 PyTuple_GET_ITEM(co->co_varnames, j));
3271 if (Py_UNICODE_strcmp(cellname, argname) == 0) {
3272 c = PyCell_New(GETLOCAL(j));
3273 if (c == NULL)
3274 goto fail;
3275 GETLOCAL(co->co_nlocals + i) = c;
3276 found = 1;
3277 break;
3278 }
3279 }
3280 if (found == 0) {
3281 c = PyCell_New(NULL);
3282 if (c == NULL)
3283 goto fail;
3284 SETLOCAL(co->co_nlocals + i, c);
3285 }
3286 }
3287 }
3288 if (PyTuple_GET_SIZE(co->co_freevars)) {
3289 int i;
3290 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
3291 PyObject *o = PyTuple_GET_ITEM(closure, i);
3292 Py_INCREF(o);
3293 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
3294 }
3295 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 if (co->co_flags & CO_GENERATOR) {
3298 /* Don't need to keep the reference to f_back, it will be set
3299 * when the generator is resumed. */
3300 Py_XDECREF(f->f_back);
3301 f->f_back = NULL;
Neil Schemenauer2b13ce82001-06-21 02:41:10 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 PCALL(PCALL_GENERATOR);
Jeremy Hylton985eba52003-02-05 23:13:00 +00003304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 /* Create a new generator that owns the ready to run frame
3306 * and return that as the value. */
3307 return PyGen_New(f);
3308 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 retval = PyEval_EvalFrameEx(f,0);
Tim Peters5ca576e2001-06-18 22:08:13 +00003311
Thomas Woutersce272b62007-09-19 21:19:28 +00003312fail: /* Jump here from prelude on failure */
Tim Peters5ca576e2001-06-18 22:08:13 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 /* decref'ing the frame can cause __del__ methods to get invoked,
3315 which can call back into Python. While we're done with the
3316 current Python frame (f), the associated C stack is still in use,
3317 so recursion_depth must be boosted for the duration.
3318 */
3319 assert(tstate != NULL);
3320 ++tstate->recursion_depth;
3321 Py_DECREF(f);
3322 --tstate->recursion_depth;
3323 return retval;
Tim Peters5ca576e2001-06-18 22:08:13 +00003324}
3325
3326
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003327static PyObject *
3328special_lookup(PyObject *o, char *meth, PyObject **cache)
3329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 PyObject *res;
3331 res = _PyObject_LookupSpecial(o, meth, cache);
3332 if (res == NULL && !PyErr_Occurred()) {
3333 PyErr_SetObject(PyExc_AttributeError, *cache);
3334 return NULL;
3335 }
3336 return res;
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003337}
3338
3339
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003340/* Logic for the raise statement (too complicated for inlining).
3341 This *consumes* a reference count to each of its arguments. */
Raymond Hettinger7c958652004-04-06 10:11:10 +00003342static enum why_code
Collin Winter828f04a2007-08-31 00:04:24 +00003343do_raise(PyObject *exc, PyObject *cause)
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 PyObject *type = NULL, *value = NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (exc == NULL) {
3348 /* Reraise */
3349 PyThreadState *tstate = PyThreadState_GET();
3350 PyObject *tb;
3351 type = tstate->exc_type;
3352 value = tstate->exc_value;
3353 tb = tstate->exc_traceback;
3354 if (type == Py_None) {
3355 PyErr_SetString(PyExc_RuntimeError,
3356 "No active exception to reraise");
3357 return WHY_EXCEPTION;
3358 }
3359 Py_XINCREF(type);
3360 Py_XINCREF(value);
3361 Py_XINCREF(tb);
3362 PyErr_Restore(type, value, tb);
3363 return WHY_RERAISE;
3364 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 /* We support the following forms of raise:
3367 raise
Collin Winter828f04a2007-08-31 00:04:24 +00003368 raise <instance>
3369 raise <type> */
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 if (PyExceptionClass_Check(exc)) {
3372 type = exc;
3373 value = PyObject_CallObject(exc, NULL);
3374 if (value == NULL)
3375 goto raise_error;
3376 }
3377 else if (PyExceptionInstance_Check(exc)) {
3378 value = exc;
3379 type = PyExceptionInstance_Class(exc);
3380 Py_INCREF(type);
3381 }
3382 else {
3383 /* Not something you can raise. You get an exception
3384 anyway, just not what you specified :-) */
3385 Py_DECREF(exc);
3386 PyErr_SetString(PyExc_TypeError,
3387 "exceptions must derive from BaseException");
3388 goto raise_error;
3389 }
Collin Winter828f04a2007-08-31 00:04:24 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 if (cause) {
3392 PyObject *fixed_cause;
3393 if (PyExceptionClass_Check(cause)) {
3394 fixed_cause = PyObject_CallObject(cause, NULL);
3395 if (fixed_cause == NULL)
3396 goto raise_error;
3397 Py_DECREF(cause);
3398 }
3399 else if (PyExceptionInstance_Check(cause)) {
3400 fixed_cause = cause;
3401 }
3402 else {
3403 PyErr_SetString(PyExc_TypeError,
3404 "exception causes must derive from "
3405 "BaseException");
3406 goto raise_error;
3407 }
3408 PyException_SetCause(value, fixed_cause);
3409 }
Collin Winter828f04a2007-08-31 00:04:24 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 PyErr_SetObject(type, value);
3412 /* PyErr_SetObject incref's its arguments */
3413 Py_XDECREF(value);
3414 Py_XDECREF(type);
3415 return WHY_EXCEPTION;
Collin Winter828f04a2007-08-31 00:04:24 +00003416
3417raise_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 Py_XDECREF(value);
3419 Py_XDECREF(type);
3420 Py_XDECREF(cause);
3421 return WHY_EXCEPTION;
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003422}
3423
Tim Petersd6d010b2001-06-21 02:49:55 +00003424/* Iterate v argcnt times and store the results on the stack (via decreasing
Guido van Rossum0368b722007-05-11 16:50:42 +00003425 sp). Return 1 for success, 0 if error.
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00003426
Guido van Rossum0368b722007-05-11 16:50:42 +00003427 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
3428 with a variable target.
3429*/
Tim Petersd6d010b2001-06-21 02:49:55 +00003430
Barry Warsawe42b18f1997-08-25 22:13:04 +00003431static int
Guido van Rossum0368b722007-05-11 16:50:42 +00003432unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp)
Barry Warsawe42b18f1997-08-25 22:13:04 +00003433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 int i = 0, j = 0;
3435 Py_ssize_t ll = 0;
3436 PyObject *it; /* iter(v) */
3437 PyObject *w;
3438 PyObject *l = NULL; /* variable list */
Guido van Rossumac7be682001-01-17 15:42:30 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 assert(v != NULL);
Tim Petersd6d010b2001-06-21 02:49:55 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 it = PyObject_GetIter(v);
3443 if (it == NULL)
3444 goto Error;
Tim Petersd6d010b2001-06-21 02:49:55 +00003445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 for (; i < argcnt; i++) {
3447 w = PyIter_Next(it);
3448 if (w == NULL) {
3449 /* Iterator done, via error or exhaustion. */
3450 if (!PyErr_Occurred()) {
3451 PyErr_Format(PyExc_ValueError,
3452 "need more than %d value%s to unpack",
3453 i, i == 1 ? "" : "s");
3454 }
3455 goto Error;
3456 }
3457 *--sp = w;
3458 }
Tim Petersd6d010b2001-06-21 02:49:55 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 if (argcntafter == -1) {
3461 /* We better have exhausted the iterator now. */
3462 w = PyIter_Next(it);
3463 if (w == NULL) {
3464 if (PyErr_Occurred())
3465 goto Error;
3466 Py_DECREF(it);
3467 return 1;
3468 }
3469 Py_DECREF(w);
Georg Brandl0310a832010-07-10 10:32:36 +00003470 PyErr_Format(PyExc_ValueError, "too many values to unpack "
3471 "(expected %d)", argcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 goto Error;
3473 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 l = PySequence_List(it);
3476 if (l == NULL)
3477 goto Error;
3478 *--sp = l;
3479 i++;
Guido van Rossum0368b722007-05-11 16:50:42 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 ll = PyList_GET_SIZE(l);
3482 if (ll < argcntafter) {
3483 PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack",
3484 argcnt + ll);
3485 goto Error;
3486 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 /* Pop the "after-variable" args off the list. */
3489 for (j = argcntafter; j > 0; j--, i++) {
3490 *--sp = PyList_GET_ITEM(l, ll - j);
3491 }
3492 /* Resize the list. */
3493 Py_SIZE(l) = ll - argcntafter;
3494 Py_DECREF(it);
3495 return 1;
Guido van Rossum0368b722007-05-11 16:50:42 +00003496
Tim Petersd6d010b2001-06-21 02:49:55 +00003497Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 for (; i > 0; i--, sp++)
3499 Py_DECREF(*sp);
3500 Py_XDECREF(it);
3501 return 0;
Barry Warsawe42b18f1997-08-25 22:13:04 +00003502}
3503
3504
Guido van Rossum96a42c81992-01-12 02:29:51 +00003505#ifdef LLTRACE
Guido van Rossum3f5da241990-12-20 15:06:42 +00003506static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003507prtrace(PyObject *v, char *str)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 printf("%s ", str);
3510 if (PyObject_Print(v, stdout, 0) != 0)
3511 PyErr_Clear(); /* Don't know what else to do */
3512 printf("\n");
3513 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003514}
Guido van Rossum3f5da241990-12-20 15:06:42 +00003515#endif
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003516
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003517static void
Fred Drake5755ce62001-06-27 19:19:46 +00003518call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 PyObject *type, *value, *traceback, *arg;
3521 int err;
3522 PyErr_Fetch(&type, &value, &traceback);
3523 if (value == NULL) {
3524 value = Py_None;
3525 Py_INCREF(value);
3526 }
3527 arg = PyTuple_Pack(3, type, value, traceback);
3528 if (arg == NULL) {
3529 PyErr_Restore(type, value, traceback);
3530 return;
3531 }
3532 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
3533 Py_DECREF(arg);
3534 if (err == 0)
3535 PyErr_Restore(type, value, traceback);
3536 else {
3537 Py_XDECREF(type);
3538 Py_XDECREF(value);
3539 Py_XDECREF(traceback);
3540 }
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003541}
3542
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +00003543static int
Fred Drake4ec5d562001-10-04 19:26:43 +00003544call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 int what, PyObject *arg)
Fred Drake4ec5d562001-10-04 19:26:43 +00003546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 PyObject *type, *value, *traceback;
3548 int err;
3549 PyErr_Fetch(&type, &value, &traceback);
3550 err = call_trace(func, obj, frame, what, arg);
3551 if (err == 0)
3552 {
3553 PyErr_Restore(type, value, traceback);
3554 return 0;
3555 }
3556 else {
3557 Py_XDECREF(type);
3558 Py_XDECREF(value);
3559 Py_XDECREF(traceback);
3560 return -1;
3561 }
Fred Drake4ec5d562001-10-04 19:26:43 +00003562}
3563
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003564static int
Fred Drake5755ce62001-06-27 19:19:46 +00003565call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 int what, PyObject *arg)
Guido van Rossum96a42c81992-01-12 02:29:51 +00003567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 register PyThreadState *tstate = frame->f_tstate;
3569 int result;
3570 if (tstate->tracing)
3571 return 0;
3572 tstate->tracing++;
3573 tstate->use_tracing = 0;
3574 result = func(obj, frame, what, arg);
3575 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3576 || (tstate->c_profilefunc != NULL));
3577 tstate->tracing--;
3578 return result;
Guido van Rossum96a42c81992-01-12 02:29:51 +00003579}
3580
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003581PyObject *
3582_PyEval_CallTracing(PyObject *func, PyObject *args)
3583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 PyFrameObject *frame = PyEval_GetFrame();
3585 PyThreadState *tstate = frame->f_tstate;
3586 int save_tracing = tstate->tracing;
3587 int save_use_tracing = tstate->use_tracing;
3588 PyObject *result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 tstate->tracing = 0;
3591 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3592 || (tstate->c_profilefunc != NULL));
3593 result = PyObject_Call(func, args, NULL);
3594 tstate->tracing = save_tracing;
3595 tstate->use_tracing = save_use_tracing;
3596 return result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003597}
3598
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003599/* See Objects/lnotab_notes.txt for a description of how tracing works. */
Michael W. Hudson006c7522002-11-08 13:08:46 +00003600static int
Tim Peters8a5c3c72004-04-05 19:36:21 +00003601maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 PyFrameObject *frame, int *instr_lb, int *instr_ub,
3603 int *instr_prev)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 int result = 0;
3606 int line = frame->f_lineno;
Michael W. Hudson006c7522002-11-08 13:08:46 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* If the last instruction executed isn't in the current
3609 instruction window, reset the window.
3610 */
3611 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
3612 PyAddrPair bounds;
3613 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
3614 &bounds);
3615 *instr_lb = bounds.ap_lower;
3616 *instr_ub = bounds.ap_upper;
3617 }
3618 /* If the last instruction falls at the start of a line or if
3619 it represents a jump backwards, update the frame's line
3620 number and call the trace function. */
3621 if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
3622 frame->f_lineno = line;
3623 result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
3624 }
3625 *instr_prev = frame->f_lasti;
3626 return result;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003627}
3628
Fred Drake5755ce62001-06-27 19:19:46 +00003629void
3630PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
Fred Draked0838392001-06-16 21:02:31 +00003631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 PyThreadState *tstate = PyThreadState_GET();
3633 PyObject *temp = tstate->c_profileobj;
3634 Py_XINCREF(arg);
3635 tstate->c_profilefunc = NULL;
3636 tstate->c_profileobj = NULL;
3637 /* Must make sure that tracing is not ignored if 'temp' is freed */
3638 tstate->use_tracing = tstate->c_tracefunc != NULL;
3639 Py_XDECREF(temp);
3640 tstate->c_profilefunc = func;
3641 tstate->c_profileobj = arg;
3642 /* Flag that tracing or profiling is turned on */
3643 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
Fred Drake5755ce62001-06-27 19:19:46 +00003644}
3645
3646void
3647PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
3648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 PyThreadState *tstate = PyThreadState_GET();
3650 PyObject *temp = tstate->c_traceobj;
3651 _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
3652 Py_XINCREF(arg);
3653 tstate->c_tracefunc = NULL;
3654 tstate->c_traceobj = NULL;
3655 /* Must make sure that profiling is not ignored if 'temp' is freed */
3656 tstate->use_tracing = tstate->c_profilefunc != NULL;
3657 Py_XDECREF(temp);
3658 tstate->c_tracefunc = func;
3659 tstate->c_traceobj = arg;
3660 /* Flag that tracing or profiling is turned on */
3661 tstate->use_tracing = ((func != NULL)
3662 || (tstate->c_profilefunc != NULL));
Fred Draked0838392001-06-16 21:02:31 +00003663}
3664
Guido van Rossumb209a111997-04-29 18:18:01 +00003665PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003666PyEval_GetBuiltins(void)
Guido van Rossum6135a871995-01-09 17:53:26 +00003667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 PyFrameObject *current_frame = PyEval_GetFrame();
3669 if (current_frame == NULL)
3670 return PyThreadState_GET()->interp->builtins;
3671 else
3672 return current_frame->f_builtins;
Guido van Rossum6135a871995-01-09 17:53:26 +00003673}
3674
Guido van Rossumb209a111997-04-29 18:18:01 +00003675PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003676PyEval_GetLocals(void)
Guido van Rossum5b722181993-03-30 17:46:03 +00003677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 PyFrameObject *current_frame = PyEval_GetFrame();
3679 if (current_frame == NULL)
3680 return NULL;
3681 PyFrame_FastToLocals(current_frame);
3682 return current_frame->f_locals;
Guido van Rossum5b722181993-03-30 17:46:03 +00003683}
3684
Guido van Rossumb209a111997-04-29 18:18:01 +00003685PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003686PyEval_GetGlobals(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 PyFrameObject *current_frame = PyEval_GetFrame();
3689 if (current_frame == NULL)
3690 return NULL;
3691 else
3692 return current_frame->f_globals;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003693}
3694
Guido van Rossum6297a7a2003-02-19 15:53:17 +00003695PyFrameObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003696PyEval_GetFrame(void)
Guido van Rossume59214e1994-08-30 08:01:59 +00003697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 PyThreadState *tstate = PyThreadState_GET();
3699 return _PyThreadState_GetFrame(tstate);
Guido van Rossume59214e1994-08-30 08:01:59 +00003700}
3701
Guido van Rossum6135a871995-01-09 17:53:26 +00003702int
Tim Peters5ba58662001-07-16 02:29:45 +00003703PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Jeremy Hylton061d1062001-03-22 02:32:48 +00003704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 PyFrameObject *current_frame = PyEval_GetFrame();
3706 int result = cf->cf_flags != 0;
Tim Peters5ba58662001-07-16 02:29:45 +00003707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 if (current_frame != NULL) {
3709 const int codeflags = current_frame->f_code->co_flags;
3710 const int compilerflags = codeflags & PyCF_MASK;
3711 if (compilerflags) {
3712 result = 1;
3713 cf->cf_flags |= compilerflags;
3714 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003715#if 0 /* future keyword */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 if (codeflags & CO_GENERATOR_ALLOWED) {
3717 result = 1;
3718 cf->cf_flags |= CO_GENERATOR_ALLOWED;
3719 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003720#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 }
3722 return result;
Jeremy Hylton061d1062001-03-22 02:32:48 +00003723}
3724
Guido van Rossum3f5da241990-12-20 15:06:42 +00003725
Guido van Rossum681d79a1995-07-18 14:51:37 +00003726/* External interface to call any callable object.
Antoine Pitrou8689a102010-04-01 16:53:15 +00003727 The arg must be a tuple or NULL. The kw must be a dict or NULL. */
Guido van Rossume59214e1994-08-30 08:01:59 +00003728
Guido van Rossumb209a111997-04-29 18:18:01 +00003729PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003730PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 PyObject *result;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 if (arg == NULL) {
3735 arg = PyTuple_New(0);
3736 if (arg == NULL)
3737 return NULL;
3738 }
3739 else if (!PyTuple_Check(arg)) {
3740 PyErr_SetString(PyExc_TypeError,
3741 "argument list must be a tuple");
3742 return NULL;
3743 }
3744 else
3745 Py_INCREF(arg);
Guido van Rossum681d79a1995-07-18 14:51:37 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 if (kw != NULL && !PyDict_Check(kw)) {
3748 PyErr_SetString(PyExc_TypeError,
3749 "keyword list must be a dictionary");
3750 Py_DECREF(arg);
3751 return NULL;
3752 }
Guido van Rossume3e61c11995-08-04 04:14:47 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 result = PyObject_Call(func, arg, kw);
3755 Py_DECREF(arg);
3756 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00003757}
3758
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003759const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003760PyEval_GetFuncName(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 if (PyMethod_Check(func))
3763 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
3764 else if (PyFunction_Check(func))
3765 return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name);
3766 else if (PyCFunction_Check(func))
3767 return ((PyCFunctionObject*)func)->m_ml->ml_name;
3768 else
3769 return func->ob_type->tp_name;
Jeremy Hylton512a2372001-04-11 13:52:29 +00003770}
3771
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003772const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773PyEval_GetFuncDesc(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 if (PyMethod_Check(func))
3776 return "()";
3777 else if (PyFunction_Check(func))
3778 return "()";
3779 else if (PyCFunction_Check(func))
3780 return "()";
3781 else
3782 return " object";
Jeremy Hylton512a2372001-04-11 13:52:29 +00003783}
3784
Neal Norwitzaddfe0c2002-11-10 14:33:26 +00003785static void
Jeremy Hylton192690e2002-08-16 18:36:11 +00003786err_args(PyObject *func, int flags, int nargs)
3787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 if (flags & METH_NOARGS)
3789 PyErr_Format(PyExc_TypeError,
3790 "%.200s() takes no arguments (%d given)",
3791 ((PyCFunctionObject *)func)->m_ml->ml_name,
3792 nargs);
3793 else
3794 PyErr_Format(PyExc_TypeError,
3795 "%.200s() takes exactly one argument (%d given)",
3796 ((PyCFunctionObject *)func)->m_ml->ml_name,
3797 nargs);
Jeremy Hylton192690e2002-08-16 18:36:11 +00003798}
3799
Armin Rigo1c2d7e52005-09-20 18:34:01 +00003800#define C_TRACE(x, call) \
Nicholas Bastind858a772004-06-25 23:31:06 +00003801if (tstate->use_tracing && tstate->c_profilefunc) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 if (call_trace(tstate->c_profilefunc, \
3803 tstate->c_profileobj, \
3804 tstate->frame, PyTrace_C_CALL, \
3805 func)) { \
3806 x = NULL; \
3807 } \
3808 else { \
3809 x = call; \
3810 if (tstate->c_profilefunc != NULL) { \
3811 if (x == NULL) { \
3812 call_trace_protected(tstate->c_profilefunc, \
3813 tstate->c_profileobj, \
3814 tstate->frame, PyTrace_C_EXCEPTION, \
3815 func); \
3816 /* XXX should pass (type, value, tb) */ \
3817 } else { \
3818 if (call_trace(tstate->c_profilefunc, \
3819 tstate->c_profileobj, \
3820 tstate->frame, PyTrace_C_RETURN, \
3821 func)) { \
3822 Py_DECREF(x); \
3823 x = NULL; \
3824 } \
3825 } \
3826 } \
3827 } \
Nicholas Bastind858a772004-06-25 23:31:06 +00003828} else { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 x = call; \
3830 }
Nicholas Bastinc69ebe82004-03-24 21:57:10 +00003831
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003832static PyObject *
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003833call_function(PyObject ***pp_stack, int oparg
3834#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 , uint64* pintr0, uint64* pintr1
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003836#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 )
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 int na = oparg & 0xff;
3840 int nk = (oparg>>8) & 0xff;
3841 int n = na + 2 * nk;
3842 PyObject **pfunc = (*pp_stack) - n - 1;
3843 PyObject *func = *pfunc;
3844 PyObject *x, *w;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 /* Always dispatch PyCFunction first, because these are
3847 presumed to be the most frequent callable object.
3848 */
3849 if (PyCFunction_Check(func) && nk == 0) {
3850 int flags = PyCFunction_GET_FLAGS(func);
3851 PyThreadState *tstate = PyThreadState_GET();
Raymond Hettingera7f56bc2004-06-26 04:34:33 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 PCALL(PCALL_CFUNCTION);
3854 if (flags & (METH_NOARGS | METH_O)) {
3855 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
3856 PyObject *self = PyCFunction_GET_SELF(func);
3857 if (flags & METH_NOARGS && na == 0) {
3858 C_TRACE(x, (*meth)(self,NULL));
3859 }
3860 else if (flags & METH_O && na == 1) {
3861 PyObject *arg = EXT_POP(*pp_stack);
3862 C_TRACE(x, (*meth)(self,arg));
3863 Py_DECREF(arg);
3864 }
3865 else {
3866 err_args(func, flags, na);
3867 x = NULL;
3868 }
3869 }
3870 else {
3871 PyObject *callargs;
3872 callargs = load_args(pp_stack, na);
3873 READ_TIMESTAMP(*pintr0);
3874 C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
3875 READ_TIMESTAMP(*pintr1);
3876 Py_XDECREF(callargs);
3877 }
3878 } else {
3879 if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
3880 /* optimize access to bound methods */
3881 PyObject *self = PyMethod_GET_SELF(func);
3882 PCALL(PCALL_METHOD);
3883 PCALL(PCALL_BOUND_METHOD);
3884 Py_INCREF(self);
3885 func = PyMethod_GET_FUNCTION(func);
3886 Py_INCREF(func);
3887 Py_DECREF(*pfunc);
3888 *pfunc = self;
3889 na++;
3890 n++;
3891 } else
3892 Py_INCREF(func);
3893 READ_TIMESTAMP(*pintr0);
3894 if (PyFunction_Check(func))
3895 x = fast_function(func, pp_stack, n, na, nk);
3896 else
3897 x = do_call(func, pp_stack, na, nk);
3898 READ_TIMESTAMP(*pintr1);
3899 Py_DECREF(func);
3900 }
Tim Peters8a5c3c72004-04-05 19:36:21 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 /* Clear the stack of the function object. Also removes
3903 the arguments in case they weren't consumed already
3904 (fast_function() and err_args() leave them on the stack).
3905 */
3906 while ((*pp_stack) > pfunc) {
3907 w = EXT_POP(*pp_stack);
3908 Py_DECREF(w);
3909 PCALL(PCALL_POP);
3910 }
3911 return x;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003912}
3913
Jeremy Hylton192690e2002-08-16 18:36:11 +00003914/* The fast_function() function optimize calls for which no argument
Jeremy Hylton52820442001-01-03 23:52:36 +00003915 tuple is necessary; the objects are passed directly from the stack.
Jeremy Hylton985eba52003-02-05 23:13:00 +00003916 For the simplest case -- a function that takes only positional
3917 arguments and is called with only positional arguments -- it
3918 inlines the most primitive frame setup code from
3919 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
3920 done before evaluating the frame.
Jeremy Hylton52820442001-01-03 23:52:36 +00003921*/
3922
3923static PyObject *
Guido van Rossumac7be682001-01-17 15:42:30 +00003924fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
Jeremy Hylton52820442001-01-03 23:52:36 +00003925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
3927 PyObject *globals = PyFunction_GET_GLOBALS(func);
3928 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
3929 PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func);
3930 PyObject **d = NULL;
3931 int nd = 0;
Jeremy Hylton52820442001-01-03 23:52:36 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 PCALL(PCALL_FUNCTION);
3934 PCALL(PCALL_FAST_FUNCTION);
3935 if (argdefs == NULL && co->co_argcount == n &&
3936 co->co_kwonlyargcount == 0 && nk==0 &&
3937 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
3938 PyFrameObject *f;
3939 PyObject *retval = NULL;
3940 PyThreadState *tstate = PyThreadState_GET();
3941 PyObject **fastlocals, **stack;
3942 int i;
Jeremy Hylton985eba52003-02-05 23:13:00 +00003943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 PCALL(PCALL_FASTER_FUNCTION);
3945 assert(globals != NULL);
3946 /* XXX Perhaps we should create a specialized
3947 PyFrame_New() that doesn't take locals, but does
3948 take builtins without sanity checking them.
3949 */
3950 assert(tstate != NULL);
3951 f = PyFrame_New(tstate, co, globals, NULL);
3952 if (f == NULL)
3953 return NULL;
Jeremy Hylton985eba52003-02-05 23:13:00 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 fastlocals = f->f_localsplus;
3956 stack = (*pp_stack) - n;
Jeremy Hylton985eba52003-02-05 23:13:00 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 for (i = 0; i < n; i++) {
3959 Py_INCREF(*stack);
3960 fastlocals[i] = *stack++;
3961 }
3962 retval = PyEval_EvalFrameEx(f,0);
3963 ++tstate->recursion_depth;
3964 Py_DECREF(f);
3965 --tstate->recursion_depth;
3966 return retval;
3967 }
3968 if (argdefs != NULL) {
3969 d = &PyTuple_GET_ITEM(argdefs, 0);
3970 nd = Py_SIZE(argdefs);
3971 }
3972 return PyEval_EvalCodeEx(co, globals,
3973 (PyObject *)NULL, (*pp_stack)-n, na,
3974 (*pp_stack)-2*nk, nk, d, nd, kwdefs,
3975 PyFunction_GET_CLOSURE(func));
Jeremy Hylton52820442001-01-03 23:52:36 +00003976}
3977
3978static PyObject *
Ka-Ping Yee20579702001-01-15 22:14:16 +00003979update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
3980 PyObject *func)
Jeremy Hylton52820442001-01-03 23:52:36 +00003981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 PyObject *kwdict = NULL;
3983 if (orig_kwdict == NULL)
3984 kwdict = PyDict_New();
3985 else {
3986 kwdict = PyDict_Copy(orig_kwdict);
3987 Py_DECREF(orig_kwdict);
3988 }
3989 if (kwdict == NULL)
3990 return NULL;
3991 while (--nk >= 0) {
3992 int err;
3993 PyObject *value = EXT_POP(*pp_stack);
3994 PyObject *key = EXT_POP(*pp_stack);
3995 if (PyDict_GetItem(kwdict, key) != NULL) {
3996 PyErr_Format(PyExc_TypeError,
3997 "%.200s%s got multiple values "
3998 "for keyword argument '%U'",
3999 PyEval_GetFuncName(func),
4000 PyEval_GetFuncDesc(func),
4001 key);
4002 Py_DECREF(key);
4003 Py_DECREF(value);
4004 Py_DECREF(kwdict);
4005 return NULL;
4006 }
4007 err = PyDict_SetItem(kwdict, key, value);
4008 Py_DECREF(key);
4009 Py_DECREF(value);
4010 if (err) {
4011 Py_DECREF(kwdict);
4012 return NULL;
4013 }
4014 }
4015 return kwdict;
Jeremy Hylton52820442001-01-03 23:52:36 +00004016}
4017
4018static PyObject *
4019update_star_args(int nstack, int nstar, PyObject *stararg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 PyObject ***pp_stack)
Jeremy Hylton52820442001-01-03 23:52:36 +00004021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 PyObject *callargs, *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 callargs = PyTuple_New(nstack + nstar);
4025 if (callargs == NULL) {
4026 return NULL;
4027 }
4028 if (nstar) {
4029 int i;
4030 for (i = 0; i < nstar; i++) {
4031 PyObject *a = PyTuple_GET_ITEM(stararg, i);
4032 Py_INCREF(a);
4033 PyTuple_SET_ITEM(callargs, nstack + i, a);
4034 }
4035 }
4036 while (--nstack >= 0) {
4037 w = EXT_POP(*pp_stack);
4038 PyTuple_SET_ITEM(callargs, nstack, w);
4039 }
4040 return callargs;
Jeremy Hylton52820442001-01-03 23:52:36 +00004041}
4042
4043static PyObject *
4044load_args(PyObject ***pp_stack, int na)
4045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 PyObject *args = PyTuple_New(na);
4047 PyObject *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 if (args == NULL)
4050 return NULL;
4051 while (--na >= 0) {
4052 w = EXT_POP(*pp_stack);
4053 PyTuple_SET_ITEM(args, na, w);
4054 }
4055 return args;
Jeremy Hylton52820442001-01-03 23:52:36 +00004056}
4057
4058static PyObject *
4059do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
4060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 PyObject *callargs = NULL;
4062 PyObject *kwdict = NULL;
4063 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 if (nk > 0) {
4066 kwdict = update_keyword_args(NULL, nk, pp_stack, func);
4067 if (kwdict == NULL)
4068 goto call_fail;
4069 }
4070 callargs = load_args(pp_stack, na);
4071 if (callargs == NULL)
4072 goto call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004073#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 /* At this point, we have to look at the type of func to
4075 update the call stats properly. Do it here so as to avoid
4076 exposing the call stats machinery outside ceval.c
4077 */
4078 if (PyFunction_Check(func))
4079 PCALL(PCALL_FUNCTION);
4080 else if (PyMethod_Check(func))
4081 PCALL(PCALL_METHOD);
4082 else if (PyType_Check(func))
4083 PCALL(PCALL_TYPE);
4084 else if (PyCFunction_Check(func))
4085 PCALL(PCALL_CFUNCTION);
4086 else
4087 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004088#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 if (PyCFunction_Check(func)) {
4090 PyThreadState *tstate = PyThreadState_GET();
4091 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4092 }
4093 else
4094 result = PyObject_Call(func, callargs, kwdict);
Thomas Wouters7ce29ca2007-09-19 21:56:32 +00004095call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 Py_XDECREF(callargs);
4097 Py_XDECREF(kwdict);
4098 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004099}
4100
4101static PyObject *
4102ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
4103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 int nstar = 0;
4105 PyObject *callargs = NULL;
4106 PyObject *stararg = NULL;
4107 PyObject *kwdict = NULL;
4108 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 if (flags & CALL_FLAG_KW) {
4111 kwdict = EXT_POP(*pp_stack);
4112 if (!PyDict_Check(kwdict)) {
4113 PyObject *d;
4114 d = PyDict_New();
4115 if (d == NULL)
4116 goto ext_call_fail;
4117 if (PyDict_Update(d, kwdict) != 0) {
4118 Py_DECREF(d);
4119 /* PyDict_Update raises attribute
4120 * error (percolated from an attempt
4121 * to get 'keys' attribute) instead of
4122 * a type error if its second argument
4123 * is not a mapping.
4124 */
4125 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
4126 PyErr_Format(PyExc_TypeError,
4127 "%.200s%.200s argument after ** "
4128 "must be a mapping, not %.200s",
4129 PyEval_GetFuncName(func),
4130 PyEval_GetFuncDesc(func),
4131 kwdict->ob_type->tp_name);
4132 }
4133 goto ext_call_fail;
4134 }
4135 Py_DECREF(kwdict);
4136 kwdict = d;
4137 }
4138 }
4139 if (flags & CALL_FLAG_VAR) {
4140 stararg = EXT_POP(*pp_stack);
4141 if (!PyTuple_Check(stararg)) {
4142 PyObject *t = NULL;
4143 t = PySequence_Tuple(stararg);
4144 if (t == NULL) {
4145 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4146 PyErr_Format(PyExc_TypeError,
4147 "%.200s%.200s argument after * "
4148 "must be a sequence, not %200s",
4149 PyEval_GetFuncName(func),
4150 PyEval_GetFuncDesc(func),
4151 stararg->ob_type->tp_name);
4152 }
4153 goto ext_call_fail;
4154 }
4155 Py_DECREF(stararg);
4156 stararg = t;
4157 }
4158 nstar = PyTuple_GET_SIZE(stararg);
4159 }
4160 if (nk > 0) {
4161 kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
4162 if (kwdict == NULL)
4163 goto ext_call_fail;
4164 }
4165 callargs = update_star_args(na, nstar, stararg, pp_stack);
4166 if (callargs == NULL)
4167 goto ext_call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004168#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 /* At this point, we have to look at the type of func to
4170 update the call stats properly. Do it here so as to avoid
4171 exposing the call stats machinery outside ceval.c
4172 */
4173 if (PyFunction_Check(func))
4174 PCALL(PCALL_FUNCTION);
4175 else if (PyMethod_Check(func))
4176 PCALL(PCALL_METHOD);
4177 else if (PyType_Check(func))
4178 PCALL(PCALL_TYPE);
4179 else if (PyCFunction_Check(func))
4180 PCALL(PCALL_CFUNCTION);
4181 else
4182 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004183#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 if (PyCFunction_Check(func)) {
4185 PyThreadState *tstate = PyThreadState_GET();
4186 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4187 }
4188 else
4189 result = PyObject_Call(func, callargs, kwdict);
Thomas Woutersce272b62007-09-19 21:19:28 +00004190ext_call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 Py_XDECREF(callargs);
4192 Py_XDECREF(kwdict);
4193 Py_XDECREF(stararg);
4194 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004195}
4196
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004197/* Extract a slice index from a PyInt or PyLong or an object with the
4198 nb_index slot defined, and store in *pi.
4199 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
4200 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
Martin v. Löwisdde99d22006-02-17 15:57:41 +00004201 Return 0 on error, 1 on success.
Tim Peterscb479e72001-12-16 19:11:44 +00004202*/
Tim Petersb5196382001-12-16 19:44:20 +00004203/* Note: If v is NULL, return success without storing into *pi. This
4204 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
4205 called by the SLICE opcode with v and/or w equal to NULL.
Tim Peterscb479e72001-12-16 19:11:44 +00004206*/
Guido van Rossum20c6add2000-05-08 14:06:50 +00004207int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004208_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 if (v != NULL) {
4211 Py_ssize_t x;
4212 if (PyIndex_Check(v)) {
4213 x = PyNumber_AsSsize_t(v, NULL);
4214 if (x == -1 && PyErr_Occurred())
4215 return 0;
4216 }
4217 else {
4218 PyErr_SetString(PyExc_TypeError,
4219 "slice indices must be integers or "
4220 "None or have an __index__ method");
4221 return 0;
4222 }
4223 *pi = x;
4224 }
4225 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004226}
4227
Guido van Rossum486364b2007-06-30 05:01:58 +00004228#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 "BaseException is not allowed"
Brett Cannonf74225d2007-02-26 21:10:16 +00004230
Guido van Rossumb209a111997-04-29 18:18:01 +00004231static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004232cmp_outcome(int op, register PyObject *v, register PyObject *w)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 int res = 0;
4235 switch (op) {
4236 case PyCmp_IS:
4237 res = (v == w);
4238 break;
4239 case PyCmp_IS_NOT:
4240 res = (v != w);
4241 break;
4242 case PyCmp_IN:
4243 res = PySequence_Contains(w, v);
4244 if (res < 0)
4245 return NULL;
4246 break;
4247 case PyCmp_NOT_IN:
4248 res = PySequence_Contains(w, v);
4249 if (res < 0)
4250 return NULL;
4251 res = !res;
4252 break;
4253 case PyCmp_EXC_MATCH:
4254 if (PyTuple_Check(w)) {
4255 Py_ssize_t i, length;
4256 length = PyTuple_Size(w);
4257 for (i = 0; i < length; i += 1) {
4258 PyObject *exc = PyTuple_GET_ITEM(w, i);
4259 if (!PyExceptionClass_Check(exc)) {
4260 PyErr_SetString(PyExc_TypeError,
4261 CANNOT_CATCH_MSG);
4262 return NULL;
4263 }
4264 }
4265 }
4266 else {
4267 if (!PyExceptionClass_Check(w)) {
4268 PyErr_SetString(PyExc_TypeError,
4269 CANNOT_CATCH_MSG);
4270 return NULL;
4271 }
4272 }
4273 res = PyErr_GivenExceptionMatches(v, w);
4274 break;
4275 default:
4276 return PyObject_RichCompare(v, w, op);
4277 }
4278 v = res ? Py_True : Py_False;
4279 Py_INCREF(v);
4280 return v;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004281}
4282
Thomas Wouters52152252000-08-17 22:55:00 +00004283static PyObject *
4284import_from(PyObject *v, PyObject *name)
Guido van Rossume9736fc1990-11-18 17:33:06 +00004285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 PyObject *x;
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 x = PyObject_GetAttr(v, name);
4289 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
4290 PyErr_Format(PyExc_ImportError, "cannot import name %S", name);
4291 }
4292 return x;
Thomas Wouters52152252000-08-17 22:55:00 +00004293}
Guido van Rossumac7be682001-01-17 15:42:30 +00004294
Thomas Wouters52152252000-08-17 22:55:00 +00004295static int
4296import_all_from(PyObject *locals, PyObject *v)
4297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 PyObject *all = PyObject_GetAttrString(v, "__all__");
4299 PyObject *dict, *name, *value;
4300 int skip_leading_underscores = 0;
4301 int pos, err;
Thomas Wouters52152252000-08-17 22:55:00 +00004302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 if (all == NULL) {
4304 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4305 return -1; /* Unexpected error */
4306 PyErr_Clear();
4307 dict = PyObject_GetAttrString(v, "__dict__");
4308 if (dict == NULL) {
4309 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4310 return -1;
4311 PyErr_SetString(PyExc_ImportError,
4312 "from-import-* object has no __dict__ and no __all__");
4313 return -1;
4314 }
4315 all = PyMapping_Keys(dict);
4316 Py_DECREF(dict);
4317 if (all == NULL)
4318 return -1;
4319 skip_leading_underscores = 1;
4320 }
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 for (pos = 0, err = 0; ; pos++) {
4323 name = PySequence_GetItem(all, pos);
4324 if (name == NULL) {
4325 if (!PyErr_ExceptionMatches(PyExc_IndexError))
4326 err = -1;
4327 else
4328 PyErr_Clear();
4329 break;
4330 }
4331 if (skip_leading_underscores &&
4332 PyUnicode_Check(name) &&
4333 PyUnicode_AS_UNICODE(name)[0] == '_')
4334 {
4335 Py_DECREF(name);
4336 continue;
4337 }
4338 value = PyObject_GetAttr(v, name);
4339 if (value == NULL)
4340 err = -1;
4341 else if (PyDict_CheckExact(locals))
4342 err = PyDict_SetItem(locals, name, value);
4343 else
4344 err = PyObject_SetItem(locals, name, value);
4345 Py_DECREF(name);
4346 Py_XDECREF(value);
4347 if (err != 0)
4348 break;
4349 }
4350 Py_DECREF(all);
4351 return err;
Guido van Rossume9736fc1990-11-18 17:33:06 +00004352}
4353
Guido van Rossumac7be682001-01-17 15:42:30 +00004354static void
Neal Norwitzda059e32007-08-26 05:33:45 +00004355format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj)
Paul Prescode68140d2000-08-30 20:25:01 +00004356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 const char *obj_str;
Paul Prescode68140d2000-08-30 20:25:01 +00004358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 if (!obj)
4360 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 obj_str = _PyUnicode_AsString(obj);
4363 if (!obj_str)
4364 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 PyErr_Format(exc, format_str, obj_str);
Paul Prescode68140d2000-08-30 20:25:01 +00004367}
Guido van Rossum950361c1997-01-24 13:49:28 +00004368
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00004369static void
4370format_exc_unbound(PyCodeObject *co, int oparg)
4371{
4372 PyObject *name;
4373 /* Don't stomp existing exception */
4374 if (PyErr_Occurred())
4375 return;
4376 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
4377 name = PyTuple_GET_ITEM(co->co_cellvars,
4378 oparg);
4379 format_exc_check_arg(
4380 PyExc_UnboundLocalError,
4381 UNBOUNDLOCAL_ERROR_MSG,
4382 name);
4383 } else {
4384 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
4385 PyTuple_GET_SIZE(co->co_cellvars));
4386 format_exc_check_arg(PyExc_NameError,
4387 UNBOUNDFREE_ERROR_MSG, name);
4388 }
4389}
4390
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004391static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00004392unicode_concatenate(PyObject *v, PyObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 PyFrameObject *f, unsigned char *next_instr)
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 /* This function implements 'variable += expr' when both arguments
4396 are (Unicode) strings. */
4397 Py_ssize_t v_len = PyUnicode_GET_SIZE(v);
4398 Py_ssize_t w_len = PyUnicode_GET_SIZE(w);
4399 Py_ssize_t new_len = v_len + w_len;
4400 if (new_len < 0) {
4401 PyErr_SetString(PyExc_OverflowError,
4402 "strings are too large to concat");
4403 return NULL;
4404 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00004405
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004406 if (Py_REFCNT(v) == 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 /* In the common case, there are 2 references to the value
4408 * stored in 'variable' when the += is performed: one on the
4409 * value stack (in 'v') and one still stored in the
4410 * 'variable'. We try to delete the variable now to reduce
4411 * the refcnt to 1.
4412 */
4413 switch (*next_instr) {
4414 case STORE_FAST:
4415 {
4416 int oparg = PEEKARG();
4417 PyObject **fastlocals = f->f_localsplus;
4418 if (GETLOCAL(oparg) == v)
4419 SETLOCAL(oparg, NULL);
4420 break;
4421 }
4422 case STORE_DEREF:
4423 {
4424 PyObject **freevars = (f->f_localsplus +
4425 f->f_code->co_nlocals);
4426 PyObject *c = freevars[PEEKARG()];
4427 if (PyCell_GET(c) == v)
4428 PyCell_Set(c, NULL);
4429 break;
4430 }
4431 case STORE_NAME:
4432 {
4433 PyObject *names = f->f_code->co_names;
4434 PyObject *name = GETITEM(names, PEEKARG());
4435 PyObject *locals = f->f_locals;
4436 if (PyDict_CheckExact(locals) &&
4437 PyDict_GetItem(locals, name) == v) {
4438 if (PyDict_DelItem(locals, name) != 0) {
4439 PyErr_Clear();
4440 }
4441 }
4442 break;
4443 }
4444 }
4445 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004446
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004447 if (Py_REFCNT(v) == 1 && !PyUnicode_CHECK_INTERNED(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 /* Now we own the last reference to 'v', so we can resize it
4449 * in-place.
4450 */
4451 if (PyUnicode_Resize(&v, new_len) != 0) {
4452 /* XXX if PyUnicode_Resize() fails, 'v' has been
4453 * deallocated so it cannot be put back into
4454 * 'variable'. The MemoryError is raised when there
4455 * is no value in 'variable', which might (very
4456 * remotely) be a cause of incompatibilities.
4457 */
4458 return NULL;
4459 }
4460 /* copy 'w' into the newly allocated area of 'v' */
4461 memcpy(PyUnicode_AS_UNICODE(v) + v_len,
4462 PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE));
4463 return v;
4464 }
4465 else {
4466 /* When in-place resizing is not an option. */
4467 w = PyUnicode_Concat(v, w);
4468 Py_DECREF(v);
4469 return w;
4470 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004471}
4472
Guido van Rossum950361c1997-01-24 13:49:28 +00004473#ifdef DYNAMIC_EXECUTION_PROFILE
4474
Skip Montanarof118cb12001-10-15 20:51:38 +00004475static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004476getarray(long a[256])
Guido van Rossum950361c1997-01-24 13:49:28 +00004477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 int i;
4479 PyObject *l = PyList_New(256);
4480 if (l == NULL) return NULL;
4481 for (i = 0; i < 256; i++) {
4482 PyObject *x = PyLong_FromLong(a[i]);
4483 if (x == NULL) {
4484 Py_DECREF(l);
4485 return NULL;
4486 }
4487 PyList_SetItem(l, i, x);
4488 }
4489 for (i = 0; i < 256; i++)
4490 a[i] = 0;
4491 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004492}
4493
4494PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004495_Py_GetDXProfile(PyObject *self, PyObject *args)
Guido van Rossum950361c1997-01-24 13:49:28 +00004496{
4497#ifndef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 return getarray(dxp);
Guido van Rossum950361c1997-01-24 13:49:28 +00004499#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 int i;
4501 PyObject *l = PyList_New(257);
4502 if (l == NULL) return NULL;
4503 for (i = 0; i < 257; i++) {
4504 PyObject *x = getarray(dxpairs[i]);
4505 if (x == NULL) {
4506 Py_DECREF(l);
4507 return NULL;
4508 }
4509 PyList_SetItem(l, i, x);
4510 }
4511 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004512#endif
4513}
4514
4515#endif