blob: 6d493633a980e80b263694b77ff237989ca0bbad [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 /* push frame */
1119 if (Py_EnterRecursiveCall(""))
1120 return NULL;
Guido van Rossum8861b741996-07-30 16:49:37 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 tstate->frame = f;
Tim Peters5ca576e2001-06-18 22:08:13 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (tstate->use_tracing) {
1125 if (tstate->c_tracefunc != NULL) {
1126 /* tstate->c_tracefunc, if defined, is a
1127 function that will be called on *every* entry
1128 to a code block. Its return value, if not
1129 None, is a function that will be called at
1130 the start of each executed line of code.
1131 (Actually, the function must return itself
1132 in order to continue tracing.) The trace
1133 functions are called with three arguments:
1134 a pointer to the current frame, a string
1135 indicating why the function is called, and
1136 an argument which depends on the situation.
1137 The global trace function is also called
1138 whenever an exception is detected. */
1139 if (call_trace_protected(tstate->c_tracefunc,
1140 tstate->c_traceobj,
1141 f, PyTrace_CALL, Py_None)) {
1142 /* Trace function raised an error */
1143 goto exit_eval_frame;
1144 }
1145 }
1146 if (tstate->c_profilefunc != NULL) {
1147 /* Similar for c_profilefunc, except it needn't
1148 return itself and isn't called for "line" events */
1149 if (call_trace_protected(tstate->c_profilefunc,
1150 tstate->c_profileobj,
1151 f, PyTrace_CALL, Py_None)) {
1152 /* Profile function raised an error */
1153 goto exit_eval_frame;
1154 }
1155 }
1156 }
Neil Schemenauer6c0f2002001-09-04 19:03:35 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 co = f->f_code;
1159 names = co->co_names;
1160 consts = co->co_consts;
1161 fastlocals = f->f_localsplus;
1162 freevars = f->f_localsplus + co->co_nlocals;
1163 first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code);
1164 /* An explanation is in order for the next line.
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 f->f_lasti now refers to the index of the last instruction
1167 executed. You might think this was obvious from the name, but
1168 this wasn't always true before 2.3! PyFrame_New now sets
1169 f->f_lasti to -1 (i.e. the index *before* the first instruction)
1170 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
1171 does work. Promise.
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 When the PREDICT() macros are enabled, some opcode pairs follow in
1174 direct succession without updating f->f_lasti. A successful
1175 prediction effectively links the two codes together as if they
1176 were a single new opcode; accordingly,f->f_lasti will point to
1177 the first code in the pair (for instance, GET_ITER followed by
1178 FOR_ITER is effectively a single opcode and f->f_lasti will point
1179 at to the beginning of the combined pair.)
1180 */
1181 next_instr = first_instr + f->f_lasti + 1;
1182 stack_pointer = f->f_stacktop;
1183 assert(stack_pointer != NULL);
1184 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (co->co_flags & CO_GENERATOR && !throwflag) {
1187 if (f->f_exc_type != NULL && f->f_exc_type != Py_None) {
1188 /* We were in an except handler when we left,
1189 restore the exception state which was put aside
1190 (see YIELD_VALUE). */
Benjamin Peterson87880242011-07-03 16:48:31 -05001191 swap_exc_state(tstate, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 }
Benjamin Peterson87880242011-07-03 16:48:31 -05001193 else
1194 save_exc_state(tstate, f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001196
Tim Peters5ca576e2001-06-18 22:08:13 +00001197#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00001199#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 why = WHY_NOT;
1202 err = 0;
1203 x = Py_None; /* Not a reference, just anything non-NULL */
1204 w = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (throwflag) { /* support for generator.throw() */
1207 why = WHY_EXCEPTION;
1208 goto on_error;
1209 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 for (;;) {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001212#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (inst1 == 0) {
1214 /* Almost surely, the opcode executed a break
1215 or a continue, preventing inst1 from being set
1216 on the way out of the loop.
1217 */
1218 READ_TIMESTAMP(inst1);
1219 loop1 = inst1;
1220 }
1221 dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1,
1222 intr0, intr1);
1223 ticked = 0;
1224 inst1 = 0;
1225 intr0 = 0;
1226 intr1 = 0;
1227 READ_TIMESTAMP(loop0);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001228#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1230 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 /* Do periodic things. Doing this every time through
1233 the loop would add too much overhead, so we do it
1234 only every Nth instruction. We also do it if
1235 ``pendingcalls_to_do'' is set, i.e. when an asynchronous
1236 event needs attention (e.g. a signal handler or
1237 async I/O handler); see Py_AddPendingCall() and
1238 Py_MakePendingCalls() above. */
Guido van Rossumac7be682001-01-17 15:42:30 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (_Py_atomic_load_relaxed(&eval_breaker)) {
1241 if (*next_instr == SETUP_FINALLY) {
1242 /* Make the last opcode before
Ezio Melotti13925002011-03-16 11:05:33 +02001243 a try: finally: block uninterruptible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 goto fast_next_opcode;
1245 }
1246 tstate->tick_counter++;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001247#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 ticked = 1;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001249#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) {
1251 if (Py_MakePendingCalls() < 0) {
1252 why = WHY_EXCEPTION;
1253 goto on_error;
1254 }
1255 }
Guido van Rossume59214e1994-08-30 08:01:59 +00001256#ifdef WITH_THREAD
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001257 if (_Py_atomic_load_relaxed(&gil_drop_request)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 /* Give another thread a chance */
1259 if (PyThreadState_Swap(NULL) != tstate)
1260 Py_FatalError("ceval: tstate mix-up");
1261 drop_gil(tstate);
1262
1263 /* Other threads may run now */
1264
1265 take_gil(tstate);
1266 if (PyThreadState_Swap(tstate) != NULL)
1267 Py_FatalError("ceval: orphan tstate");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 }
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001269#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* Check for asynchronous exceptions. */
1271 if (tstate->async_exc != NULL) {
1272 x = tstate->async_exc;
1273 tstate->async_exc = NULL;
1274 UNSIGNAL_ASYNC_EXC();
1275 PyErr_SetNone(x);
1276 Py_DECREF(x);
1277 why = WHY_EXCEPTION;
1278 goto on_error;
1279 }
1280 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 fast_next_opcode:
1283 f->f_lasti = INSTR_OFFSET();
Guido van Rossumac7be682001-01-17 15:42:30 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 /* line-by-line tracing support */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (_Py_TracingPossible &&
1288 tstate->c_tracefunc != NULL && !tstate->tracing) {
1289 /* see maybe_call_line_trace
1290 for expository comments */
1291 f->f_stacktop = stack_pointer;
Tim Peters8a5c3c72004-04-05 19:36:21 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 err = maybe_call_line_trace(tstate->c_tracefunc,
1294 tstate->c_traceobj,
1295 f, &instr_lb, &instr_ub,
1296 &instr_prev);
1297 /* Reload possibly changed frame fields */
1298 JUMPTO(f->f_lasti);
1299 if (f->f_stacktop != NULL) {
1300 stack_pointer = f->f_stacktop;
1301 f->f_stacktop = NULL;
1302 }
1303 if (err) {
1304 /* trace function raised an exception */
1305 goto on_error;
1306 }
1307 }
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 /* Extract opcode and argument */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 opcode = NEXTOP();
1312 oparg = 0; /* allows oparg to be stored in a register because
1313 it doesn't have to be remembered across a full loop */
1314 if (HAS_ARG(opcode))
1315 oparg = NEXTARG();
Stefan Krahb7e10102010-06-23 18:42:39 +00001316 dispatch_opcode:
Guido van Rossum950361c1997-01-24 13:49:28 +00001317#ifdef DYNAMIC_EXECUTION_PROFILE
1318#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 dxpairs[lastopcode][opcode]++;
1320 lastopcode = opcode;
Guido van Rossum950361c1997-01-24 13:49:28 +00001321#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 dxp[opcode]++;
Guido van Rossum950361c1997-01-24 13:49:28 +00001323#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00001324
Guido van Rossum96a42c81992-01-12 02:29:51 +00001325#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* Instruction tracing */
Guido van Rossumac7be682001-01-17 15:42:30 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (lltrace) {
1329 if (HAS_ARG(opcode)) {
1330 printf("%d: %d, %d\n",
1331 f->f_lasti, opcode, oparg);
1332 }
1333 else {
1334 printf("%d: %d\n",
1335 f->f_lasti, opcode);
1336 }
1337 }
Guido van Rossum374a9221991-04-04 10:40:29 +00001338#endif
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* Main switch on opcode */
1341 READ_TIMESTAMP(inst0);
Jeremy Hylton52820442001-01-03 23:52:36 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 switch (opcode) {
Guido van Rossumac7be682001-01-17 15:42:30 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 /* BEWARE!
1346 It is essential that any operation that fails sets either
1347 x to NULL, err to nonzero, or why to anything but WHY_NOT,
1348 and that no operation that succeeds does this! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* case STOP_CODE: this is an error! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 TARGET(NOP)
1353 FAST_DISPATCH();
Raymond Hettinger9c18e812004-06-21 16:31:15 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 TARGET(LOAD_FAST)
1356 x = GETLOCAL(oparg);
1357 if (x != NULL) {
1358 Py_INCREF(x);
1359 PUSH(x);
1360 FAST_DISPATCH();
1361 }
1362 format_exc_check_arg(PyExc_UnboundLocalError,
1363 UNBOUNDLOCAL_ERROR_MSG,
1364 PyTuple_GetItem(co->co_varnames, oparg));
1365 break;
Neil Schemenauer63543862002-02-17 19:10:14 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 TARGET(LOAD_CONST)
1368 x = GETITEM(consts, oparg);
1369 Py_INCREF(x);
1370 PUSH(x);
1371 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PREDICTED_WITH_ARG(STORE_FAST);
1374 TARGET(STORE_FAST)
1375 v = POP();
1376 SETLOCAL(oparg, v);
1377 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 TARGET(POP_TOP)
1380 v = POP();
1381 Py_DECREF(v);
1382 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 TARGET(ROT_TWO)
1385 v = TOP();
1386 w = SECOND();
1387 SET_TOP(w);
1388 SET_SECOND(v);
1389 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 TARGET(ROT_THREE)
1392 v = TOP();
1393 w = SECOND();
1394 x = THIRD();
1395 SET_TOP(w);
1396 SET_SECOND(x);
1397 SET_THIRD(v);
1398 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 TARGET(DUP_TOP)
1401 v = TOP();
1402 Py_INCREF(v);
1403 PUSH(v);
1404 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001405
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00001406 TARGET(DUP_TOP_TWO)
1407 x = TOP();
1408 Py_INCREF(x);
1409 w = SECOND();
1410 Py_INCREF(w);
1411 STACKADJ(2);
1412 SET_TOP(x);
1413 SET_SECOND(w);
1414 FAST_DISPATCH();
Thomas Wouters434d0822000-08-24 20:11:32 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 TARGET(UNARY_POSITIVE)
1417 v = TOP();
1418 x = PyNumber_Positive(v);
1419 Py_DECREF(v);
1420 SET_TOP(x);
1421 if (x != NULL) DISPATCH();
1422 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 TARGET(UNARY_NEGATIVE)
1425 v = TOP();
1426 x = PyNumber_Negative(v);
1427 Py_DECREF(v);
1428 SET_TOP(x);
1429 if (x != NULL) DISPATCH();
1430 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 TARGET(UNARY_NOT)
1433 v = TOP();
1434 err = PyObject_IsTrue(v);
1435 Py_DECREF(v);
1436 if (err == 0) {
1437 Py_INCREF(Py_True);
1438 SET_TOP(Py_True);
1439 DISPATCH();
1440 }
1441 else if (err > 0) {
1442 Py_INCREF(Py_False);
1443 SET_TOP(Py_False);
1444 err = 0;
1445 DISPATCH();
1446 }
1447 STACKADJ(-1);
1448 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 TARGET(UNARY_INVERT)
1451 v = TOP();
1452 x = PyNumber_Invert(v);
1453 Py_DECREF(v);
1454 SET_TOP(x);
1455 if (x != NULL) DISPATCH();
1456 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 TARGET(BINARY_POWER)
1459 w = POP();
1460 v = TOP();
1461 x = PyNumber_Power(v, w, Py_None);
1462 Py_DECREF(v);
1463 Py_DECREF(w);
1464 SET_TOP(x);
1465 if (x != NULL) DISPATCH();
1466 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 TARGET(BINARY_MULTIPLY)
1469 w = POP();
1470 v = TOP();
1471 x = PyNumber_Multiply(v, w);
1472 Py_DECREF(v);
1473 Py_DECREF(w);
1474 SET_TOP(x);
1475 if (x != NULL) DISPATCH();
1476 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 TARGET(BINARY_TRUE_DIVIDE)
1479 w = POP();
1480 v = TOP();
1481 x = PyNumber_TrueDivide(v, w);
1482 Py_DECREF(v);
1483 Py_DECREF(w);
1484 SET_TOP(x);
1485 if (x != NULL) DISPATCH();
1486 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 TARGET(BINARY_FLOOR_DIVIDE)
1489 w = POP();
1490 v = TOP();
1491 x = PyNumber_FloorDivide(v, w);
1492 Py_DECREF(v);
1493 Py_DECREF(w);
1494 SET_TOP(x);
1495 if (x != NULL) DISPATCH();
1496 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 TARGET(BINARY_MODULO)
1499 w = POP();
1500 v = TOP();
1501 if (PyUnicode_CheckExact(v))
1502 x = PyUnicode_Format(v, w);
1503 else
1504 x = PyNumber_Remainder(v, w);
1505 Py_DECREF(v);
1506 Py_DECREF(w);
1507 SET_TOP(x);
1508 if (x != NULL) DISPATCH();
1509 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 TARGET(BINARY_ADD)
1512 w = POP();
1513 v = TOP();
1514 if (PyUnicode_CheckExact(v) &&
1515 PyUnicode_CheckExact(w)) {
1516 x = unicode_concatenate(v, w, f, next_instr);
1517 /* unicode_concatenate consumed the ref to v */
1518 goto skip_decref_vx;
1519 }
1520 else {
1521 x = PyNumber_Add(v, w);
1522 }
1523 Py_DECREF(v);
1524 skip_decref_vx:
1525 Py_DECREF(w);
1526 SET_TOP(x);
1527 if (x != NULL) DISPATCH();
1528 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 TARGET(BINARY_SUBTRACT)
1531 w = POP();
1532 v = TOP();
1533 x = PyNumber_Subtract(v, w);
1534 Py_DECREF(v);
1535 Py_DECREF(w);
1536 SET_TOP(x);
1537 if (x != NULL) DISPATCH();
1538 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 TARGET(BINARY_SUBSCR)
1541 w = POP();
1542 v = TOP();
1543 x = PyObject_GetItem(v, w);
1544 Py_DECREF(v);
1545 Py_DECREF(w);
1546 SET_TOP(x);
1547 if (x != NULL) DISPATCH();
1548 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 TARGET(BINARY_LSHIFT)
1551 w = POP();
1552 v = TOP();
1553 x = PyNumber_Lshift(v, w);
1554 Py_DECREF(v);
1555 Py_DECREF(w);
1556 SET_TOP(x);
1557 if (x != NULL) DISPATCH();
1558 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 TARGET(BINARY_RSHIFT)
1561 w = POP();
1562 v = TOP();
1563 x = PyNumber_Rshift(v, w);
1564 Py_DECREF(v);
1565 Py_DECREF(w);
1566 SET_TOP(x);
1567 if (x != NULL) DISPATCH();
1568 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 TARGET(BINARY_AND)
1571 w = POP();
1572 v = TOP();
1573 x = PyNumber_And(v, w);
1574 Py_DECREF(v);
1575 Py_DECREF(w);
1576 SET_TOP(x);
1577 if (x != NULL) DISPATCH();
1578 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 TARGET(BINARY_XOR)
1581 w = POP();
1582 v = TOP();
1583 x = PyNumber_Xor(v, w);
1584 Py_DECREF(v);
1585 Py_DECREF(w);
1586 SET_TOP(x);
1587 if (x != NULL) DISPATCH();
1588 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 TARGET(BINARY_OR)
1591 w = POP();
1592 v = TOP();
1593 x = PyNumber_Or(v, w);
1594 Py_DECREF(v);
1595 Py_DECREF(w);
1596 SET_TOP(x);
1597 if (x != NULL) DISPATCH();
1598 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 TARGET(LIST_APPEND)
1601 w = POP();
1602 v = PEEK(oparg);
1603 err = PyList_Append(v, w);
1604 Py_DECREF(w);
1605 if (err == 0) {
1606 PREDICT(JUMP_ABSOLUTE);
1607 DISPATCH();
1608 }
1609 break;
Raymond Hettingerdd80f762004-03-07 07:31:06 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 TARGET(SET_ADD)
1612 w = POP();
1613 v = stack_pointer[-oparg];
1614 err = PySet_Add(v, w);
1615 Py_DECREF(w);
1616 if (err == 0) {
1617 PREDICT(JUMP_ABSOLUTE);
1618 DISPATCH();
1619 }
1620 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 TARGET(INPLACE_POWER)
1623 w = POP();
1624 v = TOP();
1625 x = PyNumber_InPlacePower(v, w, Py_None);
1626 Py_DECREF(v);
1627 Py_DECREF(w);
1628 SET_TOP(x);
1629 if (x != NULL) DISPATCH();
1630 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 TARGET(INPLACE_MULTIPLY)
1633 w = POP();
1634 v = TOP();
1635 x = PyNumber_InPlaceMultiply(v, w);
1636 Py_DECREF(v);
1637 Py_DECREF(w);
1638 SET_TOP(x);
1639 if (x != NULL) DISPATCH();
1640 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 TARGET(INPLACE_TRUE_DIVIDE)
1643 w = POP();
1644 v = TOP();
1645 x = PyNumber_InPlaceTrueDivide(v, w);
1646 Py_DECREF(v);
1647 Py_DECREF(w);
1648 SET_TOP(x);
1649 if (x != NULL) DISPATCH();
1650 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 TARGET(INPLACE_FLOOR_DIVIDE)
1653 w = POP();
1654 v = TOP();
1655 x = PyNumber_InPlaceFloorDivide(v, w);
1656 Py_DECREF(v);
1657 Py_DECREF(w);
1658 SET_TOP(x);
1659 if (x != NULL) DISPATCH();
1660 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 TARGET(INPLACE_MODULO)
1663 w = POP();
1664 v = TOP();
1665 x = PyNumber_InPlaceRemainder(v, w);
1666 Py_DECREF(v);
1667 Py_DECREF(w);
1668 SET_TOP(x);
1669 if (x != NULL) DISPATCH();
1670 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 TARGET(INPLACE_ADD)
1673 w = POP();
1674 v = TOP();
1675 if (PyUnicode_CheckExact(v) &&
1676 PyUnicode_CheckExact(w)) {
1677 x = unicode_concatenate(v, w, f, next_instr);
1678 /* unicode_concatenate consumed the ref to v */
1679 goto skip_decref_v;
1680 }
1681 else {
1682 x = PyNumber_InPlaceAdd(v, w);
1683 }
1684 Py_DECREF(v);
1685 skip_decref_v:
1686 Py_DECREF(w);
1687 SET_TOP(x);
1688 if (x != NULL) DISPATCH();
1689 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 TARGET(INPLACE_SUBTRACT)
1692 w = POP();
1693 v = TOP();
1694 x = PyNumber_InPlaceSubtract(v, w);
1695 Py_DECREF(v);
1696 Py_DECREF(w);
1697 SET_TOP(x);
1698 if (x != NULL) DISPATCH();
1699 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 TARGET(INPLACE_LSHIFT)
1702 w = POP();
1703 v = TOP();
1704 x = PyNumber_InPlaceLshift(v, w);
1705 Py_DECREF(v);
1706 Py_DECREF(w);
1707 SET_TOP(x);
1708 if (x != NULL) DISPATCH();
1709 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 TARGET(INPLACE_RSHIFT)
1712 w = POP();
1713 v = TOP();
1714 x = PyNumber_InPlaceRshift(v, w);
1715 Py_DECREF(v);
1716 Py_DECREF(w);
1717 SET_TOP(x);
1718 if (x != NULL) DISPATCH();
1719 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 TARGET(INPLACE_AND)
1722 w = POP();
1723 v = TOP();
1724 x = PyNumber_InPlaceAnd(v, w);
1725 Py_DECREF(v);
1726 Py_DECREF(w);
1727 SET_TOP(x);
1728 if (x != NULL) DISPATCH();
1729 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 TARGET(INPLACE_XOR)
1732 w = POP();
1733 v = TOP();
1734 x = PyNumber_InPlaceXor(v, w);
1735 Py_DECREF(v);
1736 Py_DECREF(w);
1737 SET_TOP(x);
1738 if (x != NULL) DISPATCH();
1739 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 TARGET(INPLACE_OR)
1742 w = POP();
1743 v = TOP();
1744 x = PyNumber_InPlaceOr(v, w);
1745 Py_DECREF(v);
1746 Py_DECREF(w);
1747 SET_TOP(x);
1748 if (x != NULL) DISPATCH();
1749 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 TARGET(STORE_SUBSCR)
1752 w = TOP();
1753 v = SECOND();
1754 u = THIRD();
1755 STACKADJ(-3);
1756 /* v[w] = u */
1757 err = PyObject_SetItem(v, w, u);
1758 Py_DECREF(u);
1759 Py_DECREF(v);
1760 Py_DECREF(w);
1761 if (err == 0) DISPATCH();
1762 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 TARGET(DELETE_SUBSCR)
1765 w = TOP();
1766 v = SECOND();
1767 STACKADJ(-2);
1768 /* del v[w] */
1769 err = PyObject_DelItem(v, w);
1770 Py_DECREF(v);
1771 Py_DECREF(w);
1772 if (err == 0) DISPATCH();
1773 break;
Barry Warsaw23c9ec82000-08-21 15:44:01 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 TARGET(PRINT_EXPR)
1776 v = POP();
1777 w = PySys_GetObject("displayhook");
1778 if (w == NULL) {
1779 PyErr_SetString(PyExc_RuntimeError,
1780 "lost sys.displayhook");
1781 err = -1;
1782 x = NULL;
1783 }
1784 if (err == 0) {
1785 x = PyTuple_Pack(1, v);
1786 if (x == NULL)
1787 err = -1;
1788 }
1789 if (err == 0) {
1790 w = PyEval_CallObject(w, x);
1791 Py_XDECREF(w);
1792 if (w == NULL)
1793 err = -1;
1794 }
1795 Py_DECREF(v);
1796 Py_XDECREF(x);
1797 break;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +00001798
Thomas Wouters434d0822000-08-24 20:11:32 +00001799#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 default: switch (opcode) {
Thomas Wouters434d0822000-08-24 20:11:32 +00001801#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 TARGET(RAISE_VARARGS)
1803 v = w = NULL;
1804 switch (oparg) {
1805 case 2:
1806 v = POP(); /* cause */
1807 case 1:
1808 w = POP(); /* exc */
1809 case 0: /* Fallthrough */
1810 why = do_raise(w, v);
1811 break;
1812 default:
1813 PyErr_SetString(PyExc_SystemError,
1814 "bad RAISE_VARARGS oparg");
1815 why = WHY_EXCEPTION;
1816 break;
1817 }
1818 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 TARGET(STORE_LOCALS)
1821 x = POP();
1822 v = f->f_locals;
1823 Py_XDECREF(v);
1824 f->f_locals = x;
1825 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 TARGET(RETURN_VALUE)
1828 retval = POP();
1829 why = WHY_RETURN;
1830 goto fast_block_end;
Guido van Rossumdb3165e1993-10-18 17:06:59 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 TARGET(YIELD_VALUE)
1833 retval = POP();
1834 f->f_stacktop = stack_pointer;
1835 why = WHY_YIELD;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 goto fast_yield;
Tim Peters5ca576e2001-06-18 22:08:13 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 TARGET(POP_EXCEPT)
1839 {
1840 PyTryBlock *b = PyFrame_BlockPop(f);
1841 if (b->b_type != EXCEPT_HANDLER) {
1842 PyErr_SetString(PyExc_SystemError,
1843 "popped block is not an except handler");
1844 why = WHY_EXCEPTION;
1845 break;
1846 }
1847 UNWIND_EXCEPT_HANDLER(b);
1848 }
1849 DISPATCH();
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 TARGET(POP_BLOCK)
1852 {
1853 PyTryBlock *b = PyFrame_BlockPop(f);
1854 UNWIND_BLOCK(b);
1855 }
1856 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 PREDICTED(END_FINALLY);
1859 TARGET(END_FINALLY)
1860 v = POP();
1861 if (PyLong_Check(v)) {
1862 why = (enum why_code) PyLong_AS_LONG(v);
1863 assert(why != WHY_YIELD);
1864 if (why == WHY_RETURN ||
1865 why == WHY_CONTINUE)
1866 retval = POP();
1867 if (why == WHY_SILENCED) {
1868 /* An exception was silenced by 'with', we must
1869 manually unwind the EXCEPT_HANDLER block which was
1870 created when the exception was caught, otherwise
1871 the stack will be in an inconsistent state. */
1872 PyTryBlock *b = PyFrame_BlockPop(f);
1873 assert(b->b_type == EXCEPT_HANDLER);
1874 UNWIND_EXCEPT_HANDLER(b);
1875 why = WHY_NOT;
1876 }
1877 }
1878 else if (PyExceptionClass_Check(v)) {
1879 w = POP();
1880 u = POP();
1881 PyErr_Restore(v, w, u);
1882 why = WHY_RERAISE;
1883 break;
1884 }
1885 else if (v != Py_None) {
1886 PyErr_SetString(PyExc_SystemError,
1887 "'finally' pops bad exception");
1888 why = WHY_EXCEPTION;
1889 }
1890 Py_DECREF(v);
1891 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 TARGET(LOAD_BUILD_CLASS)
1894 x = PyDict_GetItemString(f->f_builtins,
1895 "__build_class__");
1896 if (x == NULL) {
1897 PyErr_SetString(PyExc_ImportError,
1898 "__build_class__ not found");
1899 break;
1900 }
1901 Py_INCREF(x);
1902 PUSH(x);
1903 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 TARGET(STORE_NAME)
1906 w = GETITEM(names, oparg);
1907 v = POP();
1908 if ((x = f->f_locals) != NULL) {
1909 if (PyDict_CheckExact(x))
1910 err = PyDict_SetItem(x, w, v);
1911 else
1912 err = PyObject_SetItem(x, w, v);
1913 Py_DECREF(v);
1914 if (err == 0) DISPATCH();
1915 break;
1916 }
1917 PyErr_Format(PyExc_SystemError,
1918 "no locals found when storing %R", w);
1919 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 TARGET(DELETE_NAME)
1922 w = GETITEM(names, oparg);
1923 if ((x = f->f_locals) != NULL) {
1924 if ((err = PyObject_DelItem(x, w)) != 0)
1925 format_exc_check_arg(PyExc_NameError,
1926 NAME_ERROR_MSG,
1927 w);
1928 break;
1929 }
1930 PyErr_Format(PyExc_SystemError,
1931 "no locals when deleting %R", w);
1932 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
1935 TARGET(UNPACK_SEQUENCE)
1936 v = POP();
1937 if (PyTuple_CheckExact(v) &&
1938 PyTuple_GET_SIZE(v) == oparg) {
1939 PyObject **items = \
1940 ((PyTupleObject *)v)->ob_item;
1941 while (oparg--) {
1942 w = items[oparg];
1943 Py_INCREF(w);
1944 PUSH(w);
1945 }
1946 Py_DECREF(v);
1947 DISPATCH();
1948 } else if (PyList_CheckExact(v) &&
1949 PyList_GET_SIZE(v) == oparg) {
1950 PyObject **items = \
1951 ((PyListObject *)v)->ob_item;
1952 while (oparg--) {
1953 w = items[oparg];
1954 Py_INCREF(w);
1955 PUSH(w);
1956 }
1957 } else if (unpack_iterable(v, oparg, -1,
1958 stack_pointer + oparg)) {
1959 STACKADJ(oparg);
1960 } else {
1961 /* unpack_iterable() raised an exception */
1962 why = WHY_EXCEPTION;
1963 }
1964 Py_DECREF(v);
1965 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 TARGET(UNPACK_EX)
1968 {
1969 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
1970 v = POP();
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 if (unpack_iterable(v, oparg & 0xFF, oparg >> 8,
1973 stack_pointer + totalargs)) {
1974 stack_pointer += totalargs;
1975 } else {
1976 why = WHY_EXCEPTION;
1977 }
1978 Py_DECREF(v);
1979 break;
1980 }
Guido van Rossum0368b722007-05-11 16:50:42 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 TARGET(STORE_ATTR)
1983 w = GETITEM(names, oparg);
1984 v = TOP();
1985 u = SECOND();
1986 STACKADJ(-2);
1987 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1988 Py_DECREF(v);
1989 Py_DECREF(u);
1990 if (err == 0) DISPATCH();
1991 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 TARGET(DELETE_ATTR)
1994 w = GETITEM(names, oparg);
1995 v = POP();
1996 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
1997 /* del v.w */
1998 Py_DECREF(v);
1999 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 TARGET(STORE_GLOBAL)
2002 w = GETITEM(names, oparg);
2003 v = POP();
2004 err = PyDict_SetItem(f->f_globals, w, v);
2005 Py_DECREF(v);
2006 if (err == 0) DISPATCH();
2007 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 TARGET(DELETE_GLOBAL)
2010 w = GETITEM(names, oparg);
2011 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
2012 format_exc_check_arg(
2013 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
2014 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 TARGET(LOAD_NAME)
2017 w = GETITEM(names, oparg);
2018 if ((v = f->f_locals) == NULL) {
2019 PyErr_Format(PyExc_SystemError,
2020 "no locals when loading %R", w);
2021 why = WHY_EXCEPTION;
2022 break;
2023 }
2024 if (PyDict_CheckExact(v)) {
2025 x = PyDict_GetItem(v, w);
2026 Py_XINCREF(x);
2027 }
2028 else {
2029 x = PyObject_GetItem(v, w);
2030 if (x == NULL && PyErr_Occurred()) {
2031 if (!PyErr_ExceptionMatches(
2032 PyExc_KeyError))
2033 break;
2034 PyErr_Clear();
2035 }
2036 }
2037 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002038 x = PyDict_GetItem(f->f_globals, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002040 x = PyDict_GetItem(f->f_builtins, w);
2041 if (x == NULL) {
2042 format_exc_check_arg(
2043 PyExc_NameError,
2044 NAME_ERROR_MSG, w);
2045 break;
2046 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 }
2048 Py_INCREF(x);
2049 }
2050 PUSH(x);
2051 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 TARGET(LOAD_GLOBAL)
2054 w = GETITEM(names, oparg);
2055 if (PyUnicode_CheckExact(w)) {
2056 /* Inline the PyDict_GetItem() calls.
2057 WARNING: this is an extreme speed hack.
2058 Do not try this at home. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002059 Py_hash_t hash = ((PyUnicodeObject *)w)->hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (hash != -1) {
2061 PyDictObject *d;
2062 PyDictEntry *e;
2063 d = (PyDictObject *)(f->f_globals);
2064 e = d->ma_lookup(d, w, hash);
2065 if (e == NULL) {
2066 x = NULL;
2067 break;
2068 }
2069 x = e->me_value;
2070 if (x != NULL) {
2071 Py_INCREF(x);
2072 PUSH(x);
2073 DISPATCH();
2074 }
2075 d = (PyDictObject *)(f->f_builtins);
2076 e = d->ma_lookup(d, w, hash);
2077 if (e == NULL) {
2078 x = NULL;
2079 break;
2080 }
2081 x = e->me_value;
2082 if (x != NULL) {
2083 Py_INCREF(x);
2084 PUSH(x);
2085 DISPATCH();
2086 }
2087 goto load_global_error;
2088 }
2089 }
2090 /* This is the un-inlined version of the code above */
2091 x = PyDict_GetItem(f->f_globals, w);
2092 if (x == NULL) {
2093 x = PyDict_GetItem(f->f_builtins, w);
2094 if (x == NULL) {
2095 load_global_error:
2096 format_exc_check_arg(
2097 PyExc_NameError,
2098 GLOBAL_NAME_ERROR_MSG, w);
2099 break;
2100 }
2101 }
2102 Py_INCREF(x);
2103 PUSH(x);
2104 DISPATCH();
Guido van Rossum681d79a1995-07-18 14:51:37 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 TARGET(DELETE_FAST)
2107 x = GETLOCAL(oparg);
2108 if (x != NULL) {
2109 SETLOCAL(oparg, NULL);
2110 DISPATCH();
2111 }
2112 format_exc_check_arg(
2113 PyExc_UnboundLocalError,
2114 UNBOUNDLOCAL_ERROR_MSG,
2115 PyTuple_GetItem(co->co_varnames, oparg)
2116 );
2117 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002118
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002119 TARGET(DELETE_DEREF)
2120 x = freevars[oparg];
2121 if (PyCell_GET(x) != NULL) {
2122 PyCell_Set(x, NULL);
Benjamin Peterson00ebe2c2010-09-10 22:02:31 +00002123 DISPATCH();
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002124 }
2125 err = -1;
2126 format_exc_unbound(co, oparg);
2127 break;
2128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 TARGET(LOAD_CLOSURE)
2130 x = freevars[oparg];
2131 Py_INCREF(x);
2132 PUSH(x);
2133 if (x != NULL) DISPATCH();
2134 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 TARGET(LOAD_DEREF)
2137 x = freevars[oparg];
2138 w = PyCell_Get(x);
2139 if (w != NULL) {
2140 PUSH(w);
2141 DISPATCH();
2142 }
2143 err = -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002144 format_exc_unbound(co, oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 TARGET(STORE_DEREF)
2148 w = POP();
2149 x = freevars[oparg];
2150 PyCell_Set(x, w);
2151 Py_DECREF(w);
2152 DISPATCH();
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 TARGET(BUILD_TUPLE)
2155 x = PyTuple_New(oparg);
2156 if (x != NULL) {
2157 for (; --oparg >= 0;) {
2158 w = POP();
2159 PyTuple_SET_ITEM(x, oparg, w);
2160 }
2161 PUSH(x);
2162 DISPATCH();
2163 }
2164 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 TARGET(BUILD_LIST)
2167 x = PyList_New(oparg);
2168 if (x != NULL) {
2169 for (; --oparg >= 0;) {
2170 w = POP();
2171 PyList_SET_ITEM(x, oparg, w);
2172 }
2173 PUSH(x);
2174 DISPATCH();
2175 }
2176 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 TARGET(BUILD_SET)
2179 x = PySet_New(NULL);
2180 if (x != NULL) {
2181 for (; --oparg >= 0;) {
2182 w = POP();
2183 if (err == 0)
2184 err = PySet_Add(x, w);
2185 Py_DECREF(w);
2186 }
2187 if (err != 0) {
2188 Py_DECREF(x);
2189 break;
2190 }
2191 PUSH(x);
2192 DISPATCH();
2193 }
2194 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 TARGET(BUILD_MAP)
2197 x = _PyDict_NewPresized((Py_ssize_t)oparg);
2198 PUSH(x);
2199 if (x != NULL) DISPATCH();
2200 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 TARGET(STORE_MAP)
2203 w = TOP(); /* key */
2204 u = SECOND(); /* value */
2205 v = THIRD(); /* dict */
2206 STACKADJ(-2);
2207 assert (PyDict_CheckExact(v));
2208 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2209 Py_DECREF(u);
2210 Py_DECREF(w);
2211 if (err == 0) DISPATCH();
2212 break;
Christian Heimes99170a52007-12-19 02:07:34 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 TARGET(MAP_ADD)
2215 w = TOP(); /* key */
2216 u = SECOND(); /* value */
2217 STACKADJ(-2);
2218 v = stack_pointer[-oparg]; /* dict */
2219 assert (PyDict_CheckExact(v));
2220 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2221 Py_DECREF(u);
2222 Py_DECREF(w);
2223 if (err == 0) {
2224 PREDICT(JUMP_ABSOLUTE);
2225 DISPATCH();
2226 }
2227 break;
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 TARGET(LOAD_ATTR)
2230 w = GETITEM(names, oparg);
2231 v = TOP();
2232 x = PyObject_GetAttr(v, w);
2233 Py_DECREF(v);
2234 SET_TOP(x);
2235 if (x != NULL) DISPATCH();
2236 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 TARGET(COMPARE_OP)
2239 w = POP();
2240 v = TOP();
2241 x = cmp_outcome(oparg, v, w);
2242 Py_DECREF(v);
2243 Py_DECREF(w);
2244 SET_TOP(x);
2245 if (x == NULL) break;
2246 PREDICT(POP_JUMP_IF_FALSE);
2247 PREDICT(POP_JUMP_IF_TRUE);
2248 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 TARGET(IMPORT_NAME)
2251 w = GETITEM(names, oparg);
2252 x = PyDict_GetItemString(f->f_builtins, "__import__");
2253 if (x == NULL) {
2254 PyErr_SetString(PyExc_ImportError,
2255 "__import__ not found");
2256 break;
2257 }
2258 Py_INCREF(x);
2259 v = POP();
2260 u = TOP();
2261 if (PyLong_AsLong(u) != -1 || PyErr_Occurred())
2262 w = PyTuple_Pack(5,
2263 w,
2264 f->f_globals,
2265 f->f_locals == NULL ?
2266 Py_None : f->f_locals,
2267 v,
2268 u);
2269 else
2270 w = PyTuple_Pack(4,
2271 w,
2272 f->f_globals,
2273 f->f_locals == NULL ?
2274 Py_None : f->f_locals,
2275 v);
2276 Py_DECREF(v);
2277 Py_DECREF(u);
2278 if (w == NULL) {
2279 u = POP();
2280 Py_DECREF(x);
2281 x = NULL;
2282 break;
2283 }
2284 READ_TIMESTAMP(intr0);
2285 v = x;
2286 x = PyEval_CallObject(v, w);
2287 Py_DECREF(v);
2288 READ_TIMESTAMP(intr1);
2289 Py_DECREF(w);
2290 SET_TOP(x);
2291 if (x != NULL) DISPATCH();
2292 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 TARGET(IMPORT_STAR)
2295 v = POP();
2296 PyFrame_FastToLocals(f);
2297 if ((x = f->f_locals) == NULL) {
2298 PyErr_SetString(PyExc_SystemError,
2299 "no locals found during 'import *'");
2300 break;
2301 }
2302 READ_TIMESTAMP(intr0);
2303 err = import_all_from(x, v);
2304 READ_TIMESTAMP(intr1);
2305 PyFrame_LocalsToFast(f, 0);
2306 Py_DECREF(v);
2307 if (err == 0) DISPATCH();
2308 break;
Guido van Rossum25831651993-05-19 14:50:45 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 TARGET(IMPORT_FROM)
2311 w = GETITEM(names, oparg);
2312 v = TOP();
2313 READ_TIMESTAMP(intr0);
2314 x = import_from(v, w);
2315 READ_TIMESTAMP(intr1);
2316 PUSH(x);
2317 if (x != NULL) DISPATCH();
2318 break;
Thomas Wouters52152252000-08-17 22:55:00 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 TARGET(JUMP_FORWARD)
2321 JUMPBY(oparg);
2322 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE);
2325 TARGET(POP_JUMP_IF_FALSE)
2326 w = POP();
2327 if (w == Py_True) {
2328 Py_DECREF(w);
2329 FAST_DISPATCH();
2330 }
2331 if (w == Py_False) {
2332 Py_DECREF(w);
2333 JUMPTO(oparg);
2334 FAST_DISPATCH();
2335 }
2336 err = PyObject_IsTrue(w);
2337 Py_DECREF(w);
2338 if (err > 0)
2339 err = 0;
2340 else if (err == 0)
2341 JUMPTO(oparg);
2342 else
2343 break;
2344 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE);
2347 TARGET(POP_JUMP_IF_TRUE)
2348 w = POP();
2349 if (w == Py_False) {
2350 Py_DECREF(w);
2351 FAST_DISPATCH();
2352 }
2353 if (w == Py_True) {
2354 Py_DECREF(w);
2355 JUMPTO(oparg);
2356 FAST_DISPATCH();
2357 }
2358 err = PyObject_IsTrue(w);
2359 Py_DECREF(w);
2360 if (err > 0) {
2361 err = 0;
2362 JUMPTO(oparg);
2363 }
2364 else if (err == 0)
2365 ;
2366 else
2367 break;
2368 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 TARGET(JUMP_IF_FALSE_OR_POP)
2371 w = TOP();
2372 if (w == Py_True) {
2373 STACKADJ(-1);
2374 Py_DECREF(w);
2375 FAST_DISPATCH();
2376 }
2377 if (w == Py_False) {
2378 JUMPTO(oparg);
2379 FAST_DISPATCH();
2380 }
2381 err = PyObject_IsTrue(w);
2382 if (err > 0) {
2383 STACKADJ(-1);
2384 Py_DECREF(w);
2385 err = 0;
2386 }
2387 else if (err == 0)
2388 JUMPTO(oparg);
2389 else
2390 break;
2391 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 TARGET(JUMP_IF_TRUE_OR_POP)
2394 w = TOP();
2395 if (w == Py_False) {
2396 STACKADJ(-1);
2397 Py_DECREF(w);
2398 FAST_DISPATCH();
2399 }
2400 if (w == Py_True) {
2401 JUMPTO(oparg);
2402 FAST_DISPATCH();
2403 }
2404 err = PyObject_IsTrue(w);
2405 if (err > 0) {
2406 err = 0;
2407 JUMPTO(oparg);
2408 }
2409 else if (err == 0) {
2410 STACKADJ(-1);
2411 Py_DECREF(w);
2412 }
2413 else
2414 break;
2415 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 PREDICTED_WITH_ARG(JUMP_ABSOLUTE);
2418 TARGET(JUMP_ABSOLUTE)
2419 JUMPTO(oparg);
Guido van Rossum58da9312007-11-10 23:39:45 +00002420#if FAST_LOOPS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 /* Enabling this path speeds-up all while and for-loops by bypassing
2422 the per-loop checks for signals. By default, this should be turned-off
2423 because it prevents detection of a control-break in tight loops like
2424 "while 1: pass". Compile with this option turned-on when you need
2425 the speed-up and do not need break checking inside tight loops (ones
2426 that contain only instructions ending with FAST_DISPATCH).
2427 */
2428 FAST_DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002429#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002431#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 TARGET(GET_ITER)
2434 /* before: [obj]; after [getiter(obj)] */
2435 v = TOP();
2436 x = PyObject_GetIter(v);
2437 Py_DECREF(v);
2438 if (x != NULL) {
2439 SET_TOP(x);
2440 PREDICT(FOR_ITER);
2441 DISPATCH();
2442 }
2443 STACKADJ(-1);
2444 break;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 PREDICTED_WITH_ARG(FOR_ITER);
2447 TARGET(FOR_ITER)
2448 /* before: [iter]; after: [iter, iter()] *or* [] */
2449 v = TOP();
2450 x = (*v->ob_type->tp_iternext)(v);
2451 if (x != NULL) {
2452 PUSH(x);
2453 PREDICT(STORE_FAST);
2454 PREDICT(UNPACK_SEQUENCE);
2455 DISPATCH();
2456 }
2457 if (PyErr_Occurred()) {
2458 if (!PyErr_ExceptionMatches(
2459 PyExc_StopIteration))
2460 break;
2461 PyErr_Clear();
2462 }
2463 /* iterator ended normally */
2464 x = v = POP();
2465 Py_DECREF(v);
2466 JUMPBY(oparg);
2467 DISPATCH();
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 TARGET(BREAK_LOOP)
2470 why = WHY_BREAK;
2471 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 TARGET(CONTINUE_LOOP)
2474 retval = PyLong_FromLong(oparg);
2475 if (!retval) {
2476 x = NULL;
2477 break;
2478 }
2479 why = WHY_CONTINUE;
2480 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally)
2483 TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally)
2484 TARGET(SETUP_FINALLY)
2485 _setup_finally:
2486 /* NOTE: If you add any new block-setup opcodes that
2487 are not try/except/finally handlers, you may need
2488 to update the PyGen_NeedsFinalizing() function.
2489 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
2492 STACK_LEVEL());
2493 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 TARGET(SETUP_WITH)
2496 {
2497 static PyObject *exit, *enter;
2498 w = TOP();
2499 x = special_lookup(w, "__exit__", &exit);
2500 if (!x)
2501 break;
2502 SET_TOP(x);
2503 u = special_lookup(w, "__enter__", &enter);
2504 Py_DECREF(w);
2505 if (!u) {
2506 x = NULL;
2507 break;
2508 }
2509 x = PyObject_CallFunctionObjArgs(u, NULL);
2510 Py_DECREF(u);
2511 if (!x)
2512 break;
2513 /* Setup the finally block before pushing the result
2514 of __enter__ on the stack. */
2515 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
2516 STACK_LEVEL());
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 PUSH(x);
2519 DISPATCH();
2520 }
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 TARGET(WITH_CLEANUP)
2523 {
2524 /* At the top of the stack are 1-3 values indicating
2525 how/why we entered the finally clause:
2526 - TOP = None
2527 - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
2528 - TOP = WHY_*; no retval below it
2529 - (TOP, SECOND, THIRD) = exc_info()
2530 (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER
2531 Below them is EXIT, the context.__exit__ bound method.
2532 In the last case, we must call
2533 EXIT(TOP, SECOND, THIRD)
2534 otherwise we must call
2535 EXIT(None, None, None)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 In the first two cases, we remove EXIT from the
2538 stack, leaving the rest in the same order. In the
2539 third case, we shift the bottom 3 values of the
2540 stack down, and replace the empty spot with NULL.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 In addition, if the stack represents an exception,
2543 *and* the function call returns a 'true' value, we
2544 push WHY_SILENCED onto the stack. END_FINALLY will
2545 then not re-raise the exception. (But non-local
2546 gotos should still be resumed.)
2547 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 PyObject *exit_func;
2550 u = TOP();
2551 if (u == Py_None) {
2552 (void)POP();
2553 exit_func = TOP();
2554 SET_TOP(u);
2555 v = w = Py_None;
2556 }
2557 else if (PyLong_Check(u)) {
2558 (void)POP();
2559 switch(PyLong_AsLong(u)) {
2560 case WHY_RETURN:
2561 case WHY_CONTINUE:
2562 /* Retval in TOP. */
2563 exit_func = SECOND();
2564 SET_SECOND(TOP());
2565 SET_TOP(u);
2566 break;
2567 default:
2568 exit_func = TOP();
2569 SET_TOP(u);
2570 break;
2571 }
2572 u = v = w = Py_None;
2573 }
2574 else {
2575 PyObject *tp, *exc, *tb;
2576 PyTryBlock *block;
2577 v = SECOND();
2578 w = THIRD();
2579 tp = FOURTH();
2580 exc = PEEK(5);
2581 tb = PEEK(6);
2582 exit_func = PEEK(7);
2583 SET_VALUE(7, tb);
2584 SET_VALUE(6, exc);
2585 SET_VALUE(5, tp);
2586 /* UNWIND_EXCEPT_HANDLER will pop this off. */
2587 SET_FOURTH(NULL);
2588 /* We just shifted the stack down, so we have
2589 to tell the except handler block that the
2590 values are lower than it expects. */
2591 block = &f->f_blockstack[f->f_iblock - 1];
2592 assert(block->b_type == EXCEPT_HANDLER);
2593 block->b_level--;
2594 }
2595 /* XXX Not the fastest way to call it... */
2596 x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
2597 NULL);
2598 Py_DECREF(exit_func);
2599 if (x == NULL)
2600 break; /* Go to error exit */
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (u != Py_None)
2603 err = PyObject_IsTrue(x);
2604 else
2605 err = 0;
2606 Py_DECREF(x);
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 if (err < 0)
2609 break; /* Go to error exit */
2610 else if (err > 0) {
2611 err = 0;
2612 /* There was an exception and a True return */
2613 PUSH(PyLong_FromLong((long) WHY_SILENCED));
2614 }
2615 PREDICT(END_FINALLY);
2616 break;
2617 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 TARGET(CALL_FUNCTION)
2620 {
2621 PyObject **sp;
2622 PCALL(PCALL_ALL);
2623 sp = stack_pointer;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002624#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 x = call_function(&sp, oparg, &intr0, &intr1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002626#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 x = call_function(&sp, oparg);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002628#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 stack_pointer = sp;
2630 PUSH(x);
2631 if (x != NULL)
2632 DISPATCH();
2633 break;
2634 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw)
2637 TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw)
2638 TARGET(CALL_FUNCTION_VAR_KW)
2639 _call_function_var_kw:
2640 {
2641 int na = oparg & 0xff;
2642 int nk = (oparg>>8) & 0xff;
2643 int flags = (opcode - CALL_FUNCTION) & 3;
2644 int n = na + 2 * nk;
2645 PyObject **pfunc, *func, **sp;
2646 PCALL(PCALL_ALL);
2647 if (flags & CALL_FLAG_VAR)
2648 n++;
2649 if (flags & CALL_FLAG_KW)
2650 n++;
2651 pfunc = stack_pointer - n - 1;
2652 func = *pfunc;
Jeremy Hylton52820442001-01-03 23:52:36 +00002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (PyMethod_Check(func)
Stefan Krahb7e10102010-06-23 18:42:39 +00002655 && PyMethod_GET_SELF(func) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 PyObject *self = PyMethod_GET_SELF(func);
2657 Py_INCREF(self);
2658 func = PyMethod_GET_FUNCTION(func);
2659 Py_INCREF(func);
2660 Py_DECREF(*pfunc);
2661 *pfunc = self;
2662 na++;
Brett Cannonb94767f2011-02-22 20:15:44 +00002663 /* n++; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 } else
2665 Py_INCREF(func);
2666 sp = stack_pointer;
2667 READ_TIMESTAMP(intr0);
2668 x = ext_do_call(func, &sp, flags, na, nk);
2669 READ_TIMESTAMP(intr1);
2670 stack_pointer = sp;
2671 Py_DECREF(func);
Jeremy Hylton52820442001-01-03 23:52:36 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 while (stack_pointer > pfunc) {
2674 w = POP();
2675 Py_DECREF(w);
2676 }
2677 PUSH(x);
2678 if (x != NULL)
2679 DISPATCH();
2680 break;
2681 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function)
2684 TARGET(MAKE_FUNCTION)
2685 _make_function:
2686 {
2687 int posdefaults = oparg & 0xff;
2688 int kwdefaults = (oparg>>8) & 0xff;
2689 int num_annotations = (oparg >> 16) & 0x7fff;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 v = POP(); /* code object */
2692 x = PyFunction_New(v, f->f_globals);
2693 Py_DECREF(v);
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00002694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 if (x != NULL && opcode == MAKE_CLOSURE) {
2696 v = POP();
2697 if (PyFunction_SetClosure(x, v) != 0) {
2698 /* Can't happen unless bytecode is corrupt. */
2699 why = WHY_EXCEPTION;
2700 }
2701 Py_DECREF(v);
2702 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 if (x != NULL && num_annotations > 0) {
2705 Py_ssize_t name_ix;
2706 u = POP(); /* names of args with annotations */
2707 v = PyDict_New();
2708 if (v == NULL) {
2709 Py_DECREF(x);
2710 x = NULL;
2711 break;
2712 }
2713 name_ix = PyTuple_Size(u);
2714 assert(num_annotations == name_ix+1);
2715 while (name_ix > 0) {
2716 --name_ix;
2717 t = PyTuple_GET_ITEM(u, name_ix);
2718 w = POP();
2719 /* XXX(nnorwitz): check for errors */
2720 PyDict_SetItem(v, t, w);
2721 Py_DECREF(w);
2722 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 if (PyFunction_SetAnnotations(x, v) != 0) {
2725 /* Can't happen unless
2726 PyFunction_SetAnnotations changes. */
2727 why = WHY_EXCEPTION;
2728 }
2729 Py_DECREF(v);
2730 Py_DECREF(u);
2731 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 /* XXX Maybe this should be a separate opcode? */
2734 if (x != NULL && posdefaults > 0) {
2735 v = PyTuple_New(posdefaults);
2736 if (v == NULL) {
2737 Py_DECREF(x);
2738 x = NULL;
2739 break;
2740 }
2741 while (--posdefaults >= 0) {
2742 w = POP();
2743 PyTuple_SET_ITEM(v, posdefaults, w);
2744 }
2745 if (PyFunction_SetDefaults(x, v) != 0) {
2746 /* Can't happen unless
2747 PyFunction_SetDefaults changes. */
2748 why = WHY_EXCEPTION;
2749 }
2750 Py_DECREF(v);
2751 }
2752 if (x != NULL && kwdefaults > 0) {
2753 v = PyDict_New();
2754 if (v == NULL) {
2755 Py_DECREF(x);
2756 x = NULL;
2757 break;
2758 }
2759 while (--kwdefaults >= 0) {
2760 w = POP(); /* default value */
2761 u = POP(); /* kw only arg name */
2762 /* XXX(nnorwitz): check for errors */
2763 PyDict_SetItem(v, u, w);
2764 Py_DECREF(w);
2765 Py_DECREF(u);
2766 }
2767 if (PyFunction_SetKwDefaults(x, v) != 0) {
2768 /* Can't happen unless
2769 PyFunction_SetKwDefaults changes. */
2770 why = WHY_EXCEPTION;
2771 }
2772 Py_DECREF(v);
2773 }
2774 PUSH(x);
2775 break;
2776 }
Guido van Rossum8861b741996-07-30 16:49:37 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 TARGET(BUILD_SLICE)
2779 if (oparg == 3)
2780 w = POP();
2781 else
2782 w = NULL;
2783 v = POP();
2784 u = TOP();
2785 x = PySlice_New(u, v, w);
2786 Py_DECREF(u);
2787 Py_DECREF(v);
2788 Py_XDECREF(w);
2789 SET_TOP(x);
2790 if (x != NULL) DISPATCH();
2791 break;
Guido van Rossum8861b741996-07-30 16:49:37 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 TARGET(EXTENDED_ARG)
2794 opcode = NEXTOP();
2795 oparg = oparg<<16 | NEXTARG();
2796 goto dispatch_opcode;
Guido van Rossum8861b741996-07-30 16:49:37 +00002797
Antoine Pitrou042b1282010-08-13 21:15:58 +00002798#if USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 _unknown_opcode:
Antoine Pitroub52ec782009-01-25 16:34:23 +00002800#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 default:
2802 fprintf(stderr,
2803 "XXX lineno: %d, opcode: %d\n",
2804 PyFrame_GetLineNumber(f),
2805 opcode);
2806 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2807 why = WHY_EXCEPTION;
2808 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00002809
2810#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 }
Guido van Rossum04691fc1992-08-12 15:35:34 +00002812#endif
2813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 } /* switch */
Guido van Rossum374a9221991-04-04 10:40:29 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 on_error:
Guido van Rossumac7be682001-01-17 15:42:30 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 READ_TIMESTAMP(inst1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* Quickly continue if no error occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 if (why == WHY_NOT) {
2823 if (err == 0 && x != NULL) {
Guido van Rossum681d79a1995-07-18 14:51:37 +00002824#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* This check is expensive! */
2826 if (PyErr_Occurred())
2827 fprintf(stderr,
2828 "XXX undetected error\n");
2829 else {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002830#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 READ_TIMESTAMP(loop1);
2832 continue; /* Normal, fast path */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002833#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 }
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002835#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 }
2837 why = WHY_EXCEPTION;
2838 x = Py_None;
2839 err = 0;
2840 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 /* Double-check exception status */
Guido van Rossumac7be682001-01-17 15:42:30 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2845 if (!PyErr_Occurred()) {
2846 PyErr_SetString(PyExc_SystemError,
2847 "error return without exception set");
2848 why = WHY_EXCEPTION;
2849 }
2850 }
Guido van Rossumeb894eb1999-03-09 16:16:45 +00002851#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 else {
2853 /* This check is expensive! */
2854 if (PyErr_Occurred()) {
2855 char buf[128];
2856 sprintf(buf, "Stack unwind with exception "
2857 "set and why=%d", why);
2858 Py_FatalError(buf);
2859 }
2860 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002861#endif
2862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 /* Log traceback info if this is a real exception */
Guido van Rossumac7be682001-01-17 15:42:30 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 if (why == WHY_EXCEPTION) {
2866 PyTraceBack_Here(f);
Guido van Rossum96a42c81992-01-12 02:29:51 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 if (tstate->c_tracefunc != NULL)
2869 call_exc_trace(tstate->c_tracefunc,
2870 tstate->c_traceobj, f);
2871 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
Guido van Rossumac7be682001-01-17 15:42:30 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 if (why == WHY_RERAISE)
2876 why = WHY_EXCEPTION;
Guido van Rossum374a9221991-04-04 10:40:29 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 /* Unwind stacks if a (pseudo) exception occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002879
Raymond Hettinger1dd83092004-02-06 18:32:33 +00002880fast_block_end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 while (why != WHY_NOT && f->f_iblock > 0) {
2882 /* Peek at the current block. */
2883 PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1];
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 assert(why != WHY_YIELD);
2886 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
2887 why = WHY_NOT;
2888 JUMPTO(PyLong_AS_LONG(retval));
2889 Py_DECREF(retval);
2890 break;
2891 }
2892 /* Now we have to pop the block. */
2893 f->f_iblock--;
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 if (b->b_type == EXCEPT_HANDLER) {
2896 UNWIND_EXCEPT_HANDLER(b);
2897 continue;
2898 }
2899 UNWIND_BLOCK(b);
2900 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2901 why = WHY_NOT;
2902 JUMPTO(b->b_handler);
2903 break;
2904 }
2905 if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT
2906 || b->b_type == SETUP_FINALLY)) {
2907 PyObject *exc, *val, *tb;
2908 int handler = b->b_handler;
2909 /* Beware, this invalidates all b->b_* fields */
2910 PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL());
2911 PUSH(tstate->exc_traceback);
2912 PUSH(tstate->exc_value);
2913 if (tstate->exc_type != NULL) {
2914 PUSH(tstate->exc_type);
2915 }
2916 else {
2917 Py_INCREF(Py_None);
2918 PUSH(Py_None);
2919 }
2920 PyErr_Fetch(&exc, &val, &tb);
2921 /* Make the raw exception data
2922 available to the handler,
2923 so a program can emulate the
2924 Python main loop. */
2925 PyErr_NormalizeException(
2926 &exc, &val, &tb);
2927 PyException_SetTraceback(val, tb);
2928 Py_INCREF(exc);
2929 tstate->exc_type = exc;
2930 Py_INCREF(val);
2931 tstate->exc_value = val;
2932 tstate->exc_traceback = tb;
2933 if (tb == NULL)
2934 tb = Py_None;
2935 Py_INCREF(tb);
2936 PUSH(tb);
2937 PUSH(val);
2938 PUSH(exc);
2939 why = WHY_NOT;
2940 JUMPTO(handler);
2941 break;
2942 }
2943 if (b->b_type == SETUP_FINALLY) {
2944 if (why & (WHY_RETURN | WHY_CONTINUE))
2945 PUSH(retval);
2946 PUSH(PyLong_FromLong((long)why));
2947 why = WHY_NOT;
2948 JUMPTO(b->b_handler);
2949 break;
2950 }
2951 } /* unwind stack */
Guido van Rossum374a9221991-04-04 10:40:29 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 /* End the loop if we still have an error (or return) */
Guido van Rossumac7be682001-01-17 15:42:30 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 if (why != WHY_NOT)
2956 break;
2957 READ_TIMESTAMP(loop1);
Guido van Rossumac7be682001-01-17 15:42:30 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 } /* main loop */
Guido van Rossumac7be682001-01-17 15:42:30 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 assert(why != WHY_YIELD);
2962 /* Pop remaining stack entries. */
2963 while (!EMPTY()) {
2964 v = POP();
2965 Py_XDECREF(v);
2966 }
Guido van Rossum35974fb2001-12-06 21:28:18 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 if (why != WHY_RETURN)
2969 retval = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00002970
Raymond Hettinger1dd83092004-02-06 18:32:33 +00002971fast_yield:
Benjamin Petersonac913412011-07-03 16:25:11 -05002972 if (co->co_flags & CO_GENERATOR && (why == WHY_YIELD || why == WHY_RETURN)) {
2973 /* The purpose of this block is to put aside the generator's exception
2974 state and restore that of the calling frame. If the current
2975 exception state is from the caller, we clear the exception values
2976 on the generator frame, so they are not swapped back in latter. The
2977 origin of the current exception state is determined by checking for
2978 except handler blocks, which we must be in iff a new exception
2979 state came into existence in this frame. (An uncaught exception
2980 would have why == WHY_EXCEPTION, and we wouldn't be here). */
2981 int i;
2982 for (i = 0; i < f->f_iblock; i++)
2983 if (f->f_blockstack[i].b_type == EXCEPT_HANDLER)
2984 break;
2985 if (i == f->f_iblock)
2986 /* We did not create this exception. */
Benjamin Peterson87880242011-07-03 16:48:31 -05002987 restore_and_clear_exc_state(tstate, f);
Benjamin Petersonac913412011-07-03 16:25:11 -05002988 else
Benjamin Peterson87880242011-07-03 16:48:31 -05002989 swap_exc_state(tstate, f);
Benjamin Petersonac913412011-07-03 16:25:11 -05002990 }
Benjamin Peterson83195c32011-07-03 13:44:00 -05002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 if (tstate->use_tracing) {
2993 if (tstate->c_tracefunc) {
2994 if (why == WHY_RETURN || why == WHY_YIELD) {
2995 if (call_trace(tstate->c_tracefunc,
2996 tstate->c_traceobj, f,
2997 PyTrace_RETURN, retval)) {
2998 Py_XDECREF(retval);
2999 retval = NULL;
3000 why = WHY_EXCEPTION;
3001 }
3002 }
3003 else if (why == WHY_EXCEPTION) {
3004 call_trace_protected(tstate->c_tracefunc,
3005 tstate->c_traceobj, f,
3006 PyTrace_RETURN, NULL);
3007 }
3008 }
3009 if (tstate->c_profilefunc) {
3010 if (why == WHY_EXCEPTION)
3011 call_trace_protected(tstate->c_profilefunc,
3012 tstate->c_profileobj, f,
3013 PyTrace_RETURN, NULL);
3014 else if (call_trace(tstate->c_profilefunc,
3015 tstate->c_profileobj, f,
3016 PyTrace_RETURN, retval)) {
3017 Py_XDECREF(retval);
3018 retval = NULL;
Brett Cannonb94767f2011-02-22 20:15:44 +00003019 /* why = WHY_EXCEPTION; */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 }
3021 }
3022 }
Guido van Rossuma4240131997-01-21 21:18:36 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 /* pop frame */
Thomas Woutersce272b62007-09-19 21:19:28 +00003025exit_eval_frame:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 Py_LeaveRecursiveCall();
3027 tstate->frame = f->f_back;
Guido van Rossumac7be682001-01-17 15:42:30 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 return retval;
Guido van Rossum374a9221991-04-04 10:40:29 +00003030}
3031
Benjamin Petersonb204a422011-06-05 22:04:07 -05003032static void
Benjamin Petersone109c702011-06-24 09:37:26 -05003033format_missing(const char *kind, PyCodeObject *co, PyObject *names)
3034{
3035 int err;
3036 Py_ssize_t len = PyList_GET_SIZE(names);
3037 PyObject *name_str, *comma, *tail, *tmp;
3038
3039 assert(PyList_CheckExact(names));
3040 assert(len >= 1);
3041 /* Deal with the joys of natural language. */
3042 switch (len) {
3043 case 1:
3044 name_str = PyList_GET_ITEM(names, 0);
3045 Py_INCREF(name_str);
3046 break;
3047 case 2:
3048 name_str = PyUnicode_FromFormat("%U and %U",
3049 PyList_GET_ITEM(names, len - 2),
3050 PyList_GET_ITEM(names, len - 1));
3051 break;
3052 default:
3053 tail = PyUnicode_FromFormat(", %U, and %U",
3054 PyList_GET_ITEM(names, len - 2),
3055 PyList_GET_ITEM(names, len - 1));
3056 /* Chop off the last two objects in the list. This shouldn't actually
3057 fail, but we can't be too careful. */
3058 err = PyList_SetSlice(names, len - 2, len, NULL);
3059 if (err == -1) {
3060 Py_DECREF(tail);
3061 return;
3062 }
3063 /* Stitch everything up into a nice comma-separated list. */
3064 comma = PyUnicode_FromString(", ");
3065 if (comma == NULL) {
3066 Py_DECREF(tail);
3067 return;
3068 }
3069 tmp = PyUnicode_Join(comma, names);
3070 Py_DECREF(comma);
3071 if (tmp == NULL) {
3072 Py_DECREF(tail);
3073 return;
3074 }
3075 name_str = PyUnicode_Concat(tmp, tail);
3076 Py_DECREF(tmp);
3077 Py_DECREF(tail);
3078 break;
3079 }
3080 if (name_str == NULL)
3081 return;
3082 PyErr_Format(PyExc_TypeError,
3083 "%U() missing %i required %s argument%s: %U",
3084 co->co_name,
3085 len,
3086 kind,
3087 len == 1 ? "" : "s",
3088 name_str);
3089 Py_DECREF(name_str);
3090}
3091
3092static void
3093missing_arguments(PyCodeObject *co, int missing, int defcount,
3094 PyObject **fastlocals)
3095{
3096 int i, j = 0;
3097 int start, end;
3098 int positional = defcount != -1;
3099 const char *kind = positional ? "positional" : "keyword-only";
3100 PyObject *missing_names;
3101
3102 /* Compute the names of the arguments that are missing. */
3103 missing_names = PyList_New(missing);
3104 if (missing_names == NULL)
3105 return;
3106 if (positional) {
3107 start = 0;
3108 end = co->co_argcount - defcount;
3109 }
3110 else {
3111 start = co->co_argcount;
3112 end = start + co->co_kwonlyargcount;
3113 }
3114 for (i = start; i < end; i++) {
3115 if (GETLOCAL(i) == NULL) {
3116 PyObject *raw = PyTuple_GET_ITEM(co->co_varnames, i);
3117 PyObject *name = PyObject_Repr(raw);
3118 if (name == NULL) {
3119 Py_DECREF(missing_names);
3120 return;
3121 }
3122 PyList_SET_ITEM(missing_names, j++, name);
3123 }
3124 }
3125 assert(j == missing);
3126 format_missing(kind, co, missing_names);
3127 Py_DECREF(missing_names);
3128}
3129
3130static void
3131too_many_positional(PyCodeObject *co, int given, int defcount, PyObject **fastlocals)
Benjamin Petersonb204a422011-06-05 22:04:07 -05003132{
3133 int plural;
3134 int kwonly_given = 0;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003135 int i;
3136 PyObject *sig, *kwonly_sig;
3137
Benjamin Petersone109c702011-06-24 09:37:26 -05003138 assert((co->co_flags & CO_VARARGS) == 0);
3139 /* Count missing keyword-only args. */
Benjamin Petersonb204a422011-06-05 22:04:07 -05003140 for (i = co->co_argcount; i < co->co_argcount + co->co_kwonlyargcount; i++)
Benjamin Petersone109c702011-06-24 09:37:26 -05003141 if (GETLOCAL(i) != NULL)
Benjamin Petersonb204a422011-06-05 22:04:07 -05003142 kwonly_given++;
Benjamin Petersone109c702011-06-24 09:37:26 -05003143 if (defcount) {
3144 int atleast = co->co_argcount - defcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003145 plural = 1;
3146 sig = PyUnicode_FromFormat("from %d to %d", atleast, co->co_argcount);
3147 }
3148 else {
3149 plural = co->co_argcount != 1;
3150 sig = PyUnicode_FromFormat("%d", co->co_argcount);
3151 }
3152 if (sig == NULL)
3153 return;
3154 if (kwonly_given) {
3155 const char *format = " positional argument%s (and %d keyword-only argument%s)";
3156 kwonly_sig = PyUnicode_FromFormat(format, given != 1 ? "s" : "", kwonly_given,
3157 kwonly_given != 1 ? "s" : "");
3158 if (kwonly_sig == NULL) {
3159 Py_DECREF(sig);
3160 return;
3161 }
3162 }
3163 else {
3164 /* This will not fail. */
3165 kwonly_sig = PyUnicode_FromString("");
Benjamin Petersone109c702011-06-24 09:37:26 -05003166 assert(kwonly_sig != NULL);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003167 }
3168 PyErr_Format(PyExc_TypeError,
3169 "%U() takes %U positional argument%s but %d%U %s given",
3170 co->co_name,
3171 sig,
3172 plural ? "s" : "",
3173 given,
3174 kwonly_sig,
3175 given == 1 && !kwonly_given ? "was" : "were");
3176 Py_DECREF(sig);
3177 Py_DECREF(kwonly_sig);
3178}
3179
Guido van Rossumc2e20742006-02-27 22:32:47 +00003180/* This is gonna seem *real weird*, but if you put some other code between
Martin v. Löwis8d97e332004-06-27 15:43:12 +00003181 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
Guido van Rossumc2e20742006-02-27 22:32:47 +00003182 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
Skip Montanaro786ea6b2004-03-01 15:44:05 +00003183
Tim Peters6d6c1a32001-08-02 04:15:00 +00003184PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003185PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 PyObject **args, int argcount, PyObject **kws, int kwcount,
3187 PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure)
Tim Peters5ca576e2001-06-18 22:08:13 +00003188{
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003189 PyCodeObject* co = (PyCodeObject*)_co;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 register PyFrameObject *f;
3191 register PyObject *retval = NULL;
3192 register PyObject **fastlocals, **freevars;
3193 PyThreadState *tstate = PyThreadState_GET();
3194 PyObject *x, *u;
3195 int total_args = co->co_argcount + co->co_kwonlyargcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003196 int i;
3197 int n = argcount;
3198 PyObject *kwdict = NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 if (globals == NULL) {
3201 PyErr_SetString(PyExc_SystemError,
3202 "PyEval_EvalCodeEx: NULL globals");
3203 return NULL;
3204 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 assert(tstate != NULL);
3207 assert(globals != NULL);
3208 f = PyFrame_New(tstate, co, globals, locals);
3209 if (f == NULL)
3210 return NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 fastlocals = f->f_localsplus;
3213 freevars = f->f_localsplus + co->co_nlocals;
Tim Peters5ca576e2001-06-18 22:08:13 +00003214
Benjamin Petersonb204a422011-06-05 22:04:07 -05003215 /* Parse arguments. */
3216 if (co->co_flags & CO_VARKEYWORDS) {
3217 kwdict = PyDict_New();
3218 if (kwdict == NULL)
3219 goto fail;
3220 i = total_args;
3221 if (co->co_flags & CO_VARARGS)
3222 i++;
3223 SETLOCAL(i, kwdict);
3224 }
3225 if (argcount > co->co_argcount)
3226 n = co->co_argcount;
3227 for (i = 0; i < n; i++) {
3228 x = args[i];
3229 Py_INCREF(x);
3230 SETLOCAL(i, x);
3231 }
3232 if (co->co_flags & CO_VARARGS) {
3233 u = PyTuple_New(argcount - n);
3234 if (u == NULL)
3235 goto fail;
3236 SETLOCAL(total_args, u);
3237 for (i = n; i < argcount; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 x = args[i];
3239 Py_INCREF(x);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003240 PyTuple_SET_ITEM(u, i-n, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003242 }
3243 for (i = 0; i < kwcount; i++) {
3244 PyObject **co_varnames;
3245 PyObject *keyword = kws[2*i];
3246 PyObject *value = kws[2*i + 1];
3247 int j;
3248 if (keyword == NULL || !PyUnicode_Check(keyword)) {
3249 PyErr_Format(PyExc_TypeError,
3250 "%U() keywords must be strings",
3251 co->co_name);
3252 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003254 /* Speed hack: do raw pointer compares. As names are
3255 normally interned this should almost always hit. */
3256 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
3257 for (j = 0; j < total_args; j++) {
3258 PyObject *nm = co_varnames[j];
3259 if (nm == keyword)
3260 goto kw_found;
3261 }
3262 /* Slow fallback, just in case */
3263 for (j = 0; j < total_args; j++) {
3264 PyObject *nm = co_varnames[j];
3265 int cmp = PyObject_RichCompareBool(
3266 keyword, nm, Py_EQ);
3267 if (cmp > 0)
3268 goto kw_found;
3269 else if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 goto fail;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003271 }
3272 if (j >= total_args && kwdict == NULL) {
3273 PyErr_Format(PyExc_TypeError,
3274 "%U() got an unexpected "
3275 "keyword argument '%S'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 co->co_name,
3277 keyword);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003278 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003280 PyDict_SetItem(kwdict, keyword, value);
3281 continue;
3282 kw_found:
3283 if (GETLOCAL(j) != NULL) {
3284 PyErr_Format(PyExc_TypeError,
3285 "%U() got multiple "
3286 "values for argument '%S'",
3287 co->co_name,
3288 keyword);
3289 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003291 Py_INCREF(value);
3292 SETLOCAL(j, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003294 if (argcount > co->co_argcount && !(co->co_flags & CO_VARARGS)) {
Benjamin Petersone109c702011-06-24 09:37:26 -05003295 too_many_positional(co, argcount, defcount, fastlocals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 goto fail;
3297 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05003298 if (argcount < co->co_argcount) {
3299 int m = co->co_argcount - defcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05003300 int missing = 0;
3301 for (i = argcount; i < m; i++)
3302 if (GETLOCAL(i) == NULL)
3303 missing++;
3304 if (missing) {
3305 missing_arguments(co, missing, defcount, fastlocals);
3306 goto fail;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003307 }
3308 if (n > m)
3309 i = n - m;
3310 else
3311 i = 0;
3312 for (; i < defcount; i++) {
3313 if (GETLOCAL(m+i) == NULL) {
3314 PyObject *def = defs[i];
3315 Py_INCREF(def);
3316 SETLOCAL(m+i, def);
3317 }
3318 }
3319 }
3320 if (co->co_kwonlyargcount > 0) {
Benjamin Petersone109c702011-06-24 09:37:26 -05003321 int missing = 0;
Benjamin Petersonb204a422011-06-05 22:04:07 -05003322 for (i = co->co_argcount; i < total_args; i++) {
3323 PyObject *name;
3324 if (GETLOCAL(i) != NULL)
3325 continue;
3326 name = PyTuple_GET_ITEM(co->co_varnames, i);
3327 if (kwdefs != NULL) {
3328 PyObject *def = PyDict_GetItem(kwdefs, name);
3329 if (def) {
3330 Py_INCREF(def);
3331 SETLOCAL(i, def);
3332 continue;
3333 }
3334 }
Benjamin Petersone109c702011-06-24 09:37:26 -05003335 missing++;
3336 }
3337 if (missing) {
3338 missing_arguments(co, missing, -1, fastlocals);
Benjamin Petersonb204a422011-06-05 22:04:07 -05003339 goto fail;
3340 }
3341 }
3342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 /* Allocate and initialize storage for cell vars, and copy free
Benjamin Peterson90037602011-06-25 22:54:45 -05003344 vars into frame. */
3345 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 PyObject *c;
Benjamin Peterson90037602011-06-25 22:54:45 -05003347 int arg;
3348 /* Possibly account for the cell variable being an argument. */
3349 if (co->co_cell2arg != NULL &&
3350 (arg = co->co_cell2arg[i]) != CO_CELL_NOT_AN_ARG)
3351 c = PyCell_New(GETLOCAL(arg));
3352 else
3353 c = PyCell_New(NULL);
3354 if (c == NULL)
3355 goto fail;
3356 SETLOCAL(co->co_nlocals + i, c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 }
Benjamin Peterson90037602011-06-25 22:54:45 -05003358 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
3359 PyObject *o = PyTuple_GET_ITEM(closure, i);
3360 Py_INCREF(o);
3361 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 if (co->co_flags & CO_GENERATOR) {
3365 /* Don't need to keep the reference to f_back, it will be set
3366 * when the generator is resumed. */
3367 Py_XDECREF(f->f_back);
3368 f->f_back = NULL;
Neil Schemenauer2b13ce82001-06-21 02:41:10 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 PCALL(PCALL_GENERATOR);
Jeremy Hylton985eba52003-02-05 23:13:00 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 /* Create a new generator that owns the ready to run frame
3373 * and return that as the value. */
3374 return PyGen_New(f);
3375 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 retval = PyEval_EvalFrameEx(f,0);
Tim Peters5ca576e2001-06-18 22:08:13 +00003378
Thomas Woutersce272b62007-09-19 21:19:28 +00003379fail: /* Jump here from prelude on failure */
Tim Peters5ca576e2001-06-18 22:08:13 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 /* decref'ing the frame can cause __del__ methods to get invoked,
3382 which can call back into Python. While we're done with the
3383 current Python frame (f), the associated C stack is still in use,
3384 so recursion_depth must be boosted for the duration.
3385 */
3386 assert(tstate != NULL);
3387 ++tstate->recursion_depth;
3388 Py_DECREF(f);
3389 --tstate->recursion_depth;
3390 return retval;
Tim Peters5ca576e2001-06-18 22:08:13 +00003391}
3392
3393
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003394static PyObject *
3395special_lookup(PyObject *o, char *meth, PyObject **cache)
3396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 PyObject *res;
3398 res = _PyObject_LookupSpecial(o, meth, cache);
3399 if (res == NULL && !PyErr_Occurred()) {
3400 PyErr_SetObject(PyExc_AttributeError, *cache);
3401 return NULL;
3402 }
3403 return res;
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003404}
3405
3406
Benjamin Peterson87880242011-07-03 16:48:31 -05003407/* These 3 functions deal with the exception state of generators. */
3408
3409static void
3410save_exc_state(PyThreadState *tstate, PyFrameObject *f)
3411{
3412 PyObject *type, *value, *traceback;
3413 Py_XINCREF(tstate->exc_type);
3414 Py_XINCREF(tstate->exc_value);
3415 Py_XINCREF(tstate->exc_traceback);
3416 type = f->f_exc_type;
3417 value = f->f_exc_value;
3418 traceback = f->f_exc_traceback;
3419 f->f_exc_type = tstate->exc_type;
3420 f->f_exc_value = tstate->exc_value;
3421 f->f_exc_traceback = tstate->exc_traceback;
3422 Py_XDECREF(type);
3423 Py_XDECREF(value);
3424 Py_XDECREF(traceback);
3425}
3426
3427static void
3428swap_exc_state(PyThreadState *tstate, PyFrameObject *f)
3429{
3430 PyObject *tmp;
3431 tmp = tstate->exc_type;
3432 tstate->exc_type = f->f_exc_type;
3433 f->f_exc_type = tmp;
3434 tmp = tstate->exc_value;
3435 tstate->exc_value = f->f_exc_value;
3436 f->f_exc_value = tmp;
3437 tmp = tstate->exc_traceback;
3438 tstate->exc_traceback = f->f_exc_traceback;
3439 f->f_exc_traceback = tmp;
3440}
3441
3442static void
3443restore_and_clear_exc_state(PyThreadState *tstate, PyFrameObject *f)
3444{
3445 PyObject *type, *value, *tb;
3446 type = tstate->exc_type;
3447 value = tstate->exc_value;
3448 tb = tstate->exc_traceback;
3449 tstate->exc_type = f->f_exc_type;
3450 tstate->exc_value = f->f_exc_value;
3451 tstate->exc_traceback = f->f_exc_traceback;
3452 f->f_exc_type = NULL;
3453 f->f_exc_value = NULL;
3454 f->f_exc_traceback = NULL;
3455 Py_XDECREF(type);
3456 Py_XDECREF(value);
3457 Py_XDECREF(tb);
3458}
3459
3460
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003461/* Logic for the raise statement (too complicated for inlining).
3462 This *consumes* a reference count to each of its arguments. */
Raymond Hettinger7c958652004-04-06 10:11:10 +00003463static enum why_code
Collin Winter828f04a2007-08-31 00:04:24 +00003464do_raise(PyObject *exc, PyObject *cause)
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 PyObject *type = NULL, *value = NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00003467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 if (exc == NULL) {
3469 /* Reraise */
3470 PyThreadState *tstate = PyThreadState_GET();
3471 PyObject *tb;
3472 type = tstate->exc_type;
3473 value = tstate->exc_value;
3474 tb = tstate->exc_traceback;
3475 if (type == Py_None) {
3476 PyErr_SetString(PyExc_RuntimeError,
3477 "No active exception to reraise");
3478 return WHY_EXCEPTION;
3479 }
3480 Py_XINCREF(type);
3481 Py_XINCREF(value);
3482 Py_XINCREF(tb);
3483 PyErr_Restore(type, value, tb);
3484 return WHY_RERAISE;
3485 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 /* We support the following forms of raise:
3488 raise
Collin Winter828f04a2007-08-31 00:04:24 +00003489 raise <instance>
3490 raise <type> */
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 if (PyExceptionClass_Check(exc)) {
3493 type = exc;
3494 value = PyObject_CallObject(exc, NULL);
3495 if (value == NULL)
3496 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05003497 if (!PyExceptionInstance_Check(value)) {
3498 PyErr_Format(PyExc_TypeError,
3499 "calling %R should have returned an instance of "
3500 "BaseException, not %R",
3501 type, Py_TYPE(value));
3502 goto raise_error;
3503 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 }
3505 else if (PyExceptionInstance_Check(exc)) {
3506 value = exc;
3507 type = PyExceptionInstance_Class(exc);
3508 Py_INCREF(type);
3509 }
3510 else {
3511 /* Not something you can raise. You get an exception
3512 anyway, just not what you specified :-) */
3513 Py_DECREF(exc);
3514 PyErr_SetString(PyExc_TypeError,
3515 "exceptions must derive from BaseException");
3516 goto raise_error;
3517 }
Collin Winter828f04a2007-08-31 00:04:24 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 if (cause) {
3520 PyObject *fixed_cause;
3521 if (PyExceptionClass_Check(cause)) {
3522 fixed_cause = PyObject_CallObject(cause, NULL);
3523 if (fixed_cause == NULL)
3524 goto raise_error;
3525 Py_DECREF(cause);
3526 }
3527 else if (PyExceptionInstance_Check(cause)) {
3528 fixed_cause = cause;
3529 }
3530 else {
3531 PyErr_SetString(PyExc_TypeError,
3532 "exception causes must derive from "
3533 "BaseException");
3534 goto raise_error;
3535 }
3536 PyException_SetCause(value, fixed_cause);
3537 }
Collin Winter828f04a2007-08-31 00:04:24 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 PyErr_SetObject(type, value);
3540 /* PyErr_SetObject incref's its arguments */
3541 Py_XDECREF(value);
3542 Py_XDECREF(type);
3543 return WHY_EXCEPTION;
Collin Winter828f04a2007-08-31 00:04:24 +00003544
3545raise_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 Py_XDECREF(value);
3547 Py_XDECREF(type);
3548 Py_XDECREF(cause);
3549 return WHY_EXCEPTION;
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003550}
3551
Tim Petersd6d010b2001-06-21 02:49:55 +00003552/* Iterate v argcnt times and store the results on the stack (via decreasing
Guido van Rossum0368b722007-05-11 16:50:42 +00003553 sp). Return 1 for success, 0 if error.
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00003554
Guido van Rossum0368b722007-05-11 16:50:42 +00003555 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
3556 with a variable target.
3557*/
Tim Petersd6d010b2001-06-21 02:49:55 +00003558
Barry Warsawe42b18f1997-08-25 22:13:04 +00003559static int
Guido van Rossum0368b722007-05-11 16:50:42 +00003560unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp)
Barry Warsawe42b18f1997-08-25 22:13:04 +00003561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 int i = 0, j = 0;
3563 Py_ssize_t ll = 0;
3564 PyObject *it; /* iter(v) */
3565 PyObject *w;
3566 PyObject *l = NULL; /* variable list */
Guido van Rossumac7be682001-01-17 15:42:30 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 assert(v != NULL);
Tim Petersd6d010b2001-06-21 02:49:55 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 it = PyObject_GetIter(v);
3571 if (it == NULL)
3572 goto Error;
Tim Petersd6d010b2001-06-21 02:49:55 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 for (; i < argcnt; i++) {
3575 w = PyIter_Next(it);
3576 if (w == NULL) {
3577 /* Iterator done, via error or exhaustion. */
3578 if (!PyErr_Occurred()) {
3579 PyErr_Format(PyExc_ValueError,
3580 "need more than %d value%s to unpack",
3581 i, i == 1 ? "" : "s");
3582 }
3583 goto Error;
3584 }
3585 *--sp = w;
3586 }
Tim Petersd6d010b2001-06-21 02:49:55 +00003587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 if (argcntafter == -1) {
3589 /* We better have exhausted the iterator now. */
3590 w = PyIter_Next(it);
3591 if (w == NULL) {
3592 if (PyErr_Occurred())
3593 goto Error;
3594 Py_DECREF(it);
3595 return 1;
3596 }
3597 Py_DECREF(w);
Georg Brandl0310a832010-07-10 10:32:36 +00003598 PyErr_Format(PyExc_ValueError, "too many values to unpack "
3599 "(expected %d)", argcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 goto Error;
3601 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 l = PySequence_List(it);
3604 if (l == NULL)
3605 goto Error;
3606 *--sp = l;
3607 i++;
Guido van Rossum0368b722007-05-11 16:50:42 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 ll = PyList_GET_SIZE(l);
3610 if (ll < argcntafter) {
3611 PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack",
3612 argcnt + ll);
3613 goto Error;
3614 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 /* Pop the "after-variable" args off the list. */
3617 for (j = argcntafter; j > 0; j--, i++) {
3618 *--sp = PyList_GET_ITEM(l, ll - j);
3619 }
3620 /* Resize the list. */
3621 Py_SIZE(l) = ll - argcntafter;
3622 Py_DECREF(it);
3623 return 1;
Guido van Rossum0368b722007-05-11 16:50:42 +00003624
Tim Petersd6d010b2001-06-21 02:49:55 +00003625Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 for (; i > 0; i--, sp++)
3627 Py_DECREF(*sp);
3628 Py_XDECREF(it);
3629 return 0;
Barry Warsawe42b18f1997-08-25 22:13:04 +00003630}
3631
3632
Guido van Rossum96a42c81992-01-12 02:29:51 +00003633#ifdef LLTRACE
Guido van Rossum3f5da241990-12-20 15:06:42 +00003634static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003635prtrace(PyObject *v, char *str)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 printf("%s ", str);
3638 if (PyObject_Print(v, stdout, 0) != 0)
3639 PyErr_Clear(); /* Don't know what else to do */
3640 printf("\n");
3641 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003642}
Guido van Rossum3f5da241990-12-20 15:06:42 +00003643#endif
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003644
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003645static void
Fred Drake5755ce62001-06-27 19:19:46 +00003646call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 PyObject *type, *value, *traceback, *arg;
3649 int err;
3650 PyErr_Fetch(&type, &value, &traceback);
3651 if (value == NULL) {
3652 value = Py_None;
3653 Py_INCREF(value);
3654 }
3655 arg = PyTuple_Pack(3, type, value, traceback);
3656 if (arg == NULL) {
3657 PyErr_Restore(type, value, traceback);
3658 return;
3659 }
3660 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
3661 Py_DECREF(arg);
3662 if (err == 0)
3663 PyErr_Restore(type, value, traceback);
3664 else {
3665 Py_XDECREF(type);
3666 Py_XDECREF(value);
3667 Py_XDECREF(traceback);
3668 }
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003669}
3670
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +00003671static int
Fred Drake4ec5d562001-10-04 19:26:43 +00003672call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 int what, PyObject *arg)
Fred Drake4ec5d562001-10-04 19:26:43 +00003674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 PyObject *type, *value, *traceback;
3676 int err;
3677 PyErr_Fetch(&type, &value, &traceback);
3678 err = call_trace(func, obj, frame, what, arg);
3679 if (err == 0)
3680 {
3681 PyErr_Restore(type, value, traceback);
3682 return 0;
3683 }
3684 else {
3685 Py_XDECREF(type);
3686 Py_XDECREF(value);
3687 Py_XDECREF(traceback);
3688 return -1;
3689 }
Fred Drake4ec5d562001-10-04 19:26:43 +00003690}
3691
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003692static int
Fred Drake5755ce62001-06-27 19:19:46 +00003693call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 int what, PyObject *arg)
Guido van Rossum96a42c81992-01-12 02:29:51 +00003695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 register PyThreadState *tstate = frame->f_tstate;
3697 int result;
3698 if (tstate->tracing)
3699 return 0;
3700 tstate->tracing++;
3701 tstate->use_tracing = 0;
3702 result = func(obj, frame, what, arg);
3703 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3704 || (tstate->c_profilefunc != NULL));
3705 tstate->tracing--;
3706 return result;
Guido van Rossum96a42c81992-01-12 02:29:51 +00003707}
3708
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003709PyObject *
3710_PyEval_CallTracing(PyObject *func, PyObject *args)
3711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 PyFrameObject *frame = PyEval_GetFrame();
3713 PyThreadState *tstate = frame->f_tstate;
3714 int save_tracing = tstate->tracing;
3715 int save_use_tracing = tstate->use_tracing;
3716 PyObject *result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 tstate->tracing = 0;
3719 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3720 || (tstate->c_profilefunc != NULL));
3721 result = PyObject_Call(func, args, NULL);
3722 tstate->tracing = save_tracing;
3723 tstate->use_tracing = save_use_tracing;
3724 return result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003725}
3726
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003727/* See Objects/lnotab_notes.txt for a description of how tracing works. */
Michael W. Hudson006c7522002-11-08 13:08:46 +00003728static int
Tim Peters8a5c3c72004-04-05 19:36:21 +00003729maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 PyFrameObject *frame, int *instr_lb, int *instr_ub,
3731 int *instr_prev)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 int result = 0;
3734 int line = frame->f_lineno;
Michael W. Hudson006c7522002-11-08 13:08:46 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 /* If the last instruction executed isn't in the current
3737 instruction window, reset the window.
3738 */
3739 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
3740 PyAddrPair bounds;
3741 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
3742 &bounds);
3743 *instr_lb = bounds.ap_lower;
3744 *instr_ub = bounds.ap_upper;
3745 }
3746 /* If the last instruction falls at the start of a line or if
3747 it represents a jump backwards, update the frame's line
3748 number and call the trace function. */
3749 if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
3750 frame->f_lineno = line;
3751 result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
3752 }
3753 *instr_prev = frame->f_lasti;
3754 return result;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003755}
3756
Fred Drake5755ce62001-06-27 19:19:46 +00003757void
3758PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
Fred Draked0838392001-06-16 21:02:31 +00003759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 PyThreadState *tstate = PyThreadState_GET();
3761 PyObject *temp = tstate->c_profileobj;
3762 Py_XINCREF(arg);
3763 tstate->c_profilefunc = NULL;
3764 tstate->c_profileobj = NULL;
3765 /* Must make sure that tracing is not ignored if 'temp' is freed */
3766 tstate->use_tracing = tstate->c_tracefunc != NULL;
3767 Py_XDECREF(temp);
3768 tstate->c_profilefunc = func;
3769 tstate->c_profileobj = arg;
3770 /* Flag that tracing or profiling is turned on */
3771 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
Fred Drake5755ce62001-06-27 19:19:46 +00003772}
3773
3774void
3775PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
3776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 PyThreadState *tstate = PyThreadState_GET();
3778 PyObject *temp = tstate->c_traceobj;
3779 _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
3780 Py_XINCREF(arg);
3781 tstate->c_tracefunc = NULL;
3782 tstate->c_traceobj = NULL;
3783 /* Must make sure that profiling is not ignored if 'temp' is freed */
3784 tstate->use_tracing = tstate->c_profilefunc != NULL;
3785 Py_XDECREF(temp);
3786 tstate->c_tracefunc = func;
3787 tstate->c_traceobj = arg;
3788 /* Flag that tracing or profiling is turned on */
3789 tstate->use_tracing = ((func != NULL)
3790 || (tstate->c_profilefunc != NULL));
Fred Draked0838392001-06-16 21:02:31 +00003791}
3792
Guido van Rossumb209a111997-04-29 18:18:01 +00003793PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003794PyEval_GetBuiltins(void)
Guido van Rossum6135a871995-01-09 17:53:26 +00003795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 PyFrameObject *current_frame = PyEval_GetFrame();
3797 if (current_frame == NULL)
3798 return PyThreadState_GET()->interp->builtins;
3799 else
3800 return current_frame->f_builtins;
Guido van Rossum6135a871995-01-09 17:53:26 +00003801}
3802
Guido van Rossumb209a111997-04-29 18:18:01 +00003803PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003804PyEval_GetLocals(void)
Guido van Rossum5b722181993-03-30 17:46:03 +00003805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 PyFrameObject *current_frame = PyEval_GetFrame();
3807 if (current_frame == NULL)
3808 return NULL;
3809 PyFrame_FastToLocals(current_frame);
3810 return current_frame->f_locals;
Guido van Rossum5b722181993-03-30 17:46:03 +00003811}
3812
Guido van Rossumb209a111997-04-29 18:18:01 +00003813PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003814PyEval_GetGlobals(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 PyFrameObject *current_frame = PyEval_GetFrame();
3817 if (current_frame == NULL)
3818 return NULL;
3819 else
3820 return current_frame->f_globals;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003821}
3822
Guido van Rossum6297a7a2003-02-19 15:53:17 +00003823PyFrameObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003824PyEval_GetFrame(void)
Guido van Rossume59214e1994-08-30 08:01:59 +00003825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 PyThreadState *tstate = PyThreadState_GET();
3827 return _PyThreadState_GetFrame(tstate);
Guido van Rossume59214e1994-08-30 08:01:59 +00003828}
3829
Guido van Rossum6135a871995-01-09 17:53:26 +00003830int
Tim Peters5ba58662001-07-16 02:29:45 +00003831PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Jeremy Hylton061d1062001-03-22 02:32:48 +00003832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 PyFrameObject *current_frame = PyEval_GetFrame();
3834 int result = cf->cf_flags != 0;
Tim Peters5ba58662001-07-16 02:29:45 +00003835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 if (current_frame != NULL) {
3837 const int codeflags = current_frame->f_code->co_flags;
3838 const int compilerflags = codeflags & PyCF_MASK;
3839 if (compilerflags) {
3840 result = 1;
3841 cf->cf_flags |= compilerflags;
3842 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003843#if 0 /* future keyword */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 if (codeflags & CO_GENERATOR_ALLOWED) {
3845 result = 1;
3846 cf->cf_flags |= CO_GENERATOR_ALLOWED;
3847 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003848#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 }
3850 return result;
Jeremy Hylton061d1062001-03-22 02:32:48 +00003851}
3852
Guido van Rossum3f5da241990-12-20 15:06:42 +00003853
Guido van Rossum681d79a1995-07-18 14:51:37 +00003854/* External interface to call any callable object.
Antoine Pitrou8689a102010-04-01 16:53:15 +00003855 The arg must be a tuple or NULL. The kw must be a dict or NULL. */
Guido van Rossume59214e1994-08-30 08:01:59 +00003856
Guido van Rossumb209a111997-04-29 18:18:01 +00003857PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003858PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 PyObject *result;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 if (arg == NULL) {
3863 arg = PyTuple_New(0);
3864 if (arg == NULL)
3865 return NULL;
3866 }
3867 else if (!PyTuple_Check(arg)) {
3868 PyErr_SetString(PyExc_TypeError,
3869 "argument list must be a tuple");
3870 return NULL;
3871 }
3872 else
3873 Py_INCREF(arg);
Guido van Rossum681d79a1995-07-18 14:51:37 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 if (kw != NULL && !PyDict_Check(kw)) {
3876 PyErr_SetString(PyExc_TypeError,
3877 "keyword list must be a dictionary");
3878 Py_DECREF(arg);
3879 return NULL;
3880 }
Guido van Rossume3e61c11995-08-04 04:14:47 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 result = PyObject_Call(func, arg, kw);
3883 Py_DECREF(arg);
3884 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00003885}
3886
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003887const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888PyEval_GetFuncName(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 if (PyMethod_Check(func))
3891 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
3892 else if (PyFunction_Check(func))
3893 return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name);
3894 else if (PyCFunction_Check(func))
3895 return ((PyCFunctionObject*)func)->m_ml->ml_name;
3896 else
3897 return func->ob_type->tp_name;
Jeremy Hylton512a2372001-04-11 13:52:29 +00003898}
3899
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003900const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003901PyEval_GetFuncDesc(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 if (PyMethod_Check(func))
3904 return "()";
3905 else if (PyFunction_Check(func))
3906 return "()";
3907 else if (PyCFunction_Check(func))
3908 return "()";
3909 else
3910 return " object";
Jeremy Hylton512a2372001-04-11 13:52:29 +00003911}
3912
Neal Norwitzaddfe0c2002-11-10 14:33:26 +00003913static void
Jeremy Hylton192690e2002-08-16 18:36:11 +00003914err_args(PyObject *func, int flags, int nargs)
3915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 if (flags & METH_NOARGS)
3917 PyErr_Format(PyExc_TypeError,
3918 "%.200s() takes no arguments (%d given)",
3919 ((PyCFunctionObject *)func)->m_ml->ml_name,
3920 nargs);
3921 else
3922 PyErr_Format(PyExc_TypeError,
3923 "%.200s() takes exactly one argument (%d given)",
3924 ((PyCFunctionObject *)func)->m_ml->ml_name,
3925 nargs);
Jeremy Hylton192690e2002-08-16 18:36:11 +00003926}
3927
Armin Rigo1c2d7e52005-09-20 18:34:01 +00003928#define C_TRACE(x, call) \
Nicholas Bastind858a772004-06-25 23:31:06 +00003929if (tstate->use_tracing && tstate->c_profilefunc) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 if (call_trace(tstate->c_profilefunc, \
3931 tstate->c_profileobj, \
3932 tstate->frame, PyTrace_C_CALL, \
3933 func)) { \
3934 x = NULL; \
3935 } \
3936 else { \
3937 x = call; \
3938 if (tstate->c_profilefunc != NULL) { \
3939 if (x == NULL) { \
3940 call_trace_protected(tstate->c_profilefunc, \
3941 tstate->c_profileobj, \
3942 tstate->frame, PyTrace_C_EXCEPTION, \
3943 func); \
3944 /* XXX should pass (type, value, tb) */ \
3945 } else { \
3946 if (call_trace(tstate->c_profilefunc, \
3947 tstate->c_profileobj, \
3948 tstate->frame, PyTrace_C_RETURN, \
3949 func)) { \
3950 Py_DECREF(x); \
3951 x = NULL; \
3952 } \
3953 } \
3954 } \
3955 } \
Nicholas Bastind858a772004-06-25 23:31:06 +00003956} else { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 x = call; \
3958 }
Nicholas Bastinc69ebe82004-03-24 21:57:10 +00003959
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003960static PyObject *
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003961call_function(PyObject ***pp_stack, int oparg
3962#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 , uint64* pintr0, uint64* pintr1
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003964#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 )
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 int na = oparg & 0xff;
3968 int nk = (oparg>>8) & 0xff;
3969 int n = na + 2 * nk;
3970 PyObject **pfunc = (*pp_stack) - n - 1;
3971 PyObject *func = *pfunc;
3972 PyObject *x, *w;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* Always dispatch PyCFunction first, because these are
3975 presumed to be the most frequent callable object.
3976 */
3977 if (PyCFunction_Check(func) && nk == 0) {
3978 int flags = PyCFunction_GET_FLAGS(func);
3979 PyThreadState *tstate = PyThreadState_GET();
Raymond Hettingera7f56bc2004-06-26 04:34:33 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 PCALL(PCALL_CFUNCTION);
3982 if (flags & (METH_NOARGS | METH_O)) {
3983 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
3984 PyObject *self = PyCFunction_GET_SELF(func);
3985 if (flags & METH_NOARGS && na == 0) {
3986 C_TRACE(x, (*meth)(self,NULL));
3987 }
3988 else if (flags & METH_O && na == 1) {
3989 PyObject *arg = EXT_POP(*pp_stack);
3990 C_TRACE(x, (*meth)(self,arg));
3991 Py_DECREF(arg);
3992 }
3993 else {
3994 err_args(func, flags, na);
3995 x = NULL;
3996 }
3997 }
3998 else {
3999 PyObject *callargs;
4000 callargs = load_args(pp_stack, na);
4001 READ_TIMESTAMP(*pintr0);
4002 C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
4003 READ_TIMESTAMP(*pintr1);
4004 Py_XDECREF(callargs);
4005 }
4006 } else {
4007 if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
4008 /* optimize access to bound methods */
4009 PyObject *self = PyMethod_GET_SELF(func);
4010 PCALL(PCALL_METHOD);
4011 PCALL(PCALL_BOUND_METHOD);
4012 Py_INCREF(self);
4013 func = PyMethod_GET_FUNCTION(func);
4014 Py_INCREF(func);
4015 Py_DECREF(*pfunc);
4016 *pfunc = self;
4017 na++;
4018 n++;
4019 } else
4020 Py_INCREF(func);
4021 READ_TIMESTAMP(*pintr0);
4022 if (PyFunction_Check(func))
4023 x = fast_function(func, pp_stack, n, na, nk);
4024 else
4025 x = do_call(func, pp_stack, na, nk);
4026 READ_TIMESTAMP(*pintr1);
4027 Py_DECREF(func);
4028 }
Tim Peters8a5c3c72004-04-05 19:36:21 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 /* Clear the stack of the function object. Also removes
4031 the arguments in case they weren't consumed already
4032 (fast_function() and err_args() leave them on the stack).
4033 */
4034 while ((*pp_stack) > pfunc) {
4035 w = EXT_POP(*pp_stack);
4036 Py_DECREF(w);
4037 PCALL(PCALL_POP);
4038 }
4039 return x;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00004040}
4041
Jeremy Hylton192690e2002-08-16 18:36:11 +00004042/* The fast_function() function optimize calls for which no argument
Jeremy Hylton52820442001-01-03 23:52:36 +00004043 tuple is necessary; the objects are passed directly from the stack.
Jeremy Hylton985eba52003-02-05 23:13:00 +00004044 For the simplest case -- a function that takes only positional
4045 arguments and is called with only positional arguments -- it
4046 inlines the most primitive frame setup code from
4047 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
4048 done before evaluating the frame.
Jeremy Hylton52820442001-01-03 23:52:36 +00004049*/
4050
4051static PyObject *
Guido van Rossumac7be682001-01-17 15:42:30 +00004052fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
Jeremy Hylton52820442001-01-03 23:52:36 +00004053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
4055 PyObject *globals = PyFunction_GET_GLOBALS(func);
4056 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
4057 PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func);
4058 PyObject **d = NULL;
4059 int nd = 0;
Jeremy Hylton52820442001-01-03 23:52:36 +00004060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 PCALL(PCALL_FUNCTION);
4062 PCALL(PCALL_FAST_FUNCTION);
4063 if (argdefs == NULL && co->co_argcount == n &&
4064 co->co_kwonlyargcount == 0 && nk==0 &&
4065 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
4066 PyFrameObject *f;
4067 PyObject *retval = NULL;
4068 PyThreadState *tstate = PyThreadState_GET();
4069 PyObject **fastlocals, **stack;
4070 int i;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 PCALL(PCALL_FASTER_FUNCTION);
4073 assert(globals != NULL);
4074 /* XXX Perhaps we should create a specialized
4075 PyFrame_New() that doesn't take locals, but does
4076 take builtins without sanity checking them.
4077 */
4078 assert(tstate != NULL);
4079 f = PyFrame_New(tstate, co, globals, NULL);
4080 if (f == NULL)
4081 return NULL;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 fastlocals = f->f_localsplus;
4084 stack = (*pp_stack) - n;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 for (i = 0; i < n; i++) {
4087 Py_INCREF(*stack);
4088 fastlocals[i] = *stack++;
4089 }
4090 retval = PyEval_EvalFrameEx(f,0);
4091 ++tstate->recursion_depth;
4092 Py_DECREF(f);
4093 --tstate->recursion_depth;
4094 return retval;
4095 }
4096 if (argdefs != NULL) {
4097 d = &PyTuple_GET_ITEM(argdefs, 0);
4098 nd = Py_SIZE(argdefs);
4099 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00004100 return PyEval_EvalCodeEx((PyObject*)co, globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 (PyObject *)NULL, (*pp_stack)-n, na,
4102 (*pp_stack)-2*nk, nk, d, nd, kwdefs,
4103 PyFunction_GET_CLOSURE(func));
Jeremy Hylton52820442001-01-03 23:52:36 +00004104}
4105
4106static PyObject *
Ka-Ping Yee20579702001-01-15 22:14:16 +00004107update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
4108 PyObject *func)
Jeremy Hylton52820442001-01-03 23:52:36 +00004109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 PyObject *kwdict = NULL;
4111 if (orig_kwdict == NULL)
4112 kwdict = PyDict_New();
4113 else {
4114 kwdict = PyDict_Copy(orig_kwdict);
4115 Py_DECREF(orig_kwdict);
4116 }
4117 if (kwdict == NULL)
4118 return NULL;
4119 while (--nk >= 0) {
4120 int err;
4121 PyObject *value = EXT_POP(*pp_stack);
4122 PyObject *key = EXT_POP(*pp_stack);
4123 if (PyDict_GetItem(kwdict, key) != NULL) {
4124 PyErr_Format(PyExc_TypeError,
4125 "%.200s%s got multiple values "
4126 "for keyword argument '%U'",
4127 PyEval_GetFuncName(func),
4128 PyEval_GetFuncDesc(func),
4129 key);
4130 Py_DECREF(key);
4131 Py_DECREF(value);
4132 Py_DECREF(kwdict);
4133 return NULL;
4134 }
4135 err = PyDict_SetItem(kwdict, key, value);
4136 Py_DECREF(key);
4137 Py_DECREF(value);
4138 if (err) {
4139 Py_DECREF(kwdict);
4140 return NULL;
4141 }
4142 }
4143 return kwdict;
Jeremy Hylton52820442001-01-03 23:52:36 +00004144}
4145
4146static PyObject *
4147update_star_args(int nstack, int nstar, PyObject *stararg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 PyObject ***pp_stack)
Jeremy Hylton52820442001-01-03 23:52:36 +00004149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 PyObject *callargs, *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 callargs = PyTuple_New(nstack + nstar);
4153 if (callargs == NULL) {
4154 return NULL;
4155 }
4156 if (nstar) {
4157 int i;
4158 for (i = 0; i < nstar; i++) {
4159 PyObject *a = PyTuple_GET_ITEM(stararg, i);
4160 Py_INCREF(a);
4161 PyTuple_SET_ITEM(callargs, nstack + i, a);
4162 }
4163 }
4164 while (--nstack >= 0) {
4165 w = EXT_POP(*pp_stack);
4166 PyTuple_SET_ITEM(callargs, nstack, w);
4167 }
4168 return callargs;
Jeremy Hylton52820442001-01-03 23:52:36 +00004169}
4170
4171static PyObject *
4172load_args(PyObject ***pp_stack, int na)
4173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 PyObject *args = PyTuple_New(na);
4175 PyObject *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 if (args == NULL)
4178 return NULL;
4179 while (--na >= 0) {
4180 w = EXT_POP(*pp_stack);
4181 PyTuple_SET_ITEM(args, na, w);
4182 }
4183 return args;
Jeremy Hylton52820442001-01-03 23:52:36 +00004184}
4185
4186static PyObject *
4187do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
4188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 PyObject *callargs = NULL;
4190 PyObject *kwdict = NULL;
4191 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 if (nk > 0) {
4194 kwdict = update_keyword_args(NULL, nk, pp_stack, func);
4195 if (kwdict == NULL)
4196 goto call_fail;
4197 }
4198 callargs = load_args(pp_stack, na);
4199 if (callargs == NULL)
4200 goto call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004201#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 /* At this point, we have to look at the type of func to
4203 update the call stats properly. Do it here so as to avoid
4204 exposing the call stats machinery outside ceval.c
4205 */
4206 if (PyFunction_Check(func))
4207 PCALL(PCALL_FUNCTION);
4208 else if (PyMethod_Check(func))
4209 PCALL(PCALL_METHOD);
4210 else if (PyType_Check(func))
4211 PCALL(PCALL_TYPE);
4212 else if (PyCFunction_Check(func))
4213 PCALL(PCALL_CFUNCTION);
4214 else
4215 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004216#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 if (PyCFunction_Check(func)) {
4218 PyThreadState *tstate = PyThreadState_GET();
4219 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4220 }
4221 else
4222 result = PyObject_Call(func, callargs, kwdict);
Thomas Wouters7ce29ca2007-09-19 21:56:32 +00004223call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 Py_XDECREF(callargs);
4225 Py_XDECREF(kwdict);
4226 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004227}
4228
4229static PyObject *
4230ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
4231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 int nstar = 0;
4233 PyObject *callargs = NULL;
4234 PyObject *stararg = NULL;
4235 PyObject *kwdict = NULL;
4236 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 if (flags & CALL_FLAG_KW) {
4239 kwdict = EXT_POP(*pp_stack);
4240 if (!PyDict_Check(kwdict)) {
4241 PyObject *d;
4242 d = PyDict_New();
4243 if (d == NULL)
4244 goto ext_call_fail;
4245 if (PyDict_Update(d, kwdict) != 0) {
4246 Py_DECREF(d);
4247 /* PyDict_Update raises attribute
4248 * error (percolated from an attempt
4249 * to get 'keys' attribute) instead of
4250 * a type error if its second argument
4251 * is not a mapping.
4252 */
4253 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
4254 PyErr_Format(PyExc_TypeError,
4255 "%.200s%.200s argument after ** "
4256 "must be a mapping, not %.200s",
4257 PyEval_GetFuncName(func),
4258 PyEval_GetFuncDesc(func),
4259 kwdict->ob_type->tp_name);
4260 }
4261 goto ext_call_fail;
4262 }
4263 Py_DECREF(kwdict);
4264 kwdict = d;
4265 }
4266 }
4267 if (flags & CALL_FLAG_VAR) {
4268 stararg = EXT_POP(*pp_stack);
4269 if (!PyTuple_Check(stararg)) {
4270 PyObject *t = NULL;
4271 t = PySequence_Tuple(stararg);
4272 if (t == NULL) {
4273 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4274 PyErr_Format(PyExc_TypeError,
4275 "%.200s%.200s argument after * "
Victor Stinner0a5f65a2011-03-22 01:09:21 +01004276 "must be a sequence, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 PyEval_GetFuncName(func),
4278 PyEval_GetFuncDesc(func),
4279 stararg->ob_type->tp_name);
4280 }
4281 goto ext_call_fail;
4282 }
4283 Py_DECREF(stararg);
4284 stararg = t;
4285 }
4286 nstar = PyTuple_GET_SIZE(stararg);
4287 }
4288 if (nk > 0) {
4289 kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
4290 if (kwdict == NULL)
4291 goto ext_call_fail;
4292 }
4293 callargs = update_star_args(na, nstar, stararg, pp_stack);
4294 if (callargs == NULL)
4295 goto ext_call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004296#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 /* At this point, we have to look at the type of func to
4298 update the call stats properly. Do it here so as to avoid
4299 exposing the call stats machinery outside ceval.c
4300 */
4301 if (PyFunction_Check(func))
4302 PCALL(PCALL_FUNCTION);
4303 else if (PyMethod_Check(func))
4304 PCALL(PCALL_METHOD);
4305 else if (PyType_Check(func))
4306 PCALL(PCALL_TYPE);
4307 else if (PyCFunction_Check(func))
4308 PCALL(PCALL_CFUNCTION);
4309 else
4310 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004311#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 if (PyCFunction_Check(func)) {
4313 PyThreadState *tstate = PyThreadState_GET();
4314 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4315 }
4316 else
4317 result = PyObject_Call(func, callargs, kwdict);
Thomas Woutersce272b62007-09-19 21:19:28 +00004318ext_call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 Py_XDECREF(callargs);
4320 Py_XDECREF(kwdict);
4321 Py_XDECREF(stararg);
4322 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004323}
4324
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004325/* Extract a slice index from a PyInt or PyLong or an object with the
4326 nb_index slot defined, and store in *pi.
4327 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
4328 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 +00004329 Return 0 on error, 1 on success.
Tim Peterscb479e72001-12-16 19:11:44 +00004330*/
Tim Petersb5196382001-12-16 19:44:20 +00004331/* Note: If v is NULL, return success without storing into *pi. This
4332 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
4333 called by the SLICE opcode with v and/or w equal to NULL.
Tim Peterscb479e72001-12-16 19:11:44 +00004334*/
Guido van Rossum20c6add2000-05-08 14:06:50 +00004335int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004336_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 if (v != NULL) {
4339 Py_ssize_t x;
4340 if (PyIndex_Check(v)) {
4341 x = PyNumber_AsSsize_t(v, NULL);
4342 if (x == -1 && PyErr_Occurred())
4343 return 0;
4344 }
4345 else {
4346 PyErr_SetString(PyExc_TypeError,
4347 "slice indices must be integers or "
4348 "None or have an __index__ method");
4349 return 0;
4350 }
4351 *pi = x;
4352 }
4353 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004354}
4355
Guido van Rossum486364b2007-06-30 05:01:58 +00004356#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 "BaseException is not allowed"
Brett Cannonf74225d2007-02-26 21:10:16 +00004358
Guido van Rossumb209a111997-04-29 18:18:01 +00004359static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004360cmp_outcome(int op, register PyObject *v, register PyObject *w)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 int res = 0;
4363 switch (op) {
4364 case PyCmp_IS:
4365 res = (v == w);
4366 break;
4367 case PyCmp_IS_NOT:
4368 res = (v != w);
4369 break;
4370 case PyCmp_IN:
4371 res = PySequence_Contains(w, v);
4372 if (res < 0)
4373 return NULL;
4374 break;
4375 case PyCmp_NOT_IN:
4376 res = PySequence_Contains(w, v);
4377 if (res < 0)
4378 return NULL;
4379 res = !res;
4380 break;
4381 case PyCmp_EXC_MATCH:
4382 if (PyTuple_Check(w)) {
4383 Py_ssize_t i, length;
4384 length = PyTuple_Size(w);
4385 for (i = 0; i < length; i += 1) {
4386 PyObject *exc = PyTuple_GET_ITEM(w, i);
4387 if (!PyExceptionClass_Check(exc)) {
4388 PyErr_SetString(PyExc_TypeError,
4389 CANNOT_CATCH_MSG);
4390 return NULL;
4391 }
4392 }
4393 }
4394 else {
4395 if (!PyExceptionClass_Check(w)) {
4396 PyErr_SetString(PyExc_TypeError,
4397 CANNOT_CATCH_MSG);
4398 return NULL;
4399 }
4400 }
4401 res = PyErr_GivenExceptionMatches(v, w);
4402 break;
4403 default:
4404 return PyObject_RichCompare(v, w, op);
4405 }
4406 v = res ? Py_True : Py_False;
4407 Py_INCREF(v);
4408 return v;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004409}
4410
Thomas Wouters52152252000-08-17 22:55:00 +00004411static PyObject *
4412import_from(PyObject *v, PyObject *name)
Guido van Rossume9736fc1990-11-18 17:33:06 +00004413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 PyObject *x;
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 x = PyObject_GetAttr(v, name);
4417 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
4418 PyErr_Format(PyExc_ImportError, "cannot import name %S", name);
4419 }
4420 return x;
Thomas Wouters52152252000-08-17 22:55:00 +00004421}
Guido van Rossumac7be682001-01-17 15:42:30 +00004422
Thomas Wouters52152252000-08-17 22:55:00 +00004423static int
4424import_all_from(PyObject *locals, PyObject *v)
4425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 PyObject *all = PyObject_GetAttrString(v, "__all__");
4427 PyObject *dict, *name, *value;
4428 int skip_leading_underscores = 0;
4429 int pos, err;
Thomas Wouters52152252000-08-17 22:55:00 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 if (all == NULL) {
4432 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4433 return -1; /* Unexpected error */
4434 PyErr_Clear();
4435 dict = PyObject_GetAttrString(v, "__dict__");
4436 if (dict == NULL) {
4437 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4438 return -1;
4439 PyErr_SetString(PyExc_ImportError,
4440 "from-import-* object has no __dict__ and no __all__");
4441 return -1;
4442 }
4443 all = PyMapping_Keys(dict);
4444 Py_DECREF(dict);
4445 if (all == NULL)
4446 return -1;
4447 skip_leading_underscores = 1;
4448 }
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 for (pos = 0, err = 0; ; pos++) {
4451 name = PySequence_GetItem(all, pos);
4452 if (name == NULL) {
4453 if (!PyErr_ExceptionMatches(PyExc_IndexError))
4454 err = -1;
4455 else
4456 PyErr_Clear();
4457 break;
4458 }
4459 if (skip_leading_underscores &&
4460 PyUnicode_Check(name) &&
4461 PyUnicode_AS_UNICODE(name)[0] == '_')
4462 {
4463 Py_DECREF(name);
4464 continue;
4465 }
4466 value = PyObject_GetAttr(v, name);
4467 if (value == NULL)
4468 err = -1;
4469 else if (PyDict_CheckExact(locals))
4470 err = PyDict_SetItem(locals, name, value);
4471 else
4472 err = PyObject_SetItem(locals, name, value);
4473 Py_DECREF(name);
4474 Py_XDECREF(value);
4475 if (err != 0)
4476 break;
4477 }
4478 Py_DECREF(all);
4479 return err;
Guido van Rossume9736fc1990-11-18 17:33:06 +00004480}
4481
Guido van Rossumac7be682001-01-17 15:42:30 +00004482static void
Neal Norwitzda059e32007-08-26 05:33:45 +00004483format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj)
Paul Prescode68140d2000-08-30 20:25:01 +00004484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 const char *obj_str;
Paul Prescode68140d2000-08-30 20:25:01 +00004486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 if (!obj)
4488 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 obj_str = _PyUnicode_AsString(obj);
4491 if (!obj_str)
4492 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 PyErr_Format(exc, format_str, obj_str);
Paul Prescode68140d2000-08-30 20:25:01 +00004495}
Guido van Rossum950361c1997-01-24 13:49:28 +00004496
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00004497static void
4498format_exc_unbound(PyCodeObject *co, int oparg)
4499{
4500 PyObject *name;
4501 /* Don't stomp existing exception */
4502 if (PyErr_Occurred())
4503 return;
4504 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
4505 name = PyTuple_GET_ITEM(co->co_cellvars,
4506 oparg);
4507 format_exc_check_arg(
4508 PyExc_UnboundLocalError,
4509 UNBOUNDLOCAL_ERROR_MSG,
4510 name);
4511 } else {
4512 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
4513 PyTuple_GET_SIZE(co->co_cellvars));
4514 format_exc_check_arg(PyExc_NameError,
4515 UNBOUNDFREE_ERROR_MSG, name);
4516 }
4517}
4518
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004519static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00004520unicode_concatenate(PyObject *v, PyObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 PyFrameObject *f, unsigned char *next_instr)
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 /* This function implements 'variable += expr' when both arguments
4524 are (Unicode) strings. */
4525 Py_ssize_t v_len = PyUnicode_GET_SIZE(v);
4526 Py_ssize_t w_len = PyUnicode_GET_SIZE(w);
4527 Py_ssize_t new_len = v_len + w_len;
4528 if (new_len < 0) {
4529 PyErr_SetString(PyExc_OverflowError,
4530 "strings are too large to concat");
4531 return NULL;
4532 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00004533
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004534 if (Py_REFCNT(v) == 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 /* In the common case, there are 2 references to the value
4536 * stored in 'variable' when the += is performed: one on the
4537 * value stack (in 'v') and one still stored in the
4538 * 'variable'. We try to delete the variable now to reduce
4539 * the refcnt to 1.
4540 */
4541 switch (*next_instr) {
4542 case STORE_FAST:
4543 {
4544 int oparg = PEEKARG();
4545 PyObject **fastlocals = f->f_localsplus;
4546 if (GETLOCAL(oparg) == v)
4547 SETLOCAL(oparg, NULL);
4548 break;
4549 }
4550 case STORE_DEREF:
4551 {
4552 PyObject **freevars = (f->f_localsplus +
4553 f->f_code->co_nlocals);
4554 PyObject *c = freevars[PEEKARG()];
4555 if (PyCell_GET(c) == v)
4556 PyCell_Set(c, NULL);
4557 break;
4558 }
4559 case STORE_NAME:
4560 {
4561 PyObject *names = f->f_code->co_names;
4562 PyObject *name = GETITEM(names, PEEKARG());
4563 PyObject *locals = f->f_locals;
4564 if (PyDict_CheckExact(locals) &&
4565 PyDict_GetItem(locals, name) == v) {
4566 if (PyDict_DelItem(locals, name) != 0) {
4567 PyErr_Clear();
4568 }
4569 }
4570 break;
4571 }
4572 }
4573 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004574
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004575 if (Py_REFCNT(v) == 1 && !PyUnicode_CHECK_INTERNED(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 /* Now we own the last reference to 'v', so we can resize it
4577 * in-place.
4578 */
4579 if (PyUnicode_Resize(&v, new_len) != 0) {
4580 /* XXX if PyUnicode_Resize() fails, 'v' has been
4581 * deallocated so it cannot be put back into
4582 * 'variable'. The MemoryError is raised when there
4583 * is no value in 'variable', which might (very
4584 * remotely) be a cause of incompatibilities.
4585 */
4586 return NULL;
4587 }
4588 /* copy 'w' into the newly allocated area of 'v' */
4589 memcpy(PyUnicode_AS_UNICODE(v) + v_len,
4590 PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE));
4591 return v;
4592 }
4593 else {
4594 /* When in-place resizing is not an option. */
4595 w = PyUnicode_Concat(v, w);
4596 Py_DECREF(v);
4597 return w;
4598 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004599}
4600
Guido van Rossum950361c1997-01-24 13:49:28 +00004601#ifdef DYNAMIC_EXECUTION_PROFILE
4602
Skip Montanarof118cb12001-10-15 20:51:38 +00004603static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004604getarray(long a[256])
Guido van Rossum950361c1997-01-24 13:49:28 +00004605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 int i;
4607 PyObject *l = PyList_New(256);
4608 if (l == NULL) return NULL;
4609 for (i = 0; i < 256; i++) {
4610 PyObject *x = PyLong_FromLong(a[i]);
4611 if (x == NULL) {
4612 Py_DECREF(l);
4613 return NULL;
4614 }
4615 PyList_SetItem(l, i, x);
4616 }
4617 for (i = 0; i < 256; i++)
4618 a[i] = 0;
4619 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004620}
4621
4622PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004623_Py_GetDXProfile(PyObject *self, PyObject *args)
Guido van Rossum950361c1997-01-24 13:49:28 +00004624{
4625#ifndef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 return getarray(dxp);
Guido van Rossum950361c1997-01-24 13:49:28 +00004627#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 int i;
4629 PyObject *l = PyList_New(257);
4630 if (l == NULL) return NULL;
4631 for (i = 0; i < 257; i++) {
4632 PyObject *x = getarray(dxpairs[i]);
4633 if (x == NULL) {
4634 Py_DECREF(l);
4635 return NULL;
4636 }
4637 PyList_SetItem(l, i, x);
4638 }
4639 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004640#endif
4641}
4642
4643#endif