Issue #7455: Fix possible crash in cPickle on invalid input. Patch by
[python.git] / Python / ceval.c
blobe5e70463f74dc369547245fe8ed6f4ee108a9689
2 /* Execute compiled code */
4 /* XXX TO DO:
5 XXX speed up searching for keywords by using a dictionary
6 XXX document it!
7 */
9 /* enable more aggressive intra-module optimizations, where available */
10 #define PY_LOCAL_AGGRESSIVE
12 #include "Python.h"
14 #include "code.h"
15 #include "frameobject.h"
16 #include "eval.h"
17 #include "opcode.h"
18 #include "structmember.h"
20 #include <ctype.h>
22 #ifndef WITH_TSC
24 #define READ_TIMESTAMP(var)
26 #else
28 typedef unsigned long long uint64;
30 #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this
31 section should work for GCC on any PowerPC
32 platform, irrespective of OS.
33 POWER? Who knows :-) */
35 #define READ_TIMESTAMP(var) ppc_getcounter(&var)
37 static void
38 ppc_getcounter(uint64 *v)
40 register unsigned long tbu, tb, tbu2;
42 loop:
43 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;
48 /* 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;
54 #elif defined(__i386__)
56 /* this is for linux/x86 (and probably any other GCC/x86 combo) */
58 #define READ_TIMESTAMP(val) \
59 __asm__ __volatile__("rdtsc" : "=A" (val))
61 #elif defined(__x86_64__)
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. */
68 #define READ_TIMESTAMP(val) \
69 __asm__ __volatile__("rdtsc" : \
70 "=a" (((int*)&(val))[0]), "=d" (((int*)&(val))[1]));
73 #else
75 #error "Don't know how to implement timestamp counter for this architecture"
77 #endif
79 void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1,
80 uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1)
82 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",
90 opcode, ticked, inst, loop);
93 #endif
95 /* Turn this on if your compiler chokes on the big switch: */
96 /* #define CASE_TOO_BIG 1 */
98 #ifdef Py_DEBUG
99 /* For debugging the interpreter: */
100 #define LLTRACE 1 /* Low-level trace feature */
101 #define CHECKEXC 1 /* Double-check exception checking */
102 #endif
104 typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *);
106 /* Forward declarations */
107 #ifdef WITH_TSC
108 static PyObject * call_function(PyObject ***, int, uint64*, uint64*);
109 #else
110 static PyObject * call_function(PyObject ***, int);
111 #endif
112 static PyObject * fast_function(PyObject *, PyObject ***, int, int, int);
113 static PyObject * do_call(PyObject *, PyObject ***, int, int);
114 static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int);
115 static PyObject * update_keyword_args(PyObject *, int, PyObject ***,
116 PyObject *);
117 static PyObject * update_star_args(int, int, PyObject *, PyObject ***);
118 static PyObject * load_args(PyObject ***, int);
119 #define CALL_FLAG_VAR 1
120 #define CALL_FLAG_KW 2
122 #ifdef LLTRACE
123 static int lltrace;
124 static int prtrace(PyObject *, char *);
125 #endif
126 static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *,
127 int, PyObject *);
128 static int call_trace_protected(Py_tracefunc, PyObject *,
129 PyFrameObject *, int, PyObject *);
130 static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *);
131 static int maybe_call_line_trace(Py_tracefunc, PyObject *,
132 PyFrameObject *, int *, int *, int *);
134 static PyObject * apply_slice(PyObject *, PyObject *, PyObject *);
135 static int assign_slice(PyObject *, PyObject *,
136 PyObject *, PyObject *);
137 static PyObject * cmp_outcome(int, PyObject *, PyObject *);
138 static PyObject * import_from(PyObject *, PyObject *);
139 static int import_all_from(PyObject *, PyObject *);
140 static PyObject * build_class(PyObject *, PyObject *, PyObject *);
141 static int exec_statement(PyFrameObject *,
142 PyObject *, PyObject *, PyObject *);
143 static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
144 static void reset_exc_info(PyThreadState *);
145 static void format_exc_check_arg(PyObject *, char *, PyObject *);
146 static PyObject * string_concatenate(PyObject *, PyObject *,
147 PyFrameObject *, unsigned char *);
148 static PyObject * kwd_as_string(PyObject *);
149 static PyObject * special_lookup(PyObject *, char *, PyObject **);
151 #define NAME_ERROR_MSG \
152 "name '%.200s' is not defined"
153 #define GLOBAL_NAME_ERROR_MSG \
154 "global name '%.200s' is not defined"
155 #define UNBOUNDLOCAL_ERROR_MSG \
156 "local variable '%.200s' referenced before assignment"
157 #define UNBOUNDFREE_ERROR_MSG \
158 "free variable '%.200s' referenced before assignment" \
159 " in enclosing scope"
161 /* Dynamic execution profile */
162 #ifdef DYNAMIC_EXECUTION_PROFILE
163 #ifdef DXPAIRS
164 static long dxpairs[257][256];
165 #define dxp dxpairs[256]
166 #else
167 static long dxp[256];
168 #endif
169 #endif
171 /* Function call profile */
172 #ifdef CALL_PROFILE
173 #define PCALL_NUM 11
174 static int pcall[PCALL_NUM];
176 #define PCALL_ALL 0
177 #define PCALL_FUNCTION 1
178 #define PCALL_FAST_FUNCTION 2
179 #define PCALL_FASTER_FUNCTION 3
180 #define PCALL_METHOD 4
181 #define PCALL_BOUND_METHOD 5
182 #define PCALL_CFUNCTION 6
183 #define PCALL_TYPE 7
184 #define PCALL_GENERATOR 8
185 #define PCALL_OTHER 9
186 #define PCALL_POP 10
188 /* Notes about the statistics
190 PCALL_FAST stats
192 FAST_FUNCTION means no argument tuple needs to be created.
193 FASTER_FUNCTION means that the fast-path frame setup code is used.
195 If there is a method call where the call can be optimized by changing
196 the argument tuple and calling the function directly, it gets recorded
197 twice.
199 As a result, the relationship among the statistics appears to be
200 PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
201 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
202 PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
203 PCALL_METHOD > PCALL_BOUND_METHOD
206 #define PCALL(POS) pcall[POS]++
208 PyObject *
209 PyEval_GetCallStats(PyObject *self)
211 return Py_BuildValue("iiiiiiiiiii",
212 pcall[0], pcall[1], pcall[2], pcall[3],
213 pcall[4], pcall[5], pcall[6], pcall[7],
214 pcall[8], pcall[9], pcall[10]);
216 #else
217 #define PCALL(O)
219 PyObject *
220 PyEval_GetCallStats(PyObject *self)
222 Py_INCREF(Py_None);
223 return Py_None;
225 #endif
228 #ifdef WITH_THREAD
230 #ifdef HAVE_ERRNO_H
231 #include <errno.h>
232 #endif
233 #include "pythread.h"
235 static PyThread_type_lock interpreter_lock = 0; /* This is the GIL */
236 static PyThread_type_lock pending_lock = 0; /* for pending calls */
237 static long main_thread = 0;
240 PyEval_ThreadsInitialized(void)
242 return interpreter_lock != 0;
245 void
246 PyEval_InitThreads(void)
248 if (interpreter_lock)
249 return;
250 interpreter_lock = PyThread_allocate_lock();
251 PyThread_acquire_lock(interpreter_lock, 1);
252 main_thread = PyThread_get_thread_ident();
255 void
256 PyEval_AcquireLock(void)
258 PyThread_acquire_lock(interpreter_lock, 1);
261 void
262 PyEval_ReleaseLock(void)
264 PyThread_release_lock(interpreter_lock);
267 void
268 PyEval_AcquireThread(PyThreadState *tstate)
270 if (tstate == NULL)
271 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
272 /* Check someone has called PyEval_InitThreads() to create the lock */
273 assert(interpreter_lock);
274 PyThread_acquire_lock(interpreter_lock, 1);
275 if (PyThreadState_Swap(tstate) != NULL)
276 Py_FatalError(
277 "PyEval_AcquireThread: non-NULL old thread state");
280 void
281 PyEval_ReleaseThread(PyThreadState *tstate)
283 if (tstate == NULL)
284 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
285 if (PyThreadState_Swap(NULL) != tstate)
286 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
287 PyThread_release_lock(interpreter_lock);
290 /* This function is called from PyOS_AfterFork to ensure that newly
291 created child processes don't hold locks referring to threads which
292 are not running in the child process. (This could also be done using
293 pthread_atfork mechanism, at least for the pthreads implementation.) */
295 void
296 PyEval_ReInitThreads(void)
298 PyObject *threading, *result;
299 PyThreadState *tstate;
301 if (!interpreter_lock)
302 return;
303 /*XXX Can't use PyThread_free_lock here because it does too
304 much error-checking. Doing this cleanly would require
305 adding a new function to each thread_*.h. Instead, just
306 create a new lock and waste a little bit of memory */
307 interpreter_lock = PyThread_allocate_lock();
308 pending_lock = PyThread_allocate_lock();
309 PyThread_acquire_lock(interpreter_lock, 1);
310 main_thread = PyThread_get_thread_ident();
312 /* Update the threading module with the new state.
314 tstate = PyThreadState_GET();
315 threading = PyMapping_GetItemString(tstate->interp->modules,
316 "threading");
317 if (threading == NULL) {
318 /* threading not imported */
319 PyErr_Clear();
320 return;
322 result = PyObject_CallMethod(threading, "_after_fork", NULL);
323 if (result == NULL)
324 PyErr_WriteUnraisable(threading);
325 else
326 Py_DECREF(result);
327 Py_DECREF(threading);
329 #endif
331 /* Functions save_thread and restore_thread are always defined so
332 dynamically loaded modules needn't be compiled separately for use
333 with and without threads: */
335 PyThreadState *
336 PyEval_SaveThread(void)
338 PyThreadState *tstate = PyThreadState_Swap(NULL);
339 if (tstate == NULL)
340 Py_FatalError("PyEval_SaveThread: NULL tstate");
341 #ifdef WITH_THREAD
342 if (interpreter_lock)
343 PyThread_release_lock(interpreter_lock);
344 #endif
345 return tstate;
348 void
349 PyEval_RestoreThread(PyThreadState *tstate)
351 if (tstate == NULL)
352 Py_FatalError("PyEval_RestoreThread: NULL tstate");
353 #ifdef WITH_THREAD
354 if (interpreter_lock) {
355 int err = errno;
356 PyThread_acquire_lock(interpreter_lock, 1);
357 errno = err;
359 #endif
360 PyThreadState_Swap(tstate);
364 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
365 signal handlers or Mac I/O completion routines) can schedule calls
366 to a function to be called synchronously.
367 The synchronous function is called with one void* argument.
368 It should return 0 for success or -1 for failure -- failure should
369 be accompanied by an exception.
371 If registry succeeds, the registry function returns 0; if it fails
372 (e.g. due to too many pending calls) it returns -1 (without setting
373 an exception condition).
375 Note that because registry may occur from within signal handlers,
376 or other asynchronous events, calling malloc() is unsafe!
378 #ifdef WITH_THREAD
379 Any thread can schedule pending calls, but only the main thread
380 will execute them.
381 There is no facility to schedule calls to a particular thread, but
382 that should be easy to change, should that ever be required. In
383 that case, the static variables here should go into the python
384 threadstate.
385 #endif
388 #ifdef WITH_THREAD
390 /* The WITH_THREAD implementation is thread-safe. It allows
391 scheduling to be made from any thread, and even from an executing
392 callback.
395 #define NPENDINGCALLS 32
396 static struct {
397 int (*func)(void *);
398 void *arg;
399 } pendingcalls[NPENDINGCALLS];
400 static int pendingfirst = 0;
401 static int pendinglast = 0;
402 static volatile int pendingcalls_to_do = 1; /* trigger initialization of lock */
403 static char pendingbusy = 0;
406 Py_AddPendingCall(int (*func)(void *), void *arg)
408 int i, j, result=0;
409 PyThread_type_lock lock = pending_lock;
411 /* try a few times for the lock. Since this mechanism is used
412 * for signal handling (on the main thread), there is a (slim)
413 * chance that a signal is delivered on the same thread while we
414 * hold the lock during the Py_MakePendingCalls() function.
415 * This avoids a deadlock in that case.
416 * Note that signals can be delivered on any thread. In particular,
417 * on Windows, a SIGINT is delivered on a system-created worker
418 * thread.
419 * We also check for lock being NULL, in the unlikely case that
420 * this function is called before any bytecode evaluation takes place.
422 if (lock != NULL) {
423 for (i = 0; i<100; i++) {
424 if (PyThread_acquire_lock(lock, NOWAIT_LOCK))
425 break;
427 if (i == 100)
428 return -1;
431 i = pendinglast;
432 j = (i + 1) % NPENDINGCALLS;
433 if (j == pendingfirst) {
434 result = -1; /* Queue full */
435 } else {
436 pendingcalls[i].func = func;
437 pendingcalls[i].arg = arg;
438 pendinglast = j;
440 /* signal main loop */
441 _Py_Ticker = 0;
442 pendingcalls_to_do = 1;
443 if (lock != NULL)
444 PyThread_release_lock(lock);
445 return result;
449 Py_MakePendingCalls(void)
451 int i;
452 int r = 0;
454 if (!pending_lock) {
455 /* initial allocation of the lock */
456 pending_lock = PyThread_allocate_lock();
457 if (pending_lock == NULL)
458 return -1;
461 /* only service pending calls on main thread */
462 if (main_thread && PyThread_get_thread_ident() != main_thread)
463 return 0;
464 /* don't perform recursive pending calls */
465 if (pendingbusy)
466 return 0;
467 pendingbusy = 1;
468 /* perform a bounded number of calls, in case of recursion */
469 for (i=0; i<NPENDINGCALLS; i++) {
470 int j;
471 int (*func)(void *);
472 void *arg = NULL;
474 /* pop one item off the queue while holding the lock */
475 PyThread_acquire_lock(pending_lock, WAIT_LOCK);
476 j = pendingfirst;
477 if (j == pendinglast) {
478 func = NULL; /* Queue empty */
479 } else {
480 func = pendingcalls[j].func;
481 arg = pendingcalls[j].arg;
482 pendingfirst = (j + 1) % NPENDINGCALLS;
484 pendingcalls_to_do = pendingfirst != pendinglast;
485 PyThread_release_lock(pending_lock);
486 /* having released the lock, perform the callback */
487 if (func == NULL)
488 break;
489 r = func(arg);
490 if (r)
491 break;
493 pendingbusy = 0;
494 return r;
497 #else /* if ! defined WITH_THREAD */
500 WARNING! ASYNCHRONOUSLY EXECUTING CODE!
501 This code is used for signal handling in python that isn't built
502 with WITH_THREAD.
503 Don't use this implementation when Py_AddPendingCalls() can happen
504 on a different thread!
506 There are two possible race conditions:
507 (1) nested asynchronous calls to Py_AddPendingCall()
508 (2) AddPendingCall() calls made while pending calls are being processed.
510 (1) is very unlikely because typically signal delivery
511 is blocked during signal handling. So it should be impossible.
512 (2) is a real possibility.
513 The current code is safe against (2), but not against (1).
514 The safety against (2) is derived from the fact that only one
515 thread is present, interrupted by signals, and that the critical
516 section is protected with the "busy" variable. On Windows, which
517 delivers SIGINT on a system thread, this does not hold and therefore
518 Windows really shouldn't use this version.
519 The two threads could theoretically wiggle around the "busy" variable.
522 #define NPENDINGCALLS 32
523 static struct {
524 int (*func)(void *);
525 void *arg;
526 } pendingcalls[NPENDINGCALLS];
527 static volatile int pendingfirst = 0;
528 static volatile int pendinglast = 0;
529 static volatile int pendingcalls_to_do = 0;
532 Py_AddPendingCall(int (*func)(void *), void *arg)
534 static volatile int busy = 0;
535 int i, j;
536 /* XXX Begin critical section */
537 if (busy)
538 return -1;
539 busy = 1;
540 i = pendinglast;
541 j = (i + 1) % NPENDINGCALLS;
542 if (j == pendingfirst) {
543 busy = 0;
544 return -1; /* Queue full */
546 pendingcalls[i].func = func;
547 pendingcalls[i].arg = arg;
548 pendinglast = j;
550 _Py_Ticker = 0;
551 pendingcalls_to_do = 1; /* Signal main loop */
552 busy = 0;
553 /* XXX End critical section */
554 return 0;
558 Py_MakePendingCalls(void)
560 static int busy = 0;
561 if (busy)
562 return 0;
563 busy = 1;
564 pendingcalls_to_do = 0;
565 for (;;) {
566 int i;
567 int (*func)(void *);
568 void *arg;
569 i = pendingfirst;
570 if (i == pendinglast)
571 break; /* Queue empty */
572 func = pendingcalls[i].func;
573 arg = pendingcalls[i].arg;
574 pendingfirst = (i + 1) % NPENDINGCALLS;
575 if (func(arg) < 0) {
576 busy = 0;
577 pendingcalls_to_do = 1; /* We're not done yet */
578 return -1;
581 busy = 0;
582 return 0;
585 #endif /* WITH_THREAD */
588 /* The interpreter's recursion limit */
590 #ifndef Py_DEFAULT_RECURSION_LIMIT
591 #define Py_DEFAULT_RECURSION_LIMIT 1000
592 #endif
593 static int recursion_limit = Py_DEFAULT_RECURSION_LIMIT;
594 int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT;
597 Py_GetRecursionLimit(void)
599 return recursion_limit;
602 void
603 Py_SetRecursionLimit(int new_limit)
605 recursion_limit = new_limit;
606 _Py_CheckRecursionLimit = recursion_limit;
609 /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
610 if the recursion_depth reaches _Py_CheckRecursionLimit.
611 If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
612 to guarantee that _Py_CheckRecursiveCall() is regularly called.
613 Without USE_STACKCHECK, there is no need for this. */
615 _Py_CheckRecursiveCall(char *where)
617 PyThreadState *tstate = PyThreadState_GET();
619 #ifdef USE_STACKCHECK
620 if (PyOS_CheckStack()) {
621 --tstate->recursion_depth;
622 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
623 return -1;
625 #endif
626 if (tstate->recursion_depth > recursion_limit) {
627 --tstate->recursion_depth;
628 PyErr_Format(PyExc_RuntimeError,
629 "maximum recursion depth exceeded%s",
630 where);
631 return -1;
633 _Py_CheckRecursionLimit = recursion_limit;
634 return 0;
637 /* Status code for main loop (reason for stack unwind) */
638 enum why_code {
639 WHY_NOT = 0x0001, /* No error */
640 WHY_EXCEPTION = 0x0002, /* Exception occurred */
641 WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */
642 WHY_RETURN = 0x0008, /* 'return' statement */
643 WHY_BREAK = 0x0010, /* 'break' statement */
644 WHY_CONTINUE = 0x0020, /* 'continue' statement */
645 WHY_YIELD = 0x0040 /* 'yield' operator */
648 static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
649 static int unpack_iterable(PyObject *, int, PyObject **);
651 /* Records whether tracing is on for any thread. Counts the number of
652 threads for which tstate->c_tracefunc is non-NULL, so if the value
653 is 0, we know we don't have to check this thread's c_tracefunc.
654 This speeds up the if statement in PyEval_EvalFrameEx() after
655 fast_next_opcode*/
656 static int _Py_TracingPossible = 0;
658 /* for manipulating the thread switch and periodic "stuff" - used to be
659 per thread, now just a pair o' globals */
660 int _Py_CheckInterval = 100;
661 volatile int _Py_Ticker = 0; /* so that we hit a "tick" first thing */
663 PyObject *
664 PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
666 return PyEval_EvalCodeEx(co,
667 globals, locals,
668 (PyObject **)NULL, 0,
669 (PyObject **)NULL, 0,
670 (PyObject **)NULL, 0,
671 NULL);
675 /* Interpreter main loop */
677 PyObject *
678 PyEval_EvalFrame(PyFrameObject *f) {
679 /* This is for backward compatibility with extension modules that
680 used this API; core interpreter code should call
681 PyEval_EvalFrameEx() */
682 return PyEval_EvalFrameEx(f, 0);
685 PyObject *
686 PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
688 #ifdef DXPAIRS
689 int lastopcode = 0;
690 #endif
691 register PyObject **stack_pointer; /* Next free slot in value stack */
692 register unsigned char *next_instr;
693 register int opcode; /* Current opcode */
694 register int oparg; /* Current opcode argument, if any */
695 register enum why_code why; /* Reason for block stack unwind */
696 register int err; /* Error status -- nonzero if error */
697 register PyObject *x; /* Result object -- NULL if error */
698 register PyObject *v; /* Temporary objects popped off stack */
699 register PyObject *w;
700 register PyObject *u;
701 register PyObject *t;
702 register PyObject *stream = NULL; /* for PRINT opcodes */
703 register PyObject **fastlocals, **freevars;
704 PyObject *retval = NULL; /* Return value */
705 PyThreadState *tstate = PyThreadState_GET();
706 PyCodeObject *co;
708 /* when tracing we set things up so that
710 not (instr_lb <= current_bytecode_offset < instr_ub)
712 is true when the line being executed has changed. The
713 initial values are such as to make this false the first
714 time it is tested. */
715 int instr_ub = -1, instr_lb = 0, instr_prev = -1;
717 unsigned char *first_instr;
718 PyObject *names;
719 PyObject *consts;
720 #if defined(Py_DEBUG) || defined(LLTRACE)
721 /* Make it easier to find out where we are with a debugger */
722 char *filename;
723 #endif
725 /* Tuple access macros */
727 #ifndef Py_DEBUG
728 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
729 #else
730 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
731 #endif
733 #ifdef WITH_TSC
734 /* Use Pentium timestamp counter to mark certain events:
735 inst0 -- beginning of switch statement for opcode dispatch
736 inst1 -- end of switch statement (may be skipped)
737 loop0 -- the top of the mainloop
738 loop1 -- place where control returns again to top of mainloop
739 (may be skipped)
740 intr1 -- beginning of long interruption
741 intr2 -- end of long interruption
743 Many opcodes call out to helper C functions. In some cases, the
744 time in those functions should be counted towards the time for the
745 opcode, but not in all cases. For example, a CALL_FUNCTION opcode
746 calls another Python function; there's no point in charge all the
747 bytecode executed by the called function to the caller.
749 It's hard to make a useful judgement statically. In the presence
750 of operator overloading, it's impossible to tell if a call will
751 execute new Python code or not.
753 It's a case-by-case judgement. I'll use intr1 for the following
754 cases:
756 EXEC_STMT
757 IMPORT_STAR
758 IMPORT_FROM
759 CALL_FUNCTION (and friends)
762 uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0;
763 int ticked = 0;
765 READ_TIMESTAMP(inst0);
766 READ_TIMESTAMP(inst1);
767 READ_TIMESTAMP(loop0);
768 READ_TIMESTAMP(loop1);
770 /* shut up the compiler */
771 opcode = 0;
772 #endif
774 /* Code access macros */
776 #define INSTR_OFFSET() ((int)(next_instr - first_instr))
777 #define NEXTOP() (*next_instr++)
778 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
779 #define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
780 #define JUMPTO(x) (next_instr = first_instr + (x))
781 #define JUMPBY(x) (next_instr += (x))
783 /* OpCode prediction macros
784 Some opcodes tend to come in pairs thus making it possible to
785 predict the second code when the first is run. For example,
786 GET_ITER is often followed by FOR_ITER. And FOR_ITER is often
787 followed by STORE_FAST or UNPACK_SEQUENCE.
789 Verifying the prediction costs a single high-speed test of a register
790 variable against a constant. If the pairing was good, then the
791 processor's own internal branch predication has a high likelihood of
792 success, resulting in a nearly zero-overhead transition to the
793 next opcode. A successful prediction saves a trip through the eval-loop
794 including its two unpredictable branches, the HAS_ARG test and the
795 switch-case. Combined with the processor's internal branch prediction,
796 a successful PREDICT has the effect of making the two opcodes run as if
797 they were a single new opcode with the bodies combined.
799 If collecting opcode statistics, your choices are to either keep the
800 predictions turned-on and interpret the results as if some opcodes
801 had been combined or turn-off predictions so that the opcode frequency
802 counter updates for both opcodes.
805 #ifdef DYNAMIC_EXECUTION_PROFILE
806 #define PREDICT(op) if (0) goto PRED_##op
807 #else
808 #define PREDICT(op) if (*next_instr == op) goto PRED_##op
809 #endif
811 #define PREDICTED(op) PRED_##op: next_instr++
812 #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
814 /* Stack manipulation macros */
816 /* The stack can grow at most MAXINT deep, as co_nlocals and
817 co_stacksize are ints. */
818 #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
819 #define EMPTY() (STACK_LEVEL() == 0)
820 #define TOP() (stack_pointer[-1])
821 #define SECOND() (stack_pointer[-2])
822 #define THIRD() (stack_pointer[-3])
823 #define FOURTH() (stack_pointer[-4])
824 #define PEEK(n) (stack_pointer[-(n)])
825 #define SET_TOP(v) (stack_pointer[-1] = (v))
826 #define SET_SECOND(v) (stack_pointer[-2] = (v))
827 #define SET_THIRD(v) (stack_pointer[-3] = (v))
828 #define SET_FOURTH(v) (stack_pointer[-4] = (v))
829 #define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
830 #define BASIC_STACKADJ(n) (stack_pointer += n)
831 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
832 #define BASIC_POP() (*--stack_pointer)
834 #ifdef LLTRACE
835 #define PUSH(v) { (void)(BASIC_PUSH(v), \
836 lltrace && prtrace(TOP(), "push")); \
837 assert(STACK_LEVEL() <= co->co_stacksize); }
838 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
839 BASIC_POP())
840 #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
841 lltrace && prtrace(TOP(), "stackadj")); \
842 assert(STACK_LEVEL() <= co->co_stacksize); }
843 #define EXT_POP(STACK_POINTER) ((void)(lltrace && \
844 prtrace((STACK_POINTER)[-1], "ext_pop")), \
845 *--(STACK_POINTER))
846 #else
847 #define PUSH(v) BASIC_PUSH(v)
848 #define POP() BASIC_POP()
849 #define STACKADJ(n) BASIC_STACKADJ(n)
850 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
851 #endif
853 /* Local variable macros */
855 #define GETLOCAL(i) (fastlocals[i])
857 /* The SETLOCAL() macro must not DECREF the local variable in-place and
858 then store the new value; it must copy the old value to a temporary
859 value, then store the new value, and then DECREF the temporary value.
860 This is because it is possible that during the DECREF the frame is
861 accessed by other code (e.g. a __del__ method or gc.collect()) and the
862 variable would be pointing to already-freed memory. */
863 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
864 GETLOCAL(i) = value; \
865 Py_XDECREF(tmp); } while (0)
867 /* Start of code */
869 if (f == NULL)
870 return NULL;
872 /* push frame */
873 if (Py_EnterRecursiveCall(""))
874 return NULL;
876 tstate->frame = f;
878 if (tstate->use_tracing) {
879 if (tstate->c_tracefunc != NULL) {
880 /* tstate->c_tracefunc, if defined, is a
881 function that will be called on *every* entry
882 to a code block. Its return value, if not
883 None, is a function that will be called at
884 the start of each executed line of code.
885 (Actually, the function must return itself
886 in order to continue tracing.) The trace
887 functions are called with three arguments:
888 a pointer to the current frame, a string
889 indicating why the function is called, and
890 an argument which depends on the situation.
891 The global trace function is also called
892 whenever an exception is detected. */
893 if (call_trace_protected(tstate->c_tracefunc,
894 tstate->c_traceobj,
895 f, PyTrace_CALL, Py_None)) {
896 /* Trace function raised an error */
897 goto exit_eval_frame;
900 if (tstate->c_profilefunc != NULL) {
901 /* Similar for c_profilefunc, except it needn't
902 return itself and isn't called for "line" events */
903 if (call_trace_protected(tstate->c_profilefunc,
904 tstate->c_profileobj,
905 f, PyTrace_CALL, Py_None)) {
906 /* Profile function raised an error */
907 goto exit_eval_frame;
912 co = f->f_code;
913 names = co->co_names;
914 consts = co->co_consts;
915 fastlocals = f->f_localsplus;
916 freevars = f->f_localsplus + co->co_nlocals;
917 first_instr = (unsigned char*) PyString_AS_STRING(co->co_code);
918 /* An explanation is in order for the next line.
920 f->f_lasti now refers to the index of the last instruction
921 executed. You might think this was obvious from the name, but
922 this wasn't always true before 2.3! PyFrame_New now sets
923 f->f_lasti to -1 (i.e. the index *before* the first instruction)
924 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
925 does work. Promise.
927 When the PREDICT() macros are enabled, some opcode pairs follow in
928 direct succession without updating f->f_lasti. A successful
929 prediction effectively links the two codes together as if they
930 were a single new opcode; accordingly,f->f_lasti will point to
931 the first code in the pair (for instance, GET_ITER followed by
932 FOR_ITER is effectively a single opcode and f->f_lasti will point
933 at to the beginning of the combined pair.)
935 next_instr = first_instr + f->f_lasti + 1;
936 stack_pointer = f->f_stacktop;
937 assert(stack_pointer != NULL);
938 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
940 #ifdef LLTRACE
941 lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
942 #endif
943 #if defined(Py_DEBUG) || defined(LLTRACE)
944 filename = PyString_AsString(co->co_filename);
945 #endif
947 why = WHY_NOT;
948 err = 0;
949 x = Py_None; /* Not a reference, just anything non-NULL */
950 w = NULL;
952 if (throwflag) { /* support for generator.throw() */
953 why = WHY_EXCEPTION;
954 goto on_error;
957 for (;;) {
958 #ifdef WITH_TSC
959 if (inst1 == 0) {
960 /* Almost surely, the opcode executed a break
961 or a continue, preventing inst1 from being set
962 on the way out of the loop.
964 READ_TIMESTAMP(inst1);
965 loop1 = inst1;
967 dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1,
968 intr0, intr1);
969 ticked = 0;
970 inst1 = 0;
971 intr0 = 0;
972 intr1 = 0;
973 READ_TIMESTAMP(loop0);
974 #endif
975 assert(stack_pointer >= f->f_valuestack); /* else underflow */
976 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
978 /* Do periodic things. Doing this every time through
979 the loop would add too much overhead, so we do it
980 only every Nth instruction. We also do it if
981 ``pendingcalls_to_do'' is set, i.e. when an asynchronous
982 event needs attention (e.g. a signal handler or
983 async I/O handler); see Py_AddPendingCall() and
984 Py_MakePendingCalls() above. */
986 if (--_Py_Ticker < 0) {
987 if (*next_instr == SETUP_FINALLY) {
988 /* Make the last opcode before
989 a try: finally: block uninterruptable. */
990 goto fast_next_opcode;
992 _Py_Ticker = _Py_CheckInterval;
993 tstate->tick_counter++;
994 #ifdef WITH_TSC
995 ticked = 1;
996 #endif
997 if (pendingcalls_to_do) {
998 if (Py_MakePendingCalls() < 0) {
999 why = WHY_EXCEPTION;
1000 goto on_error;
1002 if (pendingcalls_to_do)
1003 /* MakePendingCalls() didn't succeed.
1004 Force early re-execution of this
1005 "periodic" code, possibly after
1006 a thread switch */
1007 _Py_Ticker = 0;
1009 #ifdef WITH_THREAD
1010 if (interpreter_lock) {
1011 /* Give another thread a chance */
1013 if (PyThreadState_Swap(NULL) != tstate)
1014 Py_FatalError("ceval: tstate mix-up");
1015 PyThread_release_lock(interpreter_lock);
1017 /* Other threads may run now */
1019 PyThread_acquire_lock(interpreter_lock, 1);
1020 if (PyThreadState_Swap(tstate) != NULL)
1021 Py_FatalError("ceval: orphan tstate");
1023 /* Check for thread interrupts */
1025 if (tstate->async_exc != NULL) {
1026 x = tstate->async_exc;
1027 tstate->async_exc = NULL;
1028 PyErr_SetNone(x);
1029 Py_DECREF(x);
1030 why = WHY_EXCEPTION;
1031 goto on_error;
1034 #endif
1037 fast_next_opcode:
1038 f->f_lasti = INSTR_OFFSET();
1040 /* line-by-line tracing support */
1042 if (_Py_TracingPossible &&
1043 tstate->c_tracefunc != NULL && !tstate->tracing) {
1044 /* see maybe_call_line_trace
1045 for expository comments */
1046 f->f_stacktop = stack_pointer;
1048 err = maybe_call_line_trace(tstate->c_tracefunc,
1049 tstate->c_traceobj,
1050 f, &instr_lb, &instr_ub,
1051 &instr_prev);
1052 /* Reload possibly changed frame fields */
1053 JUMPTO(f->f_lasti);
1054 if (f->f_stacktop != NULL) {
1055 stack_pointer = f->f_stacktop;
1056 f->f_stacktop = NULL;
1058 if (err) {
1059 /* trace function raised an exception */
1060 goto on_error;
1064 /* Extract opcode and argument */
1066 opcode = NEXTOP();
1067 oparg = 0; /* allows oparg to be stored in a register because
1068 it doesn't have to be remembered across a full loop */
1069 if (HAS_ARG(opcode))
1070 oparg = NEXTARG();
1071 dispatch_opcode:
1072 #ifdef DYNAMIC_EXECUTION_PROFILE
1073 #ifdef DXPAIRS
1074 dxpairs[lastopcode][opcode]++;
1075 lastopcode = opcode;
1076 #endif
1077 dxp[opcode]++;
1078 #endif
1080 #ifdef LLTRACE
1081 /* Instruction tracing */
1083 if (lltrace) {
1084 if (HAS_ARG(opcode)) {
1085 printf("%d: %d, %d\n",
1086 f->f_lasti, opcode, oparg);
1088 else {
1089 printf("%d: %d\n",
1090 f->f_lasti, opcode);
1093 #endif
1095 /* Main switch on opcode */
1096 READ_TIMESTAMP(inst0);
1098 switch (opcode) {
1100 /* BEWARE!
1101 It is essential that any operation that fails sets either
1102 x to NULL, err to nonzero, or why to anything but WHY_NOT,
1103 and that no operation that succeeds does this! */
1105 /* case STOP_CODE: this is an error! */
1107 case NOP:
1108 goto fast_next_opcode;
1110 case LOAD_FAST:
1111 x = GETLOCAL(oparg);
1112 if (x != NULL) {
1113 Py_INCREF(x);
1114 PUSH(x);
1115 goto fast_next_opcode;
1117 format_exc_check_arg(PyExc_UnboundLocalError,
1118 UNBOUNDLOCAL_ERROR_MSG,
1119 PyTuple_GetItem(co->co_varnames, oparg));
1120 break;
1122 case LOAD_CONST:
1123 x = GETITEM(consts, oparg);
1124 Py_INCREF(x);
1125 PUSH(x);
1126 goto fast_next_opcode;
1128 PREDICTED_WITH_ARG(STORE_FAST);
1129 case STORE_FAST:
1130 v = POP();
1131 SETLOCAL(oparg, v);
1132 goto fast_next_opcode;
1134 case POP_TOP:
1135 v = POP();
1136 Py_DECREF(v);
1137 goto fast_next_opcode;
1139 case ROT_TWO:
1140 v = TOP();
1141 w = SECOND();
1142 SET_TOP(w);
1143 SET_SECOND(v);
1144 goto fast_next_opcode;
1146 case ROT_THREE:
1147 v = TOP();
1148 w = SECOND();
1149 x = THIRD();
1150 SET_TOP(w);
1151 SET_SECOND(x);
1152 SET_THIRD(v);
1153 goto fast_next_opcode;
1155 case ROT_FOUR:
1156 u = TOP();
1157 v = SECOND();
1158 w = THIRD();
1159 x = FOURTH();
1160 SET_TOP(v);
1161 SET_SECOND(w);
1162 SET_THIRD(x);
1163 SET_FOURTH(u);
1164 goto fast_next_opcode;
1166 case DUP_TOP:
1167 v = TOP();
1168 Py_INCREF(v);
1169 PUSH(v);
1170 goto fast_next_opcode;
1172 case DUP_TOPX:
1173 if (oparg == 2) {
1174 x = TOP();
1175 Py_INCREF(x);
1176 w = SECOND();
1177 Py_INCREF(w);
1178 STACKADJ(2);
1179 SET_TOP(x);
1180 SET_SECOND(w);
1181 goto fast_next_opcode;
1182 } else if (oparg == 3) {
1183 x = TOP();
1184 Py_INCREF(x);
1185 w = SECOND();
1186 Py_INCREF(w);
1187 v = THIRD();
1188 Py_INCREF(v);
1189 STACKADJ(3);
1190 SET_TOP(x);
1191 SET_SECOND(w);
1192 SET_THIRD(v);
1193 goto fast_next_opcode;
1195 Py_FatalError("invalid argument to DUP_TOPX"
1196 " (bytecode corruption?)");
1197 /* Never returns, so don't bother to set why. */
1198 break;
1200 case UNARY_POSITIVE:
1201 v = TOP();
1202 x = PyNumber_Positive(v);
1203 Py_DECREF(v);
1204 SET_TOP(x);
1205 if (x != NULL) continue;
1206 break;
1208 case UNARY_NEGATIVE:
1209 v = TOP();
1210 x = PyNumber_Negative(v);
1211 Py_DECREF(v);
1212 SET_TOP(x);
1213 if (x != NULL) continue;
1214 break;
1216 case UNARY_NOT:
1217 v = TOP();
1218 err = PyObject_IsTrue(v);
1219 Py_DECREF(v);
1220 if (err == 0) {
1221 Py_INCREF(Py_True);
1222 SET_TOP(Py_True);
1223 continue;
1225 else if (err > 0) {
1226 Py_INCREF(Py_False);
1227 SET_TOP(Py_False);
1228 err = 0;
1229 continue;
1231 STACKADJ(-1);
1232 break;
1234 case UNARY_CONVERT:
1235 v = TOP();
1236 x = PyObject_Repr(v);
1237 Py_DECREF(v);
1238 SET_TOP(x);
1239 if (x != NULL) continue;
1240 break;
1242 case UNARY_INVERT:
1243 v = TOP();
1244 x = PyNumber_Invert(v);
1245 Py_DECREF(v);
1246 SET_TOP(x);
1247 if (x != NULL) continue;
1248 break;
1250 case BINARY_POWER:
1251 w = POP();
1252 v = TOP();
1253 x = PyNumber_Power(v, w, Py_None);
1254 Py_DECREF(v);
1255 Py_DECREF(w);
1256 SET_TOP(x);
1257 if (x != NULL) continue;
1258 break;
1260 case BINARY_MULTIPLY:
1261 w = POP();
1262 v = TOP();
1263 x = PyNumber_Multiply(v, w);
1264 Py_DECREF(v);
1265 Py_DECREF(w);
1266 SET_TOP(x);
1267 if (x != NULL) continue;
1268 break;
1270 case BINARY_DIVIDE:
1271 if (!_Py_QnewFlag) {
1272 w = POP();
1273 v = TOP();
1274 x = PyNumber_Divide(v, w);
1275 Py_DECREF(v);
1276 Py_DECREF(w);
1277 SET_TOP(x);
1278 if (x != NULL) continue;
1279 break;
1281 /* -Qnew is in effect: fall through to
1282 BINARY_TRUE_DIVIDE */
1283 case BINARY_TRUE_DIVIDE:
1284 w = POP();
1285 v = TOP();
1286 x = PyNumber_TrueDivide(v, w);
1287 Py_DECREF(v);
1288 Py_DECREF(w);
1289 SET_TOP(x);
1290 if (x != NULL) continue;
1291 break;
1293 case BINARY_FLOOR_DIVIDE:
1294 w = POP();
1295 v = TOP();
1296 x = PyNumber_FloorDivide(v, w);
1297 Py_DECREF(v);
1298 Py_DECREF(w);
1299 SET_TOP(x);
1300 if (x != NULL) continue;
1301 break;
1303 case BINARY_MODULO:
1304 w = POP();
1305 v = TOP();
1306 if (PyString_CheckExact(v))
1307 x = PyString_Format(v, w);
1308 else
1309 x = PyNumber_Remainder(v, w);
1310 Py_DECREF(v);
1311 Py_DECREF(w);
1312 SET_TOP(x);
1313 if (x != NULL) continue;
1314 break;
1316 case BINARY_ADD:
1317 w = POP();
1318 v = TOP();
1319 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1320 /* INLINE: int + int */
1321 register long a, b, i;
1322 a = PyInt_AS_LONG(v);
1323 b = PyInt_AS_LONG(w);
1324 /* cast to avoid undefined behaviour
1325 on overflow */
1326 i = (long)((unsigned long)a + b);
1327 if ((i^a) < 0 && (i^b) < 0)
1328 goto slow_add;
1329 x = PyInt_FromLong(i);
1331 else if (PyString_CheckExact(v) &&
1332 PyString_CheckExact(w)) {
1333 x = string_concatenate(v, w, f, next_instr);
1334 /* string_concatenate consumed the ref to v */
1335 goto skip_decref_vx;
1337 else {
1338 slow_add:
1339 x = PyNumber_Add(v, w);
1341 Py_DECREF(v);
1342 skip_decref_vx:
1343 Py_DECREF(w);
1344 SET_TOP(x);
1345 if (x != NULL) continue;
1346 break;
1348 case BINARY_SUBTRACT:
1349 w = POP();
1350 v = TOP();
1351 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1352 /* INLINE: int - int */
1353 register long a, b, i;
1354 a = PyInt_AS_LONG(v);
1355 b = PyInt_AS_LONG(w);
1356 /* cast to avoid undefined behaviour
1357 on overflow */
1358 i = (long)((unsigned long)a - b);
1359 if ((i^a) < 0 && (i^~b) < 0)
1360 goto slow_sub;
1361 x = PyInt_FromLong(i);
1363 else {
1364 slow_sub:
1365 x = PyNumber_Subtract(v, w);
1367 Py_DECREF(v);
1368 Py_DECREF(w);
1369 SET_TOP(x);
1370 if (x != NULL) continue;
1371 break;
1373 case BINARY_SUBSCR:
1374 w = POP();
1375 v = TOP();
1376 if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
1377 /* INLINE: list[int] */
1378 Py_ssize_t i = PyInt_AsSsize_t(w);
1379 if (i < 0)
1380 i += PyList_GET_SIZE(v);
1381 if (i >= 0 && i < PyList_GET_SIZE(v)) {
1382 x = PyList_GET_ITEM(v, i);
1383 Py_INCREF(x);
1385 else
1386 goto slow_get;
1388 else
1389 slow_get:
1390 x = PyObject_GetItem(v, w);
1391 Py_DECREF(v);
1392 Py_DECREF(w);
1393 SET_TOP(x);
1394 if (x != NULL) continue;
1395 break;
1397 case BINARY_LSHIFT:
1398 w = POP();
1399 v = TOP();
1400 x = PyNumber_Lshift(v, w);
1401 Py_DECREF(v);
1402 Py_DECREF(w);
1403 SET_TOP(x);
1404 if (x != NULL) continue;
1405 break;
1407 case BINARY_RSHIFT:
1408 w = POP();
1409 v = TOP();
1410 x = PyNumber_Rshift(v, w);
1411 Py_DECREF(v);
1412 Py_DECREF(w);
1413 SET_TOP(x);
1414 if (x != NULL) continue;
1415 break;
1417 case BINARY_AND:
1418 w = POP();
1419 v = TOP();
1420 x = PyNumber_And(v, w);
1421 Py_DECREF(v);
1422 Py_DECREF(w);
1423 SET_TOP(x);
1424 if (x != NULL) continue;
1425 break;
1427 case BINARY_XOR:
1428 w = POP();
1429 v = TOP();
1430 x = PyNumber_Xor(v, w);
1431 Py_DECREF(v);
1432 Py_DECREF(w);
1433 SET_TOP(x);
1434 if (x != NULL) continue;
1435 break;
1437 case BINARY_OR:
1438 w = POP();
1439 v = TOP();
1440 x = PyNumber_Or(v, w);
1441 Py_DECREF(v);
1442 Py_DECREF(w);
1443 SET_TOP(x);
1444 if (x != NULL) continue;
1445 break;
1447 case LIST_APPEND:
1448 w = POP();
1449 v = PEEK(oparg);
1450 err = PyList_Append(v, w);
1451 Py_DECREF(w);
1452 if (err == 0) {
1453 PREDICT(JUMP_ABSOLUTE);
1454 continue;
1456 break;
1458 case INPLACE_POWER:
1459 w = POP();
1460 v = TOP();
1461 x = PyNumber_InPlacePower(v, w, Py_None);
1462 Py_DECREF(v);
1463 Py_DECREF(w);
1464 SET_TOP(x);
1465 if (x != NULL) continue;
1466 break;
1468 case INPLACE_MULTIPLY:
1469 w = POP();
1470 v = TOP();
1471 x = PyNumber_InPlaceMultiply(v, w);
1472 Py_DECREF(v);
1473 Py_DECREF(w);
1474 SET_TOP(x);
1475 if (x != NULL) continue;
1476 break;
1478 case INPLACE_DIVIDE:
1479 if (!_Py_QnewFlag) {
1480 w = POP();
1481 v = TOP();
1482 x = PyNumber_InPlaceDivide(v, w);
1483 Py_DECREF(v);
1484 Py_DECREF(w);
1485 SET_TOP(x);
1486 if (x != NULL) continue;
1487 break;
1489 /* -Qnew is in effect: fall through to
1490 INPLACE_TRUE_DIVIDE */
1491 case INPLACE_TRUE_DIVIDE:
1492 w = POP();
1493 v = TOP();
1494 x = PyNumber_InPlaceTrueDivide(v, w);
1495 Py_DECREF(v);
1496 Py_DECREF(w);
1497 SET_TOP(x);
1498 if (x != NULL) continue;
1499 break;
1501 case INPLACE_FLOOR_DIVIDE:
1502 w = POP();
1503 v = TOP();
1504 x = PyNumber_InPlaceFloorDivide(v, w);
1505 Py_DECREF(v);
1506 Py_DECREF(w);
1507 SET_TOP(x);
1508 if (x != NULL) continue;
1509 break;
1511 case INPLACE_MODULO:
1512 w = POP();
1513 v = TOP();
1514 x = PyNumber_InPlaceRemainder(v, w);
1515 Py_DECREF(v);
1516 Py_DECREF(w);
1517 SET_TOP(x);
1518 if (x != NULL) continue;
1519 break;
1521 case INPLACE_ADD:
1522 w = POP();
1523 v = TOP();
1524 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1525 /* INLINE: int + int */
1526 register long a, b, i;
1527 a = PyInt_AS_LONG(v);
1528 b = PyInt_AS_LONG(w);
1529 i = a + b;
1530 if ((i^a) < 0 && (i^b) < 0)
1531 goto slow_iadd;
1532 x = PyInt_FromLong(i);
1534 else if (PyString_CheckExact(v) &&
1535 PyString_CheckExact(w)) {
1536 x = string_concatenate(v, w, f, next_instr);
1537 /* string_concatenate consumed the ref to v */
1538 goto skip_decref_v;
1540 else {
1541 slow_iadd:
1542 x = PyNumber_InPlaceAdd(v, w);
1544 Py_DECREF(v);
1545 skip_decref_v:
1546 Py_DECREF(w);
1547 SET_TOP(x);
1548 if (x != NULL) continue;
1549 break;
1551 case INPLACE_SUBTRACT:
1552 w = POP();
1553 v = TOP();
1554 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1555 /* INLINE: int - int */
1556 register long a, b, i;
1557 a = PyInt_AS_LONG(v);
1558 b = PyInt_AS_LONG(w);
1559 i = a - b;
1560 if ((i^a) < 0 && (i^~b) < 0)
1561 goto slow_isub;
1562 x = PyInt_FromLong(i);
1564 else {
1565 slow_isub:
1566 x = PyNumber_InPlaceSubtract(v, w);
1568 Py_DECREF(v);
1569 Py_DECREF(w);
1570 SET_TOP(x);
1571 if (x != NULL) continue;
1572 break;
1574 case INPLACE_LSHIFT:
1575 w = POP();
1576 v = TOP();
1577 x = PyNumber_InPlaceLshift(v, w);
1578 Py_DECREF(v);
1579 Py_DECREF(w);
1580 SET_TOP(x);
1581 if (x != NULL) continue;
1582 break;
1584 case INPLACE_RSHIFT:
1585 w = POP();
1586 v = TOP();
1587 x = PyNumber_InPlaceRshift(v, w);
1588 Py_DECREF(v);
1589 Py_DECREF(w);
1590 SET_TOP(x);
1591 if (x != NULL) continue;
1592 break;
1594 case INPLACE_AND:
1595 w = POP();
1596 v = TOP();
1597 x = PyNumber_InPlaceAnd(v, w);
1598 Py_DECREF(v);
1599 Py_DECREF(w);
1600 SET_TOP(x);
1601 if (x != NULL) continue;
1602 break;
1604 case INPLACE_XOR:
1605 w = POP();
1606 v = TOP();
1607 x = PyNumber_InPlaceXor(v, w);
1608 Py_DECREF(v);
1609 Py_DECREF(w);
1610 SET_TOP(x);
1611 if (x != NULL) continue;
1612 break;
1614 case INPLACE_OR:
1615 w = POP();
1616 v = TOP();
1617 x = PyNumber_InPlaceOr(v, w);
1618 Py_DECREF(v);
1619 Py_DECREF(w);
1620 SET_TOP(x);
1621 if (x != NULL) continue;
1622 break;
1624 case SLICE+0:
1625 case SLICE+1:
1626 case SLICE+2:
1627 case SLICE+3:
1628 if ((opcode-SLICE) & 2)
1629 w = POP();
1630 else
1631 w = NULL;
1632 if ((opcode-SLICE) & 1)
1633 v = POP();
1634 else
1635 v = NULL;
1636 u = TOP();
1637 x = apply_slice(u, v, w);
1638 Py_DECREF(u);
1639 Py_XDECREF(v);
1640 Py_XDECREF(w);
1641 SET_TOP(x);
1642 if (x != NULL) continue;
1643 break;
1645 case STORE_SLICE+0:
1646 case STORE_SLICE+1:
1647 case STORE_SLICE+2:
1648 case STORE_SLICE+3:
1649 if ((opcode-STORE_SLICE) & 2)
1650 w = POP();
1651 else
1652 w = NULL;
1653 if ((opcode-STORE_SLICE) & 1)
1654 v = POP();
1655 else
1656 v = NULL;
1657 u = POP();
1658 t = POP();
1659 err = assign_slice(u, v, w, t); /* u[v:w] = t */
1660 Py_DECREF(t);
1661 Py_DECREF(u);
1662 Py_XDECREF(v);
1663 Py_XDECREF(w);
1664 if (err == 0) continue;
1665 break;
1667 case DELETE_SLICE+0:
1668 case DELETE_SLICE+1:
1669 case DELETE_SLICE+2:
1670 case DELETE_SLICE+3:
1671 if ((opcode-DELETE_SLICE) & 2)
1672 w = POP();
1673 else
1674 w = NULL;
1675 if ((opcode-DELETE_SLICE) & 1)
1676 v = POP();
1677 else
1678 v = NULL;
1679 u = POP();
1680 err = assign_slice(u, v, w, (PyObject *)NULL);
1681 /* del u[v:w] */
1682 Py_DECREF(u);
1683 Py_XDECREF(v);
1684 Py_XDECREF(w);
1685 if (err == 0) continue;
1686 break;
1688 case STORE_SUBSCR:
1689 w = TOP();
1690 v = SECOND();
1691 u = THIRD();
1692 STACKADJ(-3);
1693 /* v[w] = u */
1694 err = PyObject_SetItem(v, w, u);
1695 Py_DECREF(u);
1696 Py_DECREF(v);
1697 Py_DECREF(w);
1698 if (err == 0) continue;
1699 break;
1701 case DELETE_SUBSCR:
1702 w = TOP();
1703 v = SECOND();
1704 STACKADJ(-2);
1705 /* del v[w] */
1706 err = PyObject_DelItem(v, w);
1707 Py_DECREF(v);
1708 Py_DECREF(w);
1709 if (err == 0) continue;
1710 break;
1712 case PRINT_EXPR:
1713 v = POP();
1714 w = PySys_GetObject("displayhook");
1715 if (w == NULL) {
1716 PyErr_SetString(PyExc_RuntimeError,
1717 "lost sys.displayhook");
1718 err = -1;
1719 x = NULL;
1721 if (err == 0) {
1722 x = PyTuple_Pack(1, v);
1723 if (x == NULL)
1724 err = -1;
1726 if (err == 0) {
1727 w = PyEval_CallObject(w, x);
1728 Py_XDECREF(w);
1729 if (w == NULL)
1730 err = -1;
1732 Py_DECREF(v);
1733 Py_XDECREF(x);
1734 break;
1736 case PRINT_ITEM_TO:
1737 w = stream = POP();
1738 /* fall through to PRINT_ITEM */
1740 case PRINT_ITEM:
1741 v = POP();
1742 if (stream == NULL || stream == Py_None) {
1743 w = PySys_GetObject("stdout");
1744 if (w == NULL) {
1745 PyErr_SetString(PyExc_RuntimeError,
1746 "lost sys.stdout");
1747 err = -1;
1750 /* PyFile_SoftSpace() can exececute arbitrary code
1751 if sys.stdout is an instance with a __getattr__.
1752 If __getattr__ raises an exception, w will
1753 be freed, so we need to prevent that temporarily. */
1754 Py_XINCREF(w);
1755 if (w != NULL && PyFile_SoftSpace(w, 0))
1756 err = PyFile_WriteString(" ", w);
1757 if (err == 0)
1758 err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
1759 if (err == 0) {
1760 /* XXX move into writeobject() ? */
1761 if (PyString_Check(v)) {
1762 char *s = PyString_AS_STRING(v);
1763 Py_ssize_t len = PyString_GET_SIZE(v);
1764 if (len == 0 ||
1765 !isspace(Py_CHARMASK(s[len-1])) ||
1766 s[len-1] == ' ')
1767 PyFile_SoftSpace(w, 1);
1769 #ifdef Py_USING_UNICODE
1770 else if (PyUnicode_Check(v)) {
1771 Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
1772 Py_ssize_t len = PyUnicode_GET_SIZE(v);
1773 if (len == 0 ||
1774 !Py_UNICODE_ISSPACE(s[len-1]) ||
1775 s[len-1] == ' ')
1776 PyFile_SoftSpace(w, 1);
1778 #endif
1779 else
1780 PyFile_SoftSpace(w, 1);
1782 Py_XDECREF(w);
1783 Py_DECREF(v);
1784 Py_XDECREF(stream);
1785 stream = NULL;
1786 if (err == 0)
1787 continue;
1788 break;
1790 case PRINT_NEWLINE_TO:
1791 w = stream = POP();
1792 /* fall through to PRINT_NEWLINE */
1794 case PRINT_NEWLINE:
1795 if (stream == NULL || stream == Py_None) {
1796 w = PySys_GetObject("stdout");
1797 if (w == NULL) {
1798 PyErr_SetString(PyExc_RuntimeError,
1799 "lost sys.stdout");
1800 why = WHY_EXCEPTION;
1803 if (w != NULL) {
1804 /* w.write() may replace sys.stdout, so we
1805 * have to keep our reference to it */
1806 Py_INCREF(w);
1807 err = PyFile_WriteString("\n", w);
1808 if (err == 0)
1809 PyFile_SoftSpace(w, 0);
1810 Py_DECREF(w);
1812 Py_XDECREF(stream);
1813 stream = NULL;
1814 break;
1817 #ifdef CASE_TOO_BIG
1818 default: switch (opcode) {
1819 #endif
1820 case RAISE_VARARGS:
1821 u = v = w = NULL;
1822 switch (oparg) {
1823 case 3:
1824 u = POP(); /* traceback */
1825 /* Fallthrough */
1826 case 2:
1827 v = POP(); /* value */
1828 /* Fallthrough */
1829 case 1:
1830 w = POP(); /* exc */
1831 case 0: /* Fallthrough */
1832 why = do_raise(w, v, u);
1833 break;
1834 default:
1835 PyErr_SetString(PyExc_SystemError,
1836 "bad RAISE_VARARGS oparg");
1837 why = WHY_EXCEPTION;
1838 break;
1840 break;
1842 case LOAD_LOCALS:
1843 if ((x = f->f_locals) != NULL) {
1844 Py_INCREF(x);
1845 PUSH(x);
1846 continue;
1848 PyErr_SetString(PyExc_SystemError, "no locals");
1849 break;
1851 case RETURN_VALUE:
1852 retval = POP();
1853 why = WHY_RETURN;
1854 goto fast_block_end;
1856 case YIELD_VALUE:
1857 retval = POP();
1858 f->f_stacktop = stack_pointer;
1859 why = WHY_YIELD;
1860 goto fast_yield;
1862 case EXEC_STMT:
1863 w = TOP();
1864 v = SECOND();
1865 u = THIRD();
1866 STACKADJ(-3);
1867 READ_TIMESTAMP(intr0);
1868 err = exec_statement(f, u, v, w);
1869 READ_TIMESTAMP(intr1);
1870 Py_DECREF(u);
1871 Py_DECREF(v);
1872 Py_DECREF(w);
1873 break;
1875 case POP_BLOCK:
1877 PyTryBlock *b = PyFrame_BlockPop(f);
1878 while (STACK_LEVEL() > b->b_level) {
1879 v = POP();
1880 Py_DECREF(v);
1883 continue;
1885 PREDICTED(END_FINALLY);
1886 case END_FINALLY:
1887 v = POP();
1888 if (PyInt_Check(v)) {
1889 why = (enum why_code) PyInt_AS_LONG(v);
1890 assert(why != WHY_YIELD);
1891 if (why == WHY_RETURN ||
1892 why == WHY_CONTINUE)
1893 retval = POP();
1895 else if (PyExceptionClass_Check(v) ||
1896 PyString_Check(v)) {
1897 w = POP();
1898 u = POP();
1899 PyErr_Restore(v, w, u);
1900 why = WHY_RERAISE;
1901 break;
1903 else if (v != Py_None) {
1904 PyErr_SetString(PyExc_SystemError,
1905 "'finally' pops bad exception");
1906 why = WHY_EXCEPTION;
1908 Py_DECREF(v);
1909 break;
1911 case BUILD_CLASS:
1912 u = TOP();
1913 v = SECOND();
1914 w = THIRD();
1915 STACKADJ(-2);
1916 x = build_class(u, v, w);
1917 SET_TOP(x);
1918 Py_DECREF(u);
1919 Py_DECREF(v);
1920 Py_DECREF(w);
1921 break;
1923 case STORE_NAME:
1924 w = GETITEM(names, oparg);
1925 v = POP();
1926 if ((x = f->f_locals) != NULL) {
1927 if (PyDict_CheckExact(x))
1928 err = PyDict_SetItem(x, w, v);
1929 else
1930 err = PyObject_SetItem(x, w, v);
1931 Py_DECREF(v);
1932 if (err == 0) continue;
1933 break;
1935 PyErr_Format(PyExc_SystemError,
1936 "no locals found when storing %s",
1937 PyObject_REPR(w));
1938 break;
1940 case DELETE_NAME:
1941 w = GETITEM(names, oparg);
1942 if ((x = f->f_locals) != NULL) {
1943 if ((err = PyObject_DelItem(x, w)) != 0)
1944 format_exc_check_arg(PyExc_NameError,
1945 NAME_ERROR_MSG,
1947 break;
1949 PyErr_Format(PyExc_SystemError,
1950 "no locals when deleting %s",
1951 PyObject_REPR(w));
1952 break;
1954 PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
1955 case UNPACK_SEQUENCE:
1956 v = POP();
1957 if (PyTuple_CheckExact(v) &&
1958 PyTuple_GET_SIZE(v) == oparg) {
1959 PyObject **items = \
1960 ((PyTupleObject *)v)->ob_item;
1961 while (oparg--) {
1962 w = items[oparg];
1963 Py_INCREF(w);
1964 PUSH(w);
1966 Py_DECREF(v);
1967 continue;
1968 } else if (PyList_CheckExact(v) &&
1969 PyList_GET_SIZE(v) == oparg) {
1970 PyObject **items = \
1971 ((PyListObject *)v)->ob_item;
1972 while (oparg--) {
1973 w = items[oparg];
1974 Py_INCREF(w);
1975 PUSH(w);
1977 } else if (unpack_iterable(v, oparg,
1978 stack_pointer + oparg)) {
1979 STACKADJ(oparg);
1980 } else {
1981 /* unpack_iterable() raised an exception */
1982 why = WHY_EXCEPTION;
1984 Py_DECREF(v);
1985 break;
1987 case STORE_ATTR:
1988 w = GETITEM(names, oparg);
1989 v = TOP();
1990 u = SECOND();
1991 STACKADJ(-2);
1992 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1993 Py_DECREF(v);
1994 Py_DECREF(u);
1995 if (err == 0) continue;
1996 break;
1998 case DELETE_ATTR:
1999 w = GETITEM(names, oparg);
2000 v = POP();
2001 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
2002 /* del v.w */
2003 Py_DECREF(v);
2004 break;
2006 case STORE_GLOBAL:
2007 w = GETITEM(names, oparg);
2008 v = POP();
2009 err = PyDict_SetItem(f->f_globals, w, v);
2010 Py_DECREF(v);
2011 if (err == 0) continue;
2012 break;
2014 case DELETE_GLOBAL:
2015 w = GETITEM(names, oparg);
2016 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
2017 format_exc_check_arg(
2018 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
2019 break;
2021 case LOAD_NAME:
2022 w = GETITEM(names, oparg);
2023 if ((v = f->f_locals) == NULL) {
2024 PyErr_Format(PyExc_SystemError,
2025 "no locals when loading %s",
2026 PyObject_REPR(w));
2027 why = WHY_EXCEPTION;
2028 break;
2030 if (PyDict_CheckExact(v)) {
2031 x = PyDict_GetItem(v, w);
2032 Py_XINCREF(x);
2034 else {
2035 x = PyObject_GetItem(v, w);
2036 if (x == NULL && PyErr_Occurred()) {
2037 if (!PyErr_ExceptionMatches(
2038 PyExc_KeyError))
2039 break;
2040 PyErr_Clear();
2043 if (x == NULL) {
2044 x = PyDict_GetItem(f->f_globals, w);
2045 if (x == NULL) {
2046 x = PyDict_GetItem(f->f_builtins, w);
2047 if (x == NULL) {
2048 format_exc_check_arg(
2049 PyExc_NameError,
2050 NAME_ERROR_MSG, w);
2051 break;
2054 Py_INCREF(x);
2056 PUSH(x);
2057 continue;
2059 case LOAD_GLOBAL:
2060 w = GETITEM(names, oparg);
2061 if (PyString_CheckExact(w)) {
2062 /* Inline the PyDict_GetItem() calls.
2063 WARNING: this is an extreme speed hack.
2064 Do not try this at home. */
2065 long hash = ((PyStringObject *)w)->ob_shash;
2066 if (hash != -1) {
2067 PyDictObject *d;
2068 PyDictEntry *e;
2069 d = (PyDictObject *)(f->f_globals);
2070 e = d->ma_lookup(d, w, hash);
2071 if (e == NULL) {
2072 x = NULL;
2073 break;
2075 x = e->me_value;
2076 if (x != NULL) {
2077 Py_INCREF(x);
2078 PUSH(x);
2079 continue;
2081 d = (PyDictObject *)(f->f_builtins);
2082 e = d->ma_lookup(d, w, hash);
2083 if (e == NULL) {
2084 x = NULL;
2085 break;
2087 x = e->me_value;
2088 if (x != NULL) {
2089 Py_INCREF(x);
2090 PUSH(x);
2091 continue;
2093 goto load_global_error;
2096 /* This is the un-inlined version of the code above */
2097 x = PyDict_GetItem(f->f_globals, w);
2098 if (x == NULL) {
2099 x = PyDict_GetItem(f->f_builtins, w);
2100 if (x == NULL) {
2101 load_global_error:
2102 format_exc_check_arg(
2103 PyExc_NameError,
2104 GLOBAL_NAME_ERROR_MSG, w);
2105 break;
2108 Py_INCREF(x);
2109 PUSH(x);
2110 continue;
2112 case DELETE_FAST:
2113 x = GETLOCAL(oparg);
2114 if (x != NULL) {
2115 SETLOCAL(oparg, NULL);
2116 continue;
2118 format_exc_check_arg(
2119 PyExc_UnboundLocalError,
2120 UNBOUNDLOCAL_ERROR_MSG,
2121 PyTuple_GetItem(co->co_varnames, oparg)
2123 break;
2125 case LOAD_CLOSURE:
2126 x = freevars[oparg];
2127 Py_INCREF(x);
2128 PUSH(x);
2129 if (x != NULL) continue;
2130 break;
2132 case LOAD_DEREF:
2133 x = freevars[oparg];
2134 w = PyCell_Get(x);
2135 if (w != NULL) {
2136 PUSH(w);
2137 continue;
2139 err = -1;
2140 /* Don't stomp existing exception */
2141 if (PyErr_Occurred())
2142 break;
2143 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
2144 v = PyTuple_GET_ITEM(co->co_cellvars,
2145 oparg);
2146 format_exc_check_arg(
2147 PyExc_UnboundLocalError,
2148 UNBOUNDLOCAL_ERROR_MSG,
2150 } else {
2151 v = PyTuple_GET_ITEM(co->co_freevars, oparg -
2152 PyTuple_GET_SIZE(co->co_cellvars));
2153 format_exc_check_arg(PyExc_NameError,
2154 UNBOUNDFREE_ERROR_MSG, v);
2156 break;
2158 case STORE_DEREF:
2159 w = POP();
2160 x = freevars[oparg];
2161 PyCell_Set(x, w);
2162 Py_DECREF(w);
2163 continue;
2165 case BUILD_TUPLE:
2166 x = PyTuple_New(oparg);
2167 if (x != NULL) {
2168 for (; --oparg >= 0;) {
2169 w = POP();
2170 PyTuple_SET_ITEM(x, oparg, w);
2172 PUSH(x);
2173 continue;
2175 break;
2177 case BUILD_LIST:
2178 x = PyList_New(oparg);
2179 if (x != NULL) {
2180 for (; --oparg >= 0;) {
2181 w = POP();
2182 PyList_SET_ITEM(x, oparg, w);
2184 PUSH(x);
2185 continue;
2187 break;
2189 case BUILD_MAP:
2190 x = _PyDict_NewPresized((Py_ssize_t)oparg);
2191 PUSH(x);
2192 if (x != NULL) continue;
2193 break;
2195 case STORE_MAP:
2196 w = TOP(); /* key */
2197 u = SECOND(); /* value */
2198 v = THIRD(); /* dict */
2199 STACKADJ(-2);
2200 assert (PyDict_CheckExact(v));
2201 err = PyDict_SetItem(v, w, u); /* v[w] = u */
2202 Py_DECREF(u);
2203 Py_DECREF(w);
2204 if (err == 0) continue;
2205 break;
2207 case LOAD_ATTR:
2208 w = GETITEM(names, oparg);
2209 v = TOP();
2210 x = PyObject_GetAttr(v, w);
2211 Py_DECREF(v);
2212 SET_TOP(x);
2213 if (x != NULL) continue;
2214 break;
2216 case COMPARE_OP:
2217 w = POP();
2218 v = TOP();
2219 if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) {
2220 /* INLINE: cmp(int, int) */
2221 register long a, b;
2222 register int res;
2223 a = PyInt_AS_LONG(v);
2224 b = PyInt_AS_LONG(w);
2225 switch (oparg) {
2226 case PyCmp_LT: res = a < b; break;
2227 case PyCmp_LE: res = a <= b; break;
2228 case PyCmp_EQ: res = a == b; break;
2229 case PyCmp_NE: res = a != b; break;
2230 case PyCmp_GT: res = a > b; break;
2231 case PyCmp_GE: res = a >= b; break;
2232 case PyCmp_IS: res = v == w; break;
2233 case PyCmp_IS_NOT: res = v != w; break;
2234 default: goto slow_compare;
2236 x = res ? Py_True : Py_False;
2237 Py_INCREF(x);
2239 else {
2240 slow_compare:
2241 x = cmp_outcome(oparg, v, w);
2243 Py_DECREF(v);
2244 Py_DECREF(w);
2245 SET_TOP(x);
2246 if (x == NULL) break;
2247 PREDICT(POP_JUMP_IF_FALSE);
2248 PREDICT(POP_JUMP_IF_TRUE);
2249 continue;
2251 case IMPORT_NAME:
2252 w = GETITEM(names, oparg);
2253 x = PyDict_GetItemString(f->f_builtins, "__import__");
2254 if (x == NULL) {
2255 PyErr_SetString(PyExc_ImportError,
2256 "__import__ not found");
2257 break;
2259 Py_INCREF(x);
2260 v = POP();
2261 u = TOP();
2262 if (PyInt_AsLong(u) != -1 || PyErr_Occurred())
2263 w = PyTuple_Pack(5,
2265 f->f_globals,
2266 f->f_locals == NULL ?
2267 Py_None : f->f_locals,
2270 else
2271 w = PyTuple_Pack(4,
2273 f->f_globals,
2274 f->f_locals == NULL ?
2275 Py_None : f->f_locals,
2277 Py_DECREF(v);
2278 Py_DECREF(u);
2279 if (w == NULL) {
2280 u = POP();
2281 Py_DECREF(x);
2282 x = NULL;
2283 break;
2285 READ_TIMESTAMP(intr0);
2286 v = x;
2287 x = PyEval_CallObject(v, w);
2288 Py_DECREF(v);
2289 READ_TIMESTAMP(intr1);
2290 Py_DECREF(w);
2291 SET_TOP(x);
2292 if (x != NULL) continue;
2293 break;
2295 case IMPORT_STAR:
2296 v = POP();
2297 PyFrame_FastToLocals(f);
2298 if ((x = f->f_locals) == NULL) {
2299 PyErr_SetString(PyExc_SystemError,
2300 "no locals found during 'import *'");
2301 break;
2303 READ_TIMESTAMP(intr0);
2304 err = import_all_from(x, v);
2305 READ_TIMESTAMP(intr1);
2306 PyFrame_LocalsToFast(f, 0);
2307 Py_DECREF(v);
2308 if (err == 0) continue;
2309 break;
2311 case IMPORT_FROM:
2312 w = GETITEM(names, oparg);
2313 v = TOP();
2314 READ_TIMESTAMP(intr0);
2315 x = import_from(v, w);
2316 READ_TIMESTAMP(intr1);
2317 PUSH(x);
2318 if (x != NULL) continue;
2319 break;
2321 case JUMP_FORWARD:
2322 JUMPBY(oparg);
2323 goto fast_next_opcode;
2325 PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE);
2326 case POP_JUMP_IF_FALSE:
2327 w = POP();
2328 if (w == Py_True) {
2329 Py_DECREF(w);
2330 goto fast_next_opcode;
2332 if (w == Py_False) {
2333 Py_DECREF(w);
2334 JUMPTO(oparg);
2335 goto fast_next_opcode;
2337 err = PyObject_IsTrue(w);
2338 Py_DECREF(w);
2339 if (err > 0)
2340 err = 0;
2341 else if (err == 0)
2342 JUMPTO(oparg);
2343 else
2344 break;
2345 continue;
2347 PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE);
2348 case POP_JUMP_IF_TRUE:
2349 w = POP();
2350 if (w == Py_False) {
2351 Py_DECREF(w);
2352 goto fast_next_opcode;
2354 if (w == Py_True) {
2355 Py_DECREF(w);
2356 JUMPTO(oparg);
2357 goto fast_next_opcode;
2359 err = PyObject_IsTrue(w);
2360 Py_DECREF(w);
2361 if (err > 0) {
2362 err = 0;
2363 JUMPTO(oparg);
2365 else if (err == 0)
2367 else
2368 break;
2369 continue;
2371 case JUMP_IF_FALSE_OR_POP:
2372 w = TOP();
2373 if (w == Py_True) {
2374 STACKADJ(-1);
2375 Py_DECREF(w);
2376 goto fast_next_opcode;
2378 if (w == Py_False) {
2379 JUMPTO(oparg);
2380 goto fast_next_opcode;
2382 err = PyObject_IsTrue(w);
2383 if (err > 0) {
2384 STACKADJ(-1);
2385 Py_DECREF(w);
2386 err = 0;
2388 else if (err == 0)
2389 JUMPTO(oparg);
2390 else
2391 break;
2392 continue;
2394 case JUMP_IF_TRUE_OR_POP:
2395 w = TOP();
2396 if (w == Py_False) {
2397 STACKADJ(-1);
2398 Py_DECREF(w);
2399 goto fast_next_opcode;
2401 if (w == Py_True) {
2402 JUMPTO(oparg);
2403 goto fast_next_opcode;
2405 err = PyObject_IsTrue(w);
2406 if (err > 0) {
2407 err = 0;
2408 JUMPTO(oparg);
2410 else if (err == 0) {
2411 STACKADJ(-1);
2412 Py_DECREF(w);
2414 else
2415 break;
2416 continue;
2418 PREDICTED_WITH_ARG(JUMP_ABSOLUTE);
2419 case JUMP_ABSOLUTE:
2420 JUMPTO(oparg);
2421 #if FAST_LOOPS
2422 /* Enabling this path speeds-up all while and for-loops by bypassing
2423 the per-loop checks for signals. By default, this should be turned-off
2424 because it prevents detection of a control-break in tight loops like
2425 "while 1: pass". Compile with this option turned-on when you need
2426 the speed-up and do not need break checking inside tight loops (ones
2427 that contain only instructions ending with goto fast_next_opcode).
2429 goto fast_next_opcode;
2430 #else
2431 continue;
2432 #endif
2434 case GET_ITER:
2435 /* before: [obj]; after [getiter(obj)] */
2436 v = TOP();
2437 x = PyObject_GetIter(v);
2438 Py_DECREF(v);
2439 if (x != NULL) {
2440 SET_TOP(x);
2441 PREDICT(FOR_ITER);
2442 continue;
2444 STACKADJ(-1);
2445 break;
2447 PREDICTED_WITH_ARG(FOR_ITER);
2448 case FOR_ITER:
2449 /* before: [iter]; after: [iter, iter()] *or* [] */
2450 v = TOP();
2451 x = (*v->ob_type->tp_iternext)(v);
2452 if (x != NULL) {
2453 PUSH(x);
2454 PREDICT(STORE_FAST);
2455 PREDICT(UNPACK_SEQUENCE);
2456 continue;
2458 if (PyErr_Occurred()) {
2459 if (!PyErr_ExceptionMatches(
2460 PyExc_StopIteration))
2461 break;
2462 PyErr_Clear();
2464 /* iterator ended normally */
2465 x = v = POP();
2466 Py_DECREF(v);
2467 JUMPBY(oparg);
2468 continue;
2470 case BREAK_LOOP:
2471 why = WHY_BREAK;
2472 goto fast_block_end;
2474 case CONTINUE_LOOP:
2475 retval = PyInt_FromLong(oparg);
2476 if (!retval) {
2477 x = NULL;
2478 break;
2480 why = WHY_CONTINUE;
2481 goto fast_block_end;
2483 case SETUP_LOOP:
2484 case SETUP_EXCEPT:
2485 case SETUP_FINALLY:
2486 /* NOTE: If you add any new block-setup opcodes that
2487 are not try/except/finally handlers, you may need
2488 to update the PyGen_NeedsFinalizing() function.
2491 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
2492 STACK_LEVEL());
2493 continue;
2495 case SETUP_WITH:
2497 static PyObject *exit, *enter;
2498 w = TOP();
2499 x = special_lookup(w, "__exit__", &exit);
2500 if (!x)
2501 break;
2502 SET_TOP(x);
2503 u = special_lookup(w, "__enter__", &enter);
2504 Py_DECREF(w);
2505 if (!u) {
2506 x = NULL;
2507 break;
2509 x = PyObject_CallFunctionObjArgs(u, NULL);
2510 Py_DECREF(u);
2511 if (!x)
2512 break;
2513 /* Setup the finally block before pushing the result
2514 of __enter__ on the stack. */
2515 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
2516 STACK_LEVEL());
2518 PUSH(x);
2519 continue;
2522 case WITH_CLEANUP:
2524 /* At the top of the stack are 1-3 values indicating
2525 how/why we entered the finally clause:
2526 - TOP = None
2527 - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
2528 - TOP = WHY_*; no retval below it
2529 - (TOP, SECOND, THIRD) = exc_info()
2530 Below them is EXIT, the context.__exit__ bound method.
2531 In the last case, we must call
2532 EXIT(TOP, SECOND, THIRD)
2533 otherwise we must call
2534 EXIT(None, None, None)
2536 In all cases, we remove EXIT from the stack, leaving
2537 the rest in the same order.
2539 In addition, if the stack represents an exception,
2540 *and* the function call returns a 'true' value, we
2541 "zap" this information, to prevent END_FINALLY from
2542 re-raising the exception. (But non-local gotos
2543 should still be resumed.)
2546 PyObject *exit_func;
2548 u = POP();
2549 if (u == Py_None) {
2550 exit_func = TOP();
2551 SET_TOP(u);
2552 v = w = Py_None;
2554 else if (PyInt_Check(u)) {
2555 switch(PyInt_AS_LONG(u)) {
2556 case WHY_RETURN:
2557 case WHY_CONTINUE:
2558 /* Retval in TOP. */
2559 exit_func = SECOND();
2560 SET_SECOND(TOP());
2561 SET_TOP(u);
2562 break;
2563 default:
2564 exit_func = TOP();
2565 SET_TOP(u);
2566 break;
2568 u = v = w = Py_None;
2570 else {
2571 v = TOP();
2572 w = SECOND();
2573 exit_func = THIRD();
2574 SET_TOP(u);
2575 SET_SECOND(v);
2576 SET_THIRD(w);
2578 /* XXX Not the fastest way to call it... */
2579 x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
2580 NULL);
2581 Py_DECREF(exit_func);
2582 if (x == NULL)
2583 break; /* Go to error exit */
2585 if (u != Py_None)
2586 err = PyObject_IsTrue(x);
2587 else
2588 err = 0;
2589 Py_DECREF(x);
2591 if (err < 0)
2592 break; /* Go to error exit */
2593 else if (err > 0) {
2594 err = 0;
2595 /* There was an exception and a true return */
2596 STACKADJ(-2);
2597 Py_INCREF(Py_None);
2598 SET_TOP(Py_None);
2599 Py_DECREF(u);
2600 Py_DECREF(v);
2601 Py_DECREF(w);
2602 } else {
2603 /* The stack was rearranged to remove EXIT
2604 above. Let END_FINALLY do its thing */
2606 PREDICT(END_FINALLY);
2607 break;
2610 case CALL_FUNCTION:
2612 PyObject **sp;
2613 PCALL(PCALL_ALL);
2614 sp = stack_pointer;
2615 #ifdef WITH_TSC
2616 x = call_function(&sp, oparg, &intr0, &intr1);
2617 #else
2618 x = call_function(&sp, oparg);
2619 #endif
2620 stack_pointer = sp;
2621 PUSH(x);
2622 if (x != NULL)
2623 continue;
2624 break;
2627 case CALL_FUNCTION_VAR:
2628 case CALL_FUNCTION_KW:
2629 case CALL_FUNCTION_VAR_KW:
2631 int na = oparg & 0xff;
2632 int nk = (oparg>>8) & 0xff;
2633 int flags = (opcode - CALL_FUNCTION) & 3;
2634 int n = na + 2 * nk;
2635 PyObject **pfunc, *func, **sp;
2636 PCALL(PCALL_ALL);
2637 if (flags & CALL_FLAG_VAR)
2638 n++;
2639 if (flags & CALL_FLAG_KW)
2640 n++;
2641 pfunc = stack_pointer - n - 1;
2642 func = *pfunc;
2644 if (PyMethod_Check(func)
2645 && PyMethod_GET_SELF(func) != NULL) {
2646 PyObject *self = PyMethod_GET_SELF(func);
2647 Py_INCREF(self);
2648 func = PyMethod_GET_FUNCTION(func);
2649 Py_INCREF(func);
2650 Py_DECREF(*pfunc);
2651 *pfunc = self;
2652 na++;
2653 n++;
2654 } else
2655 Py_INCREF(func);
2656 sp = stack_pointer;
2657 READ_TIMESTAMP(intr0);
2658 x = ext_do_call(func, &sp, flags, na, nk);
2659 READ_TIMESTAMP(intr1);
2660 stack_pointer = sp;
2661 Py_DECREF(func);
2663 while (stack_pointer > pfunc) {
2664 w = POP();
2665 Py_DECREF(w);
2667 PUSH(x);
2668 if (x != NULL)
2669 continue;
2670 break;
2673 case MAKE_FUNCTION:
2674 v = POP(); /* code object */
2675 x = PyFunction_New(v, f->f_globals);
2676 Py_DECREF(v);
2677 /* XXX Maybe this should be a separate opcode? */
2678 if (x != NULL && oparg > 0) {
2679 v = PyTuple_New(oparg);
2680 if (v == NULL) {
2681 Py_DECREF(x);
2682 x = NULL;
2683 break;
2685 while (--oparg >= 0) {
2686 w = POP();
2687 PyTuple_SET_ITEM(v, oparg, w);
2689 err = PyFunction_SetDefaults(x, v);
2690 Py_DECREF(v);
2692 PUSH(x);
2693 break;
2695 case MAKE_CLOSURE:
2697 v = POP(); /* code object */
2698 x = PyFunction_New(v, f->f_globals);
2699 Py_DECREF(v);
2700 if (x != NULL) {
2701 v = POP();
2702 if (PyFunction_SetClosure(x, v) != 0) {
2703 /* Can't happen unless bytecode is corrupt. */
2704 why = WHY_EXCEPTION;
2706 Py_DECREF(v);
2708 if (x != NULL && oparg > 0) {
2709 v = PyTuple_New(oparg);
2710 if (v == NULL) {
2711 Py_DECREF(x);
2712 x = NULL;
2713 break;
2715 while (--oparg >= 0) {
2716 w = POP();
2717 PyTuple_SET_ITEM(v, oparg, w);
2719 if (PyFunction_SetDefaults(x, v) != 0) {
2720 /* Can't happen unless
2721 PyFunction_SetDefaults changes. */
2722 why = WHY_EXCEPTION;
2724 Py_DECREF(v);
2726 PUSH(x);
2727 break;
2730 case BUILD_SLICE:
2731 if (oparg == 3)
2732 w = POP();
2733 else
2734 w = NULL;
2735 v = POP();
2736 u = TOP();
2737 x = PySlice_New(u, v, w);
2738 Py_DECREF(u);
2739 Py_DECREF(v);
2740 Py_XDECREF(w);
2741 SET_TOP(x);
2742 if (x != NULL) continue;
2743 break;
2745 case EXTENDED_ARG:
2746 opcode = NEXTOP();
2747 oparg = oparg<<16 | NEXTARG();
2748 goto dispatch_opcode;
2750 default:
2751 fprintf(stderr,
2752 "XXX lineno: %d, opcode: %d\n",
2753 PyFrame_GetLineNumber(f),
2754 opcode);
2755 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2756 why = WHY_EXCEPTION;
2757 break;
2759 #ifdef CASE_TOO_BIG
2761 #endif
2763 } /* switch */
2765 on_error:
2767 READ_TIMESTAMP(inst1);
2769 /* Quickly continue if no error occurred */
2771 if (why == WHY_NOT) {
2772 if (err == 0 && x != NULL) {
2773 #ifdef CHECKEXC
2774 /* This check is expensive! */
2775 if (PyErr_Occurred())
2776 fprintf(stderr,
2777 "XXX undetected error\n");
2778 else {
2779 #endif
2780 READ_TIMESTAMP(loop1);
2781 continue; /* Normal, fast path */
2782 #ifdef CHECKEXC
2784 #endif
2786 why = WHY_EXCEPTION;
2787 x = Py_None;
2788 err = 0;
2791 /* Double-check exception status */
2793 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2794 if (!PyErr_Occurred()) {
2795 PyErr_SetString(PyExc_SystemError,
2796 "error return without exception set");
2797 why = WHY_EXCEPTION;
2800 #ifdef CHECKEXC
2801 else {
2802 /* This check is expensive! */
2803 if (PyErr_Occurred()) {
2804 char buf[128];
2805 sprintf(buf, "Stack unwind with exception "
2806 "set and why=%d", why);
2807 Py_FatalError(buf);
2810 #endif
2812 /* Log traceback info if this is a real exception */
2814 if (why == WHY_EXCEPTION) {
2815 PyTraceBack_Here(f);
2817 if (tstate->c_tracefunc != NULL)
2818 call_exc_trace(tstate->c_tracefunc,
2819 tstate->c_traceobj, f);
2822 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2824 if (why == WHY_RERAISE)
2825 why = WHY_EXCEPTION;
2827 /* Unwind stacks if a (pseudo) exception occurred */
2829 fast_block_end:
2830 while (why != WHY_NOT && f->f_iblock > 0) {
2831 /* Peek at the current block. */
2832 PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1];
2834 assert(why != WHY_YIELD);
2835 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
2836 why = WHY_NOT;
2837 JUMPTO(PyInt_AS_LONG(retval));
2838 Py_DECREF(retval);
2839 break;
2842 /* Now we have to pop the block. */
2843 f->f_iblock--;
2845 while (STACK_LEVEL() > b->b_level) {
2846 v = POP();
2847 Py_XDECREF(v);
2849 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2850 why = WHY_NOT;
2851 JUMPTO(b->b_handler);
2852 break;
2854 if (b->b_type == SETUP_FINALLY ||
2855 (b->b_type == SETUP_EXCEPT &&
2856 why == WHY_EXCEPTION)) {
2857 if (why == WHY_EXCEPTION) {
2858 PyObject *exc, *val, *tb;
2859 PyErr_Fetch(&exc, &val, &tb);
2860 if (val == NULL) {
2861 val = Py_None;
2862 Py_INCREF(val);
2864 /* Make the raw exception data
2865 available to the handler,
2866 so a program can emulate the
2867 Python main loop. Don't do
2868 this for 'finally'. */
2869 if (b->b_type == SETUP_EXCEPT) {
2870 PyErr_NormalizeException(
2871 &exc, &val, &tb);
2872 set_exc_info(tstate,
2873 exc, val, tb);
2875 if (tb == NULL) {
2876 Py_INCREF(Py_None);
2877 PUSH(Py_None);
2878 } else
2879 PUSH(tb);
2880 PUSH(val);
2881 PUSH(exc);
2883 else {
2884 if (why & (WHY_RETURN | WHY_CONTINUE))
2885 PUSH(retval);
2886 v = PyInt_FromLong((long)why);
2887 PUSH(v);
2889 why = WHY_NOT;
2890 JUMPTO(b->b_handler);
2891 break;
2893 } /* unwind stack */
2895 /* End the loop if we still have an error (or return) */
2897 if (why != WHY_NOT)
2898 break;
2899 READ_TIMESTAMP(loop1);
2901 } /* main loop */
2903 assert(why != WHY_YIELD);
2904 /* Pop remaining stack entries. */
2905 while (!EMPTY()) {
2906 v = POP();
2907 Py_XDECREF(v);
2910 if (why != WHY_RETURN)
2911 retval = NULL;
2913 fast_yield:
2914 if (tstate->use_tracing) {
2915 if (tstate->c_tracefunc) {
2916 if (why == WHY_RETURN || why == WHY_YIELD) {
2917 if (call_trace(tstate->c_tracefunc,
2918 tstate->c_traceobj, f,
2919 PyTrace_RETURN, retval)) {
2920 Py_XDECREF(retval);
2921 retval = NULL;
2922 why = WHY_EXCEPTION;
2925 else if (why == WHY_EXCEPTION) {
2926 call_trace_protected(tstate->c_tracefunc,
2927 tstate->c_traceobj, f,
2928 PyTrace_RETURN, NULL);
2931 if (tstate->c_profilefunc) {
2932 if (why == WHY_EXCEPTION)
2933 call_trace_protected(tstate->c_profilefunc,
2934 tstate->c_profileobj, f,
2935 PyTrace_RETURN, NULL);
2936 else if (call_trace(tstate->c_profilefunc,
2937 tstate->c_profileobj, f,
2938 PyTrace_RETURN, retval)) {
2939 Py_XDECREF(retval);
2940 retval = NULL;
2941 why = WHY_EXCEPTION;
2946 if (tstate->frame->f_exc_type != NULL)
2947 reset_exc_info(tstate);
2948 else {
2949 assert(tstate->frame->f_exc_value == NULL);
2950 assert(tstate->frame->f_exc_traceback == NULL);
2953 /* pop frame */
2954 exit_eval_frame:
2955 Py_LeaveRecursiveCall();
2956 tstate->frame = f->f_back;
2958 return retval;
2961 /* This is gonna seem *real weird*, but if you put some other code between
2962 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
2963 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
2965 PyObject *
2966 PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals,
2967 PyObject **args, int argcount, PyObject **kws, int kwcount,
2968 PyObject **defs, int defcount, PyObject *closure)
2970 register PyFrameObject *f;
2971 register PyObject *retval = NULL;
2972 register PyObject **fastlocals, **freevars;
2973 PyThreadState *tstate = PyThreadState_GET();
2974 PyObject *x, *u;
2976 if (globals == NULL) {
2977 PyErr_SetString(PyExc_SystemError,
2978 "PyEval_EvalCodeEx: NULL globals");
2979 return NULL;
2982 assert(tstate != NULL);
2983 assert(globals != NULL);
2984 f = PyFrame_New(tstate, co, globals, locals);
2985 if (f == NULL)
2986 return NULL;
2988 fastlocals = f->f_localsplus;
2989 freevars = f->f_localsplus + co->co_nlocals;
2991 if (co->co_argcount > 0 ||
2992 co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
2993 int i;
2994 int n = argcount;
2995 PyObject *kwdict = NULL;
2996 if (co->co_flags & CO_VARKEYWORDS) {
2997 kwdict = PyDict_New();
2998 if (kwdict == NULL)
2999 goto fail;
3000 i = co->co_argcount;
3001 if (co->co_flags & CO_VARARGS)
3002 i++;
3003 SETLOCAL(i, kwdict);
3005 if (argcount > co->co_argcount) {
3006 if (!(co->co_flags & CO_VARARGS)) {
3007 PyErr_Format(PyExc_TypeError,
3008 "%.200s() takes %s %d "
3009 "%sargument%s (%d given)",
3010 PyString_AsString(co->co_name),
3011 defcount ? "at most" : "exactly",
3012 co->co_argcount,
3013 kwcount ? "non-keyword " : "",
3014 co->co_argcount == 1 ? "" : "s",
3015 argcount);
3016 goto fail;
3018 n = co->co_argcount;
3020 for (i = 0; i < n; i++) {
3021 x = args[i];
3022 Py_INCREF(x);
3023 SETLOCAL(i, x);
3025 if (co->co_flags & CO_VARARGS) {
3026 u = PyTuple_New(argcount - n);
3027 if (u == NULL)
3028 goto fail;
3029 SETLOCAL(co->co_argcount, u);
3030 for (i = n; i < argcount; i++) {
3031 x = args[i];
3032 Py_INCREF(x);
3033 PyTuple_SET_ITEM(u, i-n, x);
3036 for (i = 0; i < kwcount; i++) {
3037 PyObject **co_varnames;
3038 PyObject *keyword = kws[2*i];
3039 PyObject *value = kws[2*i + 1];
3040 int j;
3041 if (keyword == NULL || !(PyString_Check(keyword)
3042 #ifdef Py_USING_UNICODE
3043 || PyUnicode_Check(keyword)
3044 #endif
3045 )) {
3046 PyErr_Format(PyExc_TypeError,
3047 "%.200s() keywords must be strings",
3048 PyString_AsString(co->co_name));
3049 goto fail;
3051 /* Speed hack: do raw pointer compares. As names are
3052 normally interned this should almost always hit. */
3053 co_varnames = PySequence_Fast_ITEMS(co->co_varnames);
3054 for (j = 0; j < co->co_argcount; j++) {
3055 PyObject *nm = co_varnames[j];
3056 if (nm == keyword)
3057 goto kw_found;
3059 /* Slow fallback, just in case */
3060 for (j = 0; j < co->co_argcount; j++) {
3061 PyObject *nm = co_varnames[j];
3062 int cmp = PyObject_RichCompareBool(
3063 keyword, nm, Py_EQ);
3064 if (cmp > 0)
3065 goto kw_found;
3066 else if (cmp < 0)
3067 goto fail;
3069 /* Check errors from Compare */
3070 if (PyErr_Occurred())
3071 goto fail;
3072 if (j >= co->co_argcount) {
3073 if (kwdict == NULL) {
3074 PyObject *kwd_str = kwd_as_string(keyword);
3075 if (kwd_str) {
3076 PyErr_Format(PyExc_TypeError,
3077 "%.200s() got an unexpected "
3078 "keyword argument '%.400s'",
3079 PyString_AsString(co->co_name),
3080 PyString_AsString(kwd_str));
3081 Py_DECREF(kwd_str);
3083 goto fail;
3085 PyDict_SetItem(kwdict, keyword, value);
3086 continue;
3088 kw_found:
3089 if (GETLOCAL(j) != NULL) {
3090 PyObject *kwd_str = kwd_as_string(keyword);
3091 if (kwd_str) {
3092 PyErr_Format(PyExc_TypeError,
3093 "%.200s() got multiple "
3094 "values for keyword "
3095 "argument '%.400s'",
3096 PyString_AsString(co->co_name),
3097 PyString_AsString(kwd_str));
3098 Py_DECREF(kwd_str);
3100 goto fail;
3102 Py_INCREF(value);
3103 SETLOCAL(j, value);
3105 if (argcount < co->co_argcount) {
3106 int m = co->co_argcount - defcount;
3107 for (i = argcount; i < m; i++) {
3108 if (GETLOCAL(i) == NULL) {
3109 PyErr_Format(PyExc_TypeError,
3110 "%.200s() takes %s %d "
3111 "%sargument%s (%d given)",
3112 PyString_AsString(co->co_name),
3113 ((co->co_flags & CO_VARARGS) ||
3114 defcount) ? "at least"
3115 : "exactly",
3116 m, kwcount ? "non-keyword " : "",
3117 m == 1 ? "" : "s", i);
3118 goto fail;
3121 if (n > m)
3122 i = n - m;
3123 else
3124 i = 0;
3125 for (; i < defcount; i++) {
3126 if (GETLOCAL(m+i) == NULL) {
3127 PyObject *def = defs[i];
3128 Py_INCREF(def);
3129 SETLOCAL(m+i, def);
3134 else {
3135 if (argcount > 0 || kwcount > 0) {
3136 PyErr_Format(PyExc_TypeError,
3137 "%.200s() takes no arguments (%d given)",
3138 PyString_AsString(co->co_name),
3139 argcount + kwcount);
3140 goto fail;
3143 /* Allocate and initialize storage for cell vars, and copy free
3144 vars into frame. This isn't too efficient right now. */
3145 if (PyTuple_GET_SIZE(co->co_cellvars)) {
3146 int i, j, nargs, found;
3147 char *cellname, *argname;
3148 PyObject *c;
3150 nargs = co->co_argcount;
3151 if (co->co_flags & CO_VARARGS)
3152 nargs++;
3153 if (co->co_flags & CO_VARKEYWORDS)
3154 nargs++;
3156 /* Initialize each cell var, taking into account
3157 cell vars that are initialized from arguments.
3159 Should arrange for the compiler to put cellvars
3160 that are arguments at the beginning of the cellvars
3161 list so that we can march over it more efficiently?
3163 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
3164 cellname = PyString_AS_STRING(
3165 PyTuple_GET_ITEM(co->co_cellvars, i));
3166 found = 0;
3167 for (j = 0; j < nargs; j++) {
3168 argname = PyString_AS_STRING(
3169 PyTuple_GET_ITEM(co->co_varnames, j));
3170 if (strcmp(cellname, argname) == 0) {
3171 c = PyCell_New(GETLOCAL(j));
3172 if (c == NULL)
3173 goto fail;
3174 GETLOCAL(co->co_nlocals + i) = c;
3175 found = 1;
3176 break;
3179 if (found == 0) {
3180 c = PyCell_New(NULL);
3181 if (c == NULL)
3182 goto fail;
3183 SETLOCAL(co->co_nlocals + i, c);
3187 if (PyTuple_GET_SIZE(co->co_freevars)) {
3188 int i;
3189 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
3190 PyObject *o = PyTuple_GET_ITEM(closure, i);
3191 Py_INCREF(o);
3192 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
3196 if (co->co_flags & CO_GENERATOR) {
3197 /* Don't need to keep the reference to f_back, it will be set
3198 * when the generator is resumed. */
3199 Py_XDECREF(f->f_back);
3200 f->f_back = NULL;
3202 PCALL(PCALL_GENERATOR);
3204 /* Create a new generator that owns the ready to run frame
3205 * and return that as the value. */
3206 return PyGen_New(f);
3209 retval = PyEval_EvalFrameEx(f,0);
3211 fail: /* Jump here from prelude on failure */
3213 /* decref'ing the frame can cause __del__ methods to get invoked,
3214 which can call back into Python. While we're done with the
3215 current Python frame (f), the associated C stack is still in use,
3216 so recursion_depth must be boosted for the duration.
3218 assert(tstate != NULL);
3219 ++tstate->recursion_depth;
3220 Py_DECREF(f);
3221 --tstate->recursion_depth;
3222 return retval;
3226 static PyObject *
3227 special_lookup(PyObject *o, char *meth, PyObject **cache)
3229 PyObject *res;
3230 if (PyInstance_Check(o)) {
3231 if (!*cache)
3232 return PyObject_GetAttrString(o, meth);
3233 else
3234 return PyObject_GetAttr(o, *cache);
3236 res = _PyObject_LookupSpecial(o, meth, cache);
3237 if (res == NULL && !PyErr_Occurred()) {
3238 PyErr_SetObject(PyExc_AttributeError, *cache);
3239 return NULL;
3241 return res;
3245 static PyObject *
3246 kwd_as_string(PyObject *kwd) {
3247 #ifdef Py_USING_UNICODE
3248 if (PyString_Check(kwd)) {
3249 #else
3250 assert(PyString_Check(kwd));
3251 #endif
3252 Py_INCREF(kwd);
3253 return kwd;
3254 #ifdef Py_USING_UNICODE
3256 return _PyUnicode_AsDefaultEncodedString(kwd, "replace");
3257 #endif
3261 /* Implementation notes for set_exc_info() and reset_exc_info():
3263 - Below, 'exc_ZZZ' stands for 'exc_type', 'exc_value' and
3264 'exc_traceback'. These always travel together.
3266 - tstate->curexc_ZZZ is the "hot" exception that is set by
3267 PyErr_SetString(), cleared by PyErr_Clear(), and so on.
3269 - Once an exception is caught by an except clause, it is transferred
3270 from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info()
3271 can pick it up. This is the primary task of set_exc_info().
3272 XXX That can't be right: set_exc_info() doesn't look at tstate->curexc_ZZZ.
3274 - Now let me explain the complicated dance with frame->f_exc_ZZZ.
3276 Long ago, when none of this existed, there were just a few globals:
3277 one set corresponding to the "hot" exception, and one set
3278 corresponding to sys.exc_ZZZ. (Actually, the latter weren't C
3279 globals; they were simply stored as sys.exc_ZZZ. For backwards
3280 compatibility, they still are!) The problem was that in code like
3281 this:
3283 try:
3284 "something that may fail"
3285 except "some exception":
3286 "do something else first"
3287 "print the exception from sys.exc_ZZZ."
3289 if "do something else first" invoked something that raised and caught
3290 an exception, sys.exc_ZZZ were overwritten. That was a frequent
3291 cause of subtle bugs. I fixed this by changing the semantics as
3292 follows:
3294 - Within one frame, sys.exc_ZZZ will hold the last exception caught
3295 *in that frame*.
3297 - But initially, and as long as no exception is caught in a given
3298 frame, sys.exc_ZZZ will hold the last exception caught in the
3299 previous frame (or the frame before that, etc.).
3301 The first bullet fixed the bug in the above example. The second
3302 bullet was for backwards compatibility: it was (and is) common to
3303 have a function that is called when an exception is caught, and to
3304 have that function access the caught exception via sys.exc_ZZZ.
3305 (Example: traceback.print_exc()).
3307 At the same time I fixed the problem that sys.exc_ZZZ weren't
3308 thread-safe, by introducing sys.exc_info() which gets it from tstate;
3309 but that's really a separate improvement.
3311 The reset_exc_info() function in ceval.c restores the tstate->exc_ZZZ
3312 variables to what they were before the current frame was called. The
3313 set_exc_info() function saves them on the frame so that
3314 reset_exc_info() can restore them. The invariant is that
3315 frame->f_exc_ZZZ is NULL iff the current frame never caught an
3316 exception (where "catching" an exception applies only to successful
3317 except clauses); and if the current frame ever caught an exception,
3318 frame->f_exc_ZZZ is the exception that was stored in tstate->exc_ZZZ
3319 at the start of the current frame.
3323 static void
3324 set_exc_info(PyThreadState *tstate,
3325 PyObject *type, PyObject *value, PyObject *tb)
3327 PyFrameObject *frame = tstate->frame;
3328 PyObject *tmp_type, *tmp_value, *tmp_tb;
3330 assert(type != NULL);
3331 assert(frame != NULL);
3332 if (frame->f_exc_type == NULL) {
3333 assert(frame->f_exc_value == NULL);
3334 assert(frame->f_exc_traceback == NULL);
3335 /* This frame didn't catch an exception before. */
3336 /* Save previous exception of this thread in this frame. */
3337 if (tstate->exc_type == NULL) {
3338 /* XXX Why is this set to Py_None? */
3339 Py_INCREF(Py_None);
3340 tstate->exc_type = Py_None;
3342 Py_INCREF(tstate->exc_type);
3343 Py_XINCREF(tstate->exc_value);
3344 Py_XINCREF(tstate->exc_traceback);
3345 frame->f_exc_type = tstate->exc_type;
3346 frame->f_exc_value = tstate->exc_value;
3347 frame->f_exc_traceback = tstate->exc_traceback;
3349 /* Set new exception for this thread. */
3350 tmp_type = tstate->exc_type;
3351 tmp_value = tstate->exc_value;
3352 tmp_tb = tstate->exc_traceback;
3353 Py_INCREF(type);
3354 Py_XINCREF(value);
3355 Py_XINCREF(tb);
3356 tstate->exc_type = type;
3357 tstate->exc_value = value;
3358 tstate->exc_traceback = tb;
3359 Py_XDECREF(tmp_type);
3360 Py_XDECREF(tmp_value);
3361 Py_XDECREF(tmp_tb);
3362 /* For b/w compatibility */
3363 PySys_SetObject("exc_type", type);
3364 PySys_SetObject("exc_value", value);
3365 PySys_SetObject("exc_traceback", tb);
3368 static void
3369 reset_exc_info(PyThreadState *tstate)
3371 PyFrameObject *frame;
3372 PyObject *tmp_type, *tmp_value, *tmp_tb;
3374 /* It's a precondition that the thread state's frame caught an
3375 * exception -- verify in a debug build.
3377 assert(tstate != NULL);
3378 frame = tstate->frame;
3379 assert(frame != NULL);
3380 assert(frame->f_exc_type != NULL);
3382 /* Copy the frame's exception info back to the thread state. */
3383 tmp_type = tstate->exc_type;
3384 tmp_value = tstate->exc_value;
3385 tmp_tb = tstate->exc_traceback;
3386 Py_INCREF(frame->f_exc_type);
3387 Py_XINCREF(frame->f_exc_value);
3388 Py_XINCREF(frame->f_exc_traceback);
3389 tstate->exc_type = frame->f_exc_type;
3390 tstate->exc_value = frame->f_exc_value;
3391 tstate->exc_traceback = frame->f_exc_traceback;
3392 Py_XDECREF(tmp_type);
3393 Py_XDECREF(tmp_value);
3394 Py_XDECREF(tmp_tb);
3396 /* For b/w compatibility */
3397 PySys_SetObject("exc_type", frame->f_exc_type);
3398 PySys_SetObject("exc_value", frame->f_exc_value);
3399 PySys_SetObject("exc_traceback", frame->f_exc_traceback);
3401 /* Clear the frame's exception info. */
3402 tmp_type = frame->f_exc_type;
3403 tmp_value = frame->f_exc_value;
3404 tmp_tb = frame->f_exc_traceback;
3405 frame->f_exc_type = NULL;
3406 frame->f_exc_value = NULL;
3407 frame->f_exc_traceback = NULL;
3408 Py_DECREF(tmp_type);
3409 Py_XDECREF(tmp_value);
3410 Py_XDECREF(tmp_tb);
3413 /* Logic for the raise statement (too complicated for inlining).
3414 This *consumes* a reference count to each of its arguments. */
3415 static enum why_code
3416 do_raise(PyObject *type, PyObject *value, PyObject *tb)
3418 if (type == NULL) {
3419 /* Reraise */
3420 PyThreadState *tstate = PyThreadState_GET();
3421 type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
3422 value = tstate->exc_value;
3423 tb = tstate->exc_traceback;
3424 Py_XINCREF(type);
3425 Py_XINCREF(value);
3426 Py_XINCREF(tb);
3429 /* We support the following forms of raise:
3430 raise <class>, <classinstance>
3431 raise <class>, <argument tuple>
3432 raise <class>, None
3433 raise <class>, <argument>
3434 raise <classinstance>, None
3435 raise <string>, <object>
3436 raise <string>, None
3438 An omitted second argument is the same as None.
3440 In addition, raise <tuple>, <anything> is the same as
3441 raising the tuple's first item (and it better have one!);
3442 this rule is applied recursively.
3444 Finally, an optional third argument can be supplied, which
3445 gives the traceback to be substituted (useful when
3446 re-raising an exception after examining it). */
3448 /* First, check the traceback argument, replacing None with
3449 NULL. */
3450 if (tb == Py_None) {
3451 Py_DECREF(tb);
3452 tb = NULL;
3454 else if (tb != NULL && !PyTraceBack_Check(tb)) {
3455 PyErr_SetString(PyExc_TypeError,
3456 "raise: arg 3 must be a traceback or None");
3457 goto raise_error;
3460 /* Next, replace a missing value with None */
3461 if (value == NULL) {
3462 value = Py_None;
3463 Py_INCREF(value);
3466 /* Next, repeatedly, replace a tuple exception with its first item */
3467 while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
3468 PyObject *tmp = type;
3469 type = PyTuple_GET_ITEM(type, 0);
3470 Py_INCREF(type);
3471 Py_DECREF(tmp);
3474 if (PyExceptionClass_Check(type))
3475 PyErr_NormalizeException(&type, &value, &tb);
3477 else if (PyExceptionInstance_Check(type)) {
3478 /* Raising an instance. The value should be a dummy. */
3479 if (value != Py_None) {
3480 PyErr_SetString(PyExc_TypeError,
3481 "instance exception may not have a separate value");
3482 goto raise_error;
3484 else {
3485 /* Normalize to raise <class>, <instance> */
3486 Py_DECREF(value);
3487 value = type;
3488 type = PyExceptionInstance_Class(type);
3489 Py_INCREF(type);
3492 else {
3493 /* Not something you can raise. You get an exception
3494 anyway, just not what you specified :-) */
3495 PyErr_Format(PyExc_TypeError,
3496 "exceptions must be classes or instances, not %s",
3497 type->ob_type->tp_name);
3498 goto raise_error;
3501 assert(PyExceptionClass_Check(type));
3502 if (Py_Py3kWarningFlag && PyClass_Check(type)) {
3503 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3504 "exceptions must derive from BaseException "
3505 "in 3.x", 1) < 0)
3506 goto raise_error;
3509 PyErr_Restore(type, value, tb);
3510 if (tb == NULL)
3511 return WHY_EXCEPTION;
3512 else
3513 return WHY_RERAISE;
3514 raise_error:
3515 Py_XDECREF(value);
3516 Py_XDECREF(type);
3517 Py_XDECREF(tb);
3518 return WHY_EXCEPTION;
3521 /* Iterate v argcnt times and store the results on the stack (via decreasing
3522 sp). Return 1 for success, 0 if error. */
3524 static int
3525 unpack_iterable(PyObject *v, int argcnt, PyObject **sp)
3527 int i = 0;
3528 PyObject *it; /* iter(v) */
3529 PyObject *w;
3531 assert(v != NULL);
3533 it = PyObject_GetIter(v);
3534 if (it == NULL)
3535 goto Error;
3537 for (; i < argcnt; i++) {
3538 w = PyIter_Next(it);
3539 if (w == NULL) {
3540 /* Iterator done, via error or exhaustion. */
3541 if (!PyErr_Occurred()) {
3542 PyErr_Format(PyExc_ValueError,
3543 "need more than %d value%s to unpack",
3544 i, i == 1 ? "" : "s");
3546 goto Error;
3548 *--sp = w;
3551 /* We better have exhausted the iterator now. */
3552 w = PyIter_Next(it);
3553 if (w == NULL) {
3554 if (PyErr_Occurred())
3555 goto Error;
3556 Py_DECREF(it);
3557 return 1;
3559 Py_DECREF(w);
3560 PyErr_SetString(PyExc_ValueError, "too many values to unpack");
3561 /* fall through */
3562 Error:
3563 for (; i > 0; i--, sp++)
3564 Py_DECREF(*sp);
3565 Py_XDECREF(it);
3566 return 0;
3570 #ifdef LLTRACE
3571 static int
3572 prtrace(PyObject *v, char *str)
3574 printf("%s ", str);
3575 if (PyObject_Print(v, stdout, 0) != 0)
3576 PyErr_Clear(); /* Don't know what else to do */
3577 printf("\n");
3578 return 1;
3580 #endif
3582 static void
3583 call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
3585 PyObject *type, *value, *traceback, *arg;
3586 int err;
3587 PyErr_Fetch(&type, &value, &traceback);
3588 if (value == NULL) {
3589 value = Py_None;
3590 Py_INCREF(value);
3592 arg = PyTuple_Pack(3, type, value, traceback);
3593 if (arg == NULL) {
3594 PyErr_Restore(type, value, traceback);
3595 return;
3597 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
3598 Py_DECREF(arg);
3599 if (err == 0)
3600 PyErr_Restore(type, value, traceback);
3601 else {
3602 Py_XDECREF(type);
3603 Py_XDECREF(value);
3604 Py_XDECREF(traceback);
3608 static int
3609 call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
3610 int what, PyObject *arg)
3612 PyObject *type, *value, *traceback;
3613 int err;
3614 PyErr_Fetch(&type, &value, &traceback);
3615 err = call_trace(func, obj, frame, what, arg);
3616 if (err == 0)
3618 PyErr_Restore(type, value, traceback);
3619 return 0;
3621 else {
3622 Py_XDECREF(type);
3623 Py_XDECREF(value);
3624 Py_XDECREF(traceback);
3625 return -1;
3629 static int
3630 call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
3631 int what, PyObject *arg)
3633 register PyThreadState *tstate = frame->f_tstate;
3634 int result;
3635 if (tstate->tracing)
3636 return 0;
3637 tstate->tracing++;
3638 tstate->use_tracing = 0;
3639 result = func(obj, frame, what, arg);
3640 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3641 || (tstate->c_profilefunc != NULL));
3642 tstate->tracing--;
3643 return result;
3646 PyObject *
3647 _PyEval_CallTracing(PyObject *func, PyObject *args)
3649 PyFrameObject *frame = PyEval_GetFrame();
3650 PyThreadState *tstate = frame->f_tstate;
3651 int save_tracing = tstate->tracing;
3652 int save_use_tracing = tstate->use_tracing;
3653 PyObject *result;
3655 tstate->tracing = 0;
3656 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3657 || (tstate->c_profilefunc != NULL));
3658 result = PyObject_Call(func, args, NULL);
3659 tstate->tracing = save_tracing;
3660 tstate->use_tracing = save_use_tracing;
3661 return result;
3664 /* See Objects/lnotab_notes.txt for a description of how tracing works. */
3665 static int
3666 maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
3667 PyFrameObject *frame, int *instr_lb, int *instr_ub,
3668 int *instr_prev)
3670 int result = 0;
3671 int line = frame->f_lineno;
3673 /* If the last instruction executed isn't in the current
3674 instruction window, reset the window.
3676 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
3677 PyAddrPair bounds;
3678 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
3679 &bounds);
3680 *instr_lb = bounds.ap_lower;
3681 *instr_ub = bounds.ap_upper;
3683 /* If the last instruction falls at the start of a line or if
3684 it represents a jump backwards, update the frame's line
3685 number and call the trace function. */
3686 if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
3687 frame->f_lineno = line;
3688 result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
3690 *instr_prev = frame->f_lasti;
3691 return result;
3694 void
3695 PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
3697 PyThreadState *tstate = PyThreadState_GET();
3698 PyObject *temp = tstate->c_profileobj;
3699 Py_XINCREF(arg);
3700 tstate->c_profilefunc = NULL;
3701 tstate->c_profileobj = NULL;
3702 /* Must make sure that tracing is not ignored if 'temp' is freed */
3703 tstate->use_tracing = tstate->c_tracefunc != NULL;
3704 Py_XDECREF(temp);
3705 tstate->c_profilefunc = func;
3706 tstate->c_profileobj = arg;
3707 /* Flag that tracing or profiling is turned on */
3708 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
3711 void
3712 PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
3714 PyThreadState *tstate = PyThreadState_GET();
3715 PyObject *temp = tstate->c_traceobj;
3716 _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
3717 Py_XINCREF(arg);
3718 tstate->c_tracefunc = NULL;
3719 tstate->c_traceobj = NULL;
3720 /* Must make sure that profiling is not ignored if 'temp' is freed */
3721 tstate->use_tracing = tstate->c_profilefunc != NULL;
3722 Py_XDECREF(temp);
3723 tstate->c_tracefunc = func;
3724 tstate->c_traceobj = arg;
3725 /* Flag that tracing or profiling is turned on */
3726 tstate->use_tracing = ((func != NULL)
3727 || (tstate->c_profilefunc != NULL));
3730 PyObject *
3731 PyEval_GetBuiltins(void)
3733 PyFrameObject *current_frame = PyEval_GetFrame();
3734 if (current_frame == NULL)
3735 return PyThreadState_GET()->interp->builtins;
3736 else
3737 return current_frame->f_builtins;
3740 PyObject *
3741 PyEval_GetLocals(void)
3743 PyFrameObject *current_frame = PyEval_GetFrame();
3744 if (current_frame == NULL)
3745 return NULL;
3746 PyFrame_FastToLocals(current_frame);
3747 return current_frame->f_locals;
3750 PyObject *
3751 PyEval_GetGlobals(void)
3753 PyFrameObject *current_frame = PyEval_GetFrame();
3754 if (current_frame == NULL)
3755 return NULL;
3756 else
3757 return current_frame->f_globals;
3760 PyFrameObject *
3761 PyEval_GetFrame(void)
3763 PyThreadState *tstate = PyThreadState_GET();
3764 return _PyThreadState_GetFrame(tstate);
3768 PyEval_GetRestricted(void)
3770 PyFrameObject *current_frame = PyEval_GetFrame();
3771 return current_frame == NULL ? 0 : PyFrame_IsRestricted(current_frame);
3775 PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
3777 PyFrameObject *current_frame = PyEval_GetFrame();
3778 int result = cf->cf_flags != 0;
3780 if (current_frame != NULL) {
3781 const int codeflags = current_frame->f_code->co_flags;
3782 const int compilerflags = codeflags & PyCF_MASK;
3783 if (compilerflags) {
3784 result = 1;
3785 cf->cf_flags |= compilerflags;
3787 #if 0 /* future keyword */
3788 if (codeflags & CO_GENERATOR_ALLOWED) {
3789 result = 1;
3790 cf->cf_flags |= CO_GENERATOR_ALLOWED;
3792 #endif
3794 return result;
3798 Py_FlushLine(void)
3800 PyObject *f = PySys_GetObject("stdout");
3801 if (f == NULL)
3802 return 0;
3803 if (!PyFile_SoftSpace(f, 0))
3804 return 0;
3805 return PyFile_WriteString("\n", f);
3809 /* External interface to call any callable object.
3810 The arg must be a tuple or NULL. */
3812 #undef PyEval_CallObject
3813 /* for backward compatibility: export this interface */
3815 PyObject *
3816 PyEval_CallObject(PyObject *func, PyObject *arg)
3818 return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL);
3820 #define PyEval_CallObject(func,arg) \
3821 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
3823 PyObject *
3824 PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
3826 PyObject *result;
3828 if (arg == NULL) {
3829 arg = PyTuple_New(0);
3830 if (arg == NULL)
3831 return NULL;
3833 else if (!PyTuple_Check(arg)) {
3834 PyErr_SetString(PyExc_TypeError,
3835 "argument list must be a tuple");
3836 return NULL;
3838 else
3839 Py_INCREF(arg);
3841 if (kw != NULL && !PyDict_Check(kw)) {
3842 PyErr_SetString(PyExc_TypeError,
3843 "keyword list must be a dictionary");
3844 Py_DECREF(arg);
3845 return NULL;
3848 result = PyObject_Call(func, arg, kw);
3849 Py_DECREF(arg);
3850 return result;
3853 const char *
3854 PyEval_GetFuncName(PyObject *func)
3856 if (PyMethod_Check(func))
3857 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
3858 else if (PyFunction_Check(func))
3859 return PyString_AsString(((PyFunctionObject*)func)->func_name);
3860 else if (PyCFunction_Check(func))
3861 return ((PyCFunctionObject*)func)->m_ml->ml_name;
3862 else if (PyClass_Check(func))
3863 return PyString_AsString(((PyClassObject*)func)->cl_name);
3864 else if (PyInstance_Check(func)) {
3865 return PyString_AsString(
3866 ((PyInstanceObject*)func)->in_class->cl_name);
3867 } else {
3868 return func->ob_type->tp_name;
3872 const char *
3873 PyEval_GetFuncDesc(PyObject *func)
3875 if (PyMethod_Check(func))
3876 return "()";
3877 else if (PyFunction_Check(func))
3878 return "()";
3879 else if (PyCFunction_Check(func))
3880 return "()";
3881 else if (PyClass_Check(func))
3882 return " constructor";
3883 else if (PyInstance_Check(func)) {
3884 return " instance";
3885 } else {
3886 return " object";
3890 static void
3891 err_args(PyObject *func, int flags, int nargs)
3893 if (flags & METH_NOARGS)
3894 PyErr_Format(PyExc_TypeError,
3895 "%.200s() takes no arguments (%d given)",
3896 ((PyCFunctionObject *)func)->m_ml->ml_name,
3897 nargs);
3898 else
3899 PyErr_Format(PyExc_TypeError,
3900 "%.200s() takes exactly one argument (%d given)",
3901 ((PyCFunctionObject *)func)->m_ml->ml_name,
3902 nargs);
3905 #define C_TRACE(x, call) \
3906 if (tstate->use_tracing && tstate->c_profilefunc) { \
3907 if (call_trace(tstate->c_profilefunc, \
3908 tstate->c_profileobj, \
3909 tstate->frame, PyTrace_C_CALL, \
3910 func)) { \
3911 x = NULL; \
3913 else { \
3914 x = call; \
3915 if (tstate->c_profilefunc != NULL) { \
3916 if (x == NULL) { \
3917 call_trace_protected(tstate->c_profilefunc, \
3918 tstate->c_profileobj, \
3919 tstate->frame, PyTrace_C_EXCEPTION, \
3920 func); \
3921 /* XXX should pass (type, value, tb) */ \
3922 } else { \
3923 if (call_trace(tstate->c_profilefunc, \
3924 tstate->c_profileobj, \
3925 tstate->frame, PyTrace_C_RETURN, \
3926 func)) { \
3927 Py_DECREF(x); \
3928 x = NULL; \
3933 } else { \
3934 x = call; \
3937 static PyObject *
3938 call_function(PyObject ***pp_stack, int oparg
3939 #ifdef WITH_TSC
3940 , uint64* pintr0, uint64* pintr1
3941 #endif
3944 int na = oparg & 0xff;
3945 int nk = (oparg>>8) & 0xff;
3946 int n = na + 2 * nk;
3947 PyObject **pfunc = (*pp_stack) - n - 1;
3948 PyObject *func = *pfunc;
3949 PyObject *x, *w;
3951 /* Always dispatch PyCFunction first, because these are
3952 presumed to be the most frequent callable object.
3954 if (PyCFunction_Check(func) && nk == 0) {
3955 int flags = PyCFunction_GET_FLAGS(func);
3956 PyThreadState *tstate = PyThreadState_GET();
3958 PCALL(PCALL_CFUNCTION);
3959 if (flags & (METH_NOARGS | METH_O)) {
3960 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
3961 PyObject *self = PyCFunction_GET_SELF(func);
3962 if (flags & METH_NOARGS && na == 0) {
3963 C_TRACE(x, (*meth)(self,NULL));
3965 else if (flags & METH_O && na == 1) {
3966 PyObject *arg = EXT_POP(*pp_stack);
3967 C_TRACE(x, (*meth)(self,arg));
3968 Py_DECREF(arg);
3970 else {
3971 err_args(func, flags, na);
3972 x = NULL;
3975 else {
3976 PyObject *callargs;
3977 callargs = load_args(pp_stack, na);
3978 READ_TIMESTAMP(*pintr0);
3979 C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
3980 READ_TIMESTAMP(*pintr1);
3981 Py_XDECREF(callargs);
3983 } else {
3984 if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
3985 /* optimize access to bound methods */
3986 PyObject *self = PyMethod_GET_SELF(func);
3987 PCALL(PCALL_METHOD);
3988 PCALL(PCALL_BOUND_METHOD);
3989 Py_INCREF(self);
3990 func = PyMethod_GET_FUNCTION(func);
3991 Py_INCREF(func);
3992 Py_DECREF(*pfunc);
3993 *pfunc = self;
3994 na++;
3995 n++;
3996 } else
3997 Py_INCREF(func);
3998 READ_TIMESTAMP(*pintr0);
3999 if (PyFunction_Check(func))
4000 x = fast_function(func, pp_stack, n, na, nk);
4001 else
4002 x = do_call(func, pp_stack, na, nk);
4003 READ_TIMESTAMP(*pintr1);
4004 Py_DECREF(func);
4007 /* Clear the stack of the function object. Also removes
4008 the arguments in case they weren't consumed already
4009 (fast_function() and err_args() leave them on the stack).
4011 while ((*pp_stack) > pfunc) {
4012 w = EXT_POP(*pp_stack);
4013 Py_DECREF(w);
4014 PCALL(PCALL_POP);
4016 return x;
4019 /* The fast_function() function optimize calls for which no argument
4020 tuple is necessary; the objects are passed directly from the stack.
4021 For the simplest case -- a function that takes only positional
4022 arguments and is called with only positional arguments -- it
4023 inlines the most primitive frame setup code from
4024 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
4025 done before evaluating the frame.
4028 static PyObject *
4029 fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
4031 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
4032 PyObject *globals = PyFunction_GET_GLOBALS(func);
4033 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
4034 PyObject **d = NULL;
4035 int nd = 0;
4037 PCALL(PCALL_FUNCTION);
4038 PCALL(PCALL_FAST_FUNCTION);
4039 if (argdefs == NULL && co->co_argcount == n && nk==0 &&
4040 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
4041 PyFrameObject *f;
4042 PyObject *retval = NULL;
4043 PyThreadState *tstate = PyThreadState_GET();
4044 PyObject **fastlocals, **stack;
4045 int i;
4047 PCALL(PCALL_FASTER_FUNCTION);
4048 assert(globals != NULL);
4049 /* XXX Perhaps we should create a specialized
4050 PyFrame_New() that doesn't take locals, but does
4051 take builtins without sanity checking them.
4053 assert(tstate != NULL);
4054 f = PyFrame_New(tstate, co, globals, NULL);
4055 if (f == NULL)
4056 return NULL;
4058 fastlocals = f->f_localsplus;
4059 stack = (*pp_stack) - n;
4061 for (i = 0; i < n; i++) {
4062 Py_INCREF(*stack);
4063 fastlocals[i] = *stack++;
4065 retval = PyEval_EvalFrameEx(f,0);
4066 ++tstate->recursion_depth;
4067 Py_DECREF(f);
4068 --tstate->recursion_depth;
4069 return retval;
4071 if (argdefs != NULL) {
4072 d = &PyTuple_GET_ITEM(argdefs, 0);
4073 nd = Py_SIZE(argdefs);
4075 return PyEval_EvalCodeEx(co, globals,
4076 (PyObject *)NULL, (*pp_stack)-n, na,
4077 (*pp_stack)-2*nk, nk, d, nd,
4078 PyFunction_GET_CLOSURE(func));
4081 static PyObject *
4082 update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
4083 PyObject *func)
4085 PyObject *kwdict = NULL;
4086 if (orig_kwdict == NULL)
4087 kwdict = PyDict_New();
4088 else {
4089 kwdict = PyDict_Copy(orig_kwdict);
4090 Py_DECREF(orig_kwdict);
4092 if (kwdict == NULL)
4093 return NULL;
4094 while (--nk >= 0) {
4095 int err;
4096 PyObject *value = EXT_POP(*pp_stack);
4097 PyObject *key = EXT_POP(*pp_stack);
4098 if (PyDict_GetItem(kwdict, key) != NULL) {
4099 PyErr_Format(PyExc_TypeError,
4100 "%.200s%s got multiple values "
4101 "for keyword argument '%.200s'",
4102 PyEval_GetFuncName(func),
4103 PyEval_GetFuncDesc(func),
4104 PyString_AsString(key));
4105 Py_DECREF(key);
4106 Py_DECREF(value);
4107 Py_DECREF(kwdict);
4108 return NULL;
4110 err = PyDict_SetItem(kwdict, key, value);
4111 Py_DECREF(key);
4112 Py_DECREF(value);
4113 if (err) {
4114 Py_DECREF(kwdict);
4115 return NULL;
4118 return kwdict;
4121 static PyObject *
4122 update_star_args(int nstack, int nstar, PyObject *stararg,
4123 PyObject ***pp_stack)
4125 PyObject *callargs, *w;
4127 callargs = PyTuple_New(nstack + nstar);
4128 if (callargs == NULL) {
4129 return NULL;
4131 if (nstar) {
4132 int i;
4133 for (i = 0; i < nstar; i++) {
4134 PyObject *a = PyTuple_GET_ITEM(stararg, i);
4135 Py_INCREF(a);
4136 PyTuple_SET_ITEM(callargs, nstack + i, a);
4139 while (--nstack >= 0) {
4140 w = EXT_POP(*pp_stack);
4141 PyTuple_SET_ITEM(callargs, nstack, w);
4143 return callargs;
4146 static PyObject *
4147 load_args(PyObject ***pp_stack, int na)
4149 PyObject *args = PyTuple_New(na);
4150 PyObject *w;
4152 if (args == NULL)
4153 return NULL;
4154 while (--na >= 0) {
4155 w = EXT_POP(*pp_stack);
4156 PyTuple_SET_ITEM(args, na, w);
4158 return args;
4161 static PyObject *
4162 do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
4164 PyObject *callargs = NULL;
4165 PyObject *kwdict = NULL;
4166 PyObject *result = NULL;
4168 if (nk > 0) {
4169 kwdict = update_keyword_args(NULL, nk, pp_stack, func);
4170 if (kwdict == NULL)
4171 goto call_fail;
4173 callargs = load_args(pp_stack, na);
4174 if (callargs == NULL)
4175 goto call_fail;
4176 #ifdef CALL_PROFILE
4177 /* At this point, we have to look at the type of func to
4178 update the call stats properly. Do it here so as to avoid
4179 exposing the call stats machinery outside ceval.c
4181 if (PyFunction_Check(func))
4182 PCALL(PCALL_FUNCTION);
4183 else if (PyMethod_Check(func))
4184 PCALL(PCALL_METHOD);
4185 else if (PyType_Check(func))
4186 PCALL(PCALL_TYPE);
4187 else if (PyCFunction_Check(func))
4188 PCALL(PCALL_CFUNCTION);
4189 else
4190 PCALL(PCALL_OTHER);
4191 #endif
4192 if (PyCFunction_Check(func)) {
4193 PyThreadState *tstate = PyThreadState_GET();
4194 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4196 else
4197 result = PyObject_Call(func, callargs, kwdict);
4198 call_fail:
4199 Py_XDECREF(callargs);
4200 Py_XDECREF(kwdict);
4201 return result;
4204 static PyObject *
4205 ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
4207 int nstar = 0;
4208 PyObject *callargs = NULL;
4209 PyObject *stararg = NULL;
4210 PyObject *kwdict = NULL;
4211 PyObject *result = NULL;
4213 if (flags & CALL_FLAG_KW) {
4214 kwdict = EXT_POP(*pp_stack);
4215 if (!PyDict_Check(kwdict)) {
4216 PyObject *d;
4217 d = PyDict_New();
4218 if (d == NULL)
4219 goto ext_call_fail;
4220 if (PyDict_Update(d, kwdict) != 0) {
4221 Py_DECREF(d);
4222 /* PyDict_Update raises attribute
4223 * error (percolated from an attempt
4224 * to get 'keys' attribute) instead of
4225 * a type error if its second argument
4226 * is not a mapping.
4228 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
4229 PyErr_Format(PyExc_TypeError,
4230 "%.200s%.200s argument after ** "
4231 "must be a mapping, not %.200s",
4232 PyEval_GetFuncName(func),
4233 PyEval_GetFuncDesc(func),
4234 kwdict->ob_type->tp_name);
4236 goto ext_call_fail;
4238 Py_DECREF(kwdict);
4239 kwdict = d;
4242 if (flags & CALL_FLAG_VAR) {
4243 stararg = EXT_POP(*pp_stack);
4244 if (!PyTuple_Check(stararg)) {
4245 PyObject *t = NULL;
4246 t = PySequence_Tuple(stararg);
4247 if (t == NULL) {
4248 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4249 PyErr_Format(PyExc_TypeError,
4250 "%.200s%.200s argument after * "
4251 "must be a sequence, not %200s",
4252 PyEval_GetFuncName(func),
4253 PyEval_GetFuncDesc(func),
4254 stararg->ob_type->tp_name);
4256 goto ext_call_fail;
4258 Py_DECREF(stararg);
4259 stararg = t;
4261 nstar = PyTuple_GET_SIZE(stararg);
4263 if (nk > 0) {
4264 kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
4265 if (kwdict == NULL)
4266 goto ext_call_fail;
4268 callargs = update_star_args(na, nstar, stararg, pp_stack);
4269 if (callargs == NULL)
4270 goto ext_call_fail;
4271 #ifdef CALL_PROFILE
4272 /* At this point, we have to look at the type of func to
4273 update the call stats properly. Do it here so as to avoid
4274 exposing the call stats machinery outside ceval.c
4276 if (PyFunction_Check(func))
4277 PCALL(PCALL_FUNCTION);
4278 else if (PyMethod_Check(func))
4279 PCALL(PCALL_METHOD);
4280 else if (PyType_Check(func))
4281 PCALL(PCALL_TYPE);
4282 else if (PyCFunction_Check(func))
4283 PCALL(PCALL_CFUNCTION);
4284 else
4285 PCALL(PCALL_OTHER);
4286 #endif
4287 if (PyCFunction_Check(func)) {
4288 PyThreadState *tstate = PyThreadState_GET();
4289 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
4291 else
4292 result = PyObject_Call(func, callargs, kwdict);
4293 ext_call_fail:
4294 Py_XDECREF(callargs);
4295 Py_XDECREF(kwdict);
4296 Py_XDECREF(stararg);
4297 return result;
4300 /* Extract a slice index from a PyInt or PyLong or an object with the
4301 nb_index slot defined, and store in *pi.
4302 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
4303 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
4304 Return 0 on error, 1 on success.
4306 /* Note: If v is NULL, return success without storing into *pi. This
4307 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
4308 called by the SLICE opcode with v and/or w equal to NULL.
4311 _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
4313 if (v != NULL) {
4314 Py_ssize_t x;
4315 if (PyInt_Check(v)) {
4316 /* XXX(nnorwitz): I think PyInt_AS_LONG is correct,
4317 however, it looks like it should be AsSsize_t.
4318 There should be a comment here explaining why.
4320 x = PyInt_AS_LONG(v);
4322 else if (PyIndex_Check(v)) {
4323 x = PyNumber_AsSsize_t(v, NULL);
4324 if (x == -1 && PyErr_Occurred())
4325 return 0;
4327 else {
4328 PyErr_SetString(PyExc_TypeError,
4329 "slice indices must be integers or "
4330 "None or have an __index__ method");
4331 return 0;
4333 *pi = x;
4335 return 1;
4338 #undef ISINDEX
4339 #define ISINDEX(x) ((x) == NULL || \
4340 PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
4342 static PyObject *
4343 apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
4345 PyTypeObject *tp = u->ob_type;
4346 PySequenceMethods *sq = tp->tp_as_sequence;
4348 if (sq && sq->sq_slice && ISINDEX(v) && ISINDEX(w)) {
4349 Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
4350 if (!_PyEval_SliceIndex(v, &ilow))
4351 return NULL;
4352 if (!_PyEval_SliceIndex(w, &ihigh))
4353 return NULL;
4354 return PySequence_GetSlice(u, ilow, ihigh);
4356 else {
4357 PyObject *slice = PySlice_New(v, w, NULL);
4358 if (slice != NULL) {
4359 PyObject *res = PyObject_GetItem(u, slice);
4360 Py_DECREF(slice);
4361 return res;
4363 else
4364 return NULL;
4368 static int
4369 assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x)
4370 /* u[v:w] = x */
4372 PyTypeObject *tp = u->ob_type;
4373 PySequenceMethods *sq = tp->tp_as_sequence;
4375 if (sq && sq->sq_ass_slice && ISINDEX(v) && ISINDEX(w)) {
4376 Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
4377 if (!_PyEval_SliceIndex(v, &ilow))
4378 return -1;
4379 if (!_PyEval_SliceIndex(w, &ihigh))
4380 return -1;
4381 if (x == NULL)
4382 return PySequence_DelSlice(u, ilow, ihigh);
4383 else
4384 return PySequence_SetSlice(u, ilow, ihigh, x);
4386 else {
4387 PyObject *slice = PySlice_New(v, w, NULL);
4388 if (slice != NULL) {
4389 int res;
4390 if (x != NULL)
4391 res = PyObject_SetItem(u, slice, x);
4392 else
4393 res = PyObject_DelItem(u, slice);
4394 Py_DECREF(slice);
4395 return res;
4397 else
4398 return -1;
4402 #define Py3kExceptionClass_Check(x) \
4403 (PyType_Check((x)) && \
4404 PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
4406 #define CANNOT_CATCH_MSG "catching classes that don't inherit from " \
4407 "BaseException is not allowed in 3.x"
4409 static PyObject *
4410 cmp_outcome(int op, register PyObject *v, register PyObject *w)
4412 int res = 0;
4413 switch (op) {
4414 case PyCmp_IS:
4415 res = (v == w);
4416 break;
4417 case PyCmp_IS_NOT:
4418 res = (v != w);
4419 break;
4420 case PyCmp_IN:
4421 res = PySequence_Contains(w, v);
4422 if (res < 0)
4423 return NULL;
4424 break;
4425 case PyCmp_NOT_IN:
4426 res = PySequence_Contains(w, v);
4427 if (res < 0)
4428 return NULL;
4429 res = !res;
4430 break;
4431 case PyCmp_EXC_MATCH:
4432 if (PyTuple_Check(w)) {
4433 Py_ssize_t i, length;
4434 length = PyTuple_Size(w);
4435 for (i = 0; i < length; i += 1) {
4436 PyObject *exc = PyTuple_GET_ITEM(w, i);
4437 if (PyString_Check(exc)) {
4438 int ret_val;
4439 ret_val = PyErr_WarnEx(
4440 PyExc_DeprecationWarning,
4441 "catching of string "
4442 "exceptions is deprecated", 1);
4443 if (ret_val < 0)
4444 return NULL;
4446 else if (Py_Py3kWarningFlag &&
4447 !PyTuple_Check(exc) &&
4448 !Py3kExceptionClass_Check(exc))
4450 int ret_val;
4451 ret_val = PyErr_WarnEx(
4452 PyExc_DeprecationWarning,
4453 CANNOT_CATCH_MSG, 1);
4454 if (ret_val < 0)
4455 return NULL;
4459 else {
4460 if (PyString_Check(w)) {
4461 int ret_val;
4462 ret_val = PyErr_WarnEx(
4463 PyExc_DeprecationWarning,
4464 "catching of string "
4465 "exceptions is deprecated", 1);
4466 if (ret_val < 0)
4467 return NULL;
4469 else if (Py_Py3kWarningFlag &&
4470 !PyTuple_Check(w) &&
4471 !Py3kExceptionClass_Check(w))
4473 int ret_val;
4474 ret_val = PyErr_WarnEx(
4475 PyExc_DeprecationWarning,
4476 CANNOT_CATCH_MSG, 1);
4477 if (ret_val < 0)
4478 return NULL;
4481 res = PyErr_GivenExceptionMatches(v, w);
4482 break;
4483 default:
4484 return PyObject_RichCompare(v, w, op);
4486 v = res ? Py_True : Py_False;
4487 Py_INCREF(v);
4488 return v;
4491 static PyObject *
4492 import_from(PyObject *v, PyObject *name)
4494 PyObject *x;
4496 x = PyObject_GetAttr(v, name);
4497 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
4498 PyErr_Format(PyExc_ImportError,
4499 "cannot import name %.230s",
4500 PyString_AsString(name));
4502 return x;
4505 static int
4506 import_all_from(PyObject *locals, PyObject *v)
4508 PyObject *all = PyObject_GetAttrString(v, "__all__");
4509 PyObject *dict, *name, *value;
4510 int skip_leading_underscores = 0;
4511 int pos, err;
4513 if (all == NULL) {
4514 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4515 return -1; /* Unexpected error */
4516 PyErr_Clear();
4517 dict = PyObject_GetAttrString(v, "__dict__");
4518 if (dict == NULL) {
4519 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
4520 return -1;
4521 PyErr_SetString(PyExc_ImportError,
4522 "from-import-* object has no __dict__ and no __all__");
4523 return -1;
4525 all = PyMapping_Keys(dict);
4526 Py_DECREF(dict);
4527 if (all == NULL)
4528 return -1;
4529 skip_leading_underscores = 1;
4532 for (pos = 0, err = 0; ; pos++) {
4533 name = PySequence_GetItem(all, pos);
4534 if (name == NULL) {
4535 if (!PyErr_ExceptionMatches(PyExc_IndexError))
4536 err = -1;
4537 else
4538 PyErr_Clear();
4539 break;
4541 if (skip_leading_underscores &&
4542 PyString_Check(name) &&
4543 PyString_AS_STRING(name)[0] == '_')
4545 Py_DECREF(name);
4546 continue;
4548 value = PyObject_GetAttr(v, name);
4549 if (value == NULL)
4550 err = -1;
4551 else if (PyDict_CheckExact(locals))
4552 err = PyDict_SetItem(locals, name, value);
4553 else
4554 err = PyObject_SetItem(locals, name, value);
4555 Py_DECREF(name);
4556 Py_XDECREF(value);
4557 if (err != 0)
4558 break;
4560 Py_DECREF(all);
4561 return err;
4564 static PyObject *
4565 build_class(PyObject *methods, PyObject *bases, PyObject *name)
4567 PyObject *metaclass = NULL, *result, *base;
4569 if (PyDict_Check(methods))
4570 metaclass = PyDict_GetItemString(methods, "__metaclass__");
4571 if (metaclass != NULL)
4572 Py_INCREF(metaclass);
4573 else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
4574 base = PyTuple_GET_ITEM(bases, 0);
4575 metaclass = PyObject_GetAttrString(base, "__class__");
4576 if (metaclass == NULL) {
4577 PyErr_Clear();
4578 metaclass = (PyObject *)base->ob_type;
4579 Py_INCREF(metaclass);
4582 else {
4583 PyObject *g = PyEval_GetGlobals();
4584 if (g != NULL && PyDict_Check(g))
4585 metaclass = PyDict_GetItemString(g, "__metaclass__");
4586 if (metaclass == NULL)
4587 metaclass = (PyObject *) &PyClass_Type;
4588 Py_INCREF(metaclass);
4590 result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods,
4591 NULL);
4592 Py_DECREF(metaclass);
4593 if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
4594 /* A type error here likely means that the user passed
4595 in a base that was not a class (such the random module
4596 instead of the random.random type). Help them out with
4597 by augmenting the error message with more information.*/
4599 PyObject *ptype, *pvalue, *ptraceback;
4601 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
4602 if (PyString_Check(pvalue)) {
4603 PyObject *newmsg;
4604 newmsg = PyString_FromFormat(
4605 "Error when calling the metaclass bases\n"
4606 " %s",
4607 PyString_AS_STRING(pvalue));
4608 if (newmsg != NULL) {
4609 Py_DECREF(pvalue);
4610 pvalue = newmsg;
4613 PyErr_Restore(ptype, pvalue, ptraceback);
4615 return result;
4618 static int
4619 exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals,
4620 PyObject *locals)
4622 int n;
4623 PyObject *v;
4624 int plain = 0;
4626 if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
4627 ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
4628 /* Backward compatibility hack */
4629 globals = PyTuple_GetItem(prog, 1);
4630 if (n == 3)
4631 locals = PyTuple_GetItem(prog, 2);
4632 prog = PyTuple_GetItem(prog, 0);
4634 if (globals == Py_None) {
4635 globals = PyEval_GetGlobals();
4636 if (locals == Py_None) {
4637 locals = PyEval_GetLocals();
4638 plain = 1;
4640 if (!globals || !locals) {
4641 PyErr_SetString(PyExc_SystemError,
4642 "globals and locals cannot be NULL");
4643 return -1;
4646 else if (locals == Py_None)
4647 locals = globals;
4648 if (!PyString_Check(prog) &&
4649 #ifdef Py_USING_UNICODE
4650 !PyUnicode_Check(prog) &&
4651 #endif
4652 !PyCode_Check(prog) &&
4653 !PyFile_Check(prog)) {
4654 PyErr_SetString(PyExc_TypeError,
4655 "exec: arg 1 must be a string, file, or code object");
4656 return -1;
4658 if (!PyDict_Check(globals)) {
4659 PyErr_SetString(PyExc_TypeError,
4660 "exec: arg 2 must be a dictionary or None");
4661 return -1;
4663 if (!PyMapping_Check(locals)) {
4664 PyErr_SetString(PyExc_TypeError,
4665 "exec: arg 3 must be a mapping or None");
4666 return -1;
4668 if (PyDict_GetItemString(globals, "__builtins__") == NULL)
4669 PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
4670 if (PyCode_Check(prog)) {
4671 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
4672 PyErr_SetString(PyExc_TypeError,
4673 "code object passed to exec may not contain free variables");
4674 return -1;
4676 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
4678 else if (PyFile_Check(prog)) {
4679 FILE *fp = PyFile_AsFile(prog);
4680 char *name = PyString_AsString(PyFile_Name(prog));
4681 PyCompilerFlags cf;
4682 if (name == NULL)
4683 return -1;
4684 cf.cf_flags = 0;
4685 if (PyEval_MergeCompilerFlags(&cf))
4686 v = PyRun_FileFlags(fp, name, Py_file_input, globals,
4687 locals, &cf);
4688 else
4689 v = PyRun_File(fp, name, Py_file_input, globals,
4690 locals);
4692 else {
4693 PyObject *tmp = NULL;
4694 char *str;
4695 PyCompilerFlags cf;
4696 cf.cf_flags = 0;
4697 #ifdef Py_USING_UNICODE
4698 if (PyUnicode_Check(prog)) {
4699 tmp = PyUnicode_AsUTF8String(prog);
4700 if (tmp == NULL)
4701 return -1;
4702 prog = tmp;
4703 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
4705 #endif
4706 if (PyString_AsStringAndSize(prog, &str, NULL))
4707 return -1;
4708 if (PyEval_MergeCompilerFlags(&cf))
4709 v = PyRun_StringFlags(str, Py_file_input, globals,
4710 locals, &cf);
4711 else
4712 v = PyRun_String(str, Py_file_input, globals, locals);
4713 Py_XDECREF(tmp);
4715 if (plain)
4716 PyFrame_LocalsToFast(f, 0);
4717 if (v == NULL)
4718 return -1;
4719 Py_DECREF(v);
4720 return 0;
4723 static void
4724 format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
4726 char *obj_str;
4728 if (!obj)
4729 return;
4731 obj_str = PyString_AsString(obj);
4732 if (!obj_str)
4733 return;
4735 PyErr_Format(exc, format_str, obj_str);
4738 static PyObject *
4739 string_concatenate(PyObject *v, PyObject *w,
4740 PyFrameObject *f, unsigned char *next_instr)
4742 /* This function implements 'variable += expr' when both arguments
4743 are strings. */
4744 Py_ssize_t v_len = PyString_GET_SIZE(v);
4745 Py_ssize_t w_len = PyString_GET_SIZE(w);
4746 Py_ssize_t new_len = v_len + w_len;
4747 if (new_len < 0) {
4748 PyErr_SetString(PyExc_OverflowError,
4749 "strings are too large to concat");
4750 return NULL;
4753 if (v->ob_refcnt == 2) {
4754 /* In the common case, there are 2 references to the value
4755 * stored in 'variable' when the += is performed: one on the
4756 * value stack (in 'v') and one still stored in the
4757 * 'variable'. We try to delete the variable now to reduce
4758 * the refcnt to 1.
4760 switch (*next_instr) {
4761 case STORE_FAST:
4763 int oparg = PEEKARG();
4764 PyObject **fastlocals = f->f_localsplus;
4765 if (GETLOCAL(oparg) == v)
4766 SETLOCAL(oparg, NULL);
4767 break;
4769 case STORE_DEREF:
4771 PyObject **freevars = (f->f_localsplus +
4772 f->f_code->co_nlocals);
4773 PyObject *c = freevars[PEEKARG()];
4774 if (PyCell_GET(c) == v)
4775 PyCell_Set(c, NULL);
4776 break;
4778 case STORE_NAME:
4780 PyObject *names = f->f_code->co_names;
4781 PyObject *name = GETITEM(names, PEEKARG());
4782 PyObject *locals = f->f_locals;
4783 if (PyDict_CheckExact(locals) &&
4784 PyDict_GetItem(locals, name) == v) {
4785 if (PyDict_DelItem(locals, name) != 0) {
4786 PyErr_Clear();
4789 break;
4794 if (v->ob_refcnt == 1 && !PyString_CHECK_INTERNED(v)) {
4795 /* Now we own the last reference to 'v', so we can resize it
4796 * in-place.
4798 if (_PyString_Resize(&v, new_len) != 0) {
4799 /* XXX if _PyString_Resize() fails, 'v' has been
4800 * deallocated so it cannot be put back into
4801 * 'variable'. The MemoryError is raised when there
4802 * is no value in 'variable', which might (very
4803 * remotely) be a cause of incompatibilities.
4805 return NULL;
4807 /* copy 'w' into the newly allocated area of 'v' */
4808 memcpy(PyString_AS_STRING(v) + v_len,
4809 PyString_AS_STRING(w), w_len);
4810 return v;
4812 else {
4813 /* When in-place resizing is not an option. */
4814 PyString_Concat(&v, w);
4815 return v;
4819 #ifdef DYNAMIC_EXECUTION_PROFILE
4821 static PyObject *
4822 getarray(long a[256])
4824 int i;
4825 PyObject *l = PyList_New(256);
4826 if (l == NULL) return NULL;
4827 for (i = 0; i < 256; i++) {
4828 PyObject *x = PyInt_FromLong(a[i]);
4829 if (x == NULL) {
4830 Py_DECREF(l);
4831 return NULL;
4833 PyList_SetItem(l, i, x);
4835 for (i = 0; i < 256; i++)
4836 a[i] = 0;
4837 return l;
4840 PyObject *
4841 _Py_GetDXProfile(PyObject *self, PyObject *args)
4843 #ifndef DXPAIRS
4844 return getarray(dxp);
4845 #else
4846 int i;
4847 PyObject *l = PyList_New(257);
4848 if (l == NULL) return NULL;
4849 for (i = 0; i < 257; i++) {
4850 PyObject *x = getarray(dxpairs[i]);
4851 if (x == NULL) {
4852 Py_DECREF(l);
4853 return NULL;
4855 PyList_SetItem(l, i, x);
4857 return l;
4858 #endif
4861 #endif