blob: 5a5e23c55207c1388d9b6f747f81565c47903dfd [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 Rossum10dc2e81990-11-18 17:27:39 +000016#include "opcode.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +000017#include "structmember.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000018
Guido van Rossumc6004111993-11-05 10:22:19 +000019#include <ctype.h>
20
Thomas Wouters477c8d52006-05-27 19:21:47 +000021#ifndef WITH_TSC
Michael W. Hudson75eabd22005-01-18 15:56:11 +000022
23#define READ_TIMESTAMP(var)
24
25#else
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000026
27typedef unsigned long long uint64;
28
Ezio Melotti13925002011-03-16 11:05:33 +020029/* PowerPC support.
David Malcolmf1397ad2011-01-06 17:01:36 +000030 "__ppc__" appears to be the preprocessor definition to detect on OS X, whereas
31 "__powerpc__" appears to be the correct one for Linux with GCC
32*/
33#if defined(__ppc__) || defined (__powerpc__)
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);
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200443 /* _Py_Finalizing is protected by the GIL */
444 if (_Py_Finalizing && tstate != _Py_Finalizing) {
445 drop_gil(tstate);
446 PyThread_exit_thread();
447 assert(0); /* unreachable */
448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 errno = err;
450 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000451#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyThreadState_Swap(tstate);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000453}
454
455
Guido van Rossuma9672091994-09-14 13:31:22 +0000456/* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
457 signal handlers or Mac I/O completion routines) can schedule calls
458 to a function to be called synchronously.
459 The synchronous function is called with one void* argument.
460 It should return 0 for success or -1 for failure -- failure should
461 be accompanied by an exception.
462
463 If registry succeeds, the registry function returns 0; if it fails
464 (e.g. due to too many pending calls) it returns -1 (without setting
465 an exception condition).
466
467 Note that because registry may occur from within signal handlers,
468 or other asynchronous events, calling malloc() is unsafe!
469
470#ifdef WITH_THREAD
471 Any thread can schedule pending calls, but only the main thread
472 will execute them.
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000473 There is no facility to schedule calls to a particular thread, but
474 that should be easy to change, should that ever be required. In
475 that case, the static variables here should go into the python
476 threadstate.
Guido van Rossuma9672091994-09-14 13:31:22 +0000477#endif
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000478*/
Guido van Rossuma9672091994-09-14 13:31:22 +0000479
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000480#ifdef WITH_THREAD
481
482/* The WITH_THREAD implementation is thread-safe. It allows
483 scheduling to be made from any thread, and even from an executing
484 callback.
485 */
486
487#define NPENDINGCALLS 32
488static struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 int (*func)(void *);
490 void *arg;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000491} pendingcalls[NPENDINGCALLS];
492static int pendingfirst = 0;
493static int pendinglast = 0;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000494static char pendingbusy = 0;
495
496int
497Py_AddPendingCall(int (*func)(void *), void *arg)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 int i, j, result=0;
500 PyThread_type_lock lock = pending_lock;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* try a few times for the lock. Since this mechanism is used
503 * for signal handling (on the main thread), there is a (slim)
504 * chance that a signal is delivered on the same thread while we
505 * hold the lock during the Py_MakePendingCalls() function.
506 * This avoids a deadlock in that case.
507 * Note that signals can be delivered on any thread. In particular,
508 * on Windows, a SIGINT is delivered on a system-created worker
509 * thread.
510 * We also check for lock being NULL, in the unlikely case that
511 * this function is called before any bytecode evaluation takes place.
512 */
513 if (lock != NULL) {
514 for (i = 0; i<100; i++) {
515 if (PyThread_acquire_lock(lock, NOWAIT_LOCK))
516 break;
517 }
518 if (i == 100)
519 return -1;
520 }
521
522 i = pendinglast;
523 j = (i + 1) % NPENDINGCALLS;
524 if (j == pendingfirst) {
525 result = -1; /* Queue full */
526 } else {
527 pendingcalls[i].func = func;
528 pendingcalls[i].arg = arg;
529 pendinglast = j;
530 }
531 /* signal main loop */
532 SIGNAL_PENDING_CALLS();
533 if (lock != NULL)
534 PyThread_release_lock(lock);
535 return result;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000536}
537
538int
539Py_MakePendingCalls(void)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 int i;
542 int r = 0;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (!pending_lock) {
545 /* initial allocation of the lock */
546 pending_lock = PyThread_allocate_lock();
547 if (pending_lock == NULL)
548 return -1;
549 }
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 /* only service pending calls on main thread */
552 if (main_thread && PyThread_get_thread_ident() != main_thread)
553 return 0;
554 /* don't perform recursive pending calls */
555 if (pendingbusy)
556 return 0;
557 pendingbusy = 1;
558 /* perform a bounded number of calls, in case of recursion */
559 for (i=0; i<NPENDINGCALLS; i++) {
560 int j;
561 int (*func)(void *);
562 void *arg = NULL;
563
564 /* pop one item off the queue while holding the lock */
565 PyThread_acquire_lock(pending_lock, WAIT_LOCK);
566 j = pendingfirst;
567 if (j == pendinglast) {
568 func = NULL; /* Queue empty */
569 } else {
570 func = pendingcalls[j].func;
571 arg = pendingcalls[j].arg;
572 pendingfirst = (j + 1) % NPENDINGCALLS;
573 }
574 if (pendingfirst != pendinglast)
575 SIGNAL_PENDING_CALLS();
576 else
577 UNSIGNAL_PENDING_CALLS();
578 PyThread_release_lock(pending_lock);
579 /* having released the lock, perform the callback */
580 if (func == NULL)
581 break;
582 r = func(arg);
583 if (r)
584 break;
585 }
586 pendingbusy = 0;
587 return r;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000588}
589
590#else /* if ! defined WITH_THREAD */
591
592/*
593 WARNING! ASYNCHRONOUSLY EXECUTING CODE!
594 This code is used for signal handling in python that isn't built
595 with WITH_THREAD.
596 Don't use this implementation when Py_AddPendingCalls() can happen
597 on a different thread!
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598
Guido van Rossuma9672091994-09-14 13:31:22 +0000599 There are two possible race conditions:
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000600 (1) nested asynchronous calls to Py_AddPendingCall()
601 (2) AddPendingCall() calls made while pending calls are being processed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000603 (1) is very unlikely because typically signal delivery
604 is blocked during signal handling. So it should be impossible.
605 (2) is a real possibility.
Guido van Rossuma9672091994-09-14 13:31:22 +0000606 The current code is safe against (2), but not against (1).
607 The safety against (2) is derived from the fact that only one
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000608 thread is present, interrupted by signals, and that the critical
609 section is protected with the "busy" variable. On Windows, which
610 delivers SIGINT on a system thread, this does not hold and therefore
611 Windows really shouldn't use this version.
612 The two threads could theoretically wiggle around the "busy" variable.
Guido van Rossuma027efa1997-05-05 20:56:21 +0000613*/
Guido van Rossum8861b741996-07-30 16:49:37 +0000614
Guido van Rossuma9672091994-09-14 13:31:22 +0000615#define NPENDINGCALLS 32
616static struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 int (*func)(void *);
618 void *arg;
Guido van Rossuma9672091994-09-14 13:31:22 +0000619} pendingcalls[NPENDINGCALLS];
620static volatile int pendingfirst = 0;
621static volatile int pendinglast = 0;
Benjamin Peterson08ec84c2010-05-30 14:49:32 +0000622static _Py_atomic_int pendingcalls_to_do = {0};
Guido van Rossuma9672091994-09-14 13:31:22 +0000623
624int
Thomas Wouters334fb892000-07-25 12:56:38 +0000625Py_AddPendingCall(int (*func)(void *), void *arg)
Guido van Rossuma9672091994-09-14 13:31:22 +0000626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 static volatile int busy = 0;
628 int i, j;
629 /* XXX Begin critical section */
630 if (busy)
631 return -1;
632 busy = 1;
633 i = pendinglast;
634 j = (i + 1) % NPENDINGCALLS;
635 if (j == pendingfirst) {
636 busy = 0;
637 return -1; /* Queue full */
638 }
639 pendingcalls[i].func = func;
640 pendingcalls[i].arg = arg;
641 pendinglast = j;
Skip Montanarod581d772002-09-03 20:10:45 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 SIGNAL_PENDING_CALLS();
644 busy = 0;
645 /* XXX End critical section */
646 return 0;
Guido van Rossuma9672091994-09-14 13:31:22 +0000647}
648
Guido van Rossum180d7b41994-09-29 09:45:57 +0000649int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000650Py_MakePendingCalls(void)
Guido van Rossuma9672091994-09-14 13:31:22 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 static int busy = 0;
653 if (busy)
654 return 0;
655 busy = 1;
656 UNSIGNAL_PENDING_CALLS();
657 for (;;) {
658 int i;
659 int (*func)(void *);
660 void *arg;
661 i = pendingfirst;
662 if (i == pendinglast)
663 break; /* Queue empty */
664 func = pendingcalls[i].func;
665 arg = pendingcalls[i].arg;
666 pendingfirst = (i + 1) % NPENDINGCALLS;
667 if (func(arg) < 0) {
668 busy = 0;
669 SIGNAL_PENDING_CALLS(); /* We're not done yet */
670 return -1;
671 }
672 }
673 busy = 0;
674 return 0;
Guido van Rossuma9672091994-09-14 13:31:22 +0000675}
676
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000677#endif /* WITH_THREAD */
678
Guido van Rossuma9672091994-09-14 13:31:22 +0000679
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000680/* The interpreter's recursion limit */
681
Hye-Shik Changb6fa2812005-04-04 15:49:02 +0000682#ifndef Py_DEFAULT_RECURSION_LIMIT
683#define Py_DEFAULT_RECURSION_LIMIT 1000
684#endif
685static int recursion_limit = Py_DEFAULT_RECURSION_LIMIT;
686int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000687
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000688int
689Py_GetRecursionLimit(void)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 return recursion_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000692}
693
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000694void
695Py_SetRecursionLimit(int new_limit)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 recursion_limit = new_limit;
698 _Py_CheckRecursionLimit = recursion_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000699}
700
Armin Rigo2b3eb402003-10-28 12:05:48 +0000701/* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
702 if the recursion_depth reaches _Py_CheckRecursionLimit.
703 If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
704 to guarantee that _Py_CheckRecursiveCall() is regularly called.
705 Without USE_STACKCHECK, there is no need for this. */
706int
707_Py_CheckRecursiveCall(char *where)
708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyThreadState *tstate = PyThreadState_GET();
Armin Rigo2b3eb402003-10-28 12:05:48 +0000710
711#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (PyOS_CheckStack()) {
713 --tstate->recursion_depth;
714 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
715 return -1;
716 }
Armin Rigo2b3eb402003-10-28 12:05:48 +0000717#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 _Py_CheckRecursionLimit = recursion_limit;
719 if (tstate->recursion_critical)
720 /* Somebody asked that we don't check for recursion. */
721 return 0;
722 if (tstate->overflowed) {
723 if (tstate->recursion_depth > recursion_limit + 50) {
724 /* Overflowing while handling an overflow. Give up. */
725 Py_FatalError("Cannot recover from stack overflow.");
726 }
727 return 0;
728 }
729 if (tstate->recursion_depth > recursion_limit) {
730 --tstate->recursion_depth;
731 tstate->overflowed = 1;
732 PyErr_Format(PyExc_RuntimeError,
733 "maximum recursion depth exceeded%s",
734 where);
735 return -1;
736 }
737 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000738}
739
Guido van Rossum374a9221991-04-04 10:40:29 +0000740/* Status code for main loop (reason for stack unwind) */
Raymond Hettinger7c958652004-04-06 10:11:10 +0000741enum why_code {
Stefan Krahb7e10102010-06-23 18:42:39 +0000742 WHY_NOT = 0x0001, /* No error */
743 WHY_EXCEPTION = 0x0002, /* Exception occurred */
744 WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */
745 WHY_RETURN = 0x0008, /* 'return' statement */
746 WHY_BREAK = 0x0010, /* 'break' statement */
747 WHY_CONTINUE = 0x0020, /* 'continue' statement */
748 WHY_YIELD = 0x0040, /* 'yield' operator */
749 WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */
Raymond Hettinger7c958652004-04-06 10:11:10 +0000750};
Guido van Rossum374a9221991-04-04 10:40:29 +0000751
Benjamin Peterson87880242011-07-03 16:48:31 -0500752static void save_exc_state(PyThreadState *, PyFrameObject *);
753static void swap_exc_state(PyThreadState *, PyFrameObject *);
754static void restore_and_clear_exc_state(PyThreadState *, PyFrameObject *);
Collin Winter828f04a2007-08-31 00:04:24 +0000755static enum why_code do_raise(PyObject *, PyObject *);
Guido van Rossum0368b722007-05-11 16:50:42 +0000756static int unpack_iterable(PyObject *, int, int, PyObject **);
Guido van Rossum1aa14831997-01-21 05:34:20 +0000757
Jeffrey Yasskin008d8ef2008-12-06 17:09:27 +0000758/* Records whether tracing is on for any thread. Counts the number of
759 threads for which tstate->c_tracefunc is non-NULL, so if the value
760 is 0, we know we don't have to check this thread's c_tracefunc.
761 This speeds up the if statement in PyEval_EvalFrameEx() after
762 fast_next_opcode*/
763static int _Py_TracingPossible = 0;
764
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000765
Guido van Rossum374a9221991-04-04 10:40:29 +0000766
Guido van Rossumb209a111997-04-29 18:18:01 +0000767PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000768PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Guido van Rossum681d79a1995-07-18 14:51:37 +0000769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 return PyEval_EvalCodeEx(co,
771 globals, locals,
772 (PyObject **)NULL, 0,
773 (PyObject **)NULL, 0,
774 (PyObject **)NULL, 0,
775 NULL, NULL);
Guido van Rossum681d79a1995-07-18 14:51:37 +0000776}
777
778
779/* Interpreter main loop */
780
Martin v. Löwis8d97e332004-06-27 15:43:12 +0000781PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000782PyEval_EvalFrame(PyFrameObject *f) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* This is for backward compatibility with extension modules that
784 used this API; core interpreter code should call
785 PyEval_EvalFrameEx() */
786 return PyEval_EvalFrameEx(f, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000787}
788
789PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000790PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Guido van Rossum374a9221991-04-04 10:40:29 +0000791{
Guido van Rossum950361c1997-01-24 13:49:28 +0000792#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 int lastopcode = 0;
Guido van Rossum950361c1997-01-24 13:49:28 +0000794#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 register PyObject **stack_pointer; /* Next free slot in value stack */
796 register unsigned char *next_instr;
797 register int opcode; /* Current opcode */
798 register int oparg; /* Current opcode argument, if any */
799 register enum why_code why; /* Reason for block stack unwind */
800 register int err; /* Error status -- nonzero if error */
801 register PyObject *x; /* Result object -- NULL if error */
802 register PyObject *v; /* Temporary objects popped off stack */
803 register PyObject *w;
804 register PyObject *u;
805 register PyObject *t;
806 register PyObject **fastlocals, **freevars;
807 PyObject *retval = NULL; /* Return value */
808 PyThreadState *tstate = PyThreadState_GET();
809 PyCodeObject *co;
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 /* when tracing we set things up so that
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 not (instr_lb <= current_bytecode_offset < instr_ub)
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 is true when the line being executed has changed. The
816 initial values are such as to make this false the first
817 time it is tested. */
818 int instr_ub = -1, instr_lb = 0, instr_prev = -1;
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 unsigned char *first_instr;
821 PyObject *names;
822 PyObject *consts;
Guido van Rossum374a9221991-04-04 10:40:29 +0000823
Antoine Pitroub52ec782009-01-25 16:34:23 +0000824/* Computed GOTOs, or
825 the-optimization-commonly-but-improperly-known-as-"threaded code"
826 using gcc's labels-as-values extension
827 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
828
829 The traditional bytecode evaluation loop uses a "switch" statement, which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 decent compilers will optimize as a single indirect branch instruction
Antoine Pitroub52ec782009-01-25 16:34:23 +0000831 combined with a lookup table of jump addresses. However, since the
832 indirect jump instruction is shared by all opcodes, the CPU will have a
833 hard time making the right prediction for where to jump next (actually,
834 it will be always wrong except in the uncommon case of a sequence of
835 several identical opcodes).
836
837 "Threaded code" in contrast, uses an explicit jump table and an explicit
838 indirect jump instruction at the end of each opcode. Since the jump
839 instruction is at a different address for each opcode, the CPU will make a
840 separate prediction for each of these instructions, which is equivalent to
841 predicting the second opcode of each opcode pair. These predictions have
842 a much better chance to turn out valid, especially in small bytecode loops.
843
844 A mispredicted branch on a modern CPU flushes the whole pipeline and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 can cost several CPU cycles (depending on the pipeline depth),
Antoine Pitroub52ec782009-01-25 16:34:23 +0000846 and potentially many more instructions (depending on the pipeline width).
847 A correctly predicted branch, however, is nearly free.
848
849 At the time of this writing, the "threaded code" version is up to 15-20%
850 faster than the normal "switch" version, depending on the compiler and the
851 CPU architecture.
852
853 We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined,
854 because it would render the measurements invalid.
855
856
857 NOTE: care must be taken that the compiler doesn't try to "optimize" the
858 indirect jumps by sharing them between all opcodes. Such optimizations
859 can be disabled on gcc by using the -fno-gcse flag (or possibly
860 -fno-crossjumping).
861*/
862
Antoine Pitrou042b1282010-08-13 21:15:58 +0000863#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitroub52ec782009-01-25 16:34:23 +0000864#undef USE_COMPUTED_GOTOS
Antoine Pitrou042b1282010-08-13 21:15:58 +0000865#define USE_COMPUTED_GOTOS 0
Antoine Pitroub52ec782009-01-25 16:34:23 +0000866#endif
867
Antoine Pitrou042b1282010-08-13 21:15:58 +0000868#ifdef HAVE_COMPUTED_GOTOS
869 #ifndef USE_COMPUTED_GOTOS
870 #define USE_COMPUTED_GOTOS 1
871 #endif
872#else
873 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
874 #error "Computed gotos are not supported on this compiler."
875 #endif
876 #undef USE_COMPUTED_GOTOS
877 #define USE_COMPUTED_GOTOS 0
878#endif
879
880#if USE_COMPUTED_GOTOS
Antoine Pitroub52ec782009-01-25 16:34:23 +0000881/* Import the static jump table */
882#include "opcode_targets.h"
883
884/* This macro is used when several opcodes defer to the same implementation
885 (e.g. SETUP_LOOP, SETUP_FINALLY) */
886#define TARGET_WITH_IMPL(op, impl) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 TARGET_##op: \
888 opcode = op; \
889 if (HAS_ARG(op)) \
890 oparg = NEXTARG(); \
891 case op: \
892 goto impl; \
Antoine Pitroub52ec782009-01-25 16:34:23 +0000893
894#define TARGET(op) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 TARGET_##op: \
896 opcode = op; \
897 if (HAS_ARG(op)) \
898 oparg = NEXTARG(); \
899 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000900
901
902#define DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 { \
904 if (!_Py_atomic_load_relaxed(&eval_breaker)) { \
905 FAST_DISPATCH(); \
906 } \
907 continue; \
908 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000909
910#ifdef LLTRACE
911#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 { \
913 if (!lltrace && !_Py_TracingPossible) { \
914 f->f_lasti = INSTR_OFFSET(); \
915 goto *opcode_targets[*next_instr++]; \
916 } \
917 goto fast_next_opcode; \
918 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000919#else
920#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 { \
922 if (!_Py_TracingPossible) { \
923 f->f_lasti = INSTR_OFFSET(); \
924 goto *opcode_targets[*next_instr++]; \
925 } \
926 goto fast_next_opcode; \
927 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000928#endif
929
930#else
931#define TARGET(op) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000933#define TARGET_WITH_IMPL(op, impl) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* silence compiler warnings about `impl` unused */ \
935 if (0) goto impl; \
936 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000937#define DISPATCH() continue
938#define FAST_DISPATCH() goto fast_next_opcode
939#endif
940
941
Neal Norwitza81d2202002-07-14 00:27:26 +0000942/* Tuple access macros */
943
944#ifndef Py_DEBUG
945#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
946#else
947#define GETITEM(v, i) PyTuple_GetItem((v), (i))
948#endif
949
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000950#ifdef WITH_TSC
951/* Use Pentium timestamp counter to mark certain events:
952 inst0 -- beginning of switch statement for opcode dispatch
953 inst1 -- end of switch statement (may be skipped)
954 loop0 -- the top of the mainloop
Thomas Wouters477c8d52006-05-27 19:21:47 +0000955 loop1 -- place where control returns again to top of mainloop
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000956 (may be skipped)
957 intr1 -- beginning of long interruption
958 intr2 -- end of long interruption
959
960 Many opcodes call out to helper C functions. In some cases, the
961 time in those functions should be counted towards the time for the
962 opcode, but not in all cases. For example, a CALL_FUNCTION opcode
963 calls another Python function; there's no point in charge all the
964 bytecode executed by the called function to the caller.
965
966 It's hard to make a useful judgement statically. In the presence
967 of operator overloading, it's impossible to tell if a call will
968 execute new Python code or not.
969
970 It's a case-by-case judgement. I'll use intr1 for the following
971 cases:
972
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000973 IMPORT_STAR
974 IMPORT_FROM
975 CALL_FUNCTION (and friends)
976
977 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0;
979 int ticked = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 READ_TIMESTAMP(inst0);
982 READ_TIMESTAMP(inst1);
983 READ_TIMESTAMP(loop0);
984 READ_TIMESTAMP(loop1);
Michael W. Hudson800ba232004-08-12 18:19:17 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* shut up the compiler */
987 opcode = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000988#endif
989
Guido van Rossum374a9221991-04-04 10:40:29 +0000990/* Code access macros */
991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992#define INSTR_OFFSET() ((int)(next_instr - first_instr))
993#define NEXTOP() (*next_instr++)
994#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
995#define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
996#define JUMPTO(x) (next_instr = first_instr + (x))
997#define JUMPBY(x) (next_instr += (x))
Guido van Rossum374a9221991-04-04 10:40:29 +0000998
Raymond Hettingerf606f872003-03-16 03:11:04 +0000999/* OpCode prediction macros
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Some opcodes tend to come in pairs thus making it possible to
1001 predict the second code when the first is run. For example,
1002 COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And,
1003 those opcodes are often followed by a POP_TOP.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 Verifying the prediction costs a single high-speed test of a register
1006 variable against a constant. If the pairing was good, then the
1007 processor's own internal branch predication has a high likelihood of
1008 success, resulting in a nearly zero-overhead transition to the
1009 next opcode. A successful prediction saves a trip through the eval-loop
1010 including its two unpredictable branches, the HAS_ARG test and the
1011 switch-case. Combined with the processor's internal branch prediction,
1012 a successful PREDICT has the effect of making the two opcodes run as if
1013 they were a single new opcode with the bodies combined.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001014
Georg Brandl86b2fb92008-07-16 03:43:04 +00001015 If collecting opcode statistics, your choices are to either keep the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 predictions turned-on and interpret the results as if some opcodes
1017 had been combined or turn-off predictions so that the opcode frequency
1018 counter updates for both opcodes.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001019
1020 Opcode prediction is disabled with threaded code, since the latter allows
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 the CPU to record separate branch prediction information for each
1022 opcode.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001023
Raymond Hettingerf606f872003-03-16 03:11:04 +00001024*/
1025
Antoine Pitrou042b1282010-08-13 21:15:58 +00001026#if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027#define PREDICT(op) if (0) goto PRED_##op
1028#define PREDICTED(op) PRED_##op:
1029#define PREDICTED_WITH_ARG(op) PRED_##op:
Raymond Hettingera7216982004-02-08 19:59:27 +00001030#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031#define PREDICT(op) if (*next_instr == op) goto PRED_##op
1032#define PREDICTED(op) PRED_##op: next_instr++
1033#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
Antoine Pitroub52ec782009-01-25 16:34:23 +00001034#endif
1035
Raymond Hettingerf606f872003-03-16 03:11:04 +00001036
Guido van Rossum374a9221991-04-04 10:40:29 +00001037/* Stack manipulation macros */
1038
Martin v. Löwis18e16552006-02-15 17:27:45 +00001039/* The stack can grow at most MAXINT deep, as co_nlocals and
1040 co_stacksize are ints. */
Stefan Krahb7e10102010-06-23 18:42:39 +00001041#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
1042#define EMPTY() (STACK_LEVEL() == 0)
1043#define TOP() (stack_pointer[-1])
1044#define SECOND() (stack_pointer[-2])
1045#define THIRD() (stack_pointer[-3])
1046#define FOURTH() (stack_pointer[-4])
1047#define PEEK(n) (stack_pointer[-(n)])
1048#define SET_TOP(v) (stack_pointer[-1] = (v))
1049#define SET_SECOND(v) (stack_pointer[-2] = (v))
1050#define SET_THIRD(v) (stack_pointer[-3] = (v))
1051#define SET_FOURTH(v) (stack_pointer[-4] = (v))
1052#define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
1053#define BASIC_STACKADJ(n) (stack_pointer += n)
1054#define BASIC_PUSH(v) (*stack_pointer++ = (v))
1055#define BASIC_POP() (*--stack_pointer)
Guido van Rossum374a9221991-04-04 10:40:29 +00001056
Guido van Rossum96a42c81992-01-12 02:29:51 +00001057#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058#define PUSH(v) { (void)(BASIC_PUSH(v), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001059 lltrace && prtrace(TOP(), "push")); \
1060 assert(STACK_LEVEL() <= co->co_stacksize); }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001062 BASIC_POP())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001064 lltrace && prtrace(TOP(), "stackadj")); \
1065 assert(STACK_LEVEL() <= co->co_stacksize); }
Christian Heimes0449f632007-12-15 01:27:15 +00001066#define EXT_POP(STACK_POINTER) ((void)(lltrace && \
Stefan Krahb7e10102010-06-23 18:42:39 +00001067 prtrace((STACK_POINTER)[-1], "ext_pop")), \
1068 *--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001069#else
Stefan Krahb7e10102010-06-23 18:42:39 +00001070#define PUSH(v) BASIC_PUSH(v)
1071#define POP() BASIC_POP()
1072#define STACKADJ(n) BASIC_STACKADJ(n)
Guido van Rossumc2e20742006-02-27 22:32:47 +00001073#define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001074#endif
1075
Guido van Rossum681d79a1995-07-18 14:51:37 +00001076/* Local variable macros */
1077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078#define GETLOCAL(i) (fastlocals[i])
Guido van Rossumcfbf1a32002-03-28 20:17:52 +00001079
1080/* The SETLOCAL() macro must not DECREF the local variable in-place and
1081 then store the new value; it must copy the old value to a temporary
1082 value, then store the new value, and then DECREF the temporary value.
1083 This is because it is possible that during the DECREF the frame is
1084 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1085 variable would be pointing to already-freed memory. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001087 GETLOCAL(i) = value; \
1088 Py_XDECREF(tmp); } while (0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001089
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001090
1091#define UNWIND_BLOCK(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 while (STACK_LEVEL() > (b)->b_level) { \
1093 PyObject *v = POP(); \
1094 Py_XDECREF(v); \
1095 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001096
1097#define UNWIND_EXCEPT_HANDLER(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 { \
1099 PyObject *type, *value, *traceback; \
1100 assert(STACK_LEVEL() >= (b)->b_level + 3); \
1101 while (STACK_LEVEL() > (b)->b_level + 3) { \
1102 value = POP(); \
1103 Py_XDECREF(value); \
1104 } \
1105 type = tstate->exc_type; \
1106 value = tstate->exc_value; \
1107 traceback = tstate->exc_traceback; \
1108 tstate->exc_type = POP(); \
1109 tstate->exc_value = POP(); \
1110 tstate->exc_traceback = POP(); \
1111 Py_XDECREF(type); \
1112 Py_XDECREF(value); \
1113 Py_XDECREF(traceback); \
1114 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001115
Guido van Rossuma027efa1997-05-05 20:56:21 +00001116/* Start of code */
1117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (f == NULL)
1119 return NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 /* push frame */
1122 if (Py_EnterRecursiveCall(""))
1123 return NULL;
Guido van Rossum8861b741996-07-30 16:49:37 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 tstate->frame = f;
Tim Peters5ca576e2001-06-18 22:08:13 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 if (tstate->use_tracing) {
1128 if (tstate->c_tracefunc != NULL) {
1129 /* tstate->c_tracefunc, if defined, is a
1130 function that will be called on *every* entry
1131 to a code block. Its return value, if not
1132 None, is a function that will be called at
1133 the start of each executed line of code.
1134 (Actually, the function must return itself
1135 in order to continue tracing.) The trace
1136 functions are called with three arguments:
1137 a pointer to the current frame, a string
1138 indicating why the function is called, and
1139 an argument which depends on the situation.
1140 The global trace function is also called
1141 whenever an exception is detected. */
1142 if (call_trace_protected(tstate->c_tracefunc,
1143 tstate->c_traceobj,
1144 f, PyTrace_CALL, Py_None)) {
1145 /* Trace function raised an error */
1146 goto exit_eval_frame;
1147 }
1148 }
1149 if (tstate->c_profilefunc != NULL) {
1150 /* Similar for c_profilefunc, except it needn't
1151 return itself and isn't called for "line" events */
1152 if (call_trace_protected(tstate->c_profilefunc,
1153 tstate->c_profileobj,
1154 f, PyTrace_CALL, Py_None)) {
1155 /* Profile function raised an error */
1156 goto exit_eval_frame;
1157 }
1158 }
1159 }
Neil Schemenauer6c0f2002001-09-04 19:03:35 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 co = f->f_code;
1162 names = co->co_names;
1163 consts = co->co_consts;
1164 fastlocals = f->f_localsplus;
1165 freevars = f->f_localsplus + co->co_nlocals;
1166 first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code);
1167 /* An explanation is in order for the next line.
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 f->f_lasti now refers to the index of the last instruction
1170 executed. You might think this was obvious from the name, but
1171 this wasn't always true before 2.3! PyFrame_New now sets
1172 f->f_lasti to -1 (i.e. the index *before* the first instruction)
1173 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
1174 does work. Promise.
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 When the PREDICT() macros are enabled, some opcode pairs follow in
1177 direct succession without updating f->f_lasti. A successful
1178 prediction effectively links the two codes together as if they
1179 were a single new opcode; accordingly,f->f_lasti will point to
1180 the first code in the pair (for instance, GET_ITER followed by
1181 FOR_ITER is effectively a single opcode and f->f_lasti will point
1182 at to the beginning of the combined pair.)
1183 */
1184 next_instr = first_instr + f->f_lasti + 1;
1185 stack_pointer = f->f_stacktop;
1186 assert(stack_pointer != NULL);
1187 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (co->co_flags & CO_GENERATOR && !throwflag) {
1190 if (f->f_exc_type != NULL && f->f_exc_type != Py_None) {
1191 /* We were in an except handler when we left,
1192 restore the exception state which was put aside
1193 (see YIELD_VALUE). */
Benjamin Peterson87880242011-07-03 16:48:31 -05001194 swap_exc_state(tstate, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
Benjamin Peterson87880242011-07-03 16:48:31 -05001196 else
1197 save_exc_state(tstate, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001199
Tim Peters5ca576e2001-06-18 22:08:13 +00001200#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00001202#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 why = WHY_NOT;
1205 err = 0;
1206 x = Py_None; /* Not a reference, just anything non-NULL */
1207 w = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 if (throwflag) { /* support for generator.throw() */
1210 why = WHY_EXCEPTION;
1211 goto on_error;
1212 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 for (;;) {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001215#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (inst1 == 0) {
1217 /* Almost surely, the opcode executed a break
1218 or a continue, preventing inst1 from being set
1219 on the way out of the loop.
1220 */
1221 READ_TIMESTAMP(inst1);
1222 loop1 = inst1;
1223 }
1224 dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1,
1225 intr0, intr1);
1226 ticked = 0;
1227 inst1 = 0;
1228 intr0 = 0;
1229 intr1 = 0;
1230 READ_TIMESTAMP(loop0);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001231#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1233 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* Do periodic things. Doing this every time through
1236 the loop would add too much overhead, so we do it
1237 only every Nth instruction. We also do it if
1238 ``pendingcalls_to_do'' is set, i.e. when an asynchronous
1239 event needs attention (e.g. a signal handler or
1240 async I/O handler); see Py_AddPendingCall() and
1241 Py_MakePendingCalls() above. */
Guido van Rossumac7be682001-01-17 15:42:30 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (_Py_atomic_load_relaxed(&eval_breaker)) {
1244 if (*next_instr == SETUP_FINALLY) {
1245 /* Make the last opcode before
Ezio Melotti13925002011-03-16 11:05:33 +02001246 a try: finally: block uninterruptible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 goto fast_next_opcode;
1248 }
1249 tstate->tick_counter++;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001250#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 ticked = 1;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001252#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) {
1254 if (Py_MakePendingCalls() < 0) {
1255 why = WHY_EXCEPTION;
1256 goto on_error;
1257 }
1258 }
Guido van Rossume59214e1994-08-30 08:01:59 +00001259#ifdef WITH_THREAD
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001260 if (_Py_atomic_load_relaxed(&gil_drop_request)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 /* Give another thread a chance */
1262 if (PyThreadState_Swap(NULL) != tstate)
1263 Py_FatalError("ceval: tstate mix-up");
1264 drop_gil(tstate);
1265
1266 /* Other threads may run now */
1267
1268 take_gil(tstate);
1269 if (PyThreadState_Swap(tstate) != NULL)
1270 Py_FatalError("ceval: orphan tstate");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 }
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001272#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 /* Check for asynchronous exceptions. */
1274 if (tstate->async_exc != NULL) {
1275 x = tstate->async_exc;
1276 tstate->async_exc = NULL;
1277 UNSIGNAL_ASYNC_EXC();
1278 PyErr_SetNone(x);
1279 Py_DECREF(x);
1280 why = WHY_EXCEPTION;
1281 goto on_error;
1282 }
1283 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 fast_next_opcode:
1286 f->f_lasti = INSTR_OFFSET();
Guido van Rossumac7be682001-01-17 15:42:30 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 /* line-by-line tracing support */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (_Py_TracingPossible &&
1291 tstate->c_tracefunc != NULL && !tstate->tracing) {
1292 /* see maybe_call_line_trace
1293 for expository comments */
1294 f->f_stacktop = stack_pointer;
Tim Peters8a5c3c72004-04-05 19:36:21 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 err = maybe_call_line_trace(tstate->c_tracefunc,
1297 tstate->c_traceobj,
1298 f, &instr_lb, &instr_ub,
1299 &instr_prev);
1300 /* Reload possibly changed frame fields */
1301 JUMPTO(f->f_lasti);
1302 if (f->f_stacktop != NULL) {
1303 stack_pointer = f->f_stacktop;
1304 f->f_stacktop = NULL;
1305 }
1306 if (err) {
1307 /* trace function raised an exception */
1308 goto on_error;
1309 }
1310 }
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 /* Extract opcode and argument */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 opcode = NEXTOP();
1315 oparg = 0; /* allows oparg to be stored in a register because
1316 it doesn't have to be remembered across a full loop */
1317 if (HAS_ARG(opcode))
1318 oparg = NEXTARG();
Stefan Krahb7e10102010-06-23 18:42:39 +00001319 dispatch_opcode:
Guido van Rossum950361c1997-01-24 13:49:28 +00001320#ifdef DYNAMIC_EXECUTION_PROFILE
1321#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 dxpairs[lastopcode][opcode]++;
1323 lastopcode = opcode;
Guido van Rossum950361c1997-01-24 13:49:28 +00001324#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 dxp[opcode]++;
Guido van Rossum950361c1997-01-24 13:49:28 +00001326#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00001327
Guido van Rossum96a42c81992-01-12 02:29:51 +00001328#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* Instruction tracing */
Guido van Rossumac7be682001-01-17 15:42:30 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (lltrace) {
1332 if (HAS_ARG(opcode)) {
1333 printf("%d: %d, %d\n",
1334 f->f_lasti, opcode, oparg);
1335 }
1336 else {
1337 printf("%d: %d\n",
1338 f->f_lasti, opcode);
1339 }
1340 }
Guido van Rossum374a9221991-04-04 10:40:29 +00001341#endif
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 /* Main switch on opcode */
1344 READ_TIMESTAMP(inst0);
Jeremy Hylton52820442001-01-03 23:52:36 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 switch (opcode) {
Guido van Rossumac7be682001-01-17 15:42:30 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* BEWARE!
1349 It is essential that any operation that fails sets either
1350 x to NULL, err to nonzero, or why to anything but WHY_NOT,
1351 and that no operation that succeeds does this! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* case STOP_CODE: this is an error! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 TARGET(NOP)
1356 FAST_DISPATCH();
Raymond Hettinger9c18e812004-06-21 16:31:15 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 TARGET(LOAD_FAST)
1359 x = GETLOCAL(oparg);
1360 if (x != NULL) {
1361 Py_INCREF(x);
1362 PUSH(x);
1363 FAST_DISPATCH();
1364 }
1365 format_exc_check_arg(PyExc_UnboundLocalError,
1366 UNBOUNDLOCAL_ERROR_MSG,
1367 PyTuple_GetItem(co->co_varnames, oparg));
1368 break;
Neil Schemenauer63543862002-02-17 19:10:14 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 TARGET(LOAD_CONST)
1371 x = GETITEM(consts, oparg);
1372 Py_INCREF(x);
1373 PUSH(x);
1374 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PREDICTED_WITH_ARG(STORE_FAST);
1377 TARGET(STORE_FAST)
1378 v = POP();
1379 SETLOCAL(oparg, v);
1380 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 TARGET(POP_TOP)
1383 v = POP();
1384 Py_DECREF(v);
1385 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 TARGET(ROT_TWO)
1388 v = TOP();
1389 w = SECOND();
1390 SET_TOP(w);
1391 SET_SECOND(v);
1392 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 TARGET(ROT_THREE)
1395 v = TOP();
1396 w = SECOND();
1397 x = THIRD();
1398 SET_TOP(w);
1399 SET_SECOND(x);
1400 SET_THIRD(v);
1401 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 TARGET(DUP_TOP)
1404 v = TOP();
1405 Py_INCREF(v);
1406 PUSH(v);
1407 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001408
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00001409 TARGET(DUP_TOP_TWO)
1410 x = TOP();
1411 Py_INCREF(x);
1412 w = SECOND();
1413 Py_INCREF(w);
1414 STACKADJ(2);
1415 SET_TOP(x);
1416 SET_SECOND(w);
1417 FAST_DISPATCH();
Thomas Wouters434d0822000-08-24 20:11:32 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 TARGET(UNARY_POSITIVE)
1420 v = TOP();
1421 x = PyNumber_Positive(v);
1422 Py_DECREF(v);
1423 SET_TOP(x);
1424 if (x != NULL) DISPATCH();
1425 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 TARGET(UNARY_NEGATIVE)
1428 v = TOP();
1429 x = PyNumber_Negative(v);
1430 Py_DECREF(v);
1431 SET_TOP(x);
1432 if (x != NULL) DISPATCH();
1433 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 TARGET(UNARY_NOT)
1436 v = TOP();
1437 err = PyObject_IsTrue(v);
1438 Py_DECREF(v);
1439 if (err == 0) {
1440 Py_INCREF(Py_True);
1441 SET_TOP(Py_True);
1442 DISPATCH();
1443 }
1444 else if (err > 0) {
1445 Py_INCREF(Py_False);
1446 SET_TOP(Py_False);
1447 err = 0;
1448 DISPATCH();
1449 }
1450 STACKADJ(-1);
1451 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 TARGET(UNARY_INVERT)
1454 v = TOP();
1455 x = PyNumber_Invert(v);
1456 Py_DECREF(v);
1457 SET_TOP(x);
1458 if (x != NULL) DISPATCH();
1459 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 TARGET(BINARY_POWER)
1462 w = POP();
1463 v = TOP();
1464 x = PyNumber_Power(v, w, Py_None);
1465 Py_DECREF(v);
1466 Py_DECREF(w);
1467 SET_TOP(x);
1468 if (x != NULL) DISPATCH();
1469 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 TARGET(BINARY_MULTIPLY)
1472 w = POP();
1473 v = TOP();
1474 x = PyNumber_Multiply(v, w);
1475 Py_DECREF(v);
1476 Py_DECREF(w);
1477 SET_TOP(x);
1478 if (x != NULL) DISPATCH();
1479 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 TARGET(BINARY_TRUE_DIVIDE)
1482 w = POP();
1483 v = TOP();
1484 x = PyNumber_TrueDivide(v, w);
1485 Py_DECREF(v);
1486 Py_DECREF(w);
1487 SET_TOP(x);
1488 if (x != NULL) DISPATCH();
1489 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 TARGET(BINARY_FLOOR_DIVIDE)
1492 w = POP();
1493 v = TOP();
1494 x = PyNumber_FloorDivide(v, w);
1495 Py_DECREF(v);
1496 Py_DECREF(w);
1497 SET_TOP(x);
1498 if (x != NULL) DISPATCH();
1499 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 TARGET(BINARY_MODULO)
1502 w = POP();
1503 v = TOP();
1504 if (PyUnicode_CheckExact(v))
1505 x = PyUnicode_Format(v, w);
1506 else
1507 x = PyNumber_Remainder(v, w);
1508 Py_DECREF(v);
1509 Py_DECREF(w);
1510 SET_TOP(x);
1511 if (x != NULL) DISPATCH();
1512 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 TARGET(BINARY_ADD)
1515 w = POP();
1516 v = TOP();
1517 if (PyUnicode_CheckExact(v) &&
1518 PyUnicode_CheckExact(w)) {
1519 x = unicode_concatenate(v, w, f, next_instr);
1520 /* unicode_concatenate consumed the ref to v */
1521 goto skip_decref_vx;
1522 }
1523 else {
1524 x = PyNumber_Add(v, w);
1525 }
1526 Py_DECREF(v);
1527 skip_decref_vx:
1528 Py_DECREF(w);
1529 SET_TOP(x);
1530 if (x != NULL) DISPATCH();
1531 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 TARGET(BINARY_SUBTRACT)
1534 w = POP();
1535 v = TOP();
1536 x = PyNumber_Subtract(v, w);
1537 Py_DECREF(v);
1538 Py_DECREF(w);
1539 SET_TOP(x);
1540 if (x != NULL) DISPATCH();
1541 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 TARGET(BINARY_SUBSCR)
1544 w = POP();
1545 v = TOP();
1546 x = PyObject_GetItem(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_LSHIFT)
1554 w = POP();
1555 v = TOP();
1556 x = PyNumber_Lshift(v, w);
1557 Py_DECREF(v);
1558 Py_DECREF(w);
1559 SET_TOP(x);
1560 if (x != NULL) DISPATCH();
1561 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 TARGET(BINARY_RSHIFT)
1564 w = POP();
1565 v = TOP();
1566 x = PyNumber_Rshift(v, w);
1567 Py_DECREF(v);
1568 Py_DECREF(w);
1569 SET_TOP(x);
1570 if (x != NULL) DISPATCH();
1571 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 TARGET(BINARY_AND)
1574 w = POP();
1575 v = TOP();
1576 x = PyNumber_And(v, w);
1577 Py_DECREF(v);
1578 Py_DECREF(w);
1579 SET_TOP(x);
1580 if (x != NULL) DISPATCH();
1581 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 TARGET(BINARY_XOR)
1584 w = POP();
1585 v = TOP();
1586 x = PyNumber_Xor(v, w);
1587 Py_DECREF(v);
1588 Py_DECREF(w);
1589 SET_TOP(x);
1590 if (x != NULL) DISPATCH();
1591 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 TARGET(BINARY_OR)
1594 w = POP();
1595 v = TOP();
1596 x = PyNumber_Or(v, w);
1597 Py_DECREF(v);
1598 Py_DECREF(w);
1599 SET_TOP(x);
1600 if (x != NULL) DISPATCH();
1601 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 TARGET(LIST_APPEND)
1604 w = POP();
1605 v = PEEK(oparg);
1606 err = PyList_Append(v, w);
1607 Py_DECREF(w);
1608 if (err == 0) {
1609 PREDICT(JUMP_ABSOLUTE);
1610 DISPATCH();
1611 }
1612 break;
Raymond Hettingerdd80f762004-03-07 07:31:06 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 TARGET(SET_ADD)
1615 w = POP();
1616 v = stack_pointer[-oparg];
1617 err = PySet_Add(v, w);
1618 Py_DECREF(w);
1619 if (err == 0) {
1620 PREDICT(JUMP_ABSOLUTE);
1621 DISPATCH();
1622 }
1623 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 TARGET(INPLACE_POWER)
1626 w = POP();
1627 v = TOP();
1628 x = PyNumber_InPlacePower(v, w, Py_None);
1629 Py_DECREF(v);
1630 Py_DECREF(w);
1631 SET_TOP(x);
1632 if (x != NULL) DISPATCH();
1633 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 TARGET(INPLACE_MULTIPLY)
1636 w = POP();
1637 v = TOP();
1638 x = PyNumber_InPlaceMultiply(v, w);
1639 Py_DECREF(v);
1640 Py_DECREF(w);
1641 SET_TOP(x);
1642 if (x != NULL) DISPATCH();
1643 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 TARGET(INPLACE_TRUE_DIVIDE)
1646 w = POP();
1647 v = TOP();
1648 x = PyNumber_InPlaceTrueDivide(v, w);
1649 Py_DECREF(v);
1650 Py_DECREF(w);
1651 SET_TOP(x);
1652 if (x != NULL) DISPATCH();
1653 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 TARGET(INPLACE_FLOOR_DIVIDE)
1656 w = POP();
1657 v = TOP();
1658 x = PyNumber_InPlaceFloorDivide(v, w);
1659 Py_DECREF(v);
1660 Py_DECREF(w);
1661 SET_TOP(x);
1662 if (x != NULL) DISPATCH();
1663 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 TARGET(INPLACE_MODULO)
1666 w = POP();
1667 v = TOP();
1668 x = PyNumber_InPlaceRemainder(v, w);
1669 Py_DECREF(v);
1670 Py_DECREF(w);
1671 SET_TOP(x);
1672 if (x != NULL) DISPATCH();
1673 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 TARGET(INPLACE_ADD)
1676 w = POP();
1677 v = TOP();
1678 if (PyUnicode_CheckExact(v) &&
1679 PyUnicode_CheckExact(w)) {
1680 x = unicode_concatenate(v, w, f, next_instr);
1681 /* unicode_concatenate consumed the ref to v */
1682 goto skip_decref_v;
1683 }
1684 else {
1685 x = PyNumber_InPlaceAdd(v, w);
1686 }
1687 Py_DECREF(v);
1688 skip_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_SUBTRACT)
1695 w = POP();
1696 v = TOP();
1697 x = PyNumber_InPlaceSubtract(v, w);
1698 Py_DECREF(v);
1699 Py_DECREF(w);
1700 SET_TOP(x);
1701 if (x != NULL) DISPATCH();
1702 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 TARGET(INPLACE_LSHIFT)
1705 w = POP();
1706 v = TOP();
1707 x = PyNumber_InPlaceLshift(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_RSHIFT)
1715 w = POP();
1716 v = TOP();
1717 x = PyNumber_InPlaceRshift(v, w);
1718 Py_DECREF(v);
1719 Py_DECREF(w);
1720 SET_TOP(x);
1721 if (x != NULL) DISPATCH();
1722 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 TARGET(INPLACE_AND)
1725 w = POP();
1726 v = TOP();
1727 x = PyNumber_InPlaceAnd(v, w);
1728 Py_DECREF(v);
1729 Py_DECREF(w);
1730 SET_TOP(x);
1731 if (x != NULL) DISPATCH();
1732 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 TARGET(INPLACE_XOR)
1735 w = POP();
1736 v = TOP();
1737 x = PyNumber_InPlaceXor(v, w);
1738 Py_DECREF(v);
1739 Py_DECREF(w);
1740 SET_TOP(x);
1741 if (x != NULL) DISPATCH();
1742 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 TARGET(INPLACE_OR)
1745 w = POP();
1746 v = TOP();
1747 x = PyNumber_InPlaceOr(v, w);
1748 Py_DECREF(v);
1749 Py_DECREF(w);
1750 SET_TOP(x);
1751 if (x != NULL) DISPATCH();
1752 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 TARGET(STORE_SUBSCR)
1755 w = TOP();
1756 v = SECOND();
1757 u = THIRD();
1758 STACKADJ(-3);
1759 /* v[w] = u */
1760 err = PyObject_SetItem(v, w, u);
1761 Py_DECREF(u);
1762 Py_DECREF(v);
1763 Py_DECREF(w);
1764 if (err == 0) DISPATCH();
1765 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 TARGET(DELETE_SUBSCR)
1768 w = TOP();
1769 v = SECOND();
1770 STACKADJ(-2);
1771 /* del v[w] */
1772 err = PyObject_DelItem(v, w);
1773 Py_DECREF(v);
1774 Py_DECREF(w);
1775 if (err == 0) DISPATCH();
1776 break;
Barry Warsaw23c9ec82000-08-21 15:44:01 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 TARGET(PRINT_EXPR)
1779 v = POP();
1780 w = PySys_GetObject("displayhook");
1781 if (w == NULL) {
1782 PyErr_SetString(PyExc_RuntimeError,
1783 "lost sys.displayhook");
1784 err = -1;
1785 x = NULL;
1786 }
1787 if (err == 0) {
1788 x = PyTuple_Pack(1, v);
1789 if (x == NULL)
1790 err = -1;
1791 }
1792 if (err == 0) {
1793 w = PyEval_CallObject(w, x);
1794 Py_XDECREF(w);
1795 if (w == NULL)
1796 err = -1;
1797 }
1798 Py_DECREF(v);
1799 Py_XDECREF(x);
1800 break;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +00001801
Thomas Wouters434d0822000-08-24 20:11:32 +00001802#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 default: switch (opcode) {
Thomas Wouters434d0822000-08-24 20:11:32 +00001804#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 TARGET(RAISE_VARARGS)
1806 v = w = NULL;
1807 switch (oparg) {
1808 case 2:
1809 v = POP(); /* cause */
1810 case 1:
1811 w = POP(); /* exc */
1812 case 0: /* Fallthrough */
1813 why = do_raise(w, v);
1814 break;
1815 default:
1816 PyErr_SetString(PyExc_SystemError,
1817 "bad RAISE_VARARGS oparg");
1818 why = WHY_EXCEPTION;
1819 break;
1820 }
1821 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 TARGET(STORE_LOCALS)
1824 x = POP();
1825 v = f->f_locals;
1826 Py_XDECREF(v);
1827 f->f_locals = x;
1828 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 TARGET(RETURN_VALUE)
1831 retval = POP();
1832 why = WHY_RETURN;
1833 goto fast_block_end;
Guido van Rossumdb3165e1993-10-18 17:06:59 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 TARGET(YIELD_VALUE)
1836 retval = POP();
1837 f->f_stacktop = stack_pointer;
1838 why = WHY_YIELD;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 goto fast_yield;
Tim Peters5ca576e2001-06-18 22:08:13 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 TARGET(POP_EXCEPT)
1842 {
1843 PyTryBlock *b = PyFrame_BlockPop(f);
1844 if (b->b_type != EXCEPT_HANDLER) {
1845 PyErr_SetString(PyExc_SystemError,
1846 "popped block is not an except handler");
1847 why = WHY_EXCEPTION;
1848 break;
1849 }
1850 UNWIND_EXCEPT_HANDLER(b);
1851 }
1852 DISPATCH();
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 TARGET(POP_BLOCK)
1855 {
1856 PyTryBlock *b = PyFrame_BlockPop(f);
1857 UNWIND_BLOCK(b);
1858 }
1859 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PREDICTED(END_FINALLY);
1862 TARGET(END_FINALLY)
1863 v = POP();
1864 if (PyLong_Check(v)) {
1865 why = (enum why_code) PyLong_AS_LONG(v);
1866 assert(why != WHY_YIELD);
1867 if (why == WHY_RETURN ||
1868 why == WHY_CONTINUE)
1869 retval = POP();
1870 if (why == WHY_SILENCED) {
1871 /* An exception was silenced by 'with', we must
1872 manually unwind the EXCEPT_HANDLER block which was
1873 created when the exception was caught, otherwise
1874 the stack will be in an inconsistent state. */
1875 PyTryBlock *b = PyFrame_BlockPop(f);
1876 assert(b->b_type == EXCEPT_HANDLER);
1877 UNWIND_EXCEPT_HANDLER(b);
1878 why = WHY_NOT;
1879 }
1880 }
1881 else if (PyExceptionClass_Check(v)) {
1882 w = POP();
1883 u = POP();
1884 PyErr_Restore(v, w, u);
1885 why = WHY_RERAISE;
1886 break;
1887 }
1888 else if (v != Py_None) {
1889 PyErr_SetString(PyExc_SystemError,
1890 "'finally' pops bad exception");
1891 why = WHY_EXCEPTION;
1892 }
1893 Py_DECREF(v);
1894 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 TARGET(LOAD_BUILD_CLASS)
1897 x = PyDict_GetItemString(f->f_builtins,
1898 "__build_class__");
1899 if (x == NULL) {
1900 PyErr_SetString(PyExc_ImportError,
1901 "__build_class__ not found");
1902 break;
1903 }
1904 Py_INCREF(x);
1905 PUSH(x);
1906 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 TARGET(STORE_NAME)
1909 w = GETITEM(names, oparg);
1910 v = POP();
1911 if ((x = f->f_locals) != NULL) {
1912 if (PyDict_CheckExact(x))
1913 err = PyDict_SetItem(x, w, v);
1914 else
1915 err = PyObject_SetItem(x, w, v);
1916 Py_DECREF(v);
1917 if (err == 0) DISPATCH();
1918 break;
1919 }
1920 PyErr_Format(PyExc_SystemError,
1921 "no locals found when storing %R", w);
1922 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 TARGET(DELETE_NAME)
1925 w = GETITEM(names, oparg);
1926 if ((x = f->f_locals) != NULL) {
1927 if ((err = PyObject_DelItem(x, w)) != 0)
1928 format_exc_check_arg(PyExc_NameError,
1929 NAME_ERROR_MSG,
1930 w);
1931 break;
1932 }
1933 PyErr_Format(PyExc_SystemError,
1934 "no locals when deleting %R", w);
1935 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
1938 TARGET(UNPACK_SEQUENCE)
1939 v = POP();
1940 if (PyTuple_CheckExact(v) &&
1941 PyTuple_GET_SIZE(v) == oparg) {
1942 PyObject **items = \
1943 ((PyTupleObject *)v)->ob_item;
1944 while (oparg--) {
1945 w = items[oparg];
1946 Py_INCREF(w);
1947 PUSH(w);
1948 }
1949 Py_DECREF(v);
1950 DISPATCH();
1951 } else if (PyList_CheckExact(v) &&
1952 PyList_GET_SIZE(v) == oparg) {
1953 PyObject **items = \
1954 ((PyListObject *)v)->ob_item;
1955 while (oparg--) {
1956 w = items[oparg];
1957 Py_INCREF(w);
1958 PUSH(w);
1959 }
1960 } else if (unpack_iterable(v, oparg, -1,
1961 stack_pointer + oparg)) {
1962 STACKADJ(oparg);
1963 } else {
1964 /* unpack_iterable() raised an exception */
1965 why = WHY_EXCEPTION;
1966 }
1967 Py_DECREF(v);
1968 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 TARGET(UNPACK_EX)
1971 {
1972 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
1973 v = POP();
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (unpack_iterable(v, oparg & 0xFF, oparg >> 8,
1976 stack_pointer + totalargs)) {
1977 stack_pointer += totalargs;
1978 } else {
1979 why = WHY_EXCEPTION;
1980 }
1981 Py_DECREF(v);
1982 break;
1983 }
Guido van Rossum0368b722007-05-11 16:50:42 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 TARGET(STORE_ATTR)
1986 w = GETITEM(names, oparg);
1987 v = TOP();
1988 u = SECOND();
1989 STACKADJ(-2);
1990 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1991 Py_DECREF(v);
1992 Py_DECREF(u);
1993 if (err == 0) DISPATCH();
1994 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 TARGET(DELETE_ATTR)
1997 w = GETITEM(names, oparg);
1998 v = POP();
1999 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
2000 /* del v.w */
2001 Py_DECREF(v);
2002 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 TARGET(STORE_GLOBAL)
2005 w = GETITEM(names, oparg);
2006 v = POP();
2007 err = PyDict_SetItem(f->f_globals, w, v);
2008 Py_DECREF(v);
2009 if (err == 0) DISPATCH();
2010 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 TARGET(DELETE_GLOBAL)
2013 w = GETITEM(names, oparg);
2014 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
2015 format_exc_check_arg(
2016 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
2017 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 TARGET(LOAD_NAME)
2020 w = GETITEM(names, oparg);
2021 if ((v = f->f_locals) == NULL) {
2022 PyErr_Format(PyExc_SystemError,
2023 "no locals when loading %R", w);
2024 why = WHY_EXCEPTION;
2025 break;
2026 }
2027 if (PyDict_CheckExact(v)) {
2028 x = PyDict_GetItem(v, w);
2029 Py_XINCREF(x);
2030 }
2031 else {
2032 x = PyObject_GetItem(v, w);
2033 if (x == NULL && PyErr_Occurred()) {
2034 if (!PyErr_ExceptionMatches(
2035 PyExc_KeyError))
2036 break;
2037 PyErr_Clear();
2038 }
2039 }
2040 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002041 x = PyDict_GetItem(f->f_globals, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002043 x = PyDict_GetItem(f->f_builtins, w);
2044 if (x == NULL) {
2045 format_exc_check_arg(
2046 PyExc_NameError,
2047 NAME_ERROR_MSG, w);
2048 break;
2049 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
2051 Py_INCREF(x);
2052 }
2053 PUSH(x);
2054 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 TARGET(LOAD_GLOBAL)
2057 w = GETITEM(names, oparg);
2058 if (PyUnicode_CheckExact(w)) {
2059 /* Inline the PyDict_GetItem() calls.
2060 WARNING: this is an extreme speed hack.
2061 Do not try this at home. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002062 Py_hash_t hash = ((PyUnicodeObject *)w)->hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (hash != -1) {
2064 PyDictObject *d;
2065 PyDictEntry *e;
2066 d = (PyDictObject *)(f->f_globals);
2067 e = d->ma_lookup(d, w, hash);
2068 if (e == NULL) {
2069 x = NULL;
2070 break;
2071 }
2072 x = e->me_value;
2073 if (x != NULL) {
2074 Py_INCREF(x);
2075 PUSH(x);
2076 DISPATCH();
2077 }
2078 d = (PyDictObject *)(f->f_builtins);
2079 e = d->ma_lookup(d, w, hash);
2080 if (e == NULL) {
2081 x = NULL;
2082 break;
2083 }
2084 x = e->me_value;
2085 if (x != NULL) {
2086 Py_INCREF(x);
2087 PUSH(x);
2088 DISPATCH();
2089 }
2090 goto load_global_error;
2091 }
2092 }
2093 /* This is the un-inlined version of the code above */
2094 x = PyDict_GetItem(f->f_globals, w);
2095 if (x == NULL) {
2096 x = PyDict_GetItem(f->f_builtins, w);
2097 if (x == NULL) {
2098 load_global_error:
2099 format_exc_check_arg(
2100 PyExc_NameError,
2101 GLOBAL_NAME_ERROR_MSG, w);
2102 break;
2103 }
2104 }
2105 Py_INCREF(x);
2106 PUSH(x);
2107 DISPATCH();
Guido van Rossum681d79a1995-07-18 14:51:37 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 TARGET(DELETE_FAST)
2110 x = GETLOCAL(oparg);
2111 if (x != NULL) {
2112 SETLOCAL(oparg, NULL);
2113 DISPATCH();
2114 }
2115 format_exc_check_arg(
2116 PyExc_UnboundLocalError,
2117 UNBOUNDLOCAL_ERROR_MSG,
2118 PyTuple_GetItem(co->co_varnames, oparg)
2119 );
2120 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002121
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002122 TARGET(DELETE_DEREF)
2123 x = freevars[oparg];
2124 if (PyCell_GET(x) != NULL) {
2125 PyCell_Set(x, NULL);
Benjamin Peterson00ebe2c2010-09-10 22:02:31 +00002126 DISPATCH();
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002127 }
2128 err = -1;
2129 format_exc_unbound(co, oparg);
2130 break;
2131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 TARGET(LOAD_CLOSURE)
2133 x = freevars[oparg];
2134 Py_INCREF(x);
2135 PUSH(x);
2136 if (x != NULL) DISPATCH();
2137 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 TARGET(LOAD_DEREF)
2140 x = freevars[oparg];
2141 w = PyCell_Get(x);
2142 if (w != NULL) {
2143 PUSH(w);
2144 DISPATCH();
2145 }
2146 err = -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002147 format_exc_unbound(co, oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 TARGET(STORE_DEREF)
2151 w = POP();
2152 x = freevars[oparg];
2153 PyCell_Set(x, w);
2154 Py_DECREF(w);
2155 DISPATCH();
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 TARGET(BUILD_TUPLE)
2158 x = PyTuple_New(oparg);
2159 if (x != NULL) {
2160 for (; --oparg >= 0;) {
2161 w = POP();
2162 PyTuple_SET_ITEM(x, oparg, w);
2163 }
2164 PUSH(x);
2165 DISPATCH();
2166 }
2167 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 TARGET(BUILD_LIST)
2170 x = PyList_New(oparg);
2171 if (x != NULL) {
2172 for (; --oparg >= 0;) {
2173 w = POP();
2174 PyList_SET_ITEM(x, oparg, w);
2175 }
2176 PUSH(x);
2177 DISPATCH();
2178 }
2179 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 TARGET(BUILD_SET)
2182 x = PySet_New(NULL);
2183 if (x != NULL) {
2184 for (; --oparg >= 0;) {
2185 w = POP();
2186 if (err == 0)
2187 err = PySet_Add(x, w);
2188 Py_DECREF(w);
2189 }
2190 if (err != 0) {
2191 Py_DECREF(x);
2192 break;
2193 }
2194 PUSH(x);
2195 DISPATCH();
2196 }
2197 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 TARGET(BUILD_MAP)
2200 x = _PyDict_NewPresized((Py_ssize_t)oparg);
2201 PUSH(x);
2202 if (x != NULL) DISPATCH();
2203 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 TARGET(STORE_MAP)
2206 w = TOP(); /* key */
2207 u = SECOND(); /* value */
2208 v = THIRD(); /* dict */
2209 STACKADJ(-2);
2210 assert (PyDict_CheckExact(v));
2211 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2212 Py_DECREF(u);
2213 Py_DECREF(w);
2214 if (err == 0) DISPATCH();
2215 break;
Christian Heimes99170a52007-12-19 02:07:34 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 TARGET(MAP_ADD)
2218 w = TOP(); /* key */
2219 u = SECOND(); /* value */
2220 STACKADJ(-2);
2221 v = stack_pointer[-oparg]; /* dict */
2222 assert (PyDict_CheckExact(v));
2223 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2224 Py_DECREF(u);
2225 Py_DECREF(w);
2226 if (err == 0) {
2227 PREDICT(JUMP_ABSOLUTE);
2228 DISPATCH();
2229 }
2230 break;
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 TARGET(LOAD_ATTR)
2233 w = GETITEM(names, oparg);
2234 v = TOP();
2235 x = PyObject_GetAttr(v, w);
2236 Py_DECREF(v);
2237 SET_TOP(x);
2238 if (x != NULL) DISPATCH();
2239 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 TARGET(COMPARE_OP)
2242 w = POP();
2243 v = TOP();
2244 x = cmp_outcome(oparg, v, w);
2245 Py_DECREF(v);
2246 Py_DECREF(w);
2247 SET_TOP(x);
2248 if (x == NULL) break;
2249 PREDICT(POP_JUMP_IF_FALSE);
2250 PREDICT(POP_JUMP_IF_TRUE);
2251 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 TARGET(IMPORT_NAME)
2254 w = GETITEM(names, oparg);
2255 x = PyDict_GetItemString(f->f_builtins, "__import__");
2256 if (x == NULL) {
2257 PyErr_SetString(PyExc_ImportError,
2258 "__import__ not found");
2259 break;
2260 }
2261 Py_INCREF(x);
2262 v = POP();
2263 u = TOP();
2264 if (PyLong_AsLong(u) != -1 || PyErr_Occurred())
2265 w = PyTuple_Pack(5,
2266 w,
2267 f->f_globals,
2268 f->f_locals == NULL ?
2269 Py_None : f->f_locals,
2270 v,
2271 u);
2272 else
2273 w = PyTuple_Pack(4,
2274 w,
2275 f->f_globals,
2276 f->f_locals == NULL ?
2277 Py_None : f->f_locals,
2278 v);
2279 Py_DECREF(v);
2280 Py_DECREF(u);
2281 if (w == NULL) {
2282 u = POP();
2283 Py_DECREF(x);
2284 x = NULL;
2285 break;
2286 }
2287 READ_TIMESTAMP(intr0);
2288 v = x;
2289 x = PyEval_CallObject(v, w);
2290 Py_DECREF(v);
2291 READ_TIMESTAMP(intr1);
2292 Py_DECREF(w);
2293 SET_TOP(x);
2294 if (x != NULL) DISPATCH();
2295 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 TARGET(IMPORT_STAR)
2298 v = POP();
2299 PyFrame_FastToLocals(f);
2300 if ((x = f->f_locals) == NULL) {
2301 PyErr_SetString(PyExc_SystemError,
2302 "no locals found during 'import *'");
2303 break;
2304 }
2305 READ_TIMESTAMP(intr0);
2306 err = import_all_from(x, v);
2307 READ_TIMESTAMP(intr1);
2308 PyFrame_LocalsToFast(f, 0);
2309 Py_DECREF(v);
2310 if (err == 0) DISPATCH();
2311 break;
Guido van Rossum25831651993-05-19 14:50:45 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 TARGET(IMPORT_FROM)
2314 w = GETITEM(names, oparg);
2315 v = TOP();
2316 READ_TIMESTAMP(intr0);
2317 x = import_from(v, w);
2318 READ_TIMESTAMP(intr1);
2319 PUSH(x);
2320 if (x != NULL) DISPATCH();
2321 break;
Thomas Wouters52152252000-08-17 22:55:00 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 TARGET(JUMP_FORWARD)
2324 JUMPBY(oparg);
2325 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE);
2328 TARGET(POP_JUMP_IF_FALSE)
2329 w = POP();
2330 if (w == Py_True) {
2331 Py_DECREF(w);
2332 FAST_DISPATCH();
2333 }
2334 if (w == Py_False) {
2335 Py_DECREF(w);
2336 JUMPTO(oparg);
2337 FAST_DISPATCH();
2338 }
2339 err = PyObject_IsTrue(w);
2340 Py_DECREF(w);
2341 if (err > 0)
2342 err = 0;
2343 else if (err == 0)
2344 JUMPTO(oparg);
2345 else
2346 break;
2347 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE);
2350 TARGET(POP_JUMP_IF_TRUE)
2351 w = POP();
2352 if (w == Py_False) {
2353 Py_DECREF(w);
2354 FAST_DISPATCH();
2355 }
2356 if (w == Py_True) {
2357 Py_DECREF(w);
2358 JUMPTO(oparg);
2359 FAST_DISPATCH();
2360 }
2361 err = PyObject_IsTrue(w);
2362 Py_DECREF(w);
2363 if (err > 0) {
2364 err = 0;
2365 JUMPTO(oparg);
2366 }
2367 else if (err == 0)
2368 ;
2369 else
2370 break;
2371 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 TARGET(JUMP_IF_FALSE_OR_POP)
2374 w = TOP();
2375 if (w == Py_True) {
2376 STACKADJ(-1);
2377 Py_DECREF(w);
2378 FAST_DISPATCH();
2379 }
2380 if (w == Py_False) {
2381 JUMPTO(oparg);
2382 FAST_DISPATCH();
2383 }
2384 err = PyObject_IsTrue(w);
2385 if (err > 0) {
2386 STACKADJ(-1);
2387 Py_DECREF(w);
2388 err = 0;
2389 }
2390 else if (err == 0)
2391 JUMPTO(oparg);
2392 else
2393 break;
2394 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 TARGET(JUMP_IF_TRUE_OR_POP)
2397 w = TOP();
2398 if (w == Py_False) {
2399 STACKADJ(-1);
2400 Py_DECREF(w);
2401 FAST_DISPATCH();
2402 }
2403 if (w == Py_True) {
2404 JUMPTO(oparg);
2405 FAST_DISPATCH();
2406 }
2407 err = PyObject_IsTrue(w);
2408 if (err > 0) {
2409 err = 0;
2410 JUMPTO(oparg);
2411 }
2412 else if (err == 0) {
2413 STACKADJ(-1);
2414 Py_DECREF(w);
2415 }
2416 else
2417 break;
2418 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 PREDICTED_WITH_ARG(JUMP_ABSOLUTE);
2421 TARGET(JUMP_ABSOLUTE)
2422 JUMPTO(oparg);
Guido van Rossum58da9312007-11-10 23:39:45 +00002423#if FAST_LOOPS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 /* Enabling this path speeds-up all while and for-loops by bypassing
2425 the per-loop checks for signals. By default, this should be turned-off
2426 because it prevents detection of a control-break in tight loops like
2427 "while 1: pass". Compile with this option turned-on when you need
2428 the speed-up and do not need break checking inside tight loops (ones
2429 that contain only instructions ending with FAST_DISPATCH).
2430 */
2431 FAST_DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002432#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002434#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 TARGET(GET_ITER)
2437 /* before: [obj]; after [getiter(obj)] */
2438 v = TOP();
2439 x = PyObject_GetIter(v);
2440 Py_DECREF(v);
2441 if (x != NULL) {
2442 SET_TOP(x);
2443 PREDICT(FOR_ITER);
2444 DISPATCH();
2445 }
2446 STACKADJ(-1);
2447 break;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 PREDICTED_WITH_ARG(FOR_ITER);
2450 TARGET(FOR_ITER)
2451 /* before: [iter]; after: [iter, iter()] *or* [] */
2452 v = TOP();
2453 x = (*v->ob_type->tp_iternext)(v);
2454 if (x != NULL) {
2455 PUSH(x);
2456 PREDICT(STORE_FAST);
2457 PREDICT(UNPACK_SEQUENCE);
2458 DISPATCH();
2459 }
2460 if (PyErr_Occurred()) {
2461 if (!PyErr_ExceptionMatches(
2462 PyExc_StopIteration))
2463 break;
2464 PyErr_Clear();
2465 }
2466 /* iterator ended normally */
2467 x = v = POP();
2468 Py_DECREF(v);
2469 JUMPBY(oparg);
2470 DISPATCH();
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 TARGET(BREAK_LOOP)
2473 why = WHY_BREAK;
2474 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 TARGET(CONTINUE_LOOP)
2477 retval = PyLong_FromLong(oparg);
2478 if (!retval) {
2479 x = NULL;
2480 break;
2481 }
2482 why = WHY_CONTINUE;
2483 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally)
2486 TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally)
2487 TARGET(SETUP_FINALLY)
2488 _setup_finally:
2489 /* NOTE: If you add any new block-setup opcodes that
2490 are not try/except/finally handlers, you may need
2491 to update the PyGen_NeedsFinalizing() function.
2492 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
2495 STACK_LEVEL());
2496 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 TARGET(SETUP_WITH)
2499 {
2500 static PyObject *exit, *enter;
2501 w = TOP();
2502 x = special_lookup(w, "__exit__", &exit);
2503 if (!x)
2504 break;
2505 SET_TOP(x);
2506 u = special_lookup(w, "__enter__", &enter);
2507 Py_DECREF(w);
2508 if (!u) {
2509 x = NULL;
2510 break;
2511 }
2512 x = PyObject_CallFunctionObjArgs(u, NULL);
2513 Py_DECREF(u);
2514 if (!x)
2515 break;
2516 /* Setup the finally block before pushing the result
2517 of __enter__ on the stack. */
2518 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
2519 STACK_LEVEL());
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 PUSH(x);
2522 DISPATCH();
2523 }
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 TARGET(WITH_CLEANUP)
2526 {
2527 /* At the top of the stack are 1-3 values indicating
2528 how/why we entered the finally clause:
2529 - TOP = None
2530 - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
2531 - TOP = WHY_*; no retval below it
2532 - (TOP, SECOND, THIRD) = exc_info()
2533 (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER
2534 Below them is EXIT, the context.__exit__ bound method.
2535 In the last case, we must call
2536 EXIT(TOP, SECOND, THIRD)
2537 otherwise we must call
2538 EXIT(None, None, None)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 In the first two cases, we remove EXIT from the
2541 stack, leaving the rest in the same order. In the
2542 third case, we shift the bottom 3 values of the
2543 stack down, and replace the empty spot with NULL.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 In addition, if the stack represents an exception,
2546 *and* the function call returns a 'true' value, we
2547 push WHY_SILENCED onto the stack. END_FINALLY will
2548 then not re-raise the exception. (But non-local
2549 gotos should still be resumed.)
2550 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 PyObject *exit_func;
2553 u = TOP();
2554 if (u == Py_None) {
2555 (void)POP();
2556 exit_func = TOP();
2557 SET_TOP(u);
2558 v = w = Py_None;
2559 }
2560 else if (PyLong_Check(u)) {
2561 (void)POP();
2562 switch(PyLong_AsLong(u)) {
2563 case WHY_RETURN:
2564 case WHY_CONTINUE:
2565 /* Retval in TOP. */
2566 exit_func = SECOND();
2567 SET_SECOND(TOP());
2568 SET_TOP(u);
2569 break;
2570 default:
2571 exit_func = TOP();
2572 SET_TOP(u);
2573 break;
2574 }
2575 u = v = w = Py_None;
2576 }
2577 else {
2578 PyObject *tp, *exc, *tb;
2579 PyTryBlock *block;
2580 v = SECOND();
2581 w = THIRD();
2582 tp = FOURTH();
2583 exc = PEEK(5);
2584 tb = PEEK(6);
2585 exit_func = PEEK(7);
2586 SET_VALUE(7, tb);
2587 SET_VALUE(6, exc);
2588 SET_VALUE(5, tp);
2589 /* UNWIND_EXCEPT_HANDLER will pop this off. */
2590 SET_FOURTH(NULL);
2591 /* We just shifted the stack down, so we have
2592 to tell the except handler block that the
2593 values are lower than it expects. */
2594 block = &f->f_blockstack[f->f_iblock - 1];
2595 assert(block->b_type == EXCEPT_HANDLER);
2596 block->b_level--;
2597 }
2598 /* XXX Not the fastest way to call it... */
2599 x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
2600 NULL);
2601 Py_DECREF(exit_func);
2602 if (x == NULL)
2603 break; /* Go to error exit */
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if (u != Py_None)
2606 err = PyObject_IsTrue(x);
2607 else
2608 err = 0;
2609 Py_DECREF(x);
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 if (err < 0)
2612 break; /* Go to error exit */
2613 else if (err > 0) {
2614 err = 0;
2615 /* There was an exception and a True return */
2616 PUSH(PyLong_FromLong((long) WHY_SILENCED));
2617 }
2618 PREDICT(END_FINALLY);
2619 break;
2620 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 TARGET(CALL_FUNCTION)
2623 {
2624 PyObject **sp;
2625 PCALL(PCALL_ALL);
2626 sp = stack_pointer;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002627#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 x = call_function(&sp, oparg, &intr0, &intr1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002629#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 x = call_function(&sp, oparg);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002631#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 stack_pointer = sp;
2633 PUSH(x);
2634 if (x != NULL)
2635 DISPATCH();
2636 break;
2637 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw)
2640 TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw)
2641 TARGET(CALL_FUNCTION_VAR_KW)
2642 _call_function_var_kw:
2643 {
2644 int na = oparg & 0xff;
2645 int nk = (oparg>>8) & 0xff;
2646 int flags = (opcode - CALL_FUNCTION) & 3;
2647 int n = na + 2 * nk;
2648 PyObject **pfunc, *func, **sp;
2649 PCALL(PCALL_ALL);
2650 if (flags & CALL_FLAG_VAR)
2651 n++;
2652 if (flags & CALL_FLAG_KW)
2653 n++;
2654 pfunc = stack_pointer - n - 1;
2655 func = *pfunc;
Jeremy Hylton52820442001-01-03 23:52:36 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (PyMethod_Check(func)
Stefan Krahb7e10102010-06-23 18:42:39 +00002658 && PyMethod_GET_SELF(func) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 PyObject *self = PyMethod_GET_SELF(func);
2660 Py_INCREF(self);
2661 func = PyMethod_GET_FUNCTION(func);
2662 Py_INCREF(func);
2663 Py_DECREF(*pfunc);
2664 *pfunc = self;
2665 na++;
Brett Cannonb94767f2011-02-22 20:15:44 +00002666 /* n++; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 } else
2668 Py_INCREF(func);
2669 sp = stack_pointer;
2670 READ_TIMESTAMP(intr0);
2671 x = ext_do_call(func, &sp, flags, na, nk);
2672 READ_TIMESTAMP(intr1);
2673 stack_pointer = sp;
2674 Py_DECREF(func);
Jeremy Hylton52820442001-01-03 23:52:36 +00002675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 while (stack_pointer > pfunc) {
2677 w = POP();
2678 Py_DECREF(w);
2679 }
2680 PUSH(x);
2681 if (x != NULL)
2682 DISPATCH();
2683 break;
2684 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function)
2687 TARGET(MAKE_FUNCTION)
2688 _make_function:
2689 {
2690 int posdefaults = oparg & 0xff;
2691 int kwdefaults = (oparg>>8) & 0xff;
2692 int num_annotations = (oparg >> 16) & 0x7fff;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 v = POP(); /* code object */
2695 x = PyFunction_New(v, f->f_globals);
2696 Py_DECREF(v);
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00002697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 if (x != NULL && opcode == MAKE_CLOSURE) {
2699 v = POP();
2700 if (PyFunction_SetClosure(x, v) != 0) {
2701 /* Can't happen unless bytecode is corrupt. */
2702 why = WHY_EXCEPTION;
2703 }
2704 Py_DECREF(v);
2705 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 if (x != NULL && num_annotations > 0) {
2708 Py_ssize_t name_ix;
2709 u = POP(); /* names of args with annotations */
2710 v = PyDict_New();
2711 if (v == NULL) {
2712 Py_DECREF(x);
2713 x = NULL;
2714 break;
2715 }
2716 name_ix = PyTuple_Size(u);
2717 assert(num_annotations == name_ix+1);
2718 while (name_ix > 0) {
2719 --name_ix;
2720 t = PyTuple_GET_ITEM(u, name_ix);
2721 w = POP();
2722 /* XXX(nnorwitz): check for errors */
2723 PyDict_SetItem(v, t, w);
2724 Py_DECREF(w);
2725 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 if (PyFunction_SetAnnotations(x, v) != 0) {
2728 /* Can't happen unless
2729 PyFunction_SetAnnotations changes. */
2730 why = WHY_EXCEPTION;
2731 }
2732 Py_DECREF(v);
2733 Py_DECREF(u);
2734 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 /* XXX Maybe this should be a separate opcode? */
2737 if (x != NULL && posdefaults > 0) {
2738 v = PyTuple_New(posdefaults);
2739 if (v == NULL) {
2740 Py_DECREF(x);
2741 x = NULL;
2742 break;
2743 }
2744 while (--posdefaults >= 0) {
2745 w = POP();
2746 PyTuple_SET_ITEM(v, posdefaults, w);
2747 }
2748 if (PyFunction_SetDefaults(x, v) != 0) {
2749 /* Can't happen unless
2750 PyFunction_SetDefaults changes. */
2751 why = WHY_EXCEPTION;
2752 }
2753 Py_DECREF(v);
2754 }
2755 if (x != NULL && kwdefaults > 0) {
2756 v = PyDict_New();
2757 if (v == NULL) {
2758 Py_DECREF(x);
2759 x = NULL;
2760 break;
2761 }
2762 while (--kwdefaults >= 0) {
2763 w = POP(); /* default value */
2764 u = POP(); /* kw only arg name */
2765 /* XXX(nnorwitz): check for errors */
2766 PyDict_SetItem(v, u, w);
2767 Py_DECREF(w);
2768 Py_DECREF(u);
2769 }
2770 if (PyFunction_SetKwDefaults(x, v) != 0) {
2771 /* Can't happen unless
2772 PyFunction_SetKwDefaults changes. */
2773 why = WHY_EXCEPTION;
2774 }
2775 Py_DECREF(v);
2776 }
2777 PUSH(x);
2778 break;
2779 }
Guido van Rossum8861b741996-07-30 16:49:37 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 TARGET(BUILD_SLICE)
2782 if (oparg == 3)
2783 w = POP();
2784 else
2785 w = NULL;
2786 v = POP();
2787 u = TOP();
2788 x = PySlice_New(u, v, w);
2789 Py_DECREF(u);
2790 Py_DECREF(v);
2791 Py_XDECREF(w);
2792 SET_TOP(x);
2793 if (x != NULL) DISPATCH();
2794 break;
Guido van Rossum8861b741996-07-30 16:49:37 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 TARGET(EXTENDED_ARG)
2797 opcode = NEXTOP();
2798 oparg = oparg<<16 | NEXTARG();
2799 goto dispatch_opcode;
Guido van Rossum8861b741996-07-30 16:49:37 +00002800
Antoine Pitrou042b1282010-08-13 21:15:58 +00002801#if USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 _unknown_opcode:
Antoine Pitroub52ec782009-01-25 16:34:23 +00002803#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 default:
2805 fprintf(stderr,
2806 "XXX lineno: %d, opcode: %d\n",
2807 PyFrame_GetLineNumber(f),
2808 opcode);
2809 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2810 why = WHY_EXCEPTION;
2811 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00002812
2813#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 }
Guido van Rossum04691fc1992-08-12 15:35:34 +00002815#endif
2816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 } /* switch */
Guido van Rossum374a9221991-04-04 10:40:29 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 on_error:
Guido van Rossumac7be682001-01-17 15:42:30 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 READ_TIMESTAMP(inst1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 /* Quickly continue if no error occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 if (why == WHY_NOT) {
2826 if (err == 0 && x != NULL) {
Guido van Rossum681d79a1995-07-18 14:51:37 +00002827#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 /* This check is expensive! */
2829 if (PyErr_Occurred())
2830 fprintf(stderr,
2831 "XXX undetected error\n");
2832 else {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002833#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 READ_TIMESTAMP(loop1);
2835 continue; /* Normal, fast path */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002836#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 }
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002838#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 }
2840 why = WHY_EXCEPTION;
2841 x = Py_None;
2842 err = 0;
2843 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* Double-check exception status */
Guido van Rossumac7be682001-01-17 15:42:30 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2848 if (!PyErr_Occurred()) {
2849 PyErr_SetString(PyExc_SystemError,
2850 "error return without exception set");
2851 why = WHY_EXCEPTION;
2852 }
2853 }
Guido van Rossumeb894eb1999-03-09 16:16:45 +00002854#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 else {
2856 /* This check is expensive! */
2857 if (PyErr_Occurred()) {
2858 char buf[128];
2859 sprintf(buf, "Stack unwind with exception "
2860 "set and why=%d", why);
2861 Py_FatalError(buf);
2862 }
2863 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002864#endif
2865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 /* Log traceback info if this is a real exception */
Guido van Rossumac7be682001-01-17 15:42:30 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 if (why == WHY_EXCEPTION) {
2869 PyTraceBack_Here(f);
Guido van Rossum96a42c81992-01-12 02:29:51 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 if (tstate->c_tracefunc != NULL)
2872 call_exc_trace(tstate->c_tracefunc,
2873 tstate->c_traceobj, f);
2874 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
Guido van Rossumac7be682001-01-17 15:42:30 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 if (why == WHY_RERAISE)
2879 why = WHY_EXCEPTION;
Guido van Rossum374a9221991-04-04 10:40:29 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 /* Unwind stacks if a (pseudo) exception occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002882
Raymond Hettinger1dd83092004-02-06 18:32:33 +00002883fast_block_end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 while (why != WHY_NOT && f->f_iblock > 0) {
2885 /* Peek at the current block. */
2886 PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1];
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 assert(why != WHY_YIELD);
2889 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
2890 why = WHY_NOT;
2891 JUMPTO(PyLong_AS_LONG(retval));
2892 Py_DECREF(retval);
2893 break;
2894 }
2895 /* Now we have to pop the block. */
2896 f->f_iblock--;
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 if (b->b_type == EXCEPT_HANDLER) {
2899 UNWIND_EXCEPT_HANDLER(b);
2900 continue;
2901 }
2902 UNWIND_BLOCK(b);
2903 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2904 why = WHY_NOT;
2905 JUMPTO(b->b_handler);
2906 break;
2907 }
2908 if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT
2909 || b->b_type == SETUP_FINALLY)) {
2910 PyObject *exc, *val, *tb;
2911 int handler = b->b_handler;
2912 /* Beware, this invalidates all b->b_* fields */
2913 PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL());
2914 PUSH(tstate->exc_traceback);
2915 PUSH(tstate->exc_value);
2916 if (tstate->exc_type != NULL) {
2917 PUSH(tstate->exc_type);
2918 }
2919 else {
2920 Py_INCREF(Py_None);
2921 PUSH(Py_None);
2922 }
2923 PyErr_Fetch(&exc, &val, &tb);
2924 /* Make the raw exception data
2925 available to the handler,
2926 so a program can emulate the
2927 Python main loop. */
2928 PyErr_NormalizeException(
2929 &exc, &val, &tb);
2930 PyException_SetTraceback(val, tb);
2931 Py_INCREF(exc);
2932 tstate->exc_type = exc;
2933 Py_INCREF(val);
2934 tstate->exc_value = val;
2935 tstate->exc_traceback = tb;
2936 if (tb == NULL)
2937 tb = Py_None;
2938 Py_INCREF(tb);
2939 PUSH(tb);
2940 PUSH(val);
2941 PUSH(exc);
2942 why = WHY_NOT;
2943 JUMPTO(handler);
2944 break;
2945 }
2946 if (b->b_type == SETUP_FINALLY) {
2947 if (why & (WHY_RETURN | WHY_CONTINUE))
2948 PUSH(retval);
2949 PUSH(PyLong_FromLong((long)why));
2950 why = WHY_NOT;
2951 JUMPTO(b->b_handler);
2952 break;
2953 }
2954 } /* unwind stack */
Guido van Rossum374a9221991-04-04 10:40:29 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 /* End the loop if we still have an error (or return) */
Guido van Rossumac7be682001-01-17 15:42:30 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 if (why != WHY_NOT)
2959 break;
2960 READ_TIMESTAMP(loop1);
Guido van Rossumac7be682001-01-17 15:42:30 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 } /* main loop */
Guido van Rossumac7be682001-01-17 15:42:30 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 assert(why != WHY_YIELD);
2965 /* Pop remaining stack entries. */
2966 while (!EMPTY()) {
2967 v = POP();
2968 Py_XDECREF(v);
2969 }
Guido van Rossum35974fb2001-12-06 21:28:18 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 if (why != WHY_RETURN)
2972 retval = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00002973
Raymond Hettinger1dd83092004-02-06 18:32:33 +00002974fast_yield:
Benjamin Petersonac913412011-07-03 16:25:11 -05002975 if (co->co_flags & CO_GENERATOR && (why == WHY_YIELD || why == WHY_RETURN)) {
2976 /* The purpose of this block is to put aside the generator's exception
2977 state and restore that of the calling frame. If the current
2978 exception state is from the caller, we clear the exception values
2979 on the generator frame, so they are not swapped back in latter. The
2980 origin of the current exception state is determined by checking for
2981 except handler blocks, which we must be in iff a new exception
2982 state came into existence in this frame. (An uncaught exception
2983 would have why == WHY_EXCEPTION, and we wouldn't be here). */
2984 int i;
2985 for (i = 0; i < f->f_iblock; i++)
2986 if (f->f_blockstack[i].b_type == EXCEPT_HANDLER)
2987 break;
2988 if (i == f->f_iblock)
2989 /* We did not create this exception. */
Benjamin Peterson87880242011-07-03 16:48:31 -05002990 restore_and_clear_exc_state(tstate, f);
Benjamin Petersonac913412011-07-03 16:25:11 -05002991 else
Benjamin Peterson87880242011-07-03 16:48:31 -05002992 swap_exc_state(tstate, f);
Benjamin Petersonac913412011-07-03 16:25:11 -05002993 }
Benjamin Peterson83195c32011-07-03 13:44:00 -05002994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 if (tstate->use_tracing) {
2996 if (tstate->c_tracefunc) {
2997 if (why == WHY_RETURN || why == WHY_YIELD) {
2998 if (call_trace(tstate->c_tracefunc,
2999 tstate->c_traceobj, f,
3000 PyTrace_RETURN, retval)) {
3001 Py_XDECREF(retval);
3002 retval = NULL;
3003 why = WHY_EXCEPTION;
3004 }
3005 }
3006 else if (why == WHY_EXCEPTION) {
3007 call_trace_protected(tstate->c_tracefunc,
3008 tstate->c_traceobj, f,
3009 PyTrace_RETURN, NULL);
3010 }
3011 }
3012 if (tstate->c_profilefunc) {
3013 if (why == WHY_EXCEPTION)
3014 call_trace_protected(tstate->c_profilefunc,
3015 tstate->c_profileobj, f,
3016 PyTrace_RETURN, NULL);
3017 else if (call_trace(tstate->c_profilefunc,
3018 tstate->c_profileobj, f,
3019 PyTrace_RETURN, retval)) {
3020 Py_XDECREF(retval);
3021 retval = NULL;
Brett Cannonb94767f2011-02-22 20:15:44 +00003022 /* why = WHY_EXCEPTION; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 }
3024 }
3025 }
Guido van Rossuma4240131997-01-21 21:18:36 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 /* pop frame */
Thomas Woutersce272b62007-09-19 21:19:28 +00003028exit_eval_frame:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 Py_LeaveRecursiveCall();
3030 tstate->frame = f->f_back;
Guido van Rossumac7be682001-01-17 15:42:30 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 return retval;
Guido van Rossum374a9221991-04-04 10:40:29 +00003033}
3034
Benjamin Petersonb204a422011-06-05 22:04:07 -05003035static void
Benjamin Petersone109c702011-06-24 09:37:26 -05003036format_missing(const char *kind, PyCodeObject *co, PyObject *names)
3037{
3038 int err;
3039 Py_ssize_t len = PyList_GET_SIZE(names);
3040 PyObject *name_str, *comma, *tail, *tmp;
3041
3042 assert(PyList_CheckExact(names));
3043 assert(len >= 1);
3044 /* Deal with the joys of natural language. */
3045 switch (len) {
3046 case 1:
3047 name_str = PyList_GET_ITEM(names, 0);
3048 Py_INCREF(name_str);
3049 break;
3050 case 2:
3051 name_str = PyUnicode_FromFormat("%U and %U",
3052 PyList_GET_ITEM(names, len - 2),
3053 PyList_GET_ITEM(names, len - 1));
3054 break;
3055 default:
3056 tail = PyUnicode_FromFormat(", %U, and %U",
3057 PyList_GET_ITEM(names, len - 2),
3058 PyList_GET_ITEM(names, len - 1));
3059 /* Chop off the last two objects in the list. This shouldn't actually
3060 fail, but we can't be too careful. */
3061 err = PyList_SetSlice(names, len - 2, len, NULL);
3062 if (err == -1) {
3063 Py_DECREF(tail);
3064 return;
3065 }
3066 /* Stitch everything up into a nice comma-separated list. */
3067 comma = PyUnicode_FromString(", ");
3068 if (comma == NULL) {
3069 Py_DECREF(tail);
3070 return;
3071 }
3072 tmp = PyUnicode_Join(comma, names);
3073 Py_DECREF(comma);
3074 if (tmp == NULL) {
3075 Py_DECREF(tail);
3076 return;
3077 }
3078 name_str = PyUnicode_Concat(tmp, tail);
3079 Py_DECREF(tmp);
3080 Py_DECREF(tail);
3081 break;
3082 }
3083 if (name_str == NULL)
3084 return;
3085 PyErr_Format(PyExc_TypeError,
3086 "%U() missing %i required %s argument%s: %U",
3087 co->co_name,
3088 len,
3089 kind,
3090 len == 1 ? "" : "s",
3091 name_str);
3092 Py_DECREF(name_str);
3093}
3094
3095static void
3096missing_arguments(PyCodeObject *co, int missing, int defcount,
3097 PyObject **fastlocals)
3098{
3099 int i, j = 0;
3100 int start, end;
3101 int positional = defcount != -1;
3102 const char *kind = positional ? "positional" : "keyword-only";
3103 PyObject *missing_names;
3104
3105 /* Compute the names of the arguments that are missing. */
3106 missing_names = PyList_New(missing);
3107 if (missing_names == NULL)
3108 return;
3109 if (positional) {
3110 start = 0;
3111 end = co->co_argcount - defcount;
3112 }
3113 else {
3114 start = co->co_argcount;
3115 end = start + co->co_kwonlyargcount;
3116 }
3117 for (i = start; i < end; i++) {
3118 if (GETLOCAL(i) == NULL) {
3119 PyObject *raw = PyTuple_GET_ITEM(co->co_varnames, i);
3120 PyObject *name = PyObject_Repr(raw);
3121 if (name == NULL) {
3122 Py_DECREF(missing_names);
3123 return;
3124 }
3125 PyList_SET_ITEM(missing_names, j++, name);
3126 }
3127 }
3128 assert(j == missing);
3129 format_missing(kind, co, missing_names);
3130 Py_DECREF(missing_names);
3131}
3132
3133static void
3134too_many_positional(PyCodeObject *co, int given, int defcount, PyObject **fastlocals)
Benjamin Petersonb204a422011-06-05 22:04:07 -05003135{
3136 int plural;
3137 int kwonly_given = 0;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003138 int i;
3139 PyObject *sig, *kwonly_sig;
3140
Benjamin Petersone109c702011-06-24 09:37:26 -05003141 assert((co->co_flags & CO_VARARGS) == 0);
3142 /* Count missing keyword-only args. */
Benjamin Petersonb204a422011-06-05 22:04:07 -05003143 for (i = co->co_argcount; i < co->co_argcount + co->co_kwonlyargcount; i++)
Benjamin Petersone109c702011-06-24 09:37:26 -05003144 if (GETLOCAL(i) != NULL)
Benjamin Petersonb204a422011-06-05 22:04:07 -05003145 kwonly_given++;
Benjamin Petersone109c702011-06-24 09:37:26 -05003146 if (defcount) {
3147 int atleast = co->co_argcount - defcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003148 plural = 1;
3149 sig = PyUnicode_FromFormat("from %d to %d", atleast, co->co_argcount);
3150 }
3151 else {
3152 plural = co->co_argcount != 1;
3153 sig = PyUnicode_FromFormat("%d", co->co_argcount);
3154 }
3155 if (sig == NULL)
3156 return;
3157 if (kwonly_given) {
3158 const char *format = " positional argument%s (and %d keyword-only argument%s)";
3159 kwonly_sig = PyUnicode_FromFormat(format, given != 1 ? "s" : "", kwonly_given,
3160 kwonly_given != 1 ? "s" : "");
3161 if (kwonly_sig == NULL) {
3162 Py_DECREF(sig);
3163 return;
3164 }
3165 }
3166 else {
3167 /* This will not fail. */
3168 kwonly_sig = PyUnicode_FromString("");
Benjamin Petersone109c702011-06-24 09:37:26 -05003169 assert(kwonly_sig != NULL);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003170 }
3171 PyErr_Format(PyExc_TypeError,
3172 "%U() takes %U positional argument%s but %d%U %s given",
3173 co->co_name,
3174 sig,
3175 plural ? "s" : "",
3176 given,
3177 kwonly_sig,
3178 given == 1 && !kwonly_given ? "was" : "were");
3179 Py_DECREF(sig);
3180 Py_DECREF(kwonly_sig);
3181}
3182
Guido van Rossumc2e20742006-02-27 22:32:47 +00003183/* This is gonna seem *real weird*, but if you put some other code between
Martin v. Löwis8d97e332004-06-27 15:43:12 +00003184 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
Guido van Rossumc2e20742006-02-27 22:32:47 +00003185 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
Skip Montanaro786ea6b2004-03-01 15:44:05 +00003186
Tim Peters6d6c1a32001-08-02 04:15:00 +00003187PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003188PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 PyObject **args, int argcount, PyObject **kws, int kwcount,
3190 PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure)
Tim Peters5ca576e2001-06-18 22:08:13 +00003191{
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003192 PyCodeObject* co = (PyCodeObject*)_co;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 register PyFrameObject *f;
3194 register PyObject *retval = NULL;
3195 register PyObject **fastlocals, **freevars;
3196 PyThreadState *tstate = PyThreadState_GET();
3197 PyObject *x, *u;
3198 int total_args = co->co_argcount + co->co_kwonlyargcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003199 int i;
3200 int n = argcount;
3201 PyObject *kwdict = NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 if (globals == NULL) {
3204 PyErr_SetString(PyExc_SystemError,
3205 "PyEval_EvalCodeEx: NULL globals");
3206 return NULL;
3207 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 assert(tstate != NULL);
3210 assert(globals != NULL);
3211 f = PyFrame_New(tstate, co, globals, locals);
3212 if (f == NULL)
3213 return NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 fastlocals = f->f_localsplus;
3216 freevars = f->f_localsplus + co->co_nlocals;
Tim Peters5ca576e2001-06-18 22:08:13 +00003217
Benjamin Petersonb204a422011-06-05 22:04:07 -05003218 /* Parse arguments. */
3219 if (co->co_flags & CO_VARKEYWORDS) {
3220 kwdict = PyDict_New();
3221 if (kwdict == NULL)
3222 goto fail;
3223 i = total_args;
3224 if (co->co_flags & CO_VARARGS)
3225 i++;
3226 SETLOCAL(i, kwdict);
3227 }
3228 if (argcount > co->co_argcount)
3229 n = co->co_argcount;
3230 for (i = 0; i < n; i++) {
3231 x = args[i];
3232 Py_INCREF(x);
3233 SETLOCAL(i, x);
3234 }
3235 if (co->co_flags & CO_VARARGS) {
3236 u = PyTuple_New(argcount - n);
3237 if (u == NULL)
3238 goto fail;
3239 SETLOCAL(total_args, u);
3240 for (i = n; i < argcount; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 x = args[i];
3242 Py_INCREF(x);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003243 PyTuple_SET_ITEM(u, i-n, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003245 }
3246 for (i = 0; i < kwcount; i++) {
3247 PyObject **co_varnames;
3248 PyObject *keyword = kws[2*i];
3249 PyObject *value = kws[2*i + 1];
3250 int j;
3251 if (keyword == NULL || !PyUnicode_Check(keyword)) {
3252 PyErr_Format(PyExc_TypeError,
3253 "%U() keywords must be strings",
3254 co->co_name);
3255 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003257 /* Speed hack: do raw pointer compares. As names are
3258 normally interned this should almost always hit. */
3259 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
3260 for (j = 0; j < total_args; j++) {
3261 PyObject *nm = co_varnames[j];
3262 if (nm == keyword)
3263 goto kw_found;
3264 }
3265 /* Slow fallback, just in case */
3266 for (j = 0; j < total_args; j++) {
3267 PyObject *nm = co_varnames[j];
3268 int cmp = PyObject_RichCompareBool(
3269 keyword, nm, Py_EQ);
3270 if (cmp > 0)
3271 goto kw_found;
3272 else if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 goto fail;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003274 }
3275 if (j >= total_args && kwdict == NULL) {
3276 PyErr_Format(PyExc_TypeError,
3277 "%U() got an unexpected "
3278 "keyword argument '%S'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 co->co_name,
3280 keyword);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003281 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003283 PyDict_SetItem(kwdict, keyword, value);
3284 continue;
3285 kw_found:
3286 if (GETLOCAL(j) != NULL) {
3287 PyErr_Format(PyExc_TypeError,
3288 "%U() got multiple "
3289 "values for argument '%S'",
3290 co->co_name,
3291 keyword);
3292 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003294 Py_INCREF(value);
3295 SETLOCAL(j, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003297 if (argcount > co->co_argcount && !(co->co_flags & CO_VARARGS)) {
Benjamin Petersone109c702011-06-24 09:37:26 -05003298 too_many_positional(co, argcount, defcount, fastlocals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 goto fail;
3300 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003301 if (argcount < co->co_argcount) {
3302 int m = co->co_argcount - defcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05003303 int missing = 0;
3304 for (i = argcount; i < m; i++)
3305 if (GETLOCAL(i) == NULL)
3306 missing++;
3307 if (missing) {
3308 missing_arguments(co, missing, defcount, fastlocals);
3309 goto fail;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003310 }
3311 if (n > m)
3312 i = n - m;
3313 else
3314 i = 0;
3315 for (; i < defcount; i++) {
3316 if (GETLOCAL(m+i) == NULL) {
3317 PyObject *def = defs[i];
3318 Py_INCREF(def);
3319 SETLOCAL(m+i, def);
3320 }
3321 }
3322 }
3323 if (co->co_kwonlyargcount > 0) {
Benjamin Petersone109c702011-06-24 09:37:26 -05003324 int missing = 0;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003325 for (i = co->co_argcount; i < total_args; i++) {
3326 PyObject *name;
3327 if (GETLOCAL(i) != NULL)
3328 continue;
3329 name = PyTuple_GET_ITEM(co->co_varnames, i);
3330 if (kwdefs != NULL) {
3331 PyObject *def = PyDict_GetItem(kwdefs, name);
3332 if (def) {
3333 Py_INCREF(def);
3334 SETLOCAL(i, def);
3335 continue;
3336 }
3337 }
Benjamin Petersone109c702011-06-24 09:37:26 -05003338 missing++;
3339 }
3340 if (missing) {
3341 missing_arguments(co, missing, -1, fastlocals);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003342 goto fail;
3343 }
3344 }
3345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 /* Allocate and initialize storage for cell vars, and copy free
Benjamin Peterson90037602011-06-25 22:54:45 -05003347 vars into frame. */
3348 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 PyObject *c;
Benjamin Peterson90037602011-06-25 22:54:45 -05003350 int arg;
3351 /* Possibly account for the cell variable being an argument. */
3352 if (co->co_cell2arg != NULL &&
3353 (arg = co->co_cell2arg[i]) != CO_CELL_NOT_AN_ARG)
3354 c = PyCell_New(GETLOCAL(arg));
3355 else
3356 c = PyCell_New(NULL);
3357 if (c == NULL)
3358 goto fail;
3359 SETLOCAL(co->co_nlocals + i, c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 }
Benjamin Peterson90037602011-06-25 22:54:45 -05003361 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
3362 PyObject *o = PyTuple_GET_ITEM(closure, i);
3363 Py_INCREF(o);
3364 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 if (co->co_flags & CO_GENERATOR) {
3368 /* Don't need to keep the reference to f_back, it will be set
3369 * when the generator is resumed. */
3370 Py_XDECREF(f->f_back);
3371 f->f_back = NULL;
Neil Schemenauer2b13ce82001-06-21 02:41:10 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 PCALL(PCALL_GENERATOR);
Jeremy Hylton985eba52003-02-05 23:13:00 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 /* Create a new generator that owns the ready to run frame
3376 * and return that as the value. */
3377 return PyGen_New(f);
3378 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 retval = PyEval_EvalFrameEx(f,0);
Tim Peters5ca576e2001-06-18 22:08:13 +00003381
Thomas Woutersce272b62007-09-19 21:19:28 +00003382fail: /* Jump here from prelude on failure */
Tim Peters5ca576e2001-06-18 22:08:13 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 /* decref'ing the frame can cause __del__ methods to get invoked,
3385 which can call back into Python. While we're done with the
3386 current Python frame (f), the associated C stack is still in use,
3387 so recursion_depth must be boosted for the duration.
3388 */
3389 assert(tstate != NULL);
3390 ++tstate->recursion_depth;
3391 Py_DECREF(f);
3392 --tstate->recursion_depth;
3393 return retval;
Tim Peters5ca576e2001-06-18 22:08:13 +00003394}
3395
3396
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003397static PyObject *
3398special_lookup(PyObject *o, char *meth, PyObject **cache)
3399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 PyObject *res;
3401 res = _PyObject_LookupSpecial(o, meth, cache);
3402 if (res == NULL && !PyErr_Occurred()) {
3403 PyErr_SetObject(PyExc_AttributeError, *cache);
3404 return NULL;
3405 }
3406 return res;
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003407}
3408
3409
Benjamin Peterson87880242011-07-03 16:48:31 -05003410/* These 3 functions deal with the exception state of generators. */
3411
3412static void
3413save_exc_state(PyThreadState *tstate, PyFrameObject *f)
3414{
3415 PyObject *type, *value, *traceback;
3416 Py_XINCREF(tstate->exc_type);
3417 Py_XINCREF(tstate->exc_value);
3418 Py_XINCREF(tstate->exc_traceback);
3419 type = f->f_exc_type;
3420 value = f->f_exc_value;
3421 traceback = f->f_exc_traceback;
3422 f->f_exc_type = tstate->exc_type;
3423 f->f_exc_value = tstate->exc_value;
3424 f->f_exc_traceback = tstate->exc_traceback;
3425 Py_XDECREF(type);
3426 Py_XDECREF(value);
3427 Py_XDECREF(traceback);
3428}
3429
3430static void
3431swap_exc_state(PyThreadState *tstate, PyFrameObject *f)
3432{
3433 PyObject *tmp;
3434 tmp = tstate->exc_type;
3435 tstate->exc_type = f->f_exc_type;
3436 f->f_exc_type = tmp;
3437 tmp = tstate->exc_value;
3438 tstate->exc_value = f->f_exc_value;
3439 f->f_exc_value = tmp;
3440 tmp = tstate->exc_traceback;
3441 tstate->exc_traceback = f->f_exc_traceback;
3442 f->f_exc_traceback = tmp;
3443}
3444
3445static void
3446restore_and_clear_exc_state(PyThreadState *tstate, PyFrameObject *f)
3447{
3448 PyObject *type, *value, *tb;
3449 type = tstate->exc_type;
3450 value = tstate->exc_value;
3451 tb = tstate->exc_traceback;
3452 tstate->exc_type = f->f_exc_type;
3453 tstate->exc_value = f->f_exc_value;
3454 tstate->exc_traceback = f->f_exc_traceback;
3455 f->f_exc_type = NULL;
3456 f->f_exc_value = NULL;
3457 f->f_exc_traceback = NULL;
3458 Py_XDECREF(type);
3459 Py_XDECREF(value);
3460 Py_XDECREF(tb);
3461}
3462
3463
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003464/* Logic for the raise statement (too complicated for inlining).
3465 This *consumes* a reference count to each of its arguments. */
Raymond Hettinger7c958652004-04-06 10:11:10 +00003466static enum why_code
Collin Winter828f04a2007-08-31 00:04:24 +00003467do_raise(PyObject *exc, PyObject *cause)
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 PyObject *type = NULL, *value = NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 if (exc == NULL) {
3472 /* Reraise */
3473 PyThreadState *tstate = PyThreadState_GET();
3474 PyObject *tb;
3475 type = tstate->exc_type;
3476 value = tstate->exc_value;
3477 tb = tstate->exc_traceback;
3478 if (type == Py_None) {
3479 PyErr_SetString(PyExc_RuntimeError,
3480 "No active exception to reraise");
3481 return WHY_EXCEPTION;
3482 }
3483 Py_XINCREF(type);
3484 Py_XINCREF(value);
3485 Py_XINCREF(tb);
3486 PyErr_Restore(type, value, tb);
3487 return WHY_RERAISE;
3488 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 /* We support the following forms of raise:
3491 raise
Collin Winter828f04a2007-08-31 00:04:24 +00003492 raise <instance>
3493 raise <type> */
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 if (PyExceptionClass_Check(exc)) {
3496 type = exc;
3497 value = PyObject_CallObject(exc, NULL);
3498 if (value == NULL)
3499 goto raise_error;
3500 }
3501 else if (PyExceptionInstance_Check(exc)) {
3502 value = exc;
3503 type = PyExceptionInstance_Class(exc);
3504 Py_INCREF(type);
3505 }
3506 else {
3507 /* Not something you can raise. You get an exception
3508 anyway, just not what you specified :-) */
3509 Py_DECREF(exc);
3510 PyErr_SetString(PyExc_TypeError,
3511 "exceptions must derive from BaseException");
3512 goto raise_error;
3513 }
Collin Winter828f04a2007-08-31 00:04:24 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 if (cause) {
3516 PyObject *fixed_cause;
3517 if (PyExceptionClass_Check(cause)) {
3518 fixed_cause = PyObject_CallObject(cause, NULL);
3519 if (fixed_cause == NULL)
3520 goto raise_error;
3521 Py_DECREF(cause);
3522 }
3523 else if (PyExceptionInstance_Check(cause)) {
3524 fixed_cause = cause;
3525 }
3526 else {
3527 PyErr_SetString(PyExc_TypeError,
3528 "exception causes must derive from "
3529 "BaseException");
3530 goto raise_error;
3531 }
3532 PyException_SetCause(value, fixed_cause);
3533 }
Collin Winter828f04a2007-08-31 00:04:24 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 PyErr_SetObject(type, value);
3536 /* PyErr_SetObject incref's its arguments */
3537 Py_XDECREF(value);
3538 Py_XDECREF(type);
3539 return WHY_EXCEPTION;
Collin Winter828f04a2007-08-31 00:04:24 +00003540
3541raise_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 Py_XDECREF(value);
3543 Py_XDECREF(type);
3544 Py_XDECREF(cause);
3545 return WHY_EXCEPTION;
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003546}
3547
Tim Petersd6d010b2001-06-21 02:49:55 +00003548/* Iterate v argcnt times and store the results on the stack (via decreasing
Guido van Rossum0368b722007-05-11 16:50:42 +00003549 sp). Return 1 for success, 0 if error.
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00003550
Guido van Rossum0368b722007-05-11 16:50:42 +00003551 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
3552 with a variable target.
3553*/
Tim Petersd6d010b2001-06-21 02:49:55 +00003554
Barry Warsawe42b18f1997-08-25 22:13:04 +00003555static int
Guido van Rossum0368b722007-05-11 16:50:42 +00003556unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp)
Barry Warsawe42b18f1997-08-25 22:13:04 +00003557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 int i = 0, j = 0;
3559 Py_ssize_t ll = 0;
3560 PyObject *it; /* iter(v) */
3561 PyObject *w;
3562 PyObject *l = NULL; /* variable list */
Guido van Rossumac7be682001-01-17 15:42:30 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 assert(v != NULL);
Tim Petersd6d010b2001-06-21 02:49:55 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 it = PyObject_GetIter(v);
3567 if (it == NULL)
3568 goto Error;
Tim Petersd6d010b2001-06-21 02:49:55 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 for (; i < argcnt; i++) {
3571 w = PyIter_Next(it);
3572 if (w == NULL) {
3573 /* Iterator done, via error or exhaustion. */
3574 if (!PyErr_Occurred()) {
3575 PyErr_Format(PyExc_ValueError,
3576 "need more than %d value%s to unpack",
3577 i, i == 1 ? "" : "s");
3578 }
3579 goto Error;
3580 }
3581 *--sp = w;
3582 }
Tim Petersd6d010b2001-06-21 02:49:55 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 if (argcntafter == -1) {
3585 /* We better have exhausted the iterator now. */
3586 w = PyIter_Next(it);
3587 if (w == NULL) {
3588 if (PyErr_Occurred())
3589 goto Error;
3590 Py_DECREF(it);
3591 return 1;
3592 }
3593 Py_DECREF(w);
Georg Brandl0310a832010-07-10 10:32:36 +00003594 PyErr_Format(PyExc_ValueError, "too many values to unpack "
3595 "(expected %d)", argcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 goto Error;
3597 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 l = PySequence_List(it);
3600 if (l == NULL)
3601 goto Error;
3602 *--sp = l;
3603 i++;
Guido van Rossum0368b722007-05-11 16:50:42 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 ll = PyList_GET_SIZE(l);
3606 if (ll < argcntafter) {
3607 PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack",
3608 argcnt + ll);
3609 goto Error;
3610 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 /* Pop the "after-variable" args off the list. */
3613 for (j = argcntafter; j > 0; j--, i++) {
3614 *--sp = PyList_GET_ITEM(l, ll - j);
3615 }
3616 /* Resize the list. */
3617 Py_SIZE(l) = ll - argcntafter;
3618 Py_DECREF(it);
3619 return 1;
Guido van Rossum0368b722007-05-11 16:50:42 +00003620
Tim Petersd6d010b2001-06-21 02:49:55 +00003621Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 for (; i > 0; i--, sp++)
3623 Py_DECREF(*sp);
3624 Py_XDECREF(it);
3625 return 0;
Barry Warsawe42b18f1997-08-25 22:13:04 +00003626}
3627
3628
Guido van Rossum96a42c81992-01-12 02:29:51 +00003629#ifdef LLTRACE
Guido van Rossum3f5da241990-12-20 15:06:42 +00003630static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003631prtrace(PyObject *v, char *str)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 printf("%s ", str);
3634 if (PyObject_Print(v, stdout, 0) != 0)
3635 PyErr_Clear(); /* Don't know what else to do */
3636 printf("\n");
3637 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003638}
Guido van Rossum3f5da241990-12-20 15:06:42 +00003639#endif
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003640
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003641static void
Fred Drake5755ce62001-06-27 19:19:46 +00003642call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 PyObject *type, *value, *traceback, *arg;
3645 int err;
3646 PyErr_Fetch(&type, &value, &traceback);
3647 if (value == NULL) {
3648 value = Py_None;
3649 Py_INCREF(value);
3650 }
3651 arg = PyTuple_Pack(3, type, value, traceback);
3652 if (arg == NULL) {
3653 PyErr_Restore(type, value, traceback);
3654 return;
3655 }
3656 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
3657 Py_DECREF(arg);
3658 if (err == 0)
3659 PyErr_Restore(type, value, traceback);
3660 else {
3661 Py_XDECREF(type);
3662 Py_XDECREF(value);
3663 Py_XDECREF(traceback);
3664 }
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003665}
3666
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +00003667static int
Fred Drake4ec5d562001-10-04 19:26:43 +00003668call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 int what, PyObject *arg)
Fred Drake4ec5d562001-10-04 19:26:43 +00003670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 PyObject *type, *value, *traceback;
3672 int err;
3673 PyErr_Fetch(&type, &value, &traceback);
3674 err = call_trace(func, obj, frame, what, arg);
3675 if (err == 0)
3676 {
3677 PyErr_Restore(type, value, traceback);
3678 return 0;
3679 }
3680 else {
3681 Py_XDECREF(type);
3682 Py_XDECREF(value);
3683 Py_XDECREF(traceback);
3684 return -1;
3685 }
Fred Drake4ec5d562001-10-04 19:26:43 +00003686}
3687
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003688static int
Fred Drake5755ce62001-06-27 19:19:46 +00003689call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 int what, PyObject *arg)
Guido van Rossum96a42c81992-01-12 02:29:51 +00003691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 register PyThreadState *tstate = frame->f_tstate;
3693 int result;
3694 if (tstate->tracing)
3695 return 0;
3696 tstate->tracing++;
3697 tstate->use_tracing = 0;
3698 result = func(obj, frame, what, arg);
3699 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3700 || (tstate->c_profilefunc != NULL));
3701 tstate->tracing--;
3702 return result;
Guido van Rossum96a42c81992-01-12 02:29:51 +00003703}
3704
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003705PyObject *
3706_PyEval_CallTracing(PyObject *func, PyObject *args)
3707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 PyFrameObject *frame = PyEval_GetFrame();
3709 PyThreadState *tstate = frame->f_tstate;
3710 int save_tracing = tstate->tracing;
3711 int save_use_tracing = tstate->use_tracing;
3712 PyObject *result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 tstate->tracing = 0;
3715 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3716 || (tstate->c_profilefunc != NULL));
3717 result = PyObject_Call(func, args, NULL);
3718 tstate->tracing = save_tracing;
3719 tstate->use_tracing = save_use_tracing;
3720 return result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003721}
3722
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003723/* See Objects/lnotab_notes.txt for a description of how tracing works. */
Michael W. Hudson006c7522002-11-08 13:08:46 +00003724static int
Tim Peters8a5c3c72004-04-05 19:36:21 +00003725maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 PyFrameObject *frame, int *instr_lb, int *instr_ub,
3727 int *instr_prev)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 int result = 0;
3730 int line = frame->f_lineno;
Michael W. Hudson006c7522002-11-08 13:08:46 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 /* If the last instruction executed isn't in the current
3733 instruction window, reset the window.
3734 */
3735 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
3736 PyAddrPair bounds;
3737 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
3738 &bounds);
3739 *instr_lb = bounds.ap_lower;
3740 *instr_ub = bounds.ap_upper;
3741 }
3742 /* If the last instruction falls at the start of a line or if
3743 it represents a jump backwards, update the frame's line
3744 number and call the trace function. */
3745 if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
3746 frame->f_lineno = line;
3747 result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
3748 }
3749 *instr_prev = frame->f_lasti;
3750 return result;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003751}
3752
Fred Drake5755ce62001-06-27 19:19:46 +00003753void
3754PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
Fred Draked0838392001-06-16 21:02:31 +00003755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 PyThreadState *tstate = PyThreadState_GET();
3757 PyObject *temp = tstate->c_profileobj;
3758 Py_XINCREF(arg);
3759 tstate->c_profilefunc = NULL;
3760 tstate->c_profileobj = NULL;
3761 /* Must make sure that tracing is not ignored if 'temp' is freed */
3762 tstate->use_tracing = tstate->c_tracefunc != NULL;
3763 Py_XDECREF(temp);
3764 tstate->c_profilefunc = func;
3765 tstate->c_profileobj = arg;
3766 /* Flag that tracing or profiling is turned on */
3767 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
Fred Drake5755ce62001-06-27 19:19:46 +00003768}
3769
3770void
3771PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
3772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 PyThreadState *tstate = PyThreadState_GET();
3774 PyObject *temp = tstate->c_traceobj;
3775 _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
3776 Py_XINCREF(arg);
3777 tstate->c_tracefunc = NULL;
3778 tstate->c_traceobj = NULL;
3779 /* Must make sure that profiling is not ignored if 'temp' is freed */
3780 tstate->use_tracing = tstate->c_profilefunc != NULL;
3781 Py_XDECREF(temp);
3782 tstate->c_tracefunc = func;
3783 tstate->c_traceobj = arg;
3784 /* Flag that tracing or profiling is turned on */
3785 tstate->use_tracing = ((func != NULL)
3786 || (tstate->c_profilefunc != NULL));
Fred Draked0838392001-06-16 21:02:31 +00003787}
3788
Guido van Rossumb209a111997-04-29 18:18:01 +00003789PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003790PyEval_GetBuiltins(void)
Guido van Rossum6135a871995-01-09 17:53:26 +00003791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 PyFrameObject *current_frame = PyEval_GetFrame();
3793 if (current_frame == NULL)
3794 return PyThreadState_GET()->interp->builtins;
3795 else
3796 return current_frame->f_builtins;
Guido van Rossum6135a871995-01-09 17:53:26 +00003797}
3798
Guido van Rossumb209a111997-04-29 18:18:01 +00003799PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003800PyEval_GetLocals(void)
Guido van Rossum5b722181993-03-30 17:46:03 +00003801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 PyFrameObject *current_frame = PyEval_GetFrame();
3803 if (current_frame == NULL)
3804 return NULL;
3805 PyFrame_FastToLocals(current_frame);
3806 return current_frame->f_locals;
Guido van Rossum5b722181993-03-30 17:46:03 +00003807}
3808
Guido van Rossumb209a111997-04-29 18:18:01 +00003809PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003810PyEval_GetGlobals(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 PyFrameObject *current_frame = PyEval_GetFrame();
3813 if (current_frame == NULL)
3814 return NULL;
3815 else
3816 return current_frame->f_globals;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003817}
3818
Guido van Rossum6297a7a2003-02-19 15:53:17 +00003819PyFrameObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003820PyEval_GetFrame(void)
Guido van Rossume59214e1994-08-30 08:01:59 +00003821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 PyThreadState *tstate = PyThreadState_GET();
3823 return _PyThreadState_GetFrame(tstate);
Guido van Rossume59214e1994-08-30 08:01:59 +00003824}
3825
Guido van Rossum6135a871995-01-09 17:53:26 +00003826int
Tim Peters5ba58662001-07-16 02:29:45 +00003827PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Jeremy Hylton061d1062001-03-22 02:32:48 +00003828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 PyFrameObject *current_frame = PyEval_GetFrame();
3830 int result = cf->cf_flags != 0;
Tim Peters5ba58662001-07-16 02:29:45 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 if (current_frame != NULL) {
3833 const int codeflags = current_frame->f_code->co_flags;
3834 const int compilerflags = codeflags & PyCF_MASK;
3835 if (compilerflags) {
3836 result = 1;
3837 cf->cf_flags |= compilerflags;
3838 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003839#if 0 /* future keyword */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 if (codeflags & CO_GENERATOR_ALLOWED) {
3841 result = 1;
3842 cf->cf_flags |= CO_GENERATOR_ALLOWED;
3843 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003844#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 }
3846 return result;
Jeremy Hylton061d1062001-03-22 02:32:48 +00003847}
3848
Guido van Rossum3f5da241990-12-20 15:06:42 +00003849
Guido van Rossum681d79a1995-07-18 14:51:37 +00003850/* External interface to call any callable object.
Antoine Pitrou8689a102010-04-01 16:53:15 +00003851 The arg must be a tuple or NULL. The kw must be a dict or NULL. */
Guido van Rossume59214e1994-08-30 08:01:59 +00003852
Guido van Rossumb209a111997-04-29 18:18:01 +00003853PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003854PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 PyObject *result;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 if (arg == NULL) {
3859 arg = PyTuple_New(0);
3860 if (arg == NULL)
3861 return NULL;
3862 }
3863 else if (!PyTuple_Check(arg)) {
3864 PyErr_SetString(PyExc_TypeError,
3865 "argument list must be a tuple");
3866 return NULL;
3867 }
3868 else
3869 Py_INCREF(arg);
Guido van Rossum681d79a1995-07-18 14:51:37 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if (kw != NULL && !PyDict_Check(kw)) {
3872 PyErr_SetString(PyExc_TypeError,
3873 "keyword list must be a dictionary");
3874 Py_DECREF(arg);
3875 return NULL;
3876 }
Guido van Rossume3e61c11995-08-04 04:14:47 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 result = PyObject_Call(func, arg, kw);
3879 Py_DECREF(arg);
3880 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00003881}
3882
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003883const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884PyEval_GetFuncName(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 if (PyMethod_Check(func))
3887 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
3888 else if (PyFunction_Check(func))
3889 return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name);
3890 else if (PyCFunction_Check(func))
3891 return ((PyCFunctionObject*)func)->m_ml->ml_name;
3892 else
3893 return func->ob_type->tp_name;
Jeremy Hylton512a2372001-04-11 13:52:29 +00003894}
3895
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003896const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897PyEval_GetFuncDesc(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 if (PyMethod_Check(func))
3900 return "()";
3901 else if (PyFunction_Check(func))
3902 return "()";
3903 else if (PyCFunction_Check(func))
3904 return "()";
3905 else
3906 return " object";
Jeremy Hylton512a2372001-04-11 13:52:29 +00003907}
3908
Neal Norwitzaddfe0c2002-11-10 14:33:26 +00003909static void
Jeremy Hylton192690e2002-08-16 18:36:11 +00003910err_args(PyObject *func, int flags, int nargs)
3911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 if (flags & METH_NOARGS)
3913 PyErr_Format(PyExc_TypeError,
3914 "%.200s() takes no arguments (%d given)",
3915 ((PyCFunctionObject *)func)->m_ml->ml_name,
3916 nargs);
3917 else
3918 PyErr_Format(PyExc_TypeError,
3919 "%.200s() takes exactly one argument (%d given)",
3920 ((PyCFunctionObject *)func)->m_ml->ml_name,
3921 nargs);
Jeremy Hylton192690e2002-08-16 18:36:11 +00003922}
3923
Armin Rigo1c2d7e52005-09-20 18:34:01 +00003924#define C_TRACE(x, call) \
Nicholas Bastind858a772004-06-25 23:31:06 +00003925if (tstate->use_tracing && tstate->c_profilefunc) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 if (call_trace(tstate->c_profilefunc, \
3927 tstate->c_profileobj, \
3928 tstate->frame, PyTrace_C_CALL, \
3929 func)) { \
3930 x = NULL; \
3931 } \
3932 else { \
3933 x = call; \
3934 if (tstate->c_profilefunc != NULL) { \
3935 if (x == NULL) { \
3936 call_trace_protected(tstate->c_profilefunc, \
3937 tstate->c_profileobj, \
3938 tstate->frame, PyTrace_C_EXCEPTION, \
3939 func); \
3940 /* XXX should pass (type, value, tb) */ \
3941 } else { \
3942 if (call_trace(tstate->c_profilefunc, \
3943 tstate->c_profileobj, \
3944 tstate->frame, PyTrace_C_RETURN, \
3945 func)) { \
3946 Py_DECREF(x); \
3947 x = NULL; \
3948 } \
3949 } \
3950 } \
3951 } \
Nicholas Bastind858a772004-06-25 23:31:06 +00003952} else { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 x = call; \
3954 }
Nicholas Bastinc69ebe82004-03-24 21:57:10 +00003955
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003956static PyObject *
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003957call_function(PyObject ***pp_stack, int oparg
3958#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 , uint64* pintr0, uint64* pintr1
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003960#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 )
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 int na = oparg & 0xff;
3964 int nk = (oparg>>8) & 0xff;
3965 int n = na + 2 * nk;
3966 PyObject **pfunc = (*pp_stack) - n - 1;
3967 PyObject *func = *pfunc;
3968 PyObject *x, *w;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 /* Always dispatch PyCFunction first, because these are
3971 presumed to be the most frequent callable object.
3972 */
3973 if (PyCFunction_Check(func) && nk == 0) {
3974 int flags = PyCFunction_GET_FLAGS(func);
3975 PyThreadState *tstate = PyThreadState_GET();
Raymond Hettingera7f56bc2004-06-26 04:34:33 +00003976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 PCALL(PCALL_CFUNCTION);
3978 if (flags & (METH_NOARGS | METH_O)) {
3979 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
3980 PyObject *self = PyCFunction_GET_SELF(func);
3981 if (flags & METH_NOARGS && na == 0) {
3982 C_TRACE(x, (*meth)(self,NULL));
3983 }
3984 else if (flags & METH_O && na == 1) {
3985 PyObject *arg = EXT_POP(*pp_stack);
3986 C_TRACE(x, (*meth)(self,arg));
3987 Py_DECREF(arg);
3988 }
3989 else {
3990 err_args(func, flags, na);
3991 x = NULL;
3992 }
3993 }
3994 else {
3995 PyObject *callargs;
3996 callargs = load_args(pp_stack, na);
3997 READ_TIMESTAMP(*pintr0);
3998 C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
3999 READ_TIMESTAMP(*pintr1);
4000 Py_XDECREF(callargs);
4001 }
4002 } else {
4003 if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
4004 /* optimize access to bound methods */
4005 PyObject *self = PyMethod_GET_SELF(func);
4006 PCALL(PCALL_METHOD);
4007 PCALL(PCALL_BOUND_METHOD);
4008 Py_INCREF(self);
4009 func = PyMethod_GET_FUNCTION(func);
4010 Py_INCREF(func);
4011 Py_DECREF(*pfunc);
4012 *pfunc = self;
4013 na++;
4014 n++;
4015 } else
4016 Py_INCREF(func);
4017 READ_TIMESTAMP(*pintr0);
4018 if (PyFunction_Check(func))
4019 x = fast_function(func, pp_stack, n, na, nk);
4020 else
4021 x = do_call(func, pp_stack, na, nk);
4022 READ_TIMESTAMP(*pintr1);
4023 Py_DECREF(func);
4024 }
Tim Peters8a5c3c72004-04-05 19:36:21 +00004025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 /* Clear the stack of the function object. Also removes
4027 the arguments in case they weren't consumed already
4028 (fast_function() and err_args() leave them on the stack).
4029 */
4030 while ((*pp_stack) > pfunc) {
4031 w = EXT_POP(*pp_stack);
4032 Py_DECREF(w);
4033 PCALL(PCALL_POP);
4034 }
4035 return x;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00004036}
4037
Jeremy Hylton192690e2002-08-16 18:36:11 +00004038/* The fast_function() function optimize calls for which no argument
Jeremy Hylton52820442001-01-03 23:52:36 +00004039 tuple is necessary; the objects are passed directly from the stack.
Jeremy Hylton985eba52003-02-05 23:13:00 +00004040 For the simplest case -- a function that takes only positional
4041 arguments and is called with only positional arguments -- it
4042 inlines the most primitive frame setup code from
4043 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
4044 done before evaluating the frame.
Jeremy Hylton52820442001-01-03 23:52:36 +00004045*/
4046
4047static PyObject *
Guido van Rossumac7be682001-01-17 15:42:30 +00004048fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
Jeremy Hylton52820442001-01-03 23:52:36 +00004049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
4051 PyObject *globals = PyFunction_GET_GLOBALS(func);
4052 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
4053 PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func);
4054 PyObject **d = NULL;
4055 int nd = 0;
Jeremy Hylton52820442001-01-03 23:52:36 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 PCALL(PCALL_FUNCTION);
4058 PCALL(PCALL_FAST_FUNCTION);
4059 if (argdefs == NULL && co->co_argcount == n &&
4060 co->co_kwonlyargcount == 0 && nk==0 &&
4061 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
4062 PyFrameObject *f;
4063 PyObject *retval = NULL;
4064 PyThreadState *tstate = PyThreadState_GET();
4065 PyObject **fastlocals, **stack;
4066 int i;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 PCALL(PCALL_FASTER_FUNCTION);
4069 assert(globals != NULL);
4070 /* XXX Perhaps we should create a specialized
4071 PyFrame_New() that doesn't take locals, but does
4072 take builtins without sanity checking them.
4073 */
4074 assert(tstate != NULL);
4075 f = PyFrame_New(tstate, co, globals, NULL);
4076 if (f == NULL)
4077 return NULL;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 fastlocals = f->f_localsplus;
4080 stack = (*pp_stack) - n;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 for (i = 0; i < n; i++) {
4083 Py_INCREF(*stack);
4084 fastlocals[i] = *stack++;
4085 }
4086 retval = PyEval_EvalFrameEx(f,0);
4087 ++tstate->recursion_depth;
4088 Py_DECREF(f);
4089 --tstate->recursion_depth;
4090 return retval;
4091 }
4092 if (argdefs != NULL) {
4093 d = &PyTuple_GET_ITEM(argdefs, 0);
4094 nd = Py_SIZE(argdefs);
4095 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00004096 return PyEval_EvalCodeEx((PyObject*)co, globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 (PyObject *)NULL, (*pp_stack)-n, na,
4098 (*pp_stack)-2*nk, nk, d, nd, kwdefs,
4099 PyFunction_GET_CLOSURE(func));
Jeremy Hylton52820442001-01-03 23:52:36 +00004100}
4101
4102static PyObject *
Ka-Ping Yee20579702001-01-15 22:14:16 +00004103update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
4104 PyObject *func)
Jeremy Hylton52820442001-01-03 23:52:36 +00004105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 PyObject *kwdict = NULL;
4107 if (orig_kwdict == NULL)
4108 kwdict = PyDict_New();
4109 else {
4110 kwdict = PyDict_Copy(orig_kwdict);
4111 Py_DECREF(orig_kwdict);
4112 }
4113 if (kwdict == NULL)
4114 return NULL;
4115 while (--nk >= 0) {
4116 int err;
4117 PyObject *value = EXT_POP(*pp_stack);
4118 PyObject *key = EXT_POP(*pp_stack);
4119 if (PyDict_GetItem(kwdict, key) != NULL) {
4120 PyErr_Format(PyExc_TypeError,
4121 "%.200s%s got multiple values "
4122 "for keyword argument '%U'",
4123 PyEval_GetFuncName(func),
4124 PyEval_GetFuncDesc(func),
4125 key);
4126 Py_DECREF(key);
4127 Py_DECREF(value);
4128 Py_DECREF(kwdict);
4129 return NULL;
4130 }
4131 err = PyDict_SetItem(kwdict, key, value);
4132 Py_DECREF(key);
4133 Py_DECREF(value);
4134 if (err) {
4135 Py_DECREF(kwdict);
4136 return NULL;
4137 }
4138 }
4139 return kwdict;
Jeremy Hylton52820442001-01-03 23:52:36 +00004140}
4141
4142static PyObject *
4143update_star_args(int nstack, int nstar, PyObject *stararg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 PyObject ***pp_stack)
Jeremy Hylton52820442001-01-03 23:52:36 +00004145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 PyObject *callargs, *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 callargs = PyTuple_New(nstack + nstar);
4149 if (callargs == NULL) {
4150 return NULL;
4151 }
4152 if (nstar) {
4153 int i;
4154 for (i = 0; i < nstar; i++) {
4155 PyObject *a = PyTuple_GET_ITEM(stararg, i);
4156 Py_INCREF(a);
4157 PyTuple_SET_ITEM(callargs, nstack + i, a);
4158 }
4159 }
4160 while (--nstack >= 0) {
4161 w = EXT_POP(*pp_stack);
4162 PyTuple_SET_ITEM(callargs, nstack, w);
4163 }
4164 return callargs;
Jeremy Hylton52820442001-01-03 23:52:36 +00004165}
4166
4167static PyObject *
4168load_args(PyObject ***pp_stack, int na)
4169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 PyObject *args = PyTuple_New(na);
4171 PyObject *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 if (args == NULL)
4174 return NULL;
4175 while (--na >= 0) {
4176 w = EXT_POP(*pp_stack);
4177 PyTuple_SET_ITEM(args, na, w);
4178 }
4179 return args;
Jeremy Hylton52820442001-01-03 23:52:36 +00004180}
4181
4182static PyObject *
4183do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
4184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 PyObject *callargs = NULL;
4186 PyObject *kwdict = NULL;
4187 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 if (nk > 0) {
4190 kwdict = update_keyword_args(NULL, nk, pp_stack, func);
4191 if (kwdict == NULL)
4192 goto call_fail;
4193 }
4194 callargs = load_args(pp_stack, na);
4195 if (callargs == NULL)
4196 goto call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004197#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 /* At this point, we have to look at the type of func to
4199 update the call stats properly. Do it here so as to avoid
4200 exposing the call stats machinery outside ceval.c
4201 */
4202 if (PyFunction_Check(func))
4203 PCALL(PCALL_FUNCTION);
4204 else if (PyMethod_Check(func))
4205 PCALL(PCALL_METHOD);
4206 else if (PyType_Check(func))
4207 PCALL(PCALL_TYPE);
4208 else if (PyCFunction_Check(func))
4209 PCALL(PCALL_CFUNCTION);
4210 else
4211 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004212#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 if (PyCFunction_Check(func)) {
4214 PyThreadState *tstate = PyThreadState_GET();
4215 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4216 }
4217 else
4218 result = PyObject_Call(func, callargs, kwdict);
Thomas Wouters7ce29ca2007-09-19 21:56:32 +00004219call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 Py_XDECREF(callargs);
4221 Py_XDECREF(kwdict);
4222 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004223}
4224
4225static PyObject *
4226ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
4227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 int nstar = 0;
4229 PyObject *callargs = NULL;
4230 PyObject *stararg = NULL;
4231 PyObject *kwdict = NULL;
4232 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 if (flags & CALL_FLAG_KW) {
4235 kwdict = EXT_POP(*pp_stack);
4236 if (!PyDict_Check(kwdict)) {
4237 PyObject *d;
4238 d = PyDict_New();
4239 if (d == NULL)
4240 goto ext_call_fail;
4241 if (PyDict_Update(d, kwdict) != 0) {
4242 Py_DECREF(d);
4243 /* PyDict_Update raises attribute
4244 * error (percolated from an attempt
4245 * to get 'keys' attribute) instead of
4246 * a type error if its second argument
4247 * is not a mapping.
4248 */
4249 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
4250 PyErr_Format(PyExc_TypeError,
4251 "%.200s%.200s argument after ** "
4252 "must be a mapping, not %.200s",
4253 PyEval_GetFuncName(func),
4254 PyEval_GetFuncDesc(func),
4255 kwdict->ob_type->tp_name);
4256 }
4257 goto ext_call_fail;
4258 }
4259 Py_DECREF(kwdict);
4260 kwdict = d;
4261 }
4262 }
4263 if (flags & CALL_FLAG_VAR) {
4264 stararg = EXT_POP(*pp_stack);
4265 if (!PyTuple_Check(stararg)) {
4266 PyObject *t = NULL;
4267 t = PySequence_Tuple(stararg);
4268 if (t == NULL) {
4269 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4270 PyErr_Format(PyExc_TypeError,
4271 "%.200s%.200s argument after * "
Victor Stinner0a5f65a2011-03-22 01:09:21 +01004272 "must be a sequence, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 PyEval_GetFuncName(func),
4274 PyEval_GetFuncDesc(func),
4275 stararg->ob_type->tp_name);
4276 }
4277 goto ext_call_fail;
4278 }
4279 Py_DECREF(stararg);
4280 stararg = t;
4281 }
4282 nstar = PyTuple_GET_SIZE(stararg);
4283 }
4284 if (nk > 0) {
4285 kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
4286 if (kwdict == NULL)
4287 goto ext_call_fail;
4288 }
4289 callargs = update_star_args(na, nstar, stararg, pp_stack);
4290 if (callargs == NULL)
4291 goto ext_call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004292#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 /* At this point, we have to look at the type of func to
4294 update the call stats properly. Do it here so as to avoid
4295 exposing the call stats machinery outside ceval.c
4296 */
4297 if (PyFunction_Check(func))
4298 PCALL(PCALL_FUNCTION);
4299 else if (PyMethod_Check(func))
4300 PCALL(PCALL_METHOD);
4301 else if (PyType_Check(func))
4302 PCALL(PCALL_TYPE);
4303 else if (PyCFunction_Check(func))
4304 PCALL(PCALL_CFUNCTION);
4305 else
4306 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004307#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 if (PyCFunction_Check(func)) {
4309 PyThreadState *tstate = PyThreadState_GET();
4310 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4311 }
4312 else
4313 result = PyObject_Call(func, callargs, kwdict);
Thomas Woutersce272b62007-09-19 21:19:28 +00004314ext_call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 Py_XDECREF(callargs);
4316 Py_XDECREF(kwdict);
4317 Py_XDECREF(stararg);
4318 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004319}
4320
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004321/* Extract a slice index from a PyInt or PyLong or an object with the
4322 nb_index slot defined, and store in *pi.
4323 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
4324 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 +00004325 Return 0 on error, 1 on success.
Tim Peterscb479e72001-12-16 19:11:44 +00004326*/
Tim Petersb5196382001-12-16 19:44:20 +00004327/* Note: If v is NULL, return success without storing into *pi. This
4328 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
4329 called by the SLICE opcode with v and/or w equal to NULL.
Tim Peterscb479e72001-12-16 19:11:44 +00004330*/
Guido van Rossum20c6add2000-05-08 14:06:50 +00004331int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004332_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 if (v != NULL) {
4335 Py_ssize_t x;
4336 if (PyIndex_Check(v)) {
4337 x = PyNumber_AsSsize_t(v, NULL);
4338 if (x == -1 && PyErr_Occurred())
4339 return 0;
4340 }
4341 else {
4342 PyErr_SetString(PyExc_TypeError,
4343 "slice indices must be integers or "
4344 "None or have an __index__ method");
4345 return 0;
4346 }
4347 *pi = x;
4348 }
4349 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004350}
4351
Guido van Rossum486364b2007-06-30 05:01:58 +00004352#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 "BaseException is not allowed"
Brett Cannonf74225d2007-02-26 21:10:16 +00004354
Guido van Rossumb209a111997-04-29 18:18:01 +00004355static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004356cmp_outcome(int op, register PyObject *v, register PyObject *w)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 int res = 0;
4359 switch (op) {
4360 case PyCmp_IS:
4361 res = (v == w);
4362 break;
4363 case PyCmp_IS_NOT:
4364 res = (v != w);
4365 break;
4366 case PyCmp_IN:
4367 res = PySequence_Contains(w, v);
4368 if (res < 0)
4369 return NULL;
4370 break;
4371 case PyCmp_NOT_IN:
4372 res = PySequence_Contains(w, v);
4373 if (res < 0)
4374 return NULL;
4375 res = !res;
4376 break;
4377 case PyCmp_EXC_MATCH:
4378 if (PyTuple_Check(w)) {
4379 Py_ssize_t i, length;
4380 length = PyTuple_Size(w);
4381 for (i = 0; i < length; i += 1) {
4382 PyObject *exc = PyTuple_GET_ITEM(w, i);
4383 if (!PyExceptionClass_Check(exc)) {
4384 PyErr_SetString(PyExc_TypeError,
4385 CANNOT_CATCH_MSG);
4386 return NULL;
4387 }
4388 }
4389 }
4390 else {
4391 if (!PyExceptionClass_Check(w)) {
4392 PyErr_SetString(PyExc_TypeError,
4393 CANNOT_CATCH_MSG);
4394 return NULL;
4395 }
4396 }
4397 res = PyErr_GivenExceptionMatches(v, w);
4398 break;
4399 default:
4400 return PyObject_RichCompare(v, w, op);
4401 }
4402 v = res ? Py_True : Py_False;
4403 Py_INCREF(v);
4404 return v;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004405}
4406
Thomas Wouters52152252000-08-17 22:55:00 +00004407static PyObject *
4408import_from(PyObject *v, PyObject *name)
Guido van Rossume9736fc1990-11-18 17:33:06 +00004409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 PyObject *x;
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 x = PyObject_GetAttr(v, name);
4413 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
4414 PyErr_Format(PyExc_ImportError, "cannot import name %S", name);
4415 }
4416 return x;
Thomas Wouters52152252000-08-17 22:55:00 +00004417}
Guido van Rossumac7be682001-01-17 15:42:30 +00004418
Thomas Wouters52152252000-08-17 22:55:00 +00004419static int
4420import_all_from(PyObject *locals, PyObject *v)
4421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 PyObject *all = PyObject_GetAttrString(v, "__all__");
4423 PyObject *dict, *name, *value;
4424 int skip_leading_underscores = 0;
4425 int pos, err;
Thomas Wouters52152252000-08-17 22:55:00 +00004426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 if (all == NULL) {
4428 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4429 return -1; /* Unexpected error */
4430 PyErr_Clear();
4431 dict = PyObject_GetAttrString(v, "__dict__");
4432 if (dict == NULL) {
4433 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4434 return -1;
4435 PyErr_SetString(PyExc_ImportError,
4436 "from-import-* object has no __dict__ and no __all__");
4437 return -1;
4438 }
4439 all = PyMapping_Keys(dict);
4440 Py_DECREF(dict);
4441 if (all == NULL)
4442 return -1;
4443 skip_leading_underscores = 1;
4444 }
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 for (pos = 0, err = 0; ; pos++) {
4447 name = PySequence_GetItem(all, pos);
4448 if (name == NULL) {
4449 if (!PyErr_ExceptionMatches(PyExc_IndexError))
4450 err = -1;
4451 else
4452 PyErr_Clear();
4453 break;
4454 }
4455 if (skip_leading_underscores &&
4456 PyUnicode_Check(name) &&
4457 PyUnicode_AS_UNICODE(name)[0] == '_')
4458 {
4459 Py_DECREF(name);
4460 continue;
4461 }
4462 value = PyObject_GetAttr(v, name);
4463 if (value == NULL)
4464 err = -1;
4465 else if (PyDict_CheckExact(locals))
4466 err = PyDict_SetItem(locals, name, value);
4467 else
4468 err = PyObject_SetItem(locals, name, value);
4469 Py_DECREF(name);
4470 Py_XDECREF(value);
4471 if (err != 0)
4472 break;
4473 }
4474 Py_DECREF(all);
4475 return err;
Guido van Rossume9736fc1990-11-18 17:33:06 +00004476}
4477
Guido van Rossumac7be682001-01-17 15:42:30 +00004478static void
Neal Norwitzda059e32007-08-26 05:33:45 +00004479format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj)
Paul Prescode68140d2000-08-30 20:25:01 +00004480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 const char *obj_str;
Paul Prescode68140d2000-08-30 20:25:01 +00004482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 if (!obj)
4484 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 obj_str = _PyUnicode_AsString(obj);
4487 if (!obj_str)
4488 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 PyErr_Format(exc, format_str, obj_str);
Paul Prescode68140d2000-08-30 20:25:01 +00004491}
Guido van Rossum950361c1997-01-24 13:49:28 +00004492
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00004493static void
4494format_exc_unbound(PyCodeObject *co, int oparg)
4495{
4496 PyObject *name;
4497 /* Don't stomp existing exception */
4498 if (PyErr_Occurred())
4499 return;
4500 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
4501 name = PyTuple_GET_ITEM(co->co_cellvars,
4502 oparg);
4503 format_exc_check_arg(
4504 PyExc_UnboundLocalError,
4505 UNBOUNDLOCAL_ERROR_MSG,
4506 name);
4507 } else {
4508 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
4509 PyTuple_GET_SIZE(co->co_cellvars));
4510 format_exc_check_arg(PyExc_NameError,
4511 UNBOUNDFREE_ERROR_MSG, name);
4512 }
4513}
4514
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004515static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00004516unicode_concatenate(PyObject *v, PyObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 PyFrameObject *f, unsigned char *next_instr)
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 /* This function implements 'variable += expr' when both arguments
4520 are (Unicode) strings. */
4521 Py_ssize_t v_len = PyUnicode_GET_SIZE(v);
4522 Py_ssize_t w_len = PyUnicode_GET_SIZE(w);
4523 Py_ssize_t new_len = v_len + w_len;
4524 if (new_len < 0) {
4525 PyErr_SetString(PyExc_OverflowError,
4526 "strings are too large to concat");
4527 return NULL;
4528 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00004529
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004530 if (Py_REFCNT(v) == 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 /* In the common case, there are 2 references to the value
4532 * stored in 'variable' when the += is performed: one on the
4533 * value stack (in 'v') and one still stored in the
4534 * 'variable'. We try to delete the variable now to reduce
4535 * the refcnt to 1.
4536 */
4537 switch (*next_instr) {
4538 case STORE_FAST:
4539 {
4540 int oparg = PEEKARG();
4541 PyObject **fastlocals = f->f_localsplus;
4542 if (GETLOCAL(oparg) == v)
4543 SETLOCAL(oparg, NULL);
4544 break;
4545 }
4546 case STORE_DEREF:
4547 {
4548 PyObject **freevars = (f->f_localsplus +
4549 f->f_code->co_nlocals);
4550 PyObject *c = freevars[PEEKARG()];
4551 if (PyCell_GET(c) == v)
4552 PyCell_Set(c, NULL);
4553 break;
4554 }
4555 case STORE_NAME:
4556 {
4557 PyObject *names = f->f_code->co_names;
4558 PyObject *name = GETITEM(names, PEEKARG());
4559 PyObject *locals = f->f_locals;
4560 if (PyDict_CheckExact(locals) &&
4561 PyDict_GetItem(locals, name) == v) {
4562 if (PyDict_DelItem(locals, name) != 0) {
4563 PyErr_Clear();
4564 }
4565 }
4566 break;
4567 }
4568 }
4569 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004570
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004571 if (Py_REFCNT(v) == 1 && !PyUnicode_CHECK_INTERNED(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 /* Now we own the last reference to 'v', so we can resize it
4573 * in-place.
4574 */
4575 if (PyUnicode_Resize(&v, new_len) != 0) {
4576 /* XXX if PyUnicode_Resize() fails, 'v' has been
4577 * deallocated so it cannot be put back into
4578 * 'variable'. The MemoryError is raised when there
4579 * is no value in 'variable', which might (very
4580 * remotely) be a cause of incompatibilities.
4581 */
4582 return NULL;
4583 }
4584 /* copy 'w' into the newly allocated area of 'v' */
4585 memcpy(PyUnicode_AS_UNICODE(v) + v_len,
4586 PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE));
4587 return v;
4588 }
4589 else {
4590 /* When in-place resizing is not an option. */
4591 w = PyUnicode_Concat(v, w);
4592 Py_DECREF(v);
4593 return w;
4594 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004595}
4596
Guido van Rossum950361c1997-01-24 13:49:28 +00004597#ifdef DYNAMIC_EXECUTION_PROFILE
4598
Skip Montanarof118cb12001-10-15 20:51:38 +00004599static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004600getarray(long a[256])
Guido van Rossum950361c1997-01-24 13:49:28 +00004601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 int i;
4603 PyObject *l = PyList_New(256);
4604 if (l == NULL) return NULL;
4605 for (i = 0; i < 256; i++) {
4606 PyObject *x = PyLong_FromLong(a[i]);
4607 if (x == NULL) {
4608 Py_DECREF(l);
4609 return NULL;
4610 }
4611 PyList_SetItem(l, i, x);
4612 }
4613 for (i = 0; i < 256; i++)
4614 a[i] = 0;
4615 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004616}
4617
4618PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004619_Py_GetDXProfile(PyObject *self, PyObject *args)
Guido van Rossum950361c1997-01-24 13:49:28 +00004620{
4621#ifndef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 return getarray(dxp);
Guido van Rossum950361c1997-01-24 13:49:28 +00004623#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 int i;
4625 PyObject *l = PyList_New(257);
4626 if (l == NULL) return NULL;
4627 for (i = 0; i < 257; i++) {
4628 PyObject *x = getarray(dxpairs[i]);
4629 if (x == NULL) {
4630 Py_DECREF(l);
4631 return NULL;
4632 }
4633 PyList_SetItem(l, i, x);
4634 }
4635 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004636#endif
4637}
4638
4639#endif