blob: f0ea7c90dcac82f1fb78be38b440cc54c08fd0d2 [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
Collin Winter828f04a2007-08-31 00:04:24 +0000752static enum why_code do_raise(PyObject *, PyObject *);
Guido van Rossum0368b722007-05-11 16:50:42 +0000753static int unpack_iterable(PyObject *, int, int, PyObject **);
Guido van Rossum1aa14831997-01-21 05:34:20 +0000754
Jeffrey Yasskin008d8ef2008-12-06 17:09:27 +0000755/* Records whether tracing is on for any thread. Counts the number of
756 threads for which tstate->c_tracefunc is non-NULL, so if the value
757 is 0, we know we don't have to check this thread's c_tracefunc.
758 This speeds up the if statement in PyEval_EvalFrameEx() after
759 fast_next_opcode*/
760static int _Py_TracingPossible = 0;
761
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000762
Guido van Rossum374a9221991-04-04 10:40:29 +0000763
Guido van Rossumb209a111997-04-29 18:18:01 +0000764PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000765PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Guido van Rossum681d79a1995-07-18 14:51:37 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 return PyEval_EvalCodeEx(co,
768 globals, locals,
769 (PyObject **)NULL, 0,
770 (PyObject **)NULL, 0,
771 (PyObject **)NULL, 0,
772 NULL, NULL);
Guido van Rossum681d79a1995-07-18 14:51:37 +0000773}
774
775
776/* Interpreter main loop */
777
Martin v. Löwis8d97e332004-06-27 15:43:12 +0000778PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000779PyEval_EvalFrame(PyFrameObject *f) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 /* This is for backward compatibility with extension modules that
781 used this API; core interpreter code should call
782 PyEval_EvalFrameEx() */
783 return PyEval_EvalFrameEx(f, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000784}
785
786PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000787PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Guido van Rossum374a9221991-04-04 10:40:29 +0000788{
Guido van Rossum950361c1997-01-24 13:49:28 +0000789#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 int lastopcode = 0;
Guido van Rossum950361c1997-01-24 13:49:28 +0000791#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 register PyObject **stack_pointer; /* Next free slot in value stack */
793 register unsigned char *next_instr;
794 register int opcode; /* Current opcode */
795 register int oparg; /* Current opcode argument, if any */
796 register enum why_code why; /* Reason for block stack unwind */
797 register int err; /* Error status -- nonzero if error */
798 register PyObject *x; /* Result object -- NULL if error */
799 register PyObject *v; /* Temporary objects popped off stack */
800 register PyObject *w;
801 register PyObject *u;
802 register PyObject *t;
803 register PyObject **fastlocals, **freevars;
804 PyObject *retval = NULL; /* Return value */
805 PyThreadState *tstate = PyThreadState_GET();
806 PyCodeObject *co;
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* when tracing we set things up so that
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 not (instr_lb <= current_bytecode_offset < instr_ub)
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 is true when the line being executed has changed. The
813 initial values are such as to make this false the first
814 time it is tested. */
815 int instr_ub = -1, instr_lb = 0, instr_prev = -1;
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 unsigned char *first_instr;
818 PyObject *names;
819 PyObject *consts;
Neal Norwitz5f5153e2005-10-21 04:28:38 +0000820#if defined(Py_DEBUG) || defined(LLTRACE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 /* Make it easier to find out where we are with a debugger */
822 char *filename;
Guido van Rossum99bec951992-09-03 20:29:45 +0000823#endif
Guido van Rossum374a9221991-04-04 10:40:29 +0000824
Antoine Pitroub52ec782009-01-25 16:34:23 +0000825/* Computed GOTOs, or
826 the-optimization-commonly-but-improperly-known-as-"threaded code"
827 using gcc's labels-as-values extension
828 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
829
830 The traditional bytecode evaluation loop uses a "switch" statement, which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 decent compilers will optimize as a single indirect branch instruction
Antoine Pitroub52ec782009-01-25 16:34:23 +0000832 combined with a lookup table of jump addresses. However, since the
833 indirect jump instruction is shared by all opcodes, the CPU will have a
834 hard time making the right prediction for where to jump next (actually,
835 it will be always wrong except in the uncommon case of a sequence of
836 several identical opcodes).
837
838 "Threaded code" in contrast, uses an explicit jump table and an explicit
839 indirect jump instruction at the end of each opcode. Since the jump
840 instruction is at a different address for each opcode, the CPU will make a
841 separate prediction for each of these instructions, which is equivalent to
842 predicting the second opcode of each opcode pair. These predictions have
843 a much better chance to turn out valid, especially in small bytecode loops.
844
845 A mispredicted branch on a modern CPU flushes the whole pipeline and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 can cost several CPU cycles (depending on the pipeline depth),
Antoine Pitroub52ec782009-01-25 16:34:23 +0000847 and potentially many more instructions (depending on the pipeline width).
848 A correctly predicted branch, however, is nearly free.
849
850 At the time of this writing, the "threaded code" version is up to 15-20%
851 faster than the normal "switch" version, depending on the compiler and the
852 CPU architecture.
853
854 We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined,
855 because it would render the measurements invalid.
856
857
858 NOTE: care must be taken that the compiler doesn't try to "optimize" the
859 indirect jumps by sharing them between all opcodes. Such optimizations
860 can be disabled on gcc by using the -fno-gcse flag (or possibly
861 -fno-crossjumping).
862*/
863
Antoine Pitrou042b1282010-08-13 21:15:58 +0000864#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitroub52ec782009-01-25 16:34:23 +0000865#undef USE_COMPUTED_GOTOS
Antoine Pitrou042b1282010-08-13 21:15:58 +0000866#define USE_COMPUTED_GOTOS 0
Antoine Pitroub52ec782009-01-25 16:34:23 +0000867#endif
868
Antoine Pitrou042b1282010-08-13 21:15:58 +0000869#ifdef HAVE_COMPUTED_GOTOS
870 #ifndef USE_COMPUTED_GOTOS
871 #define USE_COMPUTED_GOTOS 1
872 #endif
873#else
874 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
875 #error "Computed gotos are not supported on this compiler."
876 #endif
877 #undef USE_COMPUTED_GOTOS
878 #define USE_COMPUTED_GOTOS 0
879#endif
880
881#if USE_COMPUTED_GOTOS
Antoine Pitroub52ec782009-01-25 16:34:23 +0000882/* Import the static jump table */
883#include "opcode_targets.h"
884
885/* This macro is used when several opcodes defer to the same implementation
886 (e.g. SETUP_LOOP, SETUP_FINALLY) */
887#define TARGET_WITH_IMPL(op, impl) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 TARGET_##op: \
889 opcode = op; \
890 if (HAS_ARG(op)) \
891 oparg = NEXTARG(); \
892 case op: \
893 goto impl; \
Antoine Pitroub52ec782009-01-25 16:34:23 +0000894
895#define TARGET(op) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 TARGET_##op: \
897 opcode = op; \
898 if (HAS_ARG(op)) \
899 oparg = NEXTARG(); \
900 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000901
902
903#define DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 { \
905 if (!_Py_atomic_load_relaxed(&eval_breaker)) { \
906 FAST_DISPATCH(); \
907 } \
908 continue; \
909 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000910
911#ifdef LLTRACE
912#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 { \
914 if (!lltrace && !_Py_TracingPossible) { \
915 f->f_lasti = INSTR_OFFSET(); \
916 goto *opcode_targets[*next_instr++]; \
917 } \
918 goto fast_next_opcode; \
919 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000920#else
921#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 { \
923 if (!_Py_TracingPossible) { \
924 f->f_lasti = INSTR_OFFSET(); \
925 goto *opcode_targets[*next_instr++]; \
926 } \
927 goto fast_next_opcode; \
928 }
Antoine Pitroub52ec782009-01-25 16:34:23 +0000929#endif
930
931#else
932#define TARGET(op) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000934#define TARGET_WITH_IMPL(op, impl) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* silence compiler warnings about `impl` unused */ \
936 if (0) goto impl; \
937 case op:
Antoine Pitroub52ec782009-01-25 16:34:23 +0000938#define DISPATCH() continue
939#define FAST_DISPATCH() goto fast_next_opcode
940#endif
941
942
Neal Norwitza81d2202002-07-14 00:27:26 +0000943/* Tuple access macros */
944
945#ifndef Py_DEBUG
946#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
947#else
948#define GETITEM(v, i) PyTuple_GetItem((v), (i))
949#endif
950
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000951#ifdef WITH_TSC
952/* Use Pentium timestamp counter to mark certain events:
953 inst0 -- beginning of switch statement for opcode dispatch
954 inst1 -- end of switch statement (may be skipped)
955 loop0 -- the top of the mainloop
Thomas Wouters477c8d52006-05-27 19:21:47 +0000956 loop1 -- place where control returns again to top of mainloop
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000957 (may be skipped)
958 intr1 -- beginning of long interruption
959 intr2 -- end of long interruption
960
961 Many opcodes call out to helper C functions. In some cases, the
962 time in those functions should be counted towards the time for the
963 opcode, but not in all cases. For example, a CALL_FUNCTION opcode
964 calls another Python function; there's no point in charge all the
965 bytecode executed by the called function to the caller.
966
967 It's hard to make a useful judgement statically. In the presence
968 of operator overloading, it's impossible to tell if a call will
969 execute new Python code or not.
970
971 It's a case-by-case judgement. I'll use intr1 for the following
972 cases:
973
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000974 IMPORT_STAR
975 IMPORT_FROM
976 CALL_FUNCTION (and friends)
977
978 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0;
980 int ticked = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 READ_TIMESTAMP(inst0);
983 READ_TIMESTAMP(inst1);
984 READ_TIMESTAMP(loop0);
985 READ_TIMESTAMP(loop1);
Michael W. Hudson800ba232004-08-12 18:19:17 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 /* shut up the compiler */
988 opcode = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000989#endif
990
Guido van Rossum374a9221991-04-04 10:40:29 +0000991/* Code access macros */
992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993#define INSTR_OFFSET() ((int)(next_instr - first_instr))
994#define NEXTOP() (*next_instr++)
995#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
996#define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
997#define JUMPTO(x) (next_instr = first_instr + (x))
998#define JUMPBY(x) (next_instr += (x))
Guido van Rossum374a9221991-04-04 10:40:29 +0000999
Raymond Hettingerf606f872003-03-16 03:11:04 +00001000/* OpCode prediction macros
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 Some opcodes tend to come in pairs thus making it possible to
1002 predict the second code when the first is run. For example,
1003 COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And,
1004 those opcodes are often followed by a POP_TOP.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 Verifying the prediction costs a single high-speed test of a register
1007 variable against a constant. If the pairing was good, then the
1008 processor's own internal branch predication has a high likelihood of
1009 success, resulting in a nearly zero-overhead transition to the
1010 next opcode. A successful prediction saves a trip through the eval-loop
1011 including its two unpredictable branches, the HAS_ARG test and the
1012 switch-case. Combined with the processor's internal branch prediction,
1013 a successful PREDICT has the effect of making the two opcodes run as if
1014 they were a single new opcode with the bodies combined.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001015
Georg Brandl86b2fb92008-07-16 03:43:04 +00001016 If collecting opcode statistics, your choices are to either keep the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 predictions turned-on and interpret the results as if some opcodes
1018 had been combined or turn-off predictions so that the opcode frequency
1019 counter updates for both opcodes.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001020
1021 Opcode prediction is disabled with threaded code, since the latter allows
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 the CPU to record separate branch prediction information for each
1023 opcode.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001024
Raymond Hettingerf606f872003-03-16 03:11:04 +00001025*/
1026
Antoine Pitrou042b1282010-08-13 21:15:58 +00001027#if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028#define PREDICT(op) if (0) goto PRED_##op
1029#define PREDICTED(op) PRED_##op:
1030#define PREDICTED_WITH_ARG(op) PRED_##op:
Raymond Hettingera7216982004-02-08 19:59:27 +00001031#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032#define PREDICT(op) if (*next_instr == op) goto PRED_##op
1033#define PREDICTED(op) PRED_##op: next_instr++
1034#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
Antoine Pitroub52ec782009-01-25 16:34:23 +00001035#endif
1036
Raymond Hettingerf606f872003-03-16 03:11:04 +00001037
Guido van Rossum374a9221991-04-04 10:40:29 +00001038/* Stack manipulation macros */
1039
Martin v. Löwis18e16552006-02-15 17:27:45 +00001040/* The stack can grow at most MAXINT deep, as co_nlocals and
1041 co_stacksize are ints. */
Stefan Krahb7e10102010-06-23 18:42:39 +00001042#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
1043#define EMPTY() (STACK_LEVEL() == 0)
1044#define TOP() (stack_pointer[-1])
1045#define SECOND() (stack_pointer[-2])
1046#define THIRD() (stack_pointer[-3])
1047#define FOURTH() (stack_pointer[-4])
1048#define PEEK(n) (stack_pointer[-(n)])
1049#define SET_TOP(v) (stack_pointer[-1] = (v))
1050#define SET_SECOND(v) (stack_pointer[-2] = (v))
1051#define SET_THIRD(v) (stack_pointer[-3] = (v))
1052#define SET_FOURTH(v) (stack_pointer[-4] = (v))
1053#define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
1054#define BASIC_STACKADJ(n) (stack_pointer += n)
1055#define BASIC_PUSH(v) (*stack_pointer++ = (v))
1056#define BASIC_POP() (*--stack_pointer)
Guido van Rossum374a9221991-04-04 10:40:29 +00001057
Guido van Rossum96a42c81992-01-12 02:29:51 +00001058#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059#define PUSH(v) { (void)(BASIC_PUSH(v), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001060 lltrace && prtrace(TOP(), "push")); \
1061 assert(STACK_LEVEL() <= co->co_stacksize); }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001063 BASIC_POP())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001065 lltrace && prtrace(TOP(), "stackadj")); \
1066 assert(STACK_LEVEL() <= co->co_stacksize); }
Christian Heimes0449f632007-12-15 01:27:15 +00001067#define EXT_POP(STACK_POINTER) ((void)(lltrace && \
Stefan Krahb7e10102010-06-23 18:42:39 +00001068 prtrace((STACK_POINTER)[-1], "ext_pop")), \
1069 *--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001070#else
Stefan Krahb7e10102010-06-23 18:42:39 +00001071#define PUSH(v) BASIC_PUSH(v)
1072#define POP() BASIC_POP()
1073#define STACKADJ(n) BASIC_STACKADJ(n)
Guido van Rossumc2e20742006-02-27 22:32:47 +00001074#define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001075#endif
1076
Guido van Rossum681d79a1995-07-18 14:51:37 +00001077/* Local variable macros */
1078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079#define GETLOCAL(i) (fastlocals[i])
Guido van Rossumcfbf1a32002-03-28 20:17:52 +00001080
1081/* The SETLOCAL() macro must not DECREF the local variable in-place and
1082 then store the new value; it must copy the old value to a temporary
1083 value, then store the new value, and then DECREF the temporary value.
1084 This is because it is possible that during the DECREF the frame is
1085 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1086 variable would be pointing to already-freed memory. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001088 GETLOCAL(i) = value; \
1089 Py_XDECREF(tmp); } while (0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001090
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001091
1092#define UNWIND_BLOCK(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 while (STACK_LEVEL() > (b)->b_level) { \
1094 PyObject *v = POP(); \
1095 Py_XDECREF(v); \
1096 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001097
1098#define UNWIND_EXCEPT_HANDLER(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 { \
1100 PyObject *type, *value, *traceback; \
1101 assert(STACK_LEVEL() >= (b)->b_level + 3); \
1102 while (STACK_LEVEL() > (b)->b_level + 3) { \
1103 value = POP(); \
1104 Py_XDECREF(value); \
1105 } \
1106 type = tstate->exc_type; \
1107 value = tstate->exc_value; \
1108 traceback = tstate->exc_traceback; \
1109 tstate->exc_type = POP(); \
1110 tstate->exc_value = POP(); \
1111 tstate->exc_traceback = POP(); \
1112 Py_XDECREF(type); \
1113 Py_XDECREF(value); \
1114 Py_XDECREF(traceback); \
1115 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001116
1117#define SAVE_EXC_STATE() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 { \
1119 PyObject *type, *value, *traceback; \
1120 Py_XINCREF(tstate->exc_type); \
1121 Py_XINCREF(tstate->exc_value); \
1122 Py_XINCREF(tstate->exc_traceback); \
1123 type = f->f_exc_type; \
1124 value = f->f_exc_value; \
1125 traceback = f->f_exc_traceback; \
1126 f->f_exc_type = tstate->exc_type; \
1127 f->f_exc_value = tstate->exc_value; \
1128 f->f_exc_traceback = tstate->exc_traceback; \
1129 Py_XDECREF(type); \
1130 Py_XDECREF(value); \
1131 Py_XDECREF(traceback); \
1132 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001133
1134#define SWAP_EXC_STATE() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 { \
1136 PyObject *tmp; \
1137 tmp = tstate->exc_type; \
1138 tstate->exc_type = f->f_exc_type; \
1139 f->f_exc_type = tmp; \
1140 tmp = tstate->exc_value; \
1141 tstate->exc_value = f->f_exc_value; \
1142 f->f_exc_value = tmp; \
1143 tmp = tstate->exc_traceback; \
1144 tstate->exc_traceback = f->f_exc_traceback; \
1145 f->f_exc_traceback = tmp; \
1146 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001147
Benjamin Petersonac913412011-07-03 16:25:11 -05001148#define RESTORE_AND_CLEAR_EXC_STATE() \
1149 { \
1150 PyObject *type, *value, *tb; \
1151 type = tstate->exc_type; \
1152 value = tstate->exc_value; \
1153 tb = tstate->exc_traceback; \
1154 tstate->exc_type = f->f_exc_type; \
1155 tstate->exc_value = f->f_exc_value; \
1156 tstate->exc_traceback = f->f_exc_traceback; \
1157 f->f_exc_type = NULL; \
1158 f->f_exc_value = NULL; \
1159 f->f_exc_traceback = NULL; \
1160 Py_XDECREF(type); \
1161 Py_XDECREF(value); \
1162 Py_XDECREF(tb); \
1163 }
1164
Guido van Rossuma027efa1997-05-05 20:56:21 +00001165/* Start of code */
1166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (f == NULL)
1168 return NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 /* push frame */
1171 if (Py_EnterRecursiveCall(""))
1172 return NULL;
Guido van Rossum8861b741996-07-30 16:49:37 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 tstate->frame = f;
Tim Peters5ca576e2001-06-18 22:08:13 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (tstate->use_tracing) {
1177 if (tstate->c_tracefunc != NULL) {
1178 /* tstate->c_tracefunc, if defined, is a
1179 function that will be called on *every* entry
1180 to a code block. Its return value, if not
1181 None, is a function that will be called at
1182 the start of each executed line of code.
1183 (Actually, the function must return itself
1184 in order to continue tracing.) The trace
1185 functions are called with three arguments:
1186 a pointer to the current frame, a string
1187 indicating why the function is called, and
1188 an argument which depends on the situation.
1189 The global trace function is also called
1190 whenever an exception is detected. */
1191 if (call_trace_protected(tstate->c_tracefunc,
1192 tstate->c_traceobj,
1193 f, PyTrace_CALL, Py_None)) {
1194 /* Trace function raised an error */
1195 goto exit_eval_frame;
1196 }
1197 }
1198 if (tstate->c_profilefunc != NULL) {
1199 /* Similar for c_profilefunc, except it needn't
1200 return itself and isn't called for "line" events */
1201 if (call_trace_protected(tstate->c_profilefunc,
1202 tstate->c_profileobj,
1203 f, PyTrace_CALL, Py_None)) {
1204 /* Profile function raised an error */
1205 goto exit_eval_frame;
1206 }
1207 }
1208 }
Neil Schemenauer6c0f2002001-09-04 19:03:35 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 co = f->f_code;
1211 names = co->co_names;
1212 consts = co->co_consts;
1213 fastlocals = f->f_localsplus;
1214 freevars = f->f_localsplus + co->co_nlocals;
1215 first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code);
1216 /* An explanation is in order for the next line.
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 f->f_lasti now refers to the index of the last instruction
1219 executed. You might think this was obvious from the name, but
1220 this wasn't always true before 2.3! PyFrame_New now sets
1221 f->f_lasti to -1 (i.e. the index *before* the first instruction)
1222 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
1223 does work. Promise.
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 When the PREDICT() macros are enabled, some opcode pairs follow in
1226 direct succession without updating f->f_lasti. A successful
1227 prediction effectively links the two codes together as if they
1228 were a single new opcode; accordingly,f->f_lasti will point to
1229 the first code in the pair (for instance, GET_ITER followed by
1230 FOR_ITER is effectively a single opcode and f->f_lasti will point
1231 at to the beginning of the combined pair.)
1232 */
1233 next_instr = first_instr + f->f_lasti + 1;
1234 stack_pointer = f->f_stacktop;
1235 assert(stack_pointer != NULL);
1236 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (co->co_flags & CO_GENERATOR && !throwflag) {
1239 if (f->f_exc_type != NULL && f->f_exc_type != Py_None) {
1240 /* We were in an except handler when we left,
1241 restore the exception state which was put aside
1242 (see YIELD_VALUE). */
1243 SWAP_EXC_STATE();
1244 }
1245 else {
1246 SAVE_EXC_STATE();
1247 }
1248 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001249
Tim Peters5ca576e2001-06-18 22:08:13 +00001250#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00001252#endif
Neal Norwitz5f5153e2005-10-21 04:28:38 +00001253#if defined(Py_DEBUG) || defined(LLTRACE)
Victor Stinner4a3733d2010-08-17 00:39:57 +00001254 {
1255 PyObject *error_type, *error_value, *error_traceback;
1256 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1257 filename = _PyUnicode_AsString(co->co_filename);
Victor Stinnera0006452010-10-13 10:48:55 +00001258 if (filename == NULL && tstate->overflowed) {
1259 /* maximum recursion depth exceeded */
1260 goto exit_eval_frame;
1261 }
Victor Stinner4a3733d2010-08-17 00:39:57 +00001262 PyErr_Restore(error_type, error_value, error_traceback);
1263 }
Tim Peters5ca576e2001-06-18 22:08:13 +00001264#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 why = WHY_NOT;
1267 err = 0;
1268 x = Py_None; /* Not a reference, just anything non-NULL */
1269 w = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 if (throwflag) { /* support for generator.throw() */
1272 why = WHY_EXCEPTION;
1273 goto on_error;
1274 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 for (;;) {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001277#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (inst1 == 0) {
1279 /* Almost surely, the opcode executed a break
1280 or a continue, preventing inst1 from being set
1281 on the way out of the loop.
1282 */
1283 READ_TIMESTAMP(inst1);
1284 loop1 = inst1;
1285 }
1286 dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1,
1287 intr0, intr1);
1288 ticked = 0;
1289 inst1 = 0;
1290 intr0 = 0;
1291 intr1 = 0;
1292 READ_TIMESTAMP(loop0);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001293#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1295 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* Do periodic things. Doing this every time through
1298 the loop would add too much overhead, so we do it
1299 only every Nth instruction. We also do it if
1300 ``pendingcalls_to_do'' is set, i.e. when an asynchronous
1301 event needs attention (e.g. a signal handler or
1302 async I/O handler); see Py_AddPendingCall() and
1303 Py_MakePendingCalls() above. */
Guido van Rossumac7be682001-01-17 15:42:30 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (_Py_atomic_load_relaxed(&eval_breaker)) {
1306 if (*next_instr == SETUP_FINALLY) {
1307 /* Make the last opcode before
Ezio Melotti13925002011-03-16 11:05:33 +02001308 a try: finally: block uninterruptible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 goto fast_next_opcode;
1310 }
1311 tstate->tick_counter++;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001312#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 ticked = 1;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001314#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) {
1316 if (Py_MakePendingCalls() < 0) {
1317 why = WHY_EXCEPTION;
1318 goto on_error;
1319 }
1320 }
Guido van Rossume59214e1994-08-30 08:01:59 +00001321#ifdef WITH_THREAD
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001322 if (_Py_atomic_load_relaxed(&gil_drop_request)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* Give another thread a chance */
1324 if (PyThreadState_Swap(NULL) != tstate)
1325 Py_FatalError("ceval: tstate mix-up");
1326 drop_gil(tstate);
1327
1328 /* Other threads may run now */
1329
1330 take_gil(tstate);
1331 if (PyThreadState_Swap(tstate) != NULL)
1332 Py_FatalError("ceval: orphan tstate");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 }
Benjamin Petersond2be5b42010-09-10 22:47:02 +00001334#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* Check for asynchronous exceptions. */
1336 if (tstate->async_exc != NULL) {
1337 x = tstate->async_exc;
1338 tstate->async_exc = NULL;
1339 UNSIGNAL_ASYNC_EXC();
1340 PyErr_SetNone(x);
1341 Py_DECREF(x);
1342 why = WHY_EXCEPTION;
1343 goto on_error;
1344 }
1345 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 fast_next_opcode:
1348 f->f_lasti = INSTR_OFFSET();
Guido van Rossumac7be682001-01-17 15:42:30 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* line-by-line tracing support */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (_Py_TracingPossible &&
1353 tstate->c_tracefunc != NULL && !tstate->tracing) {
1354 /* see maybe_call_line_trace
1355 for expository comments */
1356 f->f_stacktop = stack_pointer;
Tim Peters8a5c3c72004-04-05 19:36:21 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 err = maybe_call_line_trace(tstate->c_tracefunc,
1359 tstate->c_traceobj,
1360 f, &instr_lb, &instr_ub,
1361 &instr_prev);
1362 /* Reload possibly changed frame fields */
1363 JUMPTO(f->f_lasti);
1364 if (f->f_stacktop != NULL) {
1365 stack_pointer = f->f_stacktop;
1366 f->f_stacktop = NULL;
1367 }
1368 if (err) {
1369 /* trace function raised an exception */
1370 goto on_error;
1371 }
1372 }
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 /* Extract opcode and argument */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 opcode = NEXTOP();
1377 oparg = 0; /* allows oparg to be stored in a register because
1378 it doesn't have to be remembered across a full loop */
1379 if (HAS_ARG(opcode))
1380 oparg = NEXTARG();
Stefan Krahb7e10102010-06-23 18:42:39 +00001381 dispatch_opcode:
Guido van Rossum950361c1997-01-24 13:49:28 +00001382#ifdef DYNAMIC_EXECUTION_PROFILE
1383#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 dxpairs[lastopcode][opcode]++;
1385 lastopcode = opcode;
Guido van Rossum950361c1997-01-24 13:49:28 +00001386#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 dxp[opcode]++;
Guido van Rossum950361c1997-01-24 13:49:28 +00001388#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00001389
Guido van Rossum96a42c81992-01-12 02:29:51 +00001390#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* Instruction tracing */
Guido van Rossumac7be682001-01-17 15:42:30 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (lltrace) {
1394 if (HAS_ARG(opcode)) {
1395 printf("%d: %d, %d\n",
1396 f->f_lasti, opcode, oparg);
1397 }
1398 else {
1399 printf("%d: %d\n",
1400 f->f_lasti, opcode);
1401 }
1402 }
Guido van Rossum374a9221991-04-04 10:40:29 +00001403#endif
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 /* Main switch on opcode */
1406 READ_TIMESTAMP(inst0);
Jeremy Hylton52820442001-01-03 23:52:36 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 switch (opcode) {
Guido van Rossumac7be682001-01-17 15:42:30 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* BEWARE!
1411 It is essential that any operation that fails sets either
1412 x to NULL, err to nonzero, or why to anything but WHY_NOT,
1413 and that no operation that succeeds does this! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 /* case STOP_CODE: this is an error! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 TARGET(NOP)
1418 FAST_DISPATCH();
Raymond Hettinger9c18e812004-06-21 16:31:15 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 TARGET(LOAD_FAST)
1421 x = GETLOCAL(oparg);
1422 if (x != NULL) {
1423 Py_INCREF(x);
1424 PUSH(x);
1425 FAST_DISPATCH();
1426 }
1427 format_exc_check_arg(PyExc_UnboundLocalError,
1428 UNBOUNDLOCAL_ERROR_MSG,
1429 PyTuple_GetItem(co->co_varnames, oparg));
1430 break;
Neil Schemenauer63543862002-02-17 19:10:14 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 TARGET(LOAD_CONST)
1433 x = GETITEM(consts, oparg);
1434 Py_INCREF(x);
1435 PUSH(x);
1436 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 PREDICTED_WITH_ARG(STORE_FAST);
1439 TARGET(STORE_FAST)
1440 v = POP();
1441 SETLOCAL(oparg, v);
1442 FAST_DISPATCH();
Neil Schemenauer63543862002-02-17 19:10:14 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 TARGET(POP_TOP)
1445 v = POP();
1446 Py_DECREF(v);
1447 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 TARGET(ROT_TWO)
1450 v = TOP();
1451 w = SECOND();
1452 SET_TOP(w);
1453 SET_SECOND(v);
1454 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 TARGET(ROT_THREE)
1457 v = TOP();
1458 w = SECOND();
1459 x = THIRD();
1460 SET_TOP(w);
1461 SET_SECOND(x);
1462 SET_THIRD(v);
1463 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 TARGET(DUP_TOP)
1466 v = TOP();
1467 Py_INCREF(v);
1468 PUSH(v);
1469 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001470
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00001471 TARGET(DUP_TOP_TWO)
1472 x = TOP();
1473 Py_INCREF(x);
1474 w = SECOND();
1475 Py_INCREF(w);
1476 STACKADJ(2);
1477 SET_TOP(x);
1478 SET_SECOND(w);
1479 FAST_DISPATCH();
Thomas Wouters434d0822000-08-24 20:11:32 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 TARGET(UNARY_POSITIVE)
1482 v = TOP();
1483 x = PyNumber_Positive(v);
1484 Py_DECREF(v);
1485 SET_TOP(x);
1486 if (x != NULL) DISPATCH();
1487 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 TARGET(UNARY_NEGATIVE)
1490 v = TOP();
1491 x = PyNumber_Negative(v);
1492 Py_DECREF(v);
1493 SET_TOP(x);
1494 if (x != NULL) DISPATCH();
1495 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 TARGET(UNARY_NOT)
1498 v = TOP();
1499 err = PyObject_IsTrue(v);
1500 Py_DECREF(v);
1501 if (err == 0) {
1502 Py_INCREF(Py_True);
1503 SET_TOP(Py_True);
1504 DISPATCH();
1505 }
1506 else if (err > 0) {
1507 Py_INCREF(Py_False);
1508 SET_TOP(Py_False);
1509 err = 0;
1510 DISPATCH();
1511 }
1512 STACKADJ(-1);
1513 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 TARGET(UNARY_INVERT)
1516 v = TOP();
1517 x = PyNumber_Invert(v);
1518 Py_DECREF(v);
1519 SET_TOP(x);
1520 if (x != NULL) DISPATCH();
1521 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 TARGET(BINARY_POWER)
1524 w = POP();
1525 v = TOP();
1526 x = PyNumber_Power(v, w, Py_None);
1527 Py_DECREF(v);
1528 Py_DECREF(w);
1529 SET_TOP(x);
1530 if (x != NULL) DISPATCH();
1531 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 TARGET(BINARY_MULTIPLY)
1534 w = POP();
1535 v = TOP();
1536 x = PyNumber_Multiply(v, w);
1537 Py_DECREF(v);
1538 Py_DECREF(w);
1539 SET_TOP(x);
1540 if (x != NULL) DISPATCH();
1541 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 TARGET(BINARY_TRUE_DIVIDE)
1544 w = POP();
1545 v = TOP();
1546 x = PyNumber_TrueDivide(v, w);
1547 Py_DECREF(v);
1548 Py_DECREF(w);
1549 SET_TOP(x);
1550 if (x != NULL) DISPATCH();
1551 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 TARGET(BINARY_FLOOR_DIVIDE)
1554 w = POP();
1555 v = TOP();
1556 x = PyNumber_FloorDivide(v, w);
1557 Py_DECREF(v);
1558 Py_DECREF(w);
1559 SET_TOP(x);
1560 if (x != NULL) DISPATCH();
1561 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 TARGET(BINARY_MODULO)
1564 w = POP();
1565 v = TOP();
1566 if (PyUnicode_CheckExact(v))
1567 x = PyUnicode_Format(v, w);
1568 else
1569 x = PyNumber_Remainder(v, w);
1570 Py_DECREF(v);
1571 Py_DECREF(w);
1572 SET_TOP(x);
1573 if (x != NULL) DISPATCH();
1574 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 TARGET(BINARY_ADD)
1577 w = POP();
1578 v = TOP();
1579 if (PyUnicode_CheckExact(v) &&
1580 PyUnicode_CheckExact(w)) {
1581 x = unicode_concatenate(v, w, f, next_instr);
1582 /* unicode_concatenate consumed the ref to v */
1583 goto skip_decref_vx;
1584 }
1585 else {
1586 x = PyNumber_Add(v, w);
1587 }
1588 Py_DECREF(v);
1589 skip_decref_vx:
1590 Py_DECREF(w);
1591 SET_TOP(x);
1592 if (x != NULL) DISPATCH();
1593 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 TARGET(BINARY_SUBTRACT)
1596 w = POP();
1597 v = TOP();
1598 x = PyNumber_Subtract(v, w);
1599 Py_DECREF(v);
1600 Py_DECREF(w);
1601 SET_TOP(x);
1602 if (x != NULL) DISPATCH();
1603 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 TARGET(BINARY_SUBSCR)
1606 w = POP();
1607 v = TOP();
1608 x = PyObject_GetItem(v, w);
1609 Py_DECREF(v);
1610 Py_DECREF(w);
1611 SET_TOP(x);
1612 if (x != NULL) DISPATCH();
1613 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 TARGET(BINARY_LSHIFT)
1616 w = POP();
1617 v = TOP();
1618 x = PyNumber_Lshift(v, w);
1619 Py_DECREF(v);
1620 Py_DECREF(w);
1621 SET_TOP(x);
1622 if (x != NULL) DISPATCH();
1623 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 TARGET(BINARY_RSHIFT)
1626 w = POP();
1627 v = TOP();
1628 x = PyNumber_Rshift(v, w);
1629 Py_DECREF(v);
1630 Py_DECREF(w);
1631 SET_TOP(x);
1632 if (x != NULL) DISPATCH();
1633 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 TARGET(BINARY_AND)
1636 w = POP();
1637 v = TOP();
1638 x = PyNumber_And(v, w);
1639 Py_DECREF(v);
1640 Py_DECREF(w);
1641 SET_TOP(x);
1642 if (x != NULL) DISPATCH();
1643 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 TARGET(BINARY_XOR)
1646 w = POP();
1647 v = TOP();
1648 x = PyNumber_Xor(v, w);
1649 Py_DECREF(v);
1650 Py_DECREF(w);
1651 SET_TOP(x);
1652 if (x != NULL) DISPATCH();
1653 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 TARGET(BINARY_OR)
1656 w = POP();
1657 v = TOP();
1658 x = PyNumber_Or(v, w);
1659 Py_DECREF(v);
1660 Py_DECREF(w);
1661 SET_TOP(x);
1662 if (x != NULL) DISPATCH();
1663 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 TARGET(LIST_APPEND)
1666 w = POP();
1667 v = PEEK(oparg);
1668 err = PyList_Append(v, w);
1669 Py_DECREF(w);
1670 if (err == 0) {
1671 PREDICT(JUMP_ABSOLUTE);
1672 DISPATCH();
1673 }
1674 break;
Raymond Hettingerdd80f762004-03-07 07:31:06 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 TARGET(SET_ADD)
1677 w = POP();
1678 v = stack_pointer[-oparg];
1679 err = PySet_Add(v, w);
1680 Py_DECREF(w);
1681 if (err == 0) {
1682 PREDICT(JUMP_ABSOLUTE);
1683 DISPATCH();
1684 }
1685 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 TARGET(INPLACE_POWER)
1688 w = POP();
1689 v = TOP();
1690 x = PyNumber_InPlacePower(v, w, Py_None);
1691 Py_DECREF(v);
1692 Py_DECREF(w);
1693 SET_TOP(x);
1694 if (x != NULL) DISPATCH();
1695 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 TARGET(INPLACE_MULTIPLY)
1698 w = POP();
1699 v = TOP();
1700 x = PyNumber_InPlaceMultiply(v, w);
1701 Py_DECREF(v);
1702 Py_DECREF(w);
1703 SET_TOP(x);
1704 if (x != NULL) DISPATCH();
1705 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 TARGET(INPLACE_TRUE_DIVIDE)
1708 w = POP();
1709 v = TOP();
1710 x = PyNumber_InPlaceTrueDivide(v, w);
1711 Py_DECREF(v);
1712 Py_DECREF(w);
1713 SET_TOP(x);
1714 if (x != NULL) DISPATCH();
1715 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 TARGET(INPLACE_FLOOR_DIVIDE)
1718 w = POP();
1719 v = TOP();
1720 x = PyNumber_InPlaceFloorDivide(v, w);
1721 Py_DECREF(v);
1722 Py_DECREF(w);
1723 SET_TOP(x);
1724 if (x != NULL) DISPATCH();
1725 break;
Guido van Rossum4668b002001-08-08 05:00:18 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 TARGET(INPLACE_MODULO)
1728 w = POP();
1729 v = TOP();
1730 x = PyNumber_InPlaceRemainder(v, w);
1731 Py_DECREF(v);
1732 Py_DECREF(w);
1733 SET_TOP(x);
1734 if (x != NULL) DISPATCH();
1735 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 TARGET(INPLACE_ADD)
1738 w = POP();
1739 v = TOP();
1740 if (PyUnicode_CheckExact(v) &&
1741 PyUnicode_CheckExact(w)) {
1742 x = unicode_concatenate(v, w, f, next_instr);
1743 /* unicode_concatenate consumed the ref to v */
1744 goto skip_decref_v;
1745 }
1746 else {
1747 x = PyNumber_InPlaceAdd(v, w);
1748 }
1749 Py_DECREF(v);
1750 skip_decref_v:
1751 Py_DECREF(w);
1752 SET_TOP(x);
1753 if (x != NULL) DISPATCH();
1754 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 TARGET(INPLACE_SUBTRACT)
1757 w = POP();
1758 v = TOP();
1759 x = PyNumber_InPlaceSubtract(v, w);
1760 Py_DECREF(v);
1761 Py_DECREF(w);
1762 SET_TOP(x);
1763 if (x != NULL) DISPATCH();
1764 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 TARGET(INPLACE_LSHIFT)
1767 w = POP();
1768 v = TOP();
1769 x = PyNumber_InPlaceLshift(v, w);
1770 Py_DECREF(v);
1771 Py_DECREF(w);
1772 SET_TOP(x);
1773 if (x != NULL) DISPATCH();
1774 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 TARGET(INPLACE_RSHIFT)
1777 w = POP();
1778 v = TOP();
1779 x = PyNumber_InPlaceRshift(v, w);
1780 Py_DECREF(v);
1781 Py_DECREF(w);
1782 SET_TOP(x);
1783 if (x != NULL) DISPATCH();
1784 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 TARGET(INPLACE_AND)
1787 w = POP();
1788 v = TOP();
1789 x = PyNumber_InPlaceAnd(v, w);
1790 Py_DECREF(v);
1791 Py_DECREF(w);
1792 SET_TOP(x);
1793 if (x != NULL) DISPATCH();
1794 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 TARGET(INPLACE_XOR)
1797 w = POP();
1798 v = TOP();
1799 x = PyNumber_InPlaceXor(v, w);
1800 Py_DECREF(v);
1801 Py_DECREF(w);
1802 SET_TOP(x);
1803 if (x != NULL) DISPATCH();
1804 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 TARGET(INPLACE_OR)
1807 w = POP();
1808 v = TOP();
1809 x = PyNumber_InPlaceOr(v, w);
1810 Py_DECREF(v);
1811 Py_DECREF(w);
1812 SET_TOP(x);
1813 if (x != NULL) DISPATCH();
1814 break;
Thomas Wouters434d0822000-08-24 20:11:32 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 TARGET(STORE_SUBSCR)
1817 w = TOP();
1818 v = SECOND();
1819 u = THIRD();
1820 STACKADJ(-3);
1821 /* v[w] = u */
1822 err = PyObject_SetItem(v, w, u);
1823 Py_DECREF(u);
1824 Py_DECREF(v);
1825 Py_DECREF(w);
1826 if (err == 0) DISPATCH();
1827 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 TARGET(DELETE_SUBSCR)
1830 w = TOP();
1831 v = SECOND();
1832 STACKADJ(-2);
1833 /* del v[w] */
1834 err = PyObject_DelItem(v, w);
1835 Py_DECREF(v);
1836 Py_DECREF(w);
1837 if (err == 0) DISPATCH();
1838 break;
Barry Warsaw23c9ec82000-08-21 15:44:01 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 TARGET(PRINT_EXPR)
1841 v = POP();
1842 w = PySys_GetObject("displayhook");
1843 if (w == NULL) {
1844 PyErr_SetString(PyExc_RuntimeError,
1845 "lost sys.displayhook");
1846 err = -1;
1847 x = NULL;
1848 }
1849 if (err == 0) {
1850 x = PyTuple_Pack(1, v);
1851 if (x == NULL)
1852 err = -1;
1853 }
1854 if (err == 0) {
1855 w = PyEval_CallObject(w, x);
1856 Py_XDECREF(w);
1857 if (w == NULL)
1858 err = -1;
1859 }
1860 Py_DECREF(v);
1861 Py_XDECREF(x);
1862 break;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +00001863
Thomas Wouters434d0822000-08-24 20:11:32 +00001864#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 default: switch (opcode) {
Thomas Wouters434d0822000-08-24 20:11:32 +00001866#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 TARGET(RAISE_VARARGS)
1868 v = w = NULL;
1869 switch (oparg) {
1870 case 2:
1871 v = POP(); /* cause */
1872 case 1:
1873 w = POP(); /* exc */
1874 case 0: /* Fallthrough */
1875 why = do_raise(w, v);
1876 break;
1877 default:
1878 PyErr_SetString(PyExc_SystemError,
1879 "bad RAISE_VARARGS oparg");
1880 why = WHY_EXCEPTION;
1881 break;
1882 }
1883 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 TARGET(STORE_LOCALS)
1886 x = POP();
1887 v = f->f_locals;
1888 Py_XDECREF(v);
1889 f->f_locals = x;
1890 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 TARGET(RETURN_VALUE)
1893 retval = POP();
1894 why = WHY_RETURN;
1895 goto fast_block_end;
Guido van Rossumdb3165e1993-10-18 17:06:59 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 TARGET(YIELD_VALUE)
1898 retval = POP();
1899 f->f_stacktop = stack_pointer;
1900 why = WHY_YIELD;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 goto fast_yield;
Tim Peters5ca576e2001-06-18 22:08:13 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 TARGET(POP_EXCEPT)
1904 {
1905 PyTryBlock *b = PyFrame_BlockPop(f);
1906 if (b->b_type != EXCEPT_HANDLER) {
1907 PyErr_SetString(PyExc_SystemError,
1908 "popped block is not an except handler");
1909 why = WHY_EXCEPTION;
1910 break;
1911 }
1912 UNWIND_EXCEPT_HANDLER(b);
1913 }
1914 DISPATCH();
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 TARGET(POP_BLOCK)
1917 {
1918 PyTryBlock *b = PyFrame_BlockPop(f);
1919 UNWIND_BLOCK(b);
1920 }
1921 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 PREDICTED(END_FINALLY);
1924 TARGET(END_FINALLY)
1925 v = POP();
1926 if (PyLong_Check(v)) {
1927 why = (enum why_code) PyLong_AS_LONG(v);
1928 assert(why != WHY_YIELD);
1929 if (why == WHY_RETURN ||
1930 why == WHY_CONTINUE)
1931 retval = POP();
1932 if (why == WHY_SILENCED) {
1933 /* An exception was silenced by 'with', we must
1934 manually unwind the EXCEPT_HANDLER block which was
1935 created when the exception was caught, otherwise
1936 the stack will be in an inconsistent state. */
1937 PyTryBlock *b = PyFrame_BlockPop(f);
1938 assert(b->b_type == EXCEPT_HANDLER);
1939 UNWIND_EXCEPT_HANDLER(b);
1940 why = WHY_NOT;
1941 }
1942 }
1943 else if (PyExceptionClass_Check(v)) {
1944 w = POP();
1945 u = POP();
1946 PyErr_Restore(v, w, u);
1947 why = WHY_RERAISE;
1948 break;
1949 }
1950 else if (v != Py_None) {
1951 PyErr_SetString(PyExc_SystemError,
1952 "'finally' pops bad exception");
1953 why = WHY_EXCEPTION;
1954 }
1955 Py_DECREF(v);
1956 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 TARGET(LOAD_BUILD_CLASS)
1959 x = PyDict_GetItemString(f->f_builtins,
1960 "__build_class__");
1961 if (x == NULL) {
1962 PyErr_SetString(PyExc_ImportError,
1963 "__build_class__ not found");
1964 break;
1965 }
1966 Py_INCREF(x);
1967 PUSH(x);
1968 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 TARGET(STORE_NAME)
1971 w = GETITEM(names, oparg);
1972 v = POP();
1973 if ((x = f->f_locals) != NULL) {
1974 if (PyDict_CheckExact(x))
1975 err = PyDict_SetItem(x, w, v);
1976 else
1977 err = PyObject_SetItem(x, w, v);
1978 Py_DECREF(v);
1979 if (err == 0) DISPATCH();
1980 break;
1981 }
1982 PyErr_Format(PyExc_SystemError,
1983 "no locals found when storing %R", w);
1984 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 TARGET(DELETE_NAME)
1987 w = GETITEM(names, oparg);
1988 if ((x = f->f_locals) != NULL) {
1989 if ((err = PyObject_DelItem(x, w)) != 0)
1990 format_exc_check_arg(PyExc_NameError,
1991 NAME_ERROR_MSG,
1992 w);
1993 break;
1994 }
1995 PyErr_Format(PyExc_SystemError,
1996 "no locals when deleting %R", w);
1997 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
2000 TARGET(UNPACK_SEQUENCE)
2001 v = POP();
2002 if (PyTuple_CheckExact(v) &&
2003 PyTuple_GET_SIZE(v) == oparg) {
2004 PyObject **items = \
2005 ((PyTupleObject *)v)->ob_item;
2006 while (oparg--) {
2007 w = items[oparg];
2008 Py_INCREF(w);
2009 PUSH(w);
2010 }
2011 Py_DECREF(v);
2012 DISPATCH();
2013 } else if (PyList_CheckExact(v) &&
2014 PyList_GET_SIZE(v) == oparg) {
2015 PyObject **items = \
2016 ((PyListObject *)v)->ob_item;
2017 while (oparg--) {
2018 w = items[oparg];
2019 Py_INCREF(w);
2020 PUSH(w);
2021 }
2022 } else if (unpack_iterable(v, oparg, -1,
2023 stack_pointer + oparg)) {
2024 STACKADJ(oparg);
2025 } else {
2026 /* unpack_iterable() raised an exception */
2027 why = WHY_EXCEPTION;
2028 }
2029 Py_DECREF(v);
2030 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 TARGET(UNPACK_EX)
2033 {
2034 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
2035 v = POP();
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (unpack_iterable(v, oparg & 0xFF, oparg >> 8,
2038 stack_pointer + totalargs)) {
2039 stack_pointer += totalargs;
2040 } else {
2041 why = WHY_EXCEPTION;
2042 }
2043 Py_DECREF(v);
2044 break;
2045 }
Guido van Rossum0368b722007-05-11 16:50:42 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 TARGET(STORE_ATTR)
2048 w = GETITEM(names, oparg);
2049 v = TOP();
2050 u = SECOND();
2051 STACKADJ(-2);
2052 err = PyObject_SetAttr(v, w, u); /* v.w = u */
2053 Py_DECREF(v);
2054 Py_DECREF(u);
2055 if (err == 0) DISPATCH();
2056 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 TARGET(DELETE_ATTR)
2059 w = GETITEM(names, oparg);
2060 v = POP();
2061 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
2062 /* del v.w */
2063 Py_DECREF(v);
2064 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 TARGET(STORE_GLOBAL)
2067 w = GETITEM(names, oparg);
2068 v = POP();
2069 err = PyDict_SetItem(f->f_globals, w, v);
2070 Py_DECREF(v);
2071 if (err == 0) DISPATCH();
2072 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 TARGET(DELETE_GLOBAL)
2075 w = GETITEM(names, oparg);
2076 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
2077 format_exc_check_arg(
2078 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
2079 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 TARGET(LOAD_NAME)
2082 w = GETITEM(names, oparg);
2083 if ((v = f->f_locals) == NULL) {
2084 PyErr_Format(PyExc_SystemError,
2085 "no locals when loading %R", w);
2086 why = WHY_EXCEPTION;
2087 break;
2088 }
2089 if (PyDict_CheckExact(v)) {
2090 x = PyDict_GetItem(v, w);
2091 Py_XINCREF(x);
2092 }
2093 else {
2094 x = PyObject_GetItem(v, w);
2095 if (x == NULL && PyErr_Occurred()) {
2096 if (!PyErr_ExceptionMatches(
2097 PyExc_KeyError))
2098 break;
2099 PyErr_Clear();
2100 }
2101 }
2102 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002103 x = PyDict_GetItem(f->f_globals, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (x == NULL) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002105 x = PyDict_GetItem(f->f_builtins, w);
2106 if (x == NULL) {
2107 format_exc_check_arg(
2108 PyExc_NameError,
2109 NAME_ERROR_MSG, w);
2110 break;
2111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 }
2113 Py_INCREF(x);
2114 }
2115 PUSH(x);
2116 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 TARGET(LOAD_GLOBAL)
2119 w = GETITEM(names, oparg);
2120 if (PyUnicode_CheckExact(w)) {
2121 /* Inline the PyDict_GetItem() calls.
2122 WARNING: this is an extreme speed hack.
2123 Do not try this at home. */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002124 Py_hash_t hash = ((PyUnicodeObject *)w)->hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if (hash != -1) {
2126 PyDictObject *d;
2127 PyDictEntry *e;
2128 d = (PyDictObject *)(f->f_globals);
2129 e = d->ma_lookup(d, w, hash);
2130 if (e == NULL) {
2131 x = NULL;
2132 break;
2133 }
2134 x = e->me_value;
2135 if (x != NULL) {
2136 Py_INCREF(x);
2137 PUSH(x);
2138 DISPATCH();
2139 }
2140 d = (PyDictObject *)(f->f_builtins);
2141 e = d->ma_lookup(d, w, hash);
2142 if (e == NULL) {
2143 x = NULL;
2144 break;
2145 }
2146 x = e->me_value;
2147 if (x != NULL) {
2148 Py_INCREF(x);
2149 PUSH(x);
2150 DISPATCH();
2151 }
2152 goto load_global_error;
2153 }
2154 }
2155 /* This is the un-inlined version of the code above */
2156 x = PyDict_GetItem(f->f_globals, w);
2157 if (x == NULL) {
2158 x = PyDict_GetItem(f->f_builtins, w);
2159 if (x == NULL) {
2160 load_global_error:
2161 format_exc_check_arg(
2162 PyExc_NameError,
2163 GLOBAL_NAME_ERROR_MSG, w);
2164 break;
2165 }
2166 }
2167 Py_INCREF(x);
2168 PUSH(x);
2169 DISPATCH();
Guido van Rossum681d79a1995-07-18 14:51:37 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 TARGET(DELETE_FAST)
2172 x = GETLOCAL(oparg);
2173 if (x != NULL) {
2174 SETLOCAL(oparg, NULL);
2175 DISPATCH();
2176 }
2177 format_exc_check_arg(
2178 PyExc_UnboundLocalError,
2179 UNBOUNDLOCAL_ERROR_MSG,
2180 PyTuple_GetItem(co->co_varnames, oparg)
2181 );
2182 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002183
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002184 TARGET(DELETE_DEREF)
2185 x = freevars[oparg];
2186 if (PyCell_GET(x) != NULL) {
2187 PyCell_Set(x, NULL);
Benjamin Peterson00ebe2c2010-09-10 22:02:31 +00002188 DISPATCH();
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002189 }
2190 err = -1;
2191 format_exc_unbound(co, oparg);
2192 break;
2193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 TARGET(LOAD_CLOSURE)
2195 x = freevars[oparg];
2196 Py_INCREF(x);
2197 PUSH(x);
2198 if (x != NULL) DISPATCH();
2199 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 TARGET(LOAD_DEREF)
2202 x = freevars[oparg];
2203 w = PyCell_Get(x);
2204 if (w != NULL) {
2205 PUSH(w);
2206 DISPATCH();
2207 }
2208 err = -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002209 format_exc_unbound(co, oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 break;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 TARGET(STORE_DEREF)
2213 w = POP();
2214 x = freevars[oparg];
2215 PyCell_Set(x, w);
2216 Py_DECREF(w);
2217 DISPATCH();
Jeremy Hylton64949cb2001-01-25 20:06:59 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 TARGET(BUILD_TUPLE)
2220 x = PyTuple_New(oparg);
2221 if (x != NULL) {
2222 for (; --oparg >= 0;) {
2223 w = POP();
2224 PyTuple_SET_ITEM(x, oparg, w);
2225 }
2226 PUSH(x);
2227 DISPATCH();
2228 }
2229 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 TARGET(BUILD_LIST)
2232 x = PyList_New(oparg);
2233 if (x != NULL) {
2234 for (; --oparg >= 0;) {
2235 w = POP();
2236 PyList_SET_ITEM(x, oparg, w);
2237 }
2238 PUSH(x);
2239 DISPATCH();
2240 }
2241 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 TARGET(BUILD_SET)
2244 x = PySet_New(NULL);
2245 if (x != NULL) {
2246 for (; --oparg >= 0;) {
2247 w = POP();
2248 if (err == 0)
2249 err = PySet_Add(x, w);
2250 Py_DECREF(w);
2251 }
2252 if (err != 0) {
2253 Py_DECREF(x);
2254 break;
2255 }
2256 PUSH(x);
2257 DISPATCH();
2258 }
2259 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 TARGET(BUILD_MAP)
2262 x = _PyDict_NewPresized((Py_ssize_t)oparg);
2263 PUSH(x);
2264 if (x != NULL) DISPATCH();
2265 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 TARGET(STORE_MAP)
2268 w = TOP(); /* key */
2269 u = SECOND(); /* value */
2270 v = THIRD(); /* dict */
2271 STACKADJ(-2);
2272 assert (PyDict_CheckExact(v));
2273 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2274 Py_DECREF(u);
2275 Py_DECREF(w);
2276 if (err == 0) DISPATCH();
2277 break;
Christian Heimes99170a52007-12-19 02:07:34 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 TARGET(MAP_ADD)
2280 w = TOP(); /* key */
2281 u = SECOND(); /* value */
2282 STACKADJ(-2);
2283 v = stack_pointer[-oparg]; /* dict */
2284 assert (PyDict_CheckExact(v));
2285 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2286 Py_DECREF(u);
2287 Py_DECREF(w);
2288 if (err == 0) {
2289 PREDICT(JUMP_ABSOLUTE);
2290 DISPATCH();
2291 }
2292 break;
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 TARGET(LOAD_ATTR)
2295 w = GETITEM(names, oparg);
2296 v = TOP();
2297 x = PyObject_GetAttr(v, w);
2298 Py_DECREF(v);
2299 SET_TOP(x);
2300 if (x != NULL) DISPATCH();
2301 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 TARGET(COMPARE_OP)
2304 w = POP();
2305 v = TOP();
2306 x = cmp_outcome(oparg, v, w);
2307 Py_DECREF(v);
2308 Py_DECREF(w);
2309 SET_TOP(x);
2310 if (x == NULL) break;
2311 PREDICT(POP_JUMP_IF_FALSE);
2312 PREDICT(POP_JUMP_IF_TRUE);
2313 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 TARGET(IMPORT_NAME)
2316 w = GETITEM(names, oparg);
2317 x = PyDict_GetItemString(f->f_builtins, "__import__");
2318 if (x == NULL) {
2319 PyErr_SetString(PyExc_ImportError,
2320 "__import__ not found");
2321 break;
2322 }
2323 Py_INCREF(x);
2324 v = POP();
2325 u = TOP();
2326 if (PyLong_AsLong(u) != -1 || PyErr_Occurred())
2327 w = PyTuple_Pack(5,
2328 w,
2329 f->f_globals,
2330 f->f_locals == NULL ?
2331 Py_None : f->f_locals,
2332 v,
2333 u);
2334 else
2335 w = PyTuple_Pack(4,
2336 w,
2337 f->f_globals,
2338 f->f_locals == NULL ?
2339 Py_None : f->f_locals,
2340 v);
2341 Py_DECREF(v);
2342 Py_DECREF(u);
2343 if (w == NULL) {
2344 u = POP();
2345 Py_DECREF(x);
2346 x = NULL;
2347 break;
2348 }
2349 READ_TIMESTAMP(intr0);
2350 v = x;
2351 x = PyEval_CallObject(v, w);
2352 Py_DECREF(v);
2353 READ_TIMESTAMP(intr1);
2354 Py_DECREF(w);
2355 SET_TOP(x);
2356 if (x != NULL) DISPATCH();
2357 break;
Guido van Rossumac7be682001-01-17 15:42:30 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 TARGET(IMPORT_STAR)
2360 v = POP();
2361 PyFrame_FastToLocals(f);
2362 if ((x = f->f_locals) == NULL) {
2363 PyErr_SetString(PyExc_SystemError,
2364 "no locals found during 'import *'");
2365 break;
2366 }
2367 READ_TIMESTAMP(intr0);
2368 err = import_all_from(x, v);
2369 READ_TIMESTAMP(intr1);
2370 PyFrame_LocalsToFast(f, 0);
2371 Py_DECREF(v);
2372 if (err == 0) DISPATCH();
2373 break;
Guido van Rossum25831651993-05-19 14:50:45 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 TARGET(IMPORT_FROM)
2376 w = GETITEM(names, oparg);
2377 v = TOP();
2378 READ_TIMESTAMP(intr0);
2379 x = import_from(v, w);
2380 READ_TIMESTAMP(intr1);
2381 PUSH(x);
2382 if (x != NULL) DISPATCH();
2383 break;
Thomas Wouters52152252000-08-17 22:55:00 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 TARGET(JUMP_FORWARD)
2386 JUMPBY(oparg);
2387 FAST_DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE);
2390 TARGET(POP_JUMP_IF_FALSE)
2391 w = POP();
2392 if (w == Py_True) {
2393 Py_DECREF(w);
2394 FAST_DISPATCH();
2395 }
2396 if (w == Py_False) {
2397 Py_DECREF(w);
2398 JUMPTO(oparg);
2399 FAST_DISPATCH();
2400 }
2401 err = PyObject_IsTrue(w);
2402 Py_DECREF(w);
2403 if (err > 0)
2404 err = 0;
2405 else if (err == 0)
2406 JUMPTO(oparg);
2407 else
2408 break;
2409 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE);
2412 TARGET(POP_JUMP_IF_TRUE)
2413 w = POP();
2414 if (w == Py_False) {
2415 Py_DECREF(w);
2416 FAST_DISPATCH();
2417 }
2418 if (w == Py_True) {
2419 Py_DECREF(w);
2420 JUMPTO(oparg);
2421 FAST_DISPATCH();
2422 }
2423 err = PyObject_IsTrue(w);
2424 Py_DECREF(w);
2425 if (err > 0) {
2426 err = 0;
2427 JUMPTO(oparg);
2428 }
2429 else if (err == 0)
2430 ;
2431 else
2432 break;
2433 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 TARGET(JUMP_IF_FALSE_OR_POP)
2436 w = TOP();
2437 if (w == Py_True) {
2438 STACKADJ(-1);
2439 Py_DECREF(w);
2440 FAST_DISPATCH();
2441 }
2442 if (w == Py_False) {
2443 JUMPTO(oparg);
2444 FAST_DISPATCH();
2445 }
2446 err = PyObject_IsTrue(w);
2447 if (err > 0) {
2448 STACKADJ(-1);
2449 Py_DECREF(w);
2450 err = 0;
2451 }
2452 else if (err == 0)
2453 JUMPTO(oparg);
2454 else
2455 break;
2456 DISPATCH();
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 TARGET(JUMP_IF_TRUE_OR_POP)
2459 w = TOP();
2460 if (w == Py_False) {
2461 STACKADJ(-1);
2462 Py_DECREF(w);
2463 FAST_DISPATCH();
2464 }
2465 if (w == Py_True) {
2466 JUMPTO(oparg);
2467 FAST_DISPATCH();
2468 }
2469 err = PyObject_IsTrue(w);
2470 if (err > 0) {
2471 err = 0;
2472 JUMPTO(oparg);
2473 }
2474 else if (err == 0) {
2475 STACKADJ(-1);
2476 Py_DECREF(w);
2477 }
2478 else
2479 break;
2480 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PREDICTED_WITH_ARG(JUMP_ABSOLUTE);
2483 TARGET(JUMP_ABSOLUTE)
2484 JUMPTO(oparg);
Guido van Rossum58da9312007-11-10 23:39:45 +00002485#if FAST_LOOPS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* Enabling this path speeds-up all while and for-loops by bypassing
2487 the per-loop checks for signals. By default, this should be turned-off
2488 because it prevents detection of a control-break in tight loops like
2489 "while 1: pass". Compile with this option turned-on when you need
2490 the speed-up and do not need break checking inside tight loops (ones
2491 that contain only instructions ending with FAST_DISPATCH).
2492 */
2493 FAST_DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002494#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00002496#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 TARGET(GET_ITER)
2499 /* before: [obj]; after [getiter(obj)] */
2500 v = TOP();
2501 x = PyObject_GetIter(v);
2502 Py_DECREF(v);
2503 if (x != NULL) {
2504 SET_TOP(x);
2505 PREDICT(FOR_ITER);
2506 DISPATCH();
2507 }
2508 STACKADJ(-1);
2509 break;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 PREDICTED_WITH_ARG(FOR_ITER);
2512 TARGET(FOR_ITER)
2513 /* before: [iter]; after: [iter, iter()] *or* [] */
2514 v = TOP();
2515 x = (*v->ob_type->tp_iternext)(v);
2516 if (x != NULL) {
2517 PUSH(x);
2518 PREDICT(STORE_FAST);
2519 PREDICT(UNPACK_SEQUENCE);
2520 DISPATCH();
2521 }
2522 if (PyErr_Occurred()) {
2523 if (!PyErr_ExceptionMatches(
2524 PyExc_StopIteration))
2525 break;
2526 PyErr_Clear();
2527 }
2528 /* iterator ended normally */
2529 x = v = POP();
2530 Py_DECREF(v);
2531 JUMPBY(oparg);
2532 DISPATCH();
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 TARGET(BREAK_LOOP)
2535 why = WHY_BREAK;
2536 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 TARGET(CONTINUE_LOOP)
2539 retval = PyLong_FromLong(oparg);
2540 if (!retval) {
2541 x = NULL;
2542 break;
2543 }
2544 why = WHY_CONTINUE;
2545 goto fast_block_end;
Raymond Hettinger2d783e92004-03-12 09:12:22 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally)
2548 TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally)
2549 TARGET(SETUP_FINALLY)
2550 _setup_finally:
2551 /* NOTE: If you add any new block-setup opcodes that
2552 are not try/except/finally handlers, you may need
2553 to update the PyGen_NeedsFinalizing() function.
2554 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
2557 STACK_LEVEL());
2558 DISPATCH();
Guido van Rossumac7be682001-01-17 15:42:30 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 TARGET(SETUP_WITH)
2561 {
2562 static PyObject *exit, *enter;
2563 w = TOP();
2564 x = special_lookup(w, "__exit__", &exit);
2565 if (!x)
2566 break;
2567 SET_TOP(x);
2568 u = special_lookup(w, "__enter__", &enter);
2569 Py_DECREF(w);
2570 if (!u) {
2571 x = NULL;
2572 break;
2573 }
2574 x = PyObject_CallFunctionObjArgs(u, NULL);
2575 Py_DECREF(u);
2576 if (!x)
2577 break;
2578 /* Setup the finally block before pushing the result
2579 of __enter__ on the stack. */
2580 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
2581 STACK_LEVEL());
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 PUSH(x);
2584 DISPATCH();
2585 }
Benjamin Peterson876b2f22009-06-28 03:18:59 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 TARGET(WITH_CLEANUP)
2588 {
2589 /* At the top of the stack are 1-3 values indicating
2590 how/why we entered the finally clause:
2591 - TOP = None
2592 - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
2593 - TOP = WHY_*; no retval below it
2594 - (TOP, SECOND, THIRD) = exc_info()
2595 (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER
2596 Below them is EXIT, the context.__exit__ bound method.
2597 In the last case, we must call
2598 EXIT(TOP, SECOND, THIRD)
2599 otherwise we must call
2600 EXIT(None, None, None)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 In the first two cases, we remove EXIT from the
2603 stack, leaving the rest in the same order. In the
2604 third case, we shift the bottom 3 values of the
2605 stack down, and replace the empty spot with NULL.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 In addition, if the stack represents an exception,
2608 *and* the function call returns a 'true' value, we
2609 push WHY_SILENCED onto the stack. END_FINALLY will
2610 then not re-raise the exception. (But non-local
2611 gotos should still be resumed.)
2612 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 PyObject *exit_func;
2615 u = TOP();
2616 if (u == Py_None) {
2617 (void)POP();
2618 exit_func = TOP();
2619 SET_TOP(u);
2620 v = w = Py_None;
2621 }
2622 else if (PyLong_Check(u)) {
2623 (void)POP();
2624 switch(PyLong_AsLong(u)) {
2625 case WHY_RETURN:
2626 case WHY_CONTINUE:
2627 /* Retval in TOP. */
2628 exit_func = SECOND();
2629 SET_SECOND(TOP());
2630 SET_TOP(u);
2631 break;
2632 default:
2633 exit_func = TOP();
2634 SET_TOP(u);
2635 break;
2636 }
2637 u = v = w = Py_None;
2638 }
2639 else {
2640 PyObject *tp, *exc, *tb;
2641 PyTryBlock *block;
2642 v = SECOND();
2643 w = THIRD();
2644 tp = FOURTH();
2645 exc = PEEK(5);
2646 tb = PEEK(6);
2647 exit_func = PEEK(7);
2648 SET_VALUE(7, tb);
2649 SET_VALUE(6, exc);
2650 SET_VALUE(5, tp);
2651 /* UNWIND_EXCEPT_HANDLER will pop this off. */
2652 SET_FOURTH(NULL);
2653 /* We just shifted the stack down, so we have
2654 to tell the except handler block that the
2655 values are lower than it expects. */
2656 block = &f->f_blockstack[f->f_iblock - 1];
2657 assert(block->b_type == EXCEPT_HANDLER);
2658 block->b_level--;
2659 }
2660 /* XXX Not the fastest way to call it... */
2661 x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
2662 NULL);
2663 Py_DECREF(exit_func);
2664 if (x == NULL)
2665 break; /* Go to error exit */
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 if (u != Py_None)
2668 err = PyObject_IsTrue(x);
2669 else
2670 err = 0;
2671 Py_DECREF(x);
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (err < 0)
2674 break; /* Go to error exit */
2675 else if (err > 0) {
2676 err = 0;
2677 /* There was an exception and a True return */
2678 PUSH(PyLong_FromLong((long) WHY_SILENCED));
2679 }
2680 PREDICT(END_FINALLY);
2681 break;
2682 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 TARGET(CALL_FUNCTION)
2685 {
2686 PyObject **sp;
2687 PCALL(PCALL_ALL);
2688 sp = stack_pointer;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002689#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 x = call_function(&sp, oparg, &intr0, &intr1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002691#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 x = call_function(&sp, oparg);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002693#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 stack_pointer = sp;
2695 PUSH(x);
2696 if (x != NULL)
2697 DISPATCH();
2698 break;
2699 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw)
2702 TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw)
2703 TARGET(CALL_FUNCTION_VAR_KW)
2704 _call_function_var_kw:
2705 {
2706 int na = oparg & 0xff;
2707 int nk = (oparg>>8) & 0xff;
2708 int flags = (opcode - CALL_FUNCTION) & 3;
2709 int n = na + 2 * nk;
2710 PyObject **pfunc, *func, **sp;
2711 PCALL(PCALL_ALL);
2712 if (flags & CALL_FLAG_VAR)
2713 n++;
2714 if (flags & CALL_FLAG_KW)
2715 n++;
2716 pfunc = stack_pointer - n - 1;
2717 func = *pfunc;
Jeremy Hylton52820442001-01-03 23:52:36 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 if (PyMethod_Check(func)
Stefan Krahb7e10102010-06-23 18:42:39 +00002720 && PyMethod_GET_SELF(func) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 PyObject *self = PyMethod_GET_SELF(func);
2722 Py_INCREF(self);
2723 func = PyMethod_GET_FUNCTION(func);
2724 Py_INCREF(func);
2725 Py_DECREF(*pfunc);
2726 *pfunc = self;
2727 na++;
2728 n++;
2729 } else
2730 Py_INCREF(func);
2731 sp = stack_pointer;
2732 READ_TIMESTAMP(intr0);
2733 x = ext_do_call(func, &sp, flags, na, nk);
2734 READ_TIMESTAMP(intr1);
2735 stack_pointer = sp;
2736 Py_DECREF(func);
Jeremy Hylton52820442001-01-03 23:52:36 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 while (stack_pointer > pfunc) {
2739 w = POP();
2740 Py_DECREF(w);
2741 }
2742 PUSH(x);
2743 if (x != NULL)
2744 DISPATCH();
2745 break;
2746 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function)
2749 TARGET(MAKE_FUNCTION)
2750 _make_function:
2751 {
2752 int posdefaults = oparg & 0xff;
2753 int kwdefaults = (oparg>>8) & 0xff;
2754 int num_annotations = (oparg >> 16) & 0x7fff;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 v = POP(); /* code object */
2757 x = PyFunction_New(v, f->f_globals);
2758 Py_DECREF(v);
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00002759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 if (x != NULL && opcode == MAKE_CLOSURE) {
2761 v = POP();
2762 if (PyFunction_SetClosure(x, v) != 0) {
2763 /* Can't happen unless bytecode is corrupt. */
2764 why = WHY_EXCEPTION;
2765 }
2766 Py_DECREF(v);
2767 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 if (x != NULL && num_annotations > 0) {
2770 Py_ssize_t name_ix;
2771 u = POP(); /* names of args with annotations */
2772 v = PyDict_New();
2773 if (v == NULL) {
2774 Py_DECREF(x);
2775 x = NULL;
2776 break;
2777 }
2778 name_ix = PyTuple_Size(u);
2779 assert(num_annotations == name_ix+1);
2780 while (name_ix > 0) {
2781 --name_ix;
2782 t = PyTuple_GET_ITEM(u, name_ix);
2783 w = POP();
2784 /* XXX(nnorwitz): check for errors */
2785 PyDict_SetItem(v, t, w);
2786 Py_DECREF(w);
2787 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 if (PyFunction_SetAnnotations(x, v) != 0) {
2790 /* Can't happen unless
2791 PyFunction_SetAnnotations changes. */
2792 why = WHY_EXCEPTION;
2793 }
2794 Py_DECREF(v);
2795 Py_DECREF(u);
2796 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 /* XXX Maybe this should be a separate opcode? */
2799 if (x != NULL && posdefaults > 0) {
2800 v = PyTuple_New(posdefaults);
2801 if (v == NULL) {
2802 Py_DECREF(x);
2803 x = NULL;
2804 break;
2805 }
2806 while (--posdefaults >= 0) {
2807 w = POP();
2808 PyTuple_SET_ITEM(v, posdefaults, w);
2809 }
2810 if (PyFunction_SetDefaults(x, v) != 0) {
2811 /* Can't happen unless
2812 PyFunction_SetDefaults changes. */
2813 why = WHY_EXCEPTION;
2814 }
2815 Py_DECREF(v);
2816 }
2817 if (x != NULL && kwdefaults > 0) {
2818 v = PyDict_New();
2819 if (v == NULL) {
2820 Py_DECREF(x);
2821 x = NULL;
2822 break;
2823 }
2824 while (--kwdefaults >= 0) {
2825 w = POP(); /* default value */
2826 u = POP(); /* kw only arg name */
2827 /* XXX(nnorwitz): check for errors */
2828 PyDict_SetItem(v, u, w);
2829 Py_DECREF(w);
2830 Py_DECREF(u);
2831 }
2832 if (PyFunction_SetKwDefaults(x, v) != 0) {
2833 /* Can't happen unless
2834 PyFunction_SetKwDefaults changes. */
2835 why = WHY_EXCEPTION;
2836 }
2837 Py_DECREF(v);
2838 }
2839 PUSH(x);
2840 break;
2841 }
Guido van Rossum8861b741996-07-30 16:49:37 +00002842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 TARGET(BUILD_SLICE)
2844 if (oparg == 3)
2845 w = POP();
2846 else
2847 w = NULL;
2848 v = POP();
2849 u = TOP();
2850 x = PySlice_New(u, v, w);
2851 Py_DECREF(u);
2852 Py_DECREF(v);
2853 Py_XDECREF(w);
2854 SET_TOP(x);
2855 if (x != NULL) DISPATCH();
2856 break;
Guido van Rossum8861b741996-07-30 16:49:37 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 TARGET(EXTENDED_ARG)
2859 opcode = NEXTOP();
2860 oparg = oparg<<16 | NEXTARG();
2861 goto dispatch_opcode;
Guido van Rossum8861b741996-07-30 16:49:37 +00002862
Antoine Pitrou042b1282010-08-13 21:15:58 +00002863#if USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 _unknown_opcode:
Antoine Pitroub52ec782009-01-25 16:34:23 +00002865#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 default:
2867 fprintf(stderr,
2868 "XXX lineno: %d, opcode: %d\n",
2869 PyFrame_GetLineNumber(f),
2870 opcode);
2871 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2872 why = WHY_EXCEPTION;
2873 break;
Guido van Rossum04691fc1992-08-12 15:35:34 +00002874
2875#ifdef CASE_TOO_BIG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 }
Guido van Rossum04691fc1992-08-12 15:35:34 +00002877#endif
2878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 } /* switch */
Guido van Rossum374a9221991-04-04 10:40:29 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 on_error:
Guido van Rossumac7be682001-01-17 15:42:30 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 READ_TIMESTAMP(inst1);
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 /* Quickly continue if no error occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 if (why == WHY_NOT) {
2888 if (err == 0 && x != NULL) {
Guido van Rossum681d79a1995-07-18 14:51:37 +00002889#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 /* This check is expensive! */
2891 if (PyErr_Occurred())
2892 fprintf(stderr,
2893 "XXX undetected error\n");
2894 else {
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002895#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 READ_TIMESTAMP(loop1);
2897 continue; /* Normal, fast path */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002898#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 }
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00002900#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 }
2902 why = WHY_EXCEPTION;
2903 x = Py_None;
2904 err = 0;
2905 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 /* Double-check exception status */
Guido van Rossumac7be682001-01-17 15:42:30 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2910 if (!PyErr_Occurred()) {
2911 PyErr_SetString(PyExc_SystemError,
2912 "error return without exception set");
2913 why = WHY_EXCEPTION;
2914 }
2915 }
Guido van Rossumeb894eb1999-03-09 16:16:45 +00002916#ifdef CHECKEXC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 else {
2918 /* This check is expensive! */
2919 if (PyErr_Occurred()) {
2920 char buf[128];
2921 sprintf(buf, "Stack unwind with exception "
2922 "set and why=%d", why);
2923 Py_FatalError(buf);
2924 }
2925 }
Guido van Rossum374a9221991-04-04 10:40:29 +00002926#endif
2927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 /* Log traceback info if this is a real exception */
Guido van Rossumac7be682001-01-17 15:42:30 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 if (why == WHY_EXCEPTION) {
2931 PyTraceBack_Here(f);
Guido van Rossum96a42c81992-01-12 02:29:51 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 if (tstate->c_tracefunc != NULL)
2934 call_exc_trace(tstate->c_tracefunc,
2935 tstate->c_traceobj, f);
2936 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
Guido van Rossumac7be682001-01-17 15:42:30 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 if (why == WHY_RERAISE)
2941 why = WHY_EXCEPTION;
Guido van Rossum374a9221991-04-04 10:40:29 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 /* Unwind stacks if a (pseudo) exception occurred */
Guido van Rossumac7be682001-01-17 15:42:30 +00002944
Raymond Hettinger1dd83092004-02-06 18:32:33 +00002945fast_block_end:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 while (why != WHY_NOT && f->f_iblock > 0) {
2947 /* Peek at the current block. */
2948 PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1];
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 assert(why != WHY_YIELD);
2951 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
2952 why = WHY_NOT;
2953 JUMPTO(PyLong_AS_LONG(retval));
2954 Py_DECREF(retval);
2955 break;
2956 }
2957 /* Now we have to pop the block. */
2958 f->f_iblock--;
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 if (b->b_type == EXCEPT_HANDLER) {
2961 UNWIND_EXCEPT_HANDLER(b);
2962 continue;
2963 }
2964 UNWIND_BLOCK(b);
2965 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2966 why = WHY_NOT;
2967 JUMPTO(b->b_handler);
2968 break;
2969 }
2970 if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT
2971 || b->b_type == SETUP_FINALLY)) {
2972 PyObject *exc, *val, *tb;
2973 int handler = b->b_handler;
2974 /* Beware, this invalidates all b->b_* fields */
2975 PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL());
2976 PUSH(tstate->exc_traceback);
2977 PUSH(tstate->exc_value);
2978 if (tstate->exc_type != NULL) {
2979 PUSH(tstate->exc_type);
2980 }
2981 else {
2982 Py_INCREF(Py_None);
2983 PUSH(Py_None);
2984 }
2985 PyErr_Fetch(&exc, &val, &tb);
2986 /* Make the raw exception data
2987 available to the handler,
2988 so a program can emulate the
2989 Python main loop. */
2990 PyErr_NormalizeException(
2991 &exc, &val, &tb);
2992 PyException_SetTraceback(val, tb);
2993 Py_INCREF(exc);
2994 tstate->exc_type = exc;
2995 Py_INCREF(val);
2996 tstate->exc_value = val;
2997 tstate->exc_traceback = tb;
2998 if (tb == NULL)
2999 tb = Py_None;
3000 Py_INCREF(tb);
3001 PUSH(tb);
3002 PUSH(val);
3003 PUSH(exc);
3004 why = WHY_NOT;
3005 JUMPTO(handler);
3006 break;
3007 }
3008 if (b->b_type == SETUP_FINALLY) {
3009 if (why & (WHY_RETURN | WHY_CONTINUE))
3010 PUSH(retval);
3011 PUSH(PyLong_FromLong((long)why));
3012 why = WHY_NOT;
3013 JUMPTO(b->b_handler);
3014 break;
3015 }
3016 } /* unwind stack */
Guido van Rossum374a9221991-04-04 10:40:29 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 /* End the loop if we still have an error (or return) */
Guido van Rossumac7be682001-01-17 15:42:30 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 if (why != WHY_NOT)
3021 break;
3022 READ_TIMESTAMP(loop1);
Guido van Rossumac7be682001-01-17 15:42:30 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 } /* main loop */
Guido van Rossumac7be682001-01-17 15:42:30 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 assert(why != WHY_YIELD);
3027 /* Pop remaining stack entries. */
3028 while (!EMPTY()) {
3029 v = POP();
3030 Py_XDECREF(v);
3031 }
Guido van Rossum35974fb2001-12-06 21:28:18 +00003032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 if (why != WHY_RETURN)
3034 retval = NULL;
Guido van Rossumac7be682001-01-17 15:42:30 +00003035
Raymond Hettinger1dd83092004-02-06 18:32:33 +00003036fast_yield:
Benjamin Petersonac913412011-07-03 16:25:11 -05003037 if (co->co_flags & CO_GENERATOR && (why == WHY_YIELD || why == WHY_RETURN)) {
3038 /* The purpose of this block is to put aside the generator's exception
3039 state and restore that of the calling frame. If the current
3040 exception state is from the caller, we clear the exception values
3041 on the generator frame, so they are not swapped back in latter. The
3042 origin of the current exception state is determined by checking for
3043 except handler blocks, which we must be in iff a new exception
3044 state came into existence in this frame. (An uncaught exception
3045 would have why == WHY_EXCEPTION, and we wouldn't be here). */
3046 int i;
3047 for (i = 0; i < f->f_iblock; i++)
3048 if (f->f_blockstack[i].b_type == EXCEPT_HANDLER)
3049 break;
3050 if (i == f->f_iblock)
3051 /* We did not create this exception. */
3052 RESTORE_AND_CLEAR_EXC_STATE()
3053 else
3054 SWAP_EXC_STATE()
3055 }
Benjamin Peterson83195c32011-07-03 13:44:00 -05003056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 if (tstate->use_tracing) {
3058 if (tstate->c_tracefunc) {
3059 if (why == WHY_RETURN || why == WHY_YIELD) {
3060 if (call_trace(tstate->c_tracefunc,
3061 tstate->c_traceobj, f,
3062 PyTrace_RETURN, retval)) {
3063 Py_XDECREF(retval);
3064 retval = NULL;
3065 why = WHY_EXCEPTION;
3066 }
3067 }
3068 else if (why == WHY_EXCEPTION) {
3069 call_trace_protected(tstate->c_tracefunc,
3070 tstate->c_traceobj, f,
3071 PyTrace_RETURN, NULL);
3072 }
3073 }
3074 if (tstate->c_profilefunc) {
3075 if (why == WHY_EXCEPTION)
3076 call_trace_protected(tstate->c_profilefunc,
3077 tstate->c_profileobj, f,
3078 PyTrace_RETURN, NULL);
3079 else if (call_trace(tstate->c_profilefunc,
3080 tstate->c_profileobj, f,
3081 PyTrace_RETURN, retval)) {
3082 Py_XDECREF(retval);
3083 retval = NULL;
3084 why = WHY_EXCEPTION;
3085 }
3086 }
3087 }
Guido van Rossuma4240131997-01-21 21:18:36 +00003088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 /* pop frame */
Thomas Woutersce272b62007-09-19 21:19:28 +00003090exit_eval_frame:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 Py_LeaveRecursiveCall();
3092 tstate->frame = f->f_back;
Guido van Rossumac7be682001-01-17 15:42:30 +00003093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 return retval;
Guido van Rossum374a9221991-04-04 10:40:29 +00003095}
3096
Guido van Rossumc2e20742006-02-27 22:32:47 +00003097/* This is gonna seem *real weird*, but if you put some other code between
Martin v. Löwis8d97e332004-06-27 15:43:12 +00003098 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
Guido van Rossumc2e20742006-02-27 22:32:47 +00003099 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
Skip Montanaro786ea6b2004-03-01 15:44:05 +00003100
Tim Peters6d6c1a32001-08-02 04:15:00 +00003101PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003102PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 PyObject **args, int argcount, PyObject **kws, int kwcount,
3104 PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure)
Tim Peters5ca576e2001-06-18 22:08:13 +00003105{
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00003106 PyCodeObject* co = (PyCodeObject*)_co;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 register PyFrameObject *f;
3108 register PyObject *retval = NULL;
3109 register PyObject **fastlocals, **freevars;
3110 PyThreadState *tstate = PyThreadState_GET();
3111 PyObject *x, *u;
3112 int total_args = co->co_argcount + co->co_kwonlyargcount;
Tim Peters5ca576e2001-06-18 22:08:13 +00003113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 if (globals == NULL) {
3115 PyErr_SetString(PyExc_SystemError,
3116 "PyEval_EvalCodeEx: NULL globals");
3117 return NULL;
3118 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 assert(tstate != NULL);
3121 assert(globals != NULL);
3122 f = PyFrame_New(tstate, co, globals, locals);
3123 if (f == NULL)
3124 return NULL;
Tim Peters5ca576e2001-06-18 22:08:13 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 fastlocals = f->f_localsplus;
3127 freevars = f->f_localsplus + co->co_nlocals;
Tim Peters5ca576e2001-06-18 22:08:13 +00003128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 if (total_args || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
3130 int i;
3131 int n = argcount;
3132 PyObject *kwdict = NULL;
3133 if (co->co_flags & CO_VARKEYWORDS) {
3134 kwdict = PyDict_New();
3135 if (kwdict == NULL)
3136 goto fail;
3137 i = total_args;
3138 if (co->co_flags & CO_VARARGS)
3139 i++;
3140 SETLOCAL(i, kwdict);
3141 }
3142 if (argcount > co->co_argcount) {
3143 if (!(co->co_flags & CO_VARARGS)) {
3144 PyErr_Format(PyExc_TypeError,
3145 "%U() takes %s %d "
Benjamin Peterson88968ad2010-06-25 19:30:21 +00003146 "positional argument%s (%d given)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 co->co_name,
3148 defcount ? "at most" : "exactly",
Benjamin Peterson88968ad2010-06-25 19:30:21 +00003149 co->co_argcount,
3150 co->co_argcount == 1 ? "" : "s",
Benjamin Petersonaa7fbd92010-09-25 03:25:42 +00003151 argcount + kwcount);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 goto fail;
3153 }
3154 n = co->co_argcount;
3155 }
3156 for (i = 0; i < n; i++) {
3157 x = args[i];
3158 Py_INCREF(x);
3159 SETLOCAL(i, x);
3160 }
3161 if (co->co_flags & CO_VARARGS) {
3162 u = PyTuple_New(argcount - n);
3163 if (u == NULL)
3164 goto fail;
3165 SETLOCAL(total_args, u);
3166 for (i = n; i < argcount; i++) {
3167 x = args[i];
3168 Py_INCREF(x);
3169 PyTuple_SET_ITEM(u, i-n, x);
3170 }
3171 }
3172 for (i = 0; i < kwcount; i++) {
3173 PyObject **co_varnames;
3174 PyObject *keyword = kws[2*i];
3175 PyObject *value = kws[2*i + 1];
3176 int j;
3177 if (keyword == NULL || !PyUnicode_Check(keyword)) {
3178 PyErr_Format(PyExc_TypeError,
3179 "%U() keywords must be strings",
3180 co->co_name);
3181 goto fail;
3182 }
3183 /* Speed hack: do raw pointer compares. As names are
3184 normally interned this should almost always hit. */
3185 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
3186 for (j = 0; j < total_args; j++) {
3187 PyObject *nm = co_varnames[j];
3188 if (nm == keyword)
3189 goto kw_found;
3190 }
3191 /* Slow fallback, just in case */
3192 for (j = 0; j < total_args; j++) {
3193 PyObject *nm = co_varnames[j];
3194 int cmp = PyObject_RichCompareBool(
3195 keyword, nm, Py_EQ);
3196 if (cmp > 0)
3197 goto kw_found;
3198 else if (cmp < 0)
3199 goto fail;
3200 }
3201 if (j >= total_args && kwdict == NULL) {
3202 PyErr_Format(PyExc_TypeError,
3203 "%U() got an unexpected "
3204 "keyword argument '%S'",
3205 co->co_name,
3206 keyword);
3207 goto fail;
3208 }
3209 PyDict_SetItem(kwdict, keyword, value);
3210 continue;
3211 kw_found:
3212 if (GETLOCAL(j) != NULL) {
3213 PyErr_Format(PyExc_TypeError,
3214 "%U() got multiple "
3215 "values for keyword "
3216 "argument '%S'",
3217 co->co_name,
3218 keyword);
3219 goto fail;
3220 }
3221 Py_INCREF(value);
3222 SETLOCAL(j, value);
3223 }
3224 if (co->co_kwonlyargcount > 0) {
3225 for (i = co->co_argcount; i < total_args; i++) {
3226 PyObject *name;
3227 if (GETLOCAL(i) != NULL)
3228 continue;
3229 name = PyTuple_GET_ITEM(co->co_varnames, i);
3230 if (kwdefs != NULL) {
3231 PyObject *def = PyDict_GetItem(kwdefs, name);
3232 if (def) {
3233 Py_INCREF(def);
3234 SETLOCAL(i, def);
3235 continue;
3236 }
3237 }
3238 PyErr_Format(PyExc_TypeError,
3239 "%U() needs keyword-only argument %S",
3240 co->co_name, name);
3241 goto fail;
3242 }
3243 }
3244 if (argcount < co->co_argcount) {
3245 int m = co->co_argcount - defcount;
3246 for (i = argcount; i < m; i++) {
3247 if (GETLOCAL(i) == NULL) {
3248 int j, given = 0;
3249 for (j = 0; j < co->co_argcount; j++)
3250 if (GETLOCAL(j))
3251 given++;
3252 PyErr_Format(PyExc_TypeError,
3253 "%U() takes %s %d "
3254 "argument%s "
3255 "(%d given)",
3256 co->co_name,
3257 ((co->co_flags & CO_VARARGS) ||
3258 defcount) ? "at least"
3259 : "exactly",
3260 m, m == 1 ? "" : "s", given);
3261 goto fail;
3262 }
3263 }
3264 if (n > m)
3265 i = n - m;
3266 else
3267 i = 0;
3268 for (; i < defcount; i++) {
3269 if (GETLOCAL(m+i) == NULL) {
3270 PyObject *def = defs[i];
3271 Py_INCREF(def);
3272 SETLOCAL(m+i, def);
3273 }
3274 }
3275 }
3276 }
3277 else if (argcount > 0 || kwcount > 0) {
3278 PyErr_Format(PyExc_TypeError,
3279 "%U() takes no arguments (%d given)",
3280 co->co_name,
3281 argcount + kwcount);
3282 goto fail;
3283 }
3284 /* Allocate and initialize storage for cell vars, and copy free
3285 vars into frame. This isn't too efficient right now. */
3286 if (PyTuple_GET_SIZE(co->co_cellvars)) {
3287 int i, j, nargs, found;
3288 Py_UNICODE *cellname, *argname;
3289 PyObject *c;
Tim Peters5ca576e2001-06-18 22:08:13 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 nargs = total_args;
3292 if (co->co_flags & CO_VARARGS)
3293 nargs++;
3294 if (co->co_flags & CO_VARKEYWORDS)
3295 nargs++;
Tim Peters5ca576e2001-06-18 22:08:13 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 /* Initialize each cell var, taking into account
3298 cell vars that are initialized from arguments.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 Should arrange for the compiler to put cellvars
3301 that are arguments at the beginning of the cellvars
3302 list so that we can march over it more efficiently?
3303 */
3304 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
3305 cellname = PyUnicode_AS_UNICODE(
3306 PyTuple_GET_ITEM(co->co_cellvars, i));
3307 found = 0;
3308 for (j = 0; j < nargs; j++) {
3309 argname = PyUnicode_AS_UNICODE(
3310 PyTuple_GET_ITEM(co->co_varnames, j));
3311 if (Py_UNICODE_strcmp(cellname, argname) == 0) {
3312 c = PyCell_New(GETLOCAL(j));
3313 if (c == NULL)
3314 goto fail;
3315 GETLOCAL(co->co_nlocals + i) = c;
3316 found = 1;
3317 break;
3318 }
3319 }
3320 if (found == 0) {
3321 c = PyCell_New(NULL);
3322 if (c == NULL)
3323 goto fail;
3324 SETLOCAL(co->co_nlocals + i, c);
3325 }
3326 }
3327 }
3328 if (PyTuple_GET_SIZE(co->co_freevars)) {
3329 int i;
3330 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
3331 PyObject *o = PyTuple_GET_ITEM(closure, i);
3332 Py_INCREF(o);
3333 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
3334 }
3335 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 if (co->co_flags & CO_GENERATOR) {
3338 /* Don't need to keep the reference to f_back, it will be set
3339 * when the generator is resumed. */
3340 Py_XDECREF(f->f_back);
3341 f->f_back = NULL;
Neil Schemenauer2b13ce82001-06-21 02:41:10 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 PCALL(PCALL_GENERATOR);
Jeremy Hylton985eba52003-02-05 23:13:00 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 /* Create a new generator that owns the ready to run frame
3346 * and return that as the value. */
3347 return PyGen_New(f);
3348 }
Tim Peters5ca576e2001-06-18 22:08:13 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 retval = PyEval_EvalFrameEx(f,0);
Tim Peters5ca576e2001-06-18 22:08:13 +00003351
Thomas Woutersce272b62007-09-19 21:19:28 +00003352fail: /* Jump here from prelude on failure */
Tim Peters5ca576e2001-06-18 22:08:13 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 /* decref'ing the frame can cause __del__ methods to get invoked,
3355 which can call back into Python. While we're done with the
3356 current Python frame (f), the associated C stack is still in use,
3357 so recursion_depth must be boosted for the duration.
3358 */
3359 assert(tstate != NULL);
3360 ++tstate->recursion_depth;
3361 Py_DECREF(f);
3362 --tstate->recursion_depth;
3363 return retval;
Tim Peters5ca576e2001-06-18 22:08:13 +00003364}
3365
3366
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003367static PyObject *
3368special_lookup(PyObject *o, char *meth, PyObject **cache)
3369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 PyObject *res;
3371 res = _PyObject_LookupSpecial(o, meth, cache);
3372 if (res == NULL && !PyErr_Occurred()) {
3373 PyErr_SetObject(PyExc_AttributeError, *cache);
3374 return NULL;
3375 }
3376 return res;
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003377}
3378
3379
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003380/* Logic for the raise statement (too complicated for inlining).
3381 This *consumes* a reference count to each of its arguments. */
Raymond Hettinger7c958652004-04-06 10:11:10 +00003382static enum why_code
Collin Winter828f04a2007-08-31 00:04:24 +00003383do_raise(PyObject *exc, PyObject *cause)
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 PyObject *type = NULL, *value = NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 if (exc == NULL) {
3388 /* Reraise */
3389 PyThreadState *tstate = PyThreadState_GET();
3390 PyObject *tb;
3391 type = tstate->exc_type;
3392 value = tstate->exc_value;
3393 tb = tstate->exc_traceback;
3394 if (type == Py_None) {
3395 PyErr_SetString(PyExc_RuntimeError,
3396 "No active exception to reraise");
3397 return WHY_EXCEPTION;
3398 }
3399 Py_XINCREF(type);
3400 Py_XINCREF(value);
3401 Py_XINCREF(tb);
3402 PyErr_Restore(type, value, tb);
3403 return WHY_RERAISE;
3404 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* We support the following forms of raise:
3407 raise
Collin Winter828f04a2007-08-31 00:04:24 +00003408 raise <instance>
3409 raise <type> */
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 if (PyExceptionClass_Check(exc)) {
3412 type = exc;
3413 value = PyObject_CallObject(exc, NULL);
3414 if (value == NULL)
3415 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05003416 if (!PyExceptionInstance_Check(value)) {
3417 PyErr_Format(PyExc_TypeError,
3418 "calling %R should have returned an instance of "
3419 "BaseException, not %R",
3420 type, Py_TYPE(value));
3421 goto raise_error;
3422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 }
3424 else if (PyExceptionInstance_Check(exc)) {
3425 value = exc;
3426 type = PyExceptionInstance_Class(exc);
3427 Py_INCREF(type);
3428 }
3429 else {
3430 /* Not something you can raise. You get an exception
3431 anyway, just not what you specified :-) */
3432 Py_DECREF(exc);
3433 PyErr_SetString(PyExc_TypeError,
3434 "exceptions must derive from BaseException");
3435 goto raise_error;
3436 }
Collin Winter828f04a2007-08-31 00:04:24 +00003437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 if (cause) {
3439 PyObject *fixed_cause;
3440 if (PyExceptionClass_Check(cause)) {
3441 fixed_cause = PyObject_CallObject(cause, NULL);
3442 if (fixed_cause == NULL)
3443 goto raise_error;
3444 Py_DECREF(cause);
3445 }
3446 else if (PyExceptionInstance_Check(cause)) {
3447 fixed_cause = cause;
3448 }
3449 else {
3450 PyErr_SetString(PyExc_TypeError,
3451 "exception causes must derive from "
3452 "BaseException");
3453 goto raise_error;
3454 }
3455 PyException_SetCause(value, fixed_cause);
3456 }
Collin Winter828f04a2007-08-31 00:04:24 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 PyErr_SetObject(type, value);
3459 /* PyErr_SetObject incref's its arguments */
3460 Py_XDECREF(value);
3461 Py_XDECREF(type);
3462 return WHY_EXCEPTION;
Collin Winter828f04a2007-08-31 00:04:24 +00003463
3464raise_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 Py_XDECREF(value);
3466 Py_XDECREF(type);
3467 Py_XDECREF(cause);
3468 return WHY_EXCEPTION;
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00003469}
3470
Tim Petersd6d010b2001-06-21 02:49:55 +00003471/* Iterate v argcnt times and store the results on the stack (via decreasing
Guido van Rossum0368b722007-05-11 16:50:42 +00003472 sp). Return 1 for success, 0 if error.
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00003473
Guido van Rossum0368b722007-05-11 16:50:42 +00003474 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
3475 with a variable target.
3476*/
Tim Petersd6d010b2001-06-21 02:49:55 +00003477
Barry Warsawe42b18f1997-08-25 22:13:04 +00003478static int
Guido van Rossum0368b722007-05-11 16:50:42 +00003479unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp)
Barry Warsawe42b18f1997-08-25 22:13:04 +00003480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 int i = 0, j = 0;
3482 Py_ssize_t ll = 0;
3483 PyObject *it; /* iter(v) */
3484 PyObject *w;
3485 PyObject *l = NULL; /* variable list */
Guido van Rossumac7be682001-01-17 15:42:30 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 assert(v != NULL);
Tim Petersd6d010b2001-06-21 02:49:55 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 it = PyObject_GetIter(v);
3490 if (it == NULL)
3491 goto Error;
Tim Petersd6d010b2001-06-21 02:49:55 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 for (; i < argcnt; i++) {
3494 w = PyIter_Next(it);
3495 if (w == NULL) {
3496 /* Iterator done, via error or exhaustion. */
3497 if (!PyErr_Occurred()) {
3498 PyErr_Format(PyExc_ValueError,
3499 "need more than %d value%s to unpack",
3500 i, i == 1 ? "" : "s");
3501 }
3502 goto Error;
3503 }
3504 *--sp = w;
3505 }
Tim Petersd6d010b2001-06-21 02:49:55 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 if (argcntafter == -1) {
3508 /* We better have exhausted the iterator now. */
3509 w = PyIter_Next(it);
3510 if (w == NULL) {
3511 if (PyErr_Occurred())
3512 goto Error;
3513 Py_DECREF(it);
3514 return 1;
3515 }
3516 Py_DECREF(w);
Georg Brandl0310a832010-07-10 10:32:36 +00003517 PyErr_Format(PyExc_ValueError, "too many values to unpack "
3518 "(expected %d)", argcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 goto Error;
3520 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 l = PySequence_List(it);
3523 if (l == NULL)
3524 goto Error;
3525 *--sp = l;
3526 i++;
Guido van Rossum0368b722007-05-11 16:50:42 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 ll = PyList_GET_SIZE(l);
3529 if (ll < argcntafter) {
3530 PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack",
3531 argcnt + ll);
3532 goto Error;
3533 }
Guido van Rossum0368b722007-05-11 16:50:42 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 /* Pop the "after-variable" args off the list. */
3536 for (j = argcntafter; j > 0; j--, i++) {
3537 *--sp = PyList_GET_ITEM(l, ll - j);
3538 }
3539 /* Resize the list. */
3540 Py_SIZE(l) = ll - argcntafter;
3541 Py_DECREF(it);
3542 return 1;
Guido van Rossum0368b722007-05-11 16:50:42 +00003543
Tim Petersd6d010b2001-06-21 02:49:55 +00003544Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 for (; i > 0; i--, sp++)
3546 Py_DECREF(*sp);
3547 Py_XDECREF(it);
3548 return 0;
Barry Warsawe42b18f1997-08-25 22:13:04 +00003549}
3550
3551
Guido van Rossum96a42c81992-01-12 02:29:51 +00003552#ifdef LLTRACE
Guido van Rossum3f5da241990-12-20 15:06:42 +00003553static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003554prtrace(PyObject *v, char *str)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 printf("%s ", str);
3557 if (PyObject_Print(v, stdout, 0) != 0)
3558 PyErr_Clear(); /* Don't know what else to do */
3559 printf("\n");
3560 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003561}
Guido van Rossum3f5da241990-12-20 15:06:42 +00003562#endif
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003563
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003564static void
Fred Drake5755ce62001-06-27 19:19:46 +00003565call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 PyObject *type, *value, *traceback, *arg;
3568 int err;
3569 PyErr_Fetch(&type, &value, &traceback);
3570 if (value == NULL) {
3571 value = Py_None;
3572 Py_INCREF(value);
3573 }
3574 arg = PyTuple_Pack(3, type, value, traceback);
3575 if (arg == NULL) {
3576 PyErr_Restore(type, value, traceback);
3577 return;
3578 }
3579 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
3580 Py_DECREF(arg);
3581 if (err == 0)
3582 PyErr_Restore(type, value, traceback);
3583 else {
3584 Py_XDECREF(type);
3585 Py_XDECREF(value);
3586 Py_XDECREF(traceback);
3587 }
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003588}
3589
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +00003590static int
Fred Drake4ec5d562001-10-04 19:26:43 +00003591call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 int what, PyObject *arg)
Fred Drake4ec5d562001-10-04 19:26:43 +00003593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 PyObject *type, *value, *traceback;
3595 int err;
3596 PyErr_Fetch(&type, &value, &traceback);
3597 err = call_trace(func, obj, frame, what, arg);
3598 if (err == 0)
3599 {
3600 PyErr_Restore(type, value, traceback);
3601 return 0;
3602 }
3603 else {
3604 Py_XDECREF(type);
3605 Py_XDECREF(value);
3606 Py_XDECREF(traceback);
3607 return -1;
3608 }
Fred Drake4ec5d562001-10-04 19:26:43 +00003609}
3610
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00003611static int
Fred Drake5755ce62001-06-27 19:19:46 +00003612call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 int what, PyObject *arg)
Guido van Rossum96a42c81992-01-12 02:29:51 +00003614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 register PyThreadState *tstate = frame->f_tstate;
3616 int result;
3617 if (tstate->tracing)
3618 return 0;
3619 tstate->tracing++;
3620 tstate->use_tracing = 0;
3621 result = func(obj, frame, what, arg);
3622 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3623 || (tstate->c_profilefunc != NULL));
3624 tstate->tracing--;
3625 return result;
Guido van Rossum96a42c81992-01-12 02:29:51 +00003626}
3627
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003628PyObject *
3629_PyEval_CallTracing(PyObject *func, PyObject *args)
3630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 PyFrameObject *frame = PyEval_GetFrame();
3632 PyThreadState *tstate = frame->f_tstate;
3633 int save_tracing = tstate->tracing;
3634 int save_use_tracing = tstate->use_tracing;
3635 PyObject *result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 tstate->tracing = 0;
3638 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3639 || (tstate->c_profilefunc != NULL));
3640 result = PyObject_Call(func, args, NULL);
3641 tstate->tracing = save_tracing;
3642 tstate->use_tracing = save_use_tracing;
3643 return result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00003644}
3645
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003646/* See Objects/lnotab_notes.txt for a description of how tracing works. */
Michael W. Hudson006c7522002-11-08 13:08:46 +00003647static int
Tim Peters8a5c3c72004-04-05 19:36:21 +00003648maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 PyFrameObject *frame, int *instr_lb, int *instr_ub,
3650 int *instr_prev)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 int result = 0;
3653 int line = frame->f_lineno;
Michael W. Hudson006c7522002-11-08 13:08:46 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 /* If the last instruction executed isn't in the current
3656 instruction window, reset the window.
3657 */
3658 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
3659 PyAddrPair bounds;
3660 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
3661 &bounds);
3662 *instr_lb = bounds.ap_lower;
3663 *instr_ub = bounds.ap_upper;
3664 }
3665 /* If the last instruction falls at the start of a line or if
3666 it represents a jump backwards, update the frame's line
3667 number and call the trace function. */
3668 if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
3669 frame->f_lineno = line;
3670 result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
3671 }
3672 *instr_prev = frame->f_lasti;
3673 return result;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003674}
3675
Fred Drake5755ce62001-06-27 19:19:46 +00003676void
3677PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
Fred Draked0838392001-06-16 21:02:31 +00003678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 PyThreadState *tstate = PyThreadState_GET();
3680 PyObject *temp = tstate->c_profileobj;
3681 Py_XINCREF(arg);
3682 tstate->c_profilefunc = NULL;
3683 tstate->c_profileobj = NULL;
3684 /* Must make sure that tracing is not ignored if 'temp' is freed */
3685 tstate->use_tracing = tstate->c_tracefunc != NULL;
3686 Py_XDECREF(temp);
3687 tstate->c_profilefunc = func;
3688 tstate->c_profileobj = arg;
3689 /* Flag that tracing or profiling is turned on */
3690 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
Fred Drake5755ce62001-06-27 19:19:46 +00003691}
3692
3693void
3694PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
3695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 PyThreadState *tstate = PyThreadState_GET();
3697 PyObject *temp = tstate->c_traceobj;
3698 _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
3699 Py_XINCREF(arg);
3700 tstate->c_tracefunc = NULL;
3701 tstate->c_traceobj = NULL;
3702 /* Must make sure that profiling is not ignored if 'temp' is freed */
3703 tstate->use_tracing = tstate->c_profilefunc != NULL;
3704 Py_XDECREF(temp);
3705 tstate->c_tracefunc = func;
3706 tstate->c_traceobj = arg;
3707 /* Flag that tracing or profiling is turned on */
3708 tstate->use_tracing = ((func != NULL)
3709 || (tstate->c_profilefunc != NULL));
Fred Draked0838392001-06-16 21:02:31 +00003710}
3711
Guido van Rossumb209a111997-04-29 18:18:01 +00003712PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003713PyEval_GetBuiltins(void)
Guido van Rossum6135a871995-01-09 17:53:26 +00003714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 PyFrameObject *current_frame = PyEval_GetFrame();
3716 if (current_frame == NULL)
3717 return PyThreadState_GET()->interp->builtins;
3718 else
3719 return current_frame->f_builtins;
Guido van Rossum6135a871995-01-09 17:53:26 +00003720}
3721
Guido van Rossumb209a111997-04-29 18:18:01 +00003722PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003723PyEval_GetLocals(void)
Guido van Rossum5b722181993-03-30 17:46:03 +00003724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 PyFrameObject *current_frame = PyEval_GetFrame();
3726 if (current_frame == NULL)
3727 return NULL;
3728 PyFrame_FastToLocals(current_frame);
3729 return current_frame->f_locals;
Guido van Rossum5b722181993-03-30 17:46:03 +00003730}
3731
Guido van Rossumb209a111997-04-29 18:18:01 +00003732PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003733PyEval_GetGlobals(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 PyFrameObject *current_frame = PyEval_GetFrame();
3736 if (current_frame == NULL)
3737 return NULL;
3738 else
3739 return current_frame->f_globals;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003740}
3741
Guido van Rossum6297a7a2003-02-19 15:53:17 +00003742PyFrameObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003743PyEval_GetFrame(void)
Guido van Rossume59214e1994-08-30 08:01:59 +00003744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 PyThreadState *tstate = PyThreadState_GET();
3746 return _PyThreadState_GetFrame(tstate);
Guido van Rossume59214e1994-08-30 08:01:59 +00003747}
3748
Guido van Rossum6135a871995-01-09 17:53:26 +00003749int
Tim Peters5ba58662001-07-16 02:29:45 +00003750PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Jeremy Hylton061d1062001-03-22 02:32:48 +00003751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 PyFrameObject *current_frame = PyEval_GetFrame();
3753 int result = cf->cf_flags != 0;
Tim Peters5ba58662001-07-16 02:29:45 +00003754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 if (current_frame != NULL) {
3756 const int codeflags = current_frame->f_code->co_flags;
3757 const int compilerflags = codeflags & PyCF_MASK;
3758 if (compilerflags) {
3759 result = 1;
3760 cf->cf_flags |= compilerflags;
3761 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003762#if 0 /* future keyword */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 if (codeflags & CO_GENERATOR_ALLOWED) {
3764 result = 1;
3765 cf->cf_flags |= CO_GENERATOR_ALLOWED;
3766 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00003767#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 }
3769 return result;
Jeremy Hylton061d1062001-03-22 02:32:48 +00003770}
3771
Guido van Rossum3f5da241990-12-20 15:06:42 +00003772
Guido van Rossum681d79a1995-07-18 14:51:37 +00003773/* External interface to call any callable object.
Antoine Pitrou8689a102010-04-01 16:53:15 +00003774 The arg must be a tuple or NULL. The kw must be a dict or NULL. */
Guido van Rossume59214e1994-08-30 08:01:59 +00003775
Guido van Rossumb209a111997-04-29 18:18:01 +00003776PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003777PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 PyObject *result;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 if (arg == NULL) {
3782 arg = PyTuple_New(0);
3783 if (arg == NULL)
3784 return NULL;
3785 }
3786 else if (!PyTuple_Check(arg)) {
3787 PyErr_SetString(PyExc_TypeError,
3788 "argument list must be a tuple");
3789 return NULL;
3790 }
3791 else
3792 Py_INCREF(arg);
Guido van Rossum681d79a1995-07-18 14:51:37 +00003793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 if (kw != NULL && !PyDict_Check(kw)) {
3795 PyErr_SetString(PyExc_TypeError,
3796 "keyword list must be a dictionary");
3797 Py_DECREF(arg);
3798 return NULL;
3799 }
Guido van Rossume3e61c11995-08-04 04:14:47 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 result = PyObject_Call(func, arg, kw);
3802 Py_DECREF(arg);
3803 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00003804}
3805
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003806const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807PyEval_GetFuncName(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (PyMethod_Check(func))
3810 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
3811 else if (PyFunction_Check(func))
3812 return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name);
3813 else if (PyCFunction_Check(func))
3814 return ((PyCFunctionObject*)func)->m_ml->ml_name;
3815 else
3816 return func->ob_type->tp_name;
Jeremy Hylton512a2372001-04-11 13:52:29 +00003817}
3818
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003819const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820PyEval_GetFuncDesc(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00003821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 if (PyMethod_Check(func))
3823 return "()";
3824 else if (PyFunction_Check(func))
3825 return "()";
3826 else if (PyCFunction_Check(func))
3827 return "()";
3828 else
3829 return " object";
Jeremy Hylton512a2372001-04-11 13:52:29 +00003830}
3831
Neal Norwitzaddfe0c2002-11-10 14:33:26 +00003832static void
Jeremy Hylton192690e2002-08-16 18:36:11 +00003833err_args(PyObject *func, int flags, int nargs)
3834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 if (flags & METH_NOARGS)
3836 PyErr_Format(PyExc_TypeError,
3837 "%.200s() takes no arguments (%d given)",
3838 ((PyCFunctionObject *)func)->m_ml->ml_name,
3839 nargs);
3840 else
3841 PyErr_Format(PyExc_TypeError,
3842 "%.200s() takes exactly one argument (%d given)",
3843 ((PyCFunctionObject *)func)->m_ml->ml_name,
3844 nargs);
Jeremy Hylton192690e2002-08-16 18:36:11 +00003845}
3846
Armin Rigo1c2d7e52005-09-20 18:34:01 +00003847#define C_TRACE(x, call) \
Nicholas Bastind858a772004-06-25 23:31:06 +00003848if (tstate->use_tracing && tstate->c_profilefunc) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 if (call_trace(tstate->c_profilefunc, \
3850 tstate->c_profileobj, \
3851 tstate->frame, PyTrace_C_CALL, \
3852 func)) { \
3853 x = NULL; \
3854 } \
3855 else { \
3856 x = call; \
3857 if (tstate->c_profilefunc != NULL) { \
3858 if (x == NULL) { \
3859 call_trace_protected(tstate->c_profilefunc, \
3860 tstate->c_profileobj, \
3861 tstate->frame, PyTrace_C_EXCEPTION, \
3862 func); \
3863 /* XXX should pass (type, value, tb) */ \
3864 } else { \
3865 if (call_trace(tstate->c_profilefunc, \
3866 tstate->c_profileobj, \
3867 tstate->frame, PyTrace_C_RETURN, \
3868 func)) { \
3869 Py_DECREF(x); \
3870 x = NULL; \
3871 } \
3872 } \
3873 } \
3874 } \
Nicholas Bastind858a772004-06-25 23:31:06 +00003875} else { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 x = call; \
3877 }
Nicholas Bastinc69ebe82004-03-24 21:57:10 +00003878
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003879static PyObject *
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003880call_function(PyObject ***pp_stack, int oparg
3881#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 , uint64* pintr0, uint64* pintr1
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00003883#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 )
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 int na = oparg & 0xff;
3887 int nk = (oparg>>8) & 0xff;
3888 int n = na + 2 * nk;
3889 PyObject **pfunc = (*pp_stack) - n - 1;
3890 PyObject *func = *pfunc;
3891 PyObject *x, *w;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 /* Always dispatch PyCFunction first, because these are
3894 presumed to be the most frequent callable object.
3895 */
3896 if (PyCFunction_Check(func) && nk == 0) {
3897 int flags = PyCFunction_GET_FLAGS(func);
3898 PyThreadState *tstate = PyThreadState_GET();
Raymond Hettingera7f56bc2004-06-26 04:34:33 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 PCALL(PCALL_CFUNCTION);
3901 if (flags & (METH_NOARGS | METH_O)) {
3902 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
3903 PyObject *self = PyCFunction_GET_SELF(func);
3904 if (flags & METH_NOARGS && na == 0) {
3905 C_TRACE(x, (*meth)(self,NULL));
3906 }
3907 else if (flags & METH_O && na == 1) {
3908 PyObject *arg = EXT_POP(*pp_stack);
3909 C_TRACE(x, (*meth)(self,arg));
3910 Py_DECREF(arg);
3911 }
3912 else {
3913 err_args(func, flags, na);
3914 x = NULL;
3915 }
3916 }
3917 else {
3918 PyObject *callargs;
3919 callargs = load_args(pp_stack, na);
3920 READ_TIMESTAMP(*pintr0);
3921 C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
3922 READ_TIMESTAMP(*pintr1);
3923 Py_XDECREF(callargs);
3924 }
3925 } else {
3926 if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
3927 /* optimize access to bound methods */
3928 PyObject *self = PyMethod_GET_SELF(func);
3929 PCALL(PCALL_METHOD);
3930 PCALL(PCALL_BOUND_METHOD);
3931 Py_INCREF(self);
3932 func = PyMethod_GET_FUNCTION(func);
3933 Py_INCREF(func);
3934 Py_DECREF(*pfunc);
3935 *pfunc = self;
3936 na++;
3937 n++;
3938 } else
3939 Py_INCREF(func);
3940 READ_TIMESTAMP(*pintr0);
3941 if (PyFunction_Check(func))
3942 x = fast_function(func, pp_stack, n, na, nk);
3943 else
3944 x = do_call(func, pp_stack, na, nk);
3945 READ_TIMESTAMP(*pintr1);
3946 Py_DECREF(func);
3947 }
Tim Peters8a5c3c72004-04-05 19:36:21 +00003948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 /* Clear the stack of the function object. Also removes
3950 the arguments in case they weren't consumed already
3951 (fast_function() and err_args() leave them on the stack).
3952 */
3953 while ((*pp_stack) > pfunc) {
3954 w = EXT_POP(*pp_stack);
3955 Py_DECREF(w);
3956 PCALL(PCALL_POP);
3957 }
3958 return x;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00003959}
3960
Jeremy Hylton192690e2002-08-16 18:36:11 +00003961/* The fast_function() function optimize calls for which no argument
Jeremy Hylton52820442001-01-03 23:52:36 +00003962 tuple is necessary; the objects are passed directly from the stack.
Jeremy Hylton985eba52003-02-05 23:13:00 +00003963 For the simplest case -- a function that takes only positional
3964 arguments and is called with only positional arguments -- it
3965 inlines the most primitive frame setup code from
3966 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
3967 done before evaluating the frame.
Jeremy Hylton52820442001-01-03 23:52:36 +00003968*/
3969
3970static PyObject *
Guido van Rossumac7be682001-01-17 15:42:30 +00003971fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
Jeremy Hylton52820442001-01-03 23:52:36 +00003972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
3974 PyObject *globals = PyFunction_GET_GLOBALS(func);
3975 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
3976 PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func);
3977 PyObject **d = NULL;
3978 int nd = 0;
Jeremy Hylton52820442001-01-03 23:52:36 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 PCALL(PCALL_FUNCTION);
3981 PCALL(PCALL_FAST_FUNCTION);
3982 if (argdefs == NULL && co->co_argcount == n &&
3983 co->co_kwonlyargcount == 0 && nk==0 &&
3984 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
3985 PyFrameObject *f;
3986 PyObject *retval = NULL;
3987 PyThreadState *tstate = PyThreadState_GET();
3988 PyObject **fastlocals, **stack;
3989 int i;
Jeremy Hylton985eba52003-02-05 23:13:00 +00003990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 PCALL(PCALL_FASTER_FUNCTION);
3992 assert(globals != NULL);
3993 /* XXX Perhaps we should create a specialized
3994 PyFrame_New() that doesn't take locals, but does
3995 take builtins without sanity checking them.
3996 */
3997 assert(tstate != NULL);
3998 f = PyFrame_New(tstate, co, globals, NULL);
3999 if (f == NULL)
4000 return NULL;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 fastlocals = f->f_localsplus;
4003 stack = (*pp_stack) - n;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 for (i = 0; i < n; i++) {
4006 Py_INCREF(*stack);
4007 fastlocals[i] = *stack++;
4008 }
4009 retval = PyEval_EvalFrameEx(f,0);
4010 ++tstate->recursion_depth;
4011 Py_DECREF(f);
4012 --tstate->recursion_depth;
4013 return retval;
4014 }
4015 if (argdefs != NULL) {
4016 d = &PyTuple_GET_ITEM(argdefs, 0);
4017 nd = Py_SIZE(argdefs);
4018 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00004019 return PyEval_EvalCodeEx((PyObject*)co, globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 (PyObject *)NULL, (*pp_stack)-n, na,
4021 (*pp_stack)-2*nk, nk, d, nd, kwdefs,
4022 PyFunction_GET_CLOSURE(func));
Jeremy Hylton52820442001-01-03 23:52:36 +00004023}
4024
4025static PyObject *
Ka-Ping Yee20579702001-01-15 22:14:16 +00004026update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
4027 PyObject *func)
Jeremy Hylton52820442001-01-03 23:52:36 +00004028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 PyObject *kwdict = NULL;
4030 if (orig_kwdict == NULL)
4031 kwdict = PyDict_New();
4032 else {
4033 kwdict = PyDict_Copy(orig_kwdict);
4034 Py_DECREF(orig_kwdict);
4035 }
4036 if (kwdict == NULL)
4037 return NULL;
4038 while (--nk >= 0) {
4039 int err;
4040 PyObject *value = EXT_POP(*pp_stack);
4041 PyObject *key = EXT_POP(*pp_stack);
4042 if (PyDict_GetItem(kwdict, key) != NULL) {
4043 PyErr_Format(PyExc_TypeError,
4044 "%.200s%s got multiple values "
4045 "for keyword argument '%U'",
4046 PyEval_GetFuncName(func),
4047 PyEval_GetFuncDesc(func),
4048 key);
4049 Py_DECREF(key);
4050 Py_DECREF(value);
4051 Py_DECREF(kwdict);
4052 return NULL;
4053 }
4054 err = PyDict_SetItem(kwdict, key, value);
4055 Py_DECREF(key);
4056 Py_DECREF(value);
4057 if (err) {
4058 Py_DECREF(kwdict);
4059 return NULL;
4060 }
4061 }
4062 return kwdict;
Jeremy Hylton52820442001-01-03 23:52:36 +00004063}
4064
4065static PyObject *
4066update_star_args(int nstack, int nstar, PyObject *stararg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 PyObject ***pp_stack)
Jeremy Hylton52820442001-01-03 23:52:36 +00004068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 PyObject *callargs, *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 callargs = PyTuple_New(nstack + nstar);
4072 if (callargs == NULL) {
4073 return NULL;
4074 }
4075 if (nstar) {
4076 int i;
4077 for (i = 0; i < nstar; i++) {
4078 PyObject *a = PyTuple_GET_ITEM(stararg, i);
4079 Py_INCREF(a);
4080 PyTuple_SET_ITEM(callargs, nstack + i, a);
4081 }
4082 }
4083 while (--nstack >= 0) {
4084 w = EXT_POP(*pp_stack);
4085 PyTuple_SET_ITEM(callargs, nstack, w);
4086 }
4087 return callargs;
Jeremy Hylton52820442001-01-03 23:52:36 +00004088}
4089
4090static PyObject *
4091load_args(PyObject ***pp_stack, int na)
4092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 PyObject *args = PyTuple_New(na);
4094 PyObject *w;
Jeremy Hylton52820442001-01-03 23:52:36 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 if (args == NULL)
4097 return NULL;
4098 while (--na >= 0) {
4099 w = EXT_POP(*pp_stack);
4100 PyTuple_SET_ITEM(args, na, w);
4101 }
4102 return args;
Jeremy Hylton52820442001-01-03 23:52:36 +00004103}
4104
4105static PyObject *
4106do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
4107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 PyObject *callargs = NULL;
4109 PyObject *kwdict = NULL;
4110 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 if (nk > 0) {
4113 kwdict = update_keyword_args(NULL, nk, pp_stack, func);
4114 if (kwdict == NULL)
4115 goto call_fail;
4116 }
4117 callargs = load_args(pp_stack, na);
4118 if (callargs == NULL)
4119 goto call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004120#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 /* At this point, we have to look at the type of func to
4122 update the call stats properly. Do it here so as to avoid
4123 exposing the call stats machinery outside ceval.c
4124 */
4125 if (PyFunction_Check(func))
4126 PCALL(PCALL_FUNCTION);
4127 else if (PyMethod_Check(func))
4128 PCALL(PCALL_METHOD);
4129 else if (PyType_Check(func))
4130 PCALL(PCALL_TYPE);
4131 else if (PyCFunction_Check(func))
4132 PCALL(PCALL_CFUNCTION);
4133 else
4134 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004135#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (PyCFunction_Check(func)) {
4137 PyThreadState *tstate = PyThreadState_GET();
4138 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4139 }
4140 else
4141 result = PyObject_Call(func, callargs, kwdict);
Thomas Wouters7ce29ca2007-09-19 21:56:32 +00004142call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 Py_XDECREF(callargs);
4144 Py_XDECREF(kwdict);
4145 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004146}
4147
4148static PyObject *
4149ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
4150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 int nstar = 0;
4152 PyObject *callargs = NULL;
4153 PyObject *stararg = NULL;
4154 PyObject *kwdict = NULL;
4155 PyObject *result = NULL;
Jeremy Hylton52820442001-01-03 23:52:36 +00004156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 if (flags & CALL_FLAG_KW) {
4158 kwdict = EXT_POP(*pp_stack);
4159 if (!PyDict_Check(kwdict)) {
4160 PyObject *d;
4161 d = PyDict_New();
4162 if (d == NULL)
4163 goto ext_call_fail;
4164 if (PyDict_Update(d, kwdict) != 0) {
4165 Py_DECREF(d);
4166 /* PyDict_Update raises attribute
4167 * error (percolated from an attempt
4168 * to get 'keys' attribute) instead of
4169 * a type error if its second argument
4170 * is not a mapping.
4171 */
4172 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
4173 PyErr_Format(PyExc_TypeError,
4174 "%.200s%.200s argument after ** "
4175 "must be a mapping, not %.200s",
4176 PyEval_GetFuncName(func),
4177 PyEval_GetFuncDesc(func),
4178 kwdict->ob_type->tp_name);
4179 }
4180 goto ext_call_fail;
4181 }
4182 Py_DECREF(kwdict);
4183 kwdict = d;
4184 }
4185 }
4186 if (flags & CALL_FLAG_VAR) {
4187 stararg = EXT_POP(*pp_stack);
4188 if (!PyTuple_Check(stararg)) {
4189 PyObject *t = NULL;
4190 t = PySequence_Tuple(stararg);
4191 if (t == NULL) {
4192 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4193 PyErr_Format(PyExc_TypeError,
4194 "%.200s%.200s argument after * "
4195 "must be a sequence, not %200s",
4196 PyEval_GetFuncName(func),
4197 PyEval_GetFuncDesc(func),
4198 stararg->ob_type->tp_name);
4199 }
4200 goto ext_call_fail;
4201 }
4202 Py_DECREF(stararg);
4203 stararg = t;
4204 }
4205 nstar = PyTuple_GET_SIZE(stararg);
4206 }
4207 if (nk > 0) {
4208 kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
4209 if (kwdict == NULL)
4210 goto ext_call_fail;
4211 }
4212 callargs = update_star_args(na, nstar, stararg, pp_stack);
4213 if (callargs == NULL)
4214 goto ext_call_fail;
Jeremy Hylton985eba52003-02-05 23:13:00 +00004215#ifdef CALL_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 /* At this point, we have to look at the type of func to
4217 update the call stats properly. Do it here so as to avoid
4218 exposing the call stats machinery outside ceval.c
4219 */
4220 if (PyFunction_Check(func))
4221 PCALL(PCALL_FUNCTION);
4222 else if (PyMethod_Check(func))
4223 PCALL(PCALL_METHOD);
4224 else if (PyType_Check(func))
4225 PCALL(PCALL_TYPE);
4226 else if (PyCFunction_Check(func))
4227 PCALL(PCALL_CFUNCTION);
4228 else
4229 PCALL(PCALL_OTHER);
Jeremy Hylton985eba52003-02-05 23:13:00 +00004230#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 if (PyCFunction_Check(func)) {
4232 PyThreadState *tstate = PyThreadState_GET();
4233 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4234 }
4235 else
4236 result = PyObject_Call(func, callargs, kwdict);
Thomas Woutersce272b62007-09-19 21:19:28 +00004237ext_call_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 Py_XDECREF(callargs);
4239 Py_XDECREF(kwdict);
4240 Py_XDECREF(stararg);
4241 return result;
Jeremy Hylton52820442001-01-03 23:52:36 +00004242}
4243
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004244/* Extract a slice index from a PyInt or PyLong or an object with the
4245 nb_index slot defined, and store in *pi.
4246 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
4247 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 +00004248 Return 0 on error, 1 on success.
Tim Peterscb479e72001-12-16 19:11:44 +00004249*/
Tim Petersb5196382001-12-16 19:44:20 +00004250/* Note: If v is NULL, return success without storing into *pi. This
4251 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
4252 called by the SLICE opcode with v and/or w equal to NULL.
Tim Peterscb479e72001-12-16 19:11:44 +00004253*/
Guido van Rossum20c6add2000-05-08 14:06:50 +00004254int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004255_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 if (v != NULL) {
4258 Py_ssize_t x;
4259 if (PyIndex_Check(v)) {
4260 x = PyNumber_AsSsize_t(v, NULL);
4261 if (x == -1 && PyErr_Occurred())
4262 return 0;
4263 }
4264 else {
4265 PyErr_SetString(PyExc_TypeError,
4266 "slice indices must be integers or "
4267 "None or have an __index__ method");
4268 return 0;
4269 }
4270 *pi = x;
4271 }
4272 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004273}
4274
Guido van Rossum486364b2007-06-30 05:01:58 +00004275#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 "BaseException is not allowed"
Brett Cannonf74225d2007-02-26 21:10:16 +00004277
Guido van Rossumb209a111997-04-29 18:18:01 +00004278static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004279cmp_outcome(int op, register PyObject *v, register PyObject *w)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 int res = 0;
4282 switch (op) {
4283 case PyCmp_IS:
4284 res = (v == w);
4285 break;
4286 case PyCmp_IS_NOT:
4287 res = (v != w);
4288 break;
4289 case PyCmp_IN:
4290 res = PySequence_Contains(w, v);
4291 if (res < 0)
4292 return NULL;
4293 break;
4294 case PyCmp_NOT_IN:
4295 res = PySequence_Contains(w, v);
4296 if (res < 0)
4297 return NULL;
4298 res = !res;
4299 break;
4300 case PyCmp_EXC_MATCH:
4301 if (PyTuple_Check(w)) {
4302 Py_ssize_t i, length;
4303 length = PyTuple_Size(w);
4304 for (i = 0; i < length; i += 1) {
4305 PyObject *exc = PyTuple_GET_ITEM(w, i);
4306 if (!PyExceptionClass_Check(exc)) {
4307 PyErr_SetString(PyExc_TypeError,
4308 CANNOT_CATCH_MSG);
4309 return NULL;
4310 }
4311 }
4312 }
4313 else {
4314 if (!PyExceptionClass_Check(w)) {
4315 PyErr_SetString(PyExc_TypeError,
4316 CANNOT_CATCH_MSG);
4317 return NULL;
4318 }
4319 }
4320 res = PyErr_GivenExceptionMatches(v, w);
4321 break;
4322 default:
4323 return PyObject_RichCompare(v, w, op);
4324 }
4325 v = res ? Py_True : Py_False;
4326 Py_INCREF(v);
4327 return v;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004328}
4329
Thomas Wouters52152252000-08-17 22:55:00 +00004330static PyObject *
4331import_from(PyObject *v, PyObject *name)
Guido van Rossume9736fc1990-11-18 17:33:06 +00004332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 PyObject *x;
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 x = PyObject_GetAttr(v, name);
4336 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
4337 PyErr_Format(PyExc_ImportError, "cannot import name %S", name);
4338 }
4339 return x;
Thomas Wouters52152252000-08-17 22:55:00 +00004340}
Guido van Rossumac7be682001-01-17 15:42:30 +00004341
Thomas Wouters52152252000-08-17 22:55:00 +00004342static int
4343import_all_from(PyObject *locals, PyObject *v)
4344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 PyObject *all = PyObject_GetAttrString(v, "__all__");
4346 PyObject *dict, *name, *value;
4347 int skip_leading_underscores = 0;
4348 int pos, err;
Thomas Wouters52152252000-08-17 22:55:00 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 if (all == NULL) {
4351 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4352 return -1; /* Unexpected error */
4353 PyErr_Clear();
4354 dict = PyObject_GetAttrString(v, "__dict__");
4355 if (dict == NULL) {
4356 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4357 return -1;
4358 PyErr_SetString(PyExc_ImportError,
4359 "from-import-* object has no __dict__ and no __all__");
4360 return -1;
4361 }
4362 all = PyMapping_Keys(dict);
4363 Py_DECREF(dict);
4364 if (all == NULL)
4365 return -1;
4366 skip_leading_underscores = 1;
4367 }
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00004368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 for (pos = 0, err = 0; ; pos++) {
4370 name = PySequence_GetItem(all, pos);
4371 if (name == NULL) {
4372 if (!PyErr_ExceptionMatches(PyExc_IndexError))
4373 err = -1;
4374 else
4375 PyErr_Clear();
4376 break;
4377 }
4378 if (skip_leading_underscores &&
4379 PyUnicode_Check(name) &&
4380 PyUnicode_AS_UNICODE(name)[0] == '_')
4381 {
4382 Py_DECREF(name);
4383 continue;
4384 }
4385 value = PyObject_GetAttr(v, name);
4386 if (value == NULL)
4387 err = -1;
4388 else if (PyDict_CheckExact(locals))
4389 err = PyDict_SetItem(locals, name, value);
4390 else
4391 err = PyObject_SetItem(locals, name, value);
4392 Py_DECREF(name);
4393 Py_XDECREF(value);
4394 if (err != 0)
4395 break;
4396 }
4397 Py_DECREF(all);
4398 return err;
Guido van Rossume9736fc1990-11-18 17:33:06 +00004399}
4400
Guido van Rossumac7be682001-01-17 15:42:30 +00004401static void
Neal Norwitzda059e32007-08-26 05:33:45 +00004402format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj)
Paul Prescode68140d2000-08-30 20:25:01 +00004403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 const char *obj_str;
Paul Prescode68140d2000-08-30 20:25:01 +00004405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 if (!obj)
4407 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 obj_str = _PyUnicode_AsString(obj);
4410 if (!obj_str)
4411 return;
Paul Prescode68140d2000-08-30 20:25:01 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 PyErr_Format(exc, format_str, obj_str);
Paul Prescode68140d2000-08-30 20:25:01 +00004414}
Guido van Rossum950361c1997-01-24 13:49:28 +00004415
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00004416static void
4417format_exc_unbound(PyCodeObject *co, int oparg)
4418{
4419 PyObject *name;
4420 /* Don't stomp existing exception */
4421 if (PyErr_Occurred())
4422 return;
4423 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
4424 name = PyTuple_GET_ITEM(co->co_cellvars,
4425 oparg);
4426 format_exc_check_arg(
4427 PyExc_UnboundLocalError,
4428 UNBOUNDLOCAL_ERROR_MSG,
4429 name);
4430 } else {
4431 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
4432 PyTuple_GET_SIZE(co->co_cellvars));
4433 format_exc_check_arg(PyExc_NameError,
4434 UNBOUNDFREE_ERROR_MSG, name);
4435 }
4436}
4437
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004438static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00004439unicode_concatenate(PyObject *v, PyObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 PyFrameObject *f, unsigned char *next_instr)
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 /* This function implements 'variable += expr' when both arguments
4443 are (Unicode) strings. */
4444 Py_ssize_t v_len = PyUnicode_GET_SIZE(v);
4445 Py_ssize_t w_len = PyUnicode_GET_SIZE(w);
4446 Py_ssize_t new_len = v_len + w_len;
4447 if (new_len < 0) {
4448 PyErr_SetString(PyExc_OverflowError,
4449 "strings are too large to concat");
4450 return NULL;
4451 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00004452
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004453 if (Py_REFCNT(v) == 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 /* In the common case, there are 2 references to the value
4455 * stored in 'variable' when the += is performed: one on the
4456 * value stack (in 'v') and one still stored in the
4457 * 'variable'. We try to delete the variable now to reduce
4458 * the refcnt to 1.
4459 */
4460 switch (*next_instr) {
4461 case STORE_FAST:
4462 {
4463 int oparg = PEEKARG();
4464 PyObject **fastlocals = f->f_localsplus;
4465 if (GETLOCAL(oparg) == v)
4466 SETLOCAL(oparg, NULL);
4467 break;
4468 }
4469 case STORE_DEREF:
4470 {
4471 PyObject **freevars = (f->f_localsplus +
4472 f->f_code->co_nlocals);
4473 PyObject *c = freevars[PEEKARG()];
4474 if (PyCell_GET(c) == v)
4475 PyCell_Set(c, NULL);
4476 break;
4477 }
4478 case STORE_NAME:
4479 {
4480 PyObject *names = f->f_code->co_names;
4481 PyObject *name = GETITEM(names, PEEKARG());
4482 PyObject *locals = f->f_locals;
4483 if (PyDict_CheckExact(locals) &&
4484 PyDict_GetItem(locals, name) == v) {
4485 if (PyDict_DelItem(locals, name) != 0) {
4486 PyErr_Clear();
4487 }
4488 }
4489 break;
4490 }
4491 }
4492 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004493
Benjamin Petersone208b7c2010-09-10 23:53:14 +00004494 if (Py_REFCNT(v) == 1 && !PyUnicode_CHECK_INTERNED(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 /* Now we own the last reference to 'v', so we can resize it
4496 * in-place.
4497 */
4498 if (PyUnicode_Resize(&v, new_len) != 0) {
4499 /* XXX if PyUnicode_Resize() fails, 'v' has been
4500 * deallocated so it cannot be put back into
4501 * 'variable'. The MemoryError is raised when there
4502 * is no value in 'variable', which might (very
4503 * remotely) be a cause of incompatibilities.
4504 */
4505 return NULL;
4506 }
4507 /* copy 'w' into the newly allocated area of 'v' */
4508 memcpy(PyUnicode_AS_UNICODE(v) + v_len,
4509 PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE));
4510 return v;
4511 }
4512 else {
4513 /* When in-place resizing is not an option. */
4514 w = PyUnicode_Concat(v, w);
4515 Py_DECREF(v);
4516 return w;
4517 }
Raymond Hettinger52a21b82004-08-06 18:43:09 +00004518}
4519
Guido van Rossum950361c1997-01-24 13:49:28 +00004520#ifdef DYNAMIC_EXECUTION_PROFILE
4521
Skip Montanarof118cb12001-10-15 20:51:38 +00004522static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004523getarray(long a[256])
Guido van Rossum950361c1997-01-24 13:49:28 +00004524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 int i;
4526 PyObject *l = PyList_New(256);
4527 if (l == NULL) return NULL;
4528 for (i = 0; i < 256; i++) {
4529 PyObject *x = PyLong_FromLong(a[i]);
4530 if (x == NULL) {
4531 Py_DECREF(l);
4532 return NULL;
4533 }
4534 PyList_SetItem(l, i, x);
4535 }
4536 for (i = 0; i < 256; i++)
4537 a[i] = 0;
4538 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004539}
4540
4541PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004542_Py_GetDXProfile(PyObject *self, PyObject *args)
Guido van Rossum950361c1997-01-24 13:49:28 +00004543{
4544#ifndef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 return getarray(dxp);
Guido van Rossum950361c1997-01-24 13:49:28 +00004546#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 int i;
4548 PyObject *l = PyList_New(257);
4549 if (l == NULL) return NULL;
4550 for (i = 0; i < 257; i++) {
4551 PyObject *x = getarray(dxpairs[i]);
4552 if (x == NULL) {
4553 Py_DECREF(l);
4554 return NULL;
4555 }
4556 PyList_SetItem(l, i, x);
4557 }
4558 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00004559#endif
4560}
4561
4562#endif