2 /* Execute compiled code */
5 XXX speed up searching for keywords by using a dictionary
12 #include "frameobject.h"
15 #include "structmember.h"
21 #define READ_TIMESTAMP(var)
25 typedef unsigned long long uint64
;
27 #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this
28 section should work for GCC on any PowerPC platform,
29 irrespective of OS. POWER? Who knows :-) */
31 #define READ_TIMESTAMP(var) ppc_getcounter(&var)
34 ppc_getcounter(uint64
*v
)
36 register unsigned long tbu
, tb
, tbu2
;
39 asm volatile ("mftbu %0" : "=r" (tbu
) );
40 asm volatile ("mftb %0" : "=r" (tb
) );
41 asm volatile ("mftbu %0" : "=r" (tbu2
));
42 if (__builtin_expect(tbu
!= tbu2
, 0)) goto loop
;
44 /* The slightly peculiar way of writing the next lines is
45 compiled better by GCC than any other way I tried. */
46 ((long*)(v
))[0] = tbu
;
50 #else /* this is for linux/x86 (and probably any other GCC/x86 combo) */
52 #define READ_TIMESTAMP(val) \
53 __asm__ __volatile__("rdtsc" : "=A" (val))
57 void dump_tsc(int opcode
, int ticked
, uint64 inst0
, uint64 inst1
,
58 uint64 loop0
, uint64 loop1
, uint64 intr0
, uint64 intr1
)
60 uint64 intr
, inst
, loop
;
61 PyThreadState
*tstate
= PyThreadState_Get();
62 if (!tstate
->interp
->tscdump
)
65 inst
= inst1
- inst0
- intr
;
66 loop
= loop1
- loop0
- intr
;
67 fprintf(stderr
, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
68 opcode
, ticked
, inst
, loop
);
73 /* Turn this on if your compiler chokes on the big switch: */
74 /* #define CASE_TOO_BIG 1 */
77 /* For debugging the interpreter: */
78 #define LLTRACE 1 /* Low-level trace feature */
79 #define CHECKEXC 1 /* Double-check exception checking */
82 typedef PyObject
*(*callproc
)(PyObject
*, PyObject
*, PyObject
*);
84 /* Forward declarations */
86 static PyObject
*call_function(PyObject
***, int, uint64
*, uint64
*);
88 static PyObject
*call_function(PyObject
***, int);
90 static PyObject
*fast_function(PyObject
*, PyObject
***, int, int, int);
91 static PyObject
*do_call(PyObject
*, PyObject
***, int, int);
92 static PyObject
*ext_do_call(PyObject
*, PyObject
***, int, int, int);
93 static PyObject
*update_keyword_args(PyObject
*, int, PyObject
***,PyObject
*);
94 static PyObject
*update_star_args(int, int, PyObject
*, PyObject
***);
95 static PyObject
*load_args(PyObject
***, int);
96 #define CALL_FLAG_VAR 1
97 #define CALL_FLAG_KW 2
101 static int prtrace(PyObject
*, char *);
103 static int call_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*,
105 static void call_trace_protected(Py_tracefunc
, PyObject
*,
106 PyFrameObject
*, int, PyObject
*);
107 static void call_exc_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*);
108 static int maybe_call_line_trace(Py_tracefunc
, PyObject
*,
109 PyFrameObject
*, int *, int *, int *);
111 static PyObject
*apply_slice(PyObject
*, PyObject
*, PyObject
*);
112 static int assign_slice(PyObject
*, PyObject
*,
113 PyObject
*, PyObject
*);
114 static PyObject
*cmp_outcome(int, PyObject
*, PyObject
*);
115 static PyObject
*import_from(PyObject
*, PyObject
*);
116 static int import_all_from(PyObject
*, PyObject
*);
117 static PyObject
*build_class(PyObject
*, PyObject
*, PyObject
*);
118 static int exec_statement(PyFrameObject
*,
119 PyObject
*, PyObject
*, PyObject
*);
120 static void set_exc_info(PyThreadState
*, PyObject
*, PyObject
*, PyObject
*);
121 static void reset_exc_info(PyThreadState
*);
122 static void format_exc_check_arg(PyObject
*, char *, PyObject
*);
123 static PyObject
*string_concatenate(PyObject
*, PyObject
*,
124 PyFrameObject
*, unsigned char *);
126 #define NAME_ERROR_MSG \
127 "name '%.200s' is not defined"
128 #define GLOBAL_NAME_ERROR_MSG \
129 "global name '%.200s' is not defined"
130 #define UNBOUNDLOCAL_ERROR_MSG \
131 "local variable '%.200s' referenced before assignment"
132 #define UNBOUNDFREE_ERROR_MSG \
133 "free variable '%.200s' referenced before assignment" \
134 " in enclosing scope"
136 /* Dynamic execution profile */
137 #ifdef DYNAMIC_EXECUTION_PROFILE
139 static long dxpairs
[257][256];
140 #define dxp dxpairs[256]
142 static long dxp
[256];
146 /* Function call profile */
149 static int pcall
[PCALL_NUM
];
152 #define PCALL_FUNCTION 1
153 #define PCALL_FAST_FUNCTION 2
154 #define PCALL_FASTER_FUNCTION 3
155 #define PCALL_METHOD 4
156 #define PCALL_BOUND_METHOD 5
157 #define PCALL_CFUNCTION 6
159 #define PCALL_GENERATOR 8
160 #define PCALL_OTHER 9
163 /* Notes about the statistics
167 FAST_FUNCTION means no argument tuple needs to be created.
168 FASTER_FUNCTION means that the fast-path frame setup code is used.
170 If there is a method call where the call can be optimized by changing
171 the argument tuple and calling the function directly, it gets recorded
174 As a result, the relationship among the statistics appears to be
175 PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
176 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
177 PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
178 PCALL_METHOD > PCALL_BOUND_METHOD
181 #define PCALL(POS) pcall[POS]++
184 PyEval_GetCallStats(PyObject
*self
)
186 return Py_BuildValue("iiiiiiiiii",
187 pcall
[0], pcall
[1], pcall
[2], pcall
[3],
188 pcall
[4], pcall
[5], pcall
[6], pcall
[7],
195 PyEval_GetCallStats(PyObject
*self
)
205 #ifndef DONT_HAVE_ERRNO_H
208 #include "pythread.h"
210 static PyThread_type_lock interpreter_lock
= 0; /* This is the GIL */
211 static long main_thread
= 0;
214 PyEval_ThreadsInitialized(void)
216 return interpreter_lock
!= 0;
220 PyEval_InitThreads(void)
222 if (interpreter_lock
)
224 interpreter_lock
= PyThread_allocate_lock();
225 PyThread_acquire_lock(interpreter_lock
, 1);
226 main_thread
= PyThread_get_thread_ident();
230 PyEval_AcquireLock(void)
232 PyThread_acquire_lock(interpreter_lock
, 1);
236 PyEval_ReleaseLock(void)
238 PyThread_release_lock(interpreter_lock
);
242 PyEval_AcquireThread(PyThreadState
*tstate
)
245 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
246 /* Check someone has called PyEval_InitThreads() to create the lock */
247 assert(interpreter_lock
);
248 PyThread_acquire_lock(interpreter_lock
, 1);
249 if (PyThreadState_Swap(tstate
) != NULL
)
251 "PyEval_AcquireThread: non-NULL old thread state");
255 PyEval_ReleaseThread(PyThreadState
*tstate
)
258 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
259 if (PyThreadState_Swap(NULL
) != tstate
)
260 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
261 PyThread_release_lock(interpreter_lock
);
264 /* This function is called from PyOS_AfterFork to ensure that newly
265 created child processes don't hold locks referring to threads which
266 are not running in the child process. (This could also be done using
267 pthread_atfork mechanism, at least for the pthreads implementation.) */
270 PyEval_ReInitThreads(void)
272 if (!interpreter_lock
)
274 /*XXX Can't use PyThread_free_lock here because it does too
275 much error-checking. Doing this cleanly would require
276 adding a new function to each thread_*.h. Instead, just
277 create a new lock and waste a little bit of memory */
278 interpreter_lock
= PyThread_allocate_lock();
279 PyThread_acquire_lock(interpreter_lock
, 1);
280 main_thread
= PyThread_get_thread_ident();
284 /* Functions save_thread and restore_thread are always defined so
285 dynamically loaded modules needn't be compiled separately for use
286 with and without threads: */
289 PyEval_SaveThread(void)
291 PyThreadState
*tstate
= PyThreadState_Swap(NULL
);
293 Py_FatalError("PyEval_SaveThread: NULL tstate");
295 if (interpreter_lock
)
296 PyThread_release_lock(interpreter_lock
);
302 PyEval_RestoreThread(PyThreadState
*tstate
)
305 Py_FatalError("PyEval_RestoreThread: NULL tstate");
307 if (interpreter_lock
) {
309 PyThread_acquire_lock(interpreter_lock
, 1);
313 PyThreadState_Swap(tstate
);
317 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
318 signal handlers or Mac I/O completion routines) can schedule calls
319 to a function to be called synchronously.
320 The synchronous function is called with one void* argument.
321 It should return 0 for success or -1 for failure -- failure should
322 be accompanied by an exception.
324 If registry succeeds, the registry function returns 0; if it fails
325 (e.g. due to too many pending calls) it returns -1 (without setting
326 an exception condition).
328 Note that because registry may occur from within signal handlers,
329 or other asynchronous events, calling malloc() is unsafe!
332 Any thread can schedule pending calls, but only the main thread
336 XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE!
337 There are two possible race conditions:
338 (1) nested asynchronous registry calls;
339 (2) registry calls made while pending calls are being processed.
340 While (1) is very unlikely, (2) is a real possibility.
341 The current code is safe against (2), but not against (1).
342 The safety against (2) is derived from the fact that only one
343 thread (the main thread) ever takes things out of the queue.
345 XXX Darn! With the advent of thread state, we should have an array
346 of pending calls per thread in the thread state! Later...
349 #define NPENDINGCALLS 32
353 } pendingcalls
[NPENDINGCALLS
];
354 static volatile int pendingfirst
= 0;
355 static volatile int pendinglast
= 0;
356 static volatile int things_to_do
= 0;
359 Py_AddPendingCall(int (*func
)(void *), void *arg
)
361 static volatile int busy
= 0;
363 /* XXX Begin critical section */
364 /* XXX If you want this to be safe against nested
365 XXX asynchronous calls, you'll have to work harder! */
370 j
= (i
+ 1) % NPENDINGCALLS
;
371 if (j
== pendingfirst
) {
373 return -1; /* Queue full */
375 pendingcalls
[i
].func
= func
;
376 pendingcalls
[i
].arg
= arg
;
380 things_to_do
= 1; /* Signal main loop */
382 /* XXX End critical section */
387 Py_MakePendingCalls(void)
391 if (main_thread
&& PyThread_get_thread_ident() != main_thread
)
403 if (i
== pendinglast
)
404 break; /* Queue empty */
405 func
= pendingcalls
[i
].func
;
406 arg
= pendingcalls
[i
].arg
;
407 pendingfirst
= (i
+ 1) % NPENDINGCALLS
;
410 things_to_do
= 1; /* We're not done yet */
419 /* The interpreter's recursion limit */
421 #ifndef Py_DEFAULT_RECURSION_LIMIT
422 #define Py_DEFAULT_RECURSION_LIMIT 1000
424 static int recursion_limit
= Py_DEFAULT_RECURSION_LIMIT
;
425 int _Py_CheckRecursionLimit
= Py_DEFAULT_RECURSION_LIMIT
;
428 Py_GetRecursionLimit(void)
430 return recursion_limit
;
434 Py_SetRecursionLimit(int new_limit
)
436 recursion_limit
= new_limit
;
437 _Py_CheckRecursionLimit
= recursion_limit
;
440 /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
441 if the recursion_depth reaches _Py_CheckRecursionLimit.
442 If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
443 to guarantee that _Py_CheckRecursiveCall() is regularly called.
444 Without USE_STACKCHECK, there is no need for this. */
446 _Py_CheckRecursiveCall(char *where
)
448 PyThreadState
*tstate
= PyThreadState_GET();
450 #ifdef USE_STACKCHECK
451 if (PyOS_CheckStack()) {
452 --tstate
->recursion_depth
;
453 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
457 if (tstate
->recursion_depth
> recursion_limit
) {
458 --tstate
->recursion_depth
;
459 PyErr_Format(PyExc_RuntimeError
,
460 "maximum recursion depth exceeded%s",
464 _Py_CheckRecursionLimit
= recursion_limit
;
468 /* Status code for main loop (reason for stack unwind) */
470 WHY_NOT
= 0x0001, /* No error */
471 WHY_EXCEPTION
= 0x0002, /* Exception occurred */
472 WHY_RERAISE
= 0x0004, /* Exception re-raised by 'finally' */
473 WHY_RETURN
= 0x0008, /* 'return' statement */
474 WHY_BREAK
= 0x0010, /* 'break' statement */
475 WHY_CONTINUE
= 0x0020, /* 'continue' statement */
476 WHY_YIELD
= 0x0040 /* 'yield' operator */
479 static enum why_code
do_raise(PyObject
*, PyObject
*, PyObject
*);
480 static int unpack_iterable(PyObject
*, int, PyObject
**);
482 /* for manipulating the thread switch and periodic "stuff" - used to be
483 per thread, now just a pair o' globals */
484 int _Py_CheckInterval
= 100;
485 volatile int _Py_Ticker
= 100;
488 PyEval_EvalCode(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
)
490 /* XXX raise SystemError if globals is NULL */
491 return PyEval_EvalCodeEx(co
,
493 (PyObject
**)NULL
, 0,
494 (PyObject
**)NULL
, 0,
495 (PyObject
**)NULL
, 0,
500 /* Interpreter main loop */
503 PyEval_EvalFrame(PyFrameObject
*f
) {
504 /* This is for backward compatibility with extension modules that
505 used this API; core interpreter code should call PyEval_EvalFrameEx() */
506 return PyEval_EvalFrameEx(f
, 0);
510 PyEval_EvalFrameEx(PyFrameObject
*f
, int throw)
515 register PyObject
**stack_pointer
; /* Next free slot in value stack */
516 register unsigned char *next_instr
;
517 register int opcode
; /* Current opcode */
518 register int oparg
; /* Current opcode argument, if any */
519 register enum why_code why
; /* Reason for block stack unwind */
520 register int err
; /* Error status -- nonzero if error */
521 register PyObject
*x
; /* Result object -- NULL if error */
522 register PyObject
*v
; /* Temporary objects popped off stack */
523 register PyObject
*w
;
524 register PyObject
*u
;
525 register PyObject
*t
;
526 register PyObject
*stream
= NULL
; /* for PRINT opcodes */
527 register PyObject
**fastlocals
, **freevars
;
528 PyObject
*retval
= NULL
; /* Return value */
529 PyThreadState
*tstate
= PyThreadState_GET();
532 /* when tracing we set things up so that
534 not (instr_lb <= current_bytecode_offset < instr_ub)
536 is true when the line being executed has changed. The
537 initial values are such as to make this false the first
538 time it is tested. */
539 int instr_ub
= -1, instr_lb
= 0, instr_prev
= -1;
541 unsigned char *first_instr
;
544 #if defined(Py_DEBUG) || defined(LLTRACE)
545 /* Make it easier to find out where we are with a debugger */
549 /* Tuple access macros */
552 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
554 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
558 /* Use Pentium timestamp counter to mark certain events:
559 inst0 -- beginning of switch statement for opcode dispatch
560 inst1 -- end of switch statement (may be skipped)
561 loop0 -- the top of the mainloop
562 loop1 -- place where control returns again to top of mainloop
564 intr1 -- beginning of long interruption
565 intr2 -- end of long interruption
567 Many opcodes call out to helper C functions. In some cases, the
568 time in those functions should be counted towards the time for the
569 opcode, but not in all cases. For example, a CALL_FUNCTION opcode
570 calls another Python function; there's no point in charge all the
571 bytecode executed by the called function to the caller.
573 It's hard to make a useful judgement statically. In the presence
574 of operator overloading, it's impossible to tell if a call will
575 execute new Python code or not.
577 It's a case-by-case judgement. I'll use intr1 for the following
583 CALL_FUNCTION (and friends)
586 uint64 inst0
, inst1
, loop0
, loop1
, intr0
= 0, intr1
= 0;
589 READ_TIMESTAMP(inst0
);
590 READ_TIMESTAMP(inst1
);
591 READ_TIMESTAMP(loop0
);
592 READ_TIMESTAMP(loop1
);
594 /* shut up the compiler */
598 /* Code access macros */
600 #define INSTR_OFFSET() ((int)(next_instr - first_instr))
601 #define NEXTOP() (*next_instr++)
602 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
603 #define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
604 #define JUMPTO(x) (next_instr = first_instr + (x))
605 #define JUMPBY(x) (next_instr += (x))
607 /* OpCode prediction macros
608 Some opcodes tend to come in pairs thus making it possible to predict
609 the second code when the first is run. For example, COMPARE_OP is often
610 followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, those opcodes are often
611 followed by a POP_TOP.
613 Verifying the prediction costs a single high-speed test of register
614 variable against a constant. If the pairing was good, then the
615 processor has a high likelihood of making its own successful branch
616 prediction which results in a nearly zero overhead transition to the
619 A successful prediction saves a trip through the eval-loop including
620 its two unpredictable branches, the HASARG test and the switch-case.
622 If collecting opcode statistics, turn off prediction so that
623 statistics are accurately maintained (the predictions bypass
624 the opcode frequency counter updates).
627 #ifdef DYNAMIC_EXECUTION_PROFILE
628 #define PREDICT(op) if (0) goto PRED_##op
630 #define PREDICT(op) if (*next_instr == op) goto PRED_##op
633 #define PREDICTED(op) PRED_##op: next_instr++
634 #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
636 /* Stack manipulation macros */
638 /* The stack can grow at most MAXINT deep, as co_nlocals and
639 co_stacksize are ints. */
640 #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
641 #define EMPTY() (STACK_LEVEL() == 0)
642 #define TOP() (stack_pointer[-1])
643 #define SECOND() (stack_pointer[-2])
644 #define THIRD() (stack_pointer[-3])
645 #define FOURTH() (stack_pointer[-4])
646 #define SET_TOP(v) (stack_pointer[-1] = (v))
647 #define SET_SECOND(v) (stack_pointer[-2] = (v))
648 #define SET_THIRD(v) (stack_pointer[-3] = (v))
649 #define SET_FOURTH(v) (stack_pointer[-4] = (v))
650 #define BASIC_STACKADJ(n) (stack_pointer += n)
651 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
652 #define BASIC_POP() (*--stack_pointer)
655 #define PUSH(v) { (void)(BASIC_PUSH(v), \
656 lltrace && prtrace(TOP(), "push")); \
657 assert(STACK_LEVEL() <= f->f_stacksize); }
658 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP())
659 #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
660 lltrace && prtrace(TOP(), "stackadj")); \
661 assert(STACK_LEVEL() <= f->f_stacksize); }
662 #define EXT_POP(STACK_POINTER) (lltrace && prtrace(*(STACK_POINTER), "ext_pop"), *--(STACK_POINTER))
664 #define PUSH(v) BASIC_PUSH(v)
665 #define POP() BASIC_POP()
666 #define STACKADJ(n) BASIC_STACKADJ(n)
667 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
670 /* Local variable macros */
672 #define GETLOCAL(i) (fastlocals[i])
674 /* The SETLOCAL() macro must not DECREF the local variable in-place and
675 then store the new value; it must copy the old value to a temporary
676 value, then store the new value, and then DECREF the temporary value.
677 This is because it is possible that during the DECREF the frame is
678 accessed by other code (e.g. a __del__ method or gc.collect()) and the
679 variable would be pointing to already-freed memory. */
680 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
681 GETLOCAL(i) = value; \
682 Py_XDECREF(tmp); } while (0)
690 if (Py_EnterRecursiveCall(""))
695 if (tstate
->use_tracing
) {
696 if (tstate
->c_tracefunc
!= NULL
) {
697 /* tstate->c_tracefunc, if defined, is a
698 function that will be called on *every* entry
699 to a code block. Its return value, if not
700 None, is a function that will be called at
701 the start of each executed line of code.
702 (Actually, the function must return itself
703 in order to continue tracing.) The trace
704 functions are called with three arguments:
705 a pointer to the current frame, a string
706 indicating why the function is called, and
707 an argument which depends on the situation.
708 The global trace function is also called
709 whenever an exception is detected. */
710 if (call_trace(tstate
->c_tracefunc
, tstate
->c_traceobj
,
711 f
, PyTrace_CALL
, Py_None
)) {
712 /* Trace function raised an error */
713 goto exit_eval_frame
;
716 if (tstate
->c_profilefunc
!= NULL
) {
717 /* Similar for c_profilefunc, except it needn't
718 return itself and isn't called for "line" events */
719 if (call_trace(tstate
->c_profilefunc
,
720 tstate
->c_profileobj
,
721 f
, PyTrace_CALL
, Py_None
)) {
722 /* Profile function raised an error */
723 goto exit_eval_frame
;
729 names
= co
->co_names
;
730 consts
= co
->co_consts
;
731 fastlocals
= f
->f_localsplus
;
732 freevars
= f
->f_localsplus
+ f
->f_nlocals
;
733 first_instr
= (unsigned char*) PyString_AS_STRING(co
->co_code
);
734 /* An explanation is in order for the next line.
736 f->f_lasti now refers to the index of the last instruction
737 executed. You might think this was obvious from the name, but
738 this wasn't always true before 2.3! PyFrame_New now sets
739 f->f_lasti to -1 (i.e. the index *before* the first instruction)
740 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
741 does work. Promise. */
742 next_instr
= first_instr
+ f
->f_lasti
+ 1;
743 stack_pointer
= f
->f_stacktop
;
744 assert(stack_pointer
!= NULL
);
745 f
->f_stacktop
= NULL
; /* remains NULL unless yield suspends frame */
748 lltrace
= PyDict_GetItemString(f
->f_globals
, "__lltrace__") != NULL
;
750 #if defined(Py_DEBUG) || defined(LLTRACE)
751 filename
= PyString_AsString(co
->co_filename
);
756 x
= Py_None
; /* Not a reference, just anything non-NULL */
759 if (throw) { /* support for generator.throw() */
767 /* Almost surely, the opcode executed a break
768 or a continue, preventing inst1 from being set
769 on the way out of the loop.
771 READ_TIMESTAMP(inst1
);
774 dump_tsc(opcode
, ticked
, inst0
, inst1
, loop0
, loop1
,
780 READ_TIMESTAMP(loop0
);
782 assert(stack_pointer
>= f
->f_valuestack
); /* else underflow */
783 assert(STACK_LEVEL() <= f
->f_stacksize
); /* else overflow */
785 /* Do periodic things. Doing this every time through
786 the loop would add too much overhead, so we do it
787 only every Nth instruction. We also do it if
788 ``things_to_do'' is set, i.e. when an asynchronous
789 event needs attention (e.g. a signal handler or
790 async I/O handler); see Py_AddPendingCall() and
791 Py_MakePendingCalls() above. */
793 if (--_Py_Ticker
< 0) {
794 if (*next_instr
== SETUP_FINALLY
) {
795 /* Make the last opcode before
796 a try: finally: block uninterruptable. */
797 goto fast_next_opcode
;
799 _Py_Ticker
= _Py_CheckInterval
;
800 tstate
->tick_counter
++;
805 if (Py_MakePendingCalls() < 0) {
810 /* MakePendingCalls() didn't succeed.
811 Force early re-execution of this
812 "periodic" code, possibly after
817 if (interpreter_lock
) {
818 /* Give another thread a chance */
820 if (PyThreadState_Swap(NULL
) != tstate
)
821 Py_FatalError("ceval: tstate mix-up");
822 PyThread_release_lock(interpreter_lock
);
824 /* Other threads may run now */
826 PyThread_acquire_lock(interpreter_lock
, 1);
827 if (PyThreadState_Swap(tstate
) != NULL
)
828 Py_FatalError("ceval: orphan tstate");
830 /* Check for thread interrupts */
832 if (tstate
->async_exc
!= NULL
) {
833 x
= tstate
->async_exc
;
834 tstate
->async_exc
= NULL
;
845 f
->f_lasti
= INSTR_OFFSET();
847 /* line-by-line tracing support */
849 if (tstate
->c_tracefunc
!= NULL
&& !tstate
->tracing
) {
850 /* see maybe_call_line_trace
851 for expository comments */
852 f
->f_stacktop
= stack_pointer
;
854 err
= maybe_call_line_trace(tstate
->c_tracefunc
,
856 f
, &instr_lb
, &instr_ub
,
858 /* Reload possibly changed frame fields */
860 if (f
->f_stacktop
!= NULL
) {
861 stack_pointer
= f
->f_stacktop
;
862 f
->f_stacktop
= NULL
;
865 /* trace function raised an exception */
870 /* Extract opcode and argument */
873 oparg
= 0; /* allows oparg to be stored in a register because
874 it doesn't have to be remembered across a full loop */
878 #ifdef DYNAMIC_EXECUTION_PROFILE
880 dxpairs
[lastopcode
][opcode
]++;
887 /* Instruction tracing */
890 if (HAS_ARG(opcode
)) {
891 printf("%d: %d, %d\n",
892 f
->f_lasti
, opcode
, oparg
);
901 /* Main switch on opcode */
902 READ_TIMESTAMP(inst0
);
907 It is essential that any operation that fails sets either
908 x to NULL, err to nonzero, or why to anything but WHY_NOT,
909 and that no operation that succeeds does this! */
911 /* case STOP_CODE: this is an error! */
914 goto fast_next_opcode
;
921 goto fast_next_opcode
;
923 format_exc_check_arg(PyExc_UnboundLocalError
,
924 UNBOUNDLOCAL_ERROR_MSG
,
925 PyTuple_GetItem(co
->co_varnames
, oparg
));
929 x
= GETITEM(consts
, oparg
);
932 goto fast_next_opcode
;
934 PREDICTED_WITH_ARG(STORE_FAST
);
938 goto fast_next_opcode
;
944 goto fast_next_opcode
;
951 goto fast_next_opcode
;
960 goto fast_next_opcode
;
971 goto fast_next_opcode
;
977 goto fast_next_opcode
;
988 goto fast_next_opcode
;
989 } else if (oparg
== 3) {
1000 goto fast_next_opcode
;
1002 Py_FatalError("invalid argument to DUP_TOPX"
1003 " (bytecode corruption?)");
1006 case UNARY_POSITIVE
:
1008 x
= PyNumber_Positive(v
);
1011 if (x
!= NULL
) continue;
1014 case UNARY_NEGATIVE
:
1016 x
= PyNumber_Negative(v
);
1019 if (x
!= NULL
) continue;
1024 err
= PyObject_IsTrue(v
);
1032 Py_INCREF(Py_False
);
1042 x
= PyObject_Repr(v
);
1045 if (x
!= NULL
) continue;
1050 x
= PyNumber_Invert(v
);
1053 if (x
!= NULL
) continue;
1059 x
= PyNumber_Power(v
, w
, Py_None
);
1063 if (x
!= NULL
) continue;
1066 case BINARY_MULTIPLY
:
1069 x
= PyNumber_Multiply(v
, w
);
1073 if (x
!= NULL
) continue;
1077 if (!_Py_QnewFlag
) {
1080 x
= PyNumber_Divide(v
, w
);
1084 if (x
!= NULL
) continue;
1087 /* -Qnew is in effect: fall through to
1088 BINARY_TRUE_DIVIDE */
1089 case BINARY_TRUE_DIVIDE
:
1092 x
= PyNumber_TrueDivide(v
, w
);
1096 if (x
!= NULL
) continue;
1099 case BINARY_FLOOR_DIVIDE
:
1102 x
= PyNumber_FloorDivide(v
, w
);
1106 if (x
!= NULL
) continue;
1112 x
= PyNumber_Remainder(v
, w
);
1116 if (x
!= NULL
) continue;
1122 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1123 /* INLINE: int + int */
1124 register long a
, b
, i
;
1125 a
= PyInt_AS_LONG(v
);
1126 b
= PyInt_AS_LONG(w
);
1128 if ((i
^a
) < 0 && (i
^b
) < 0)
1130 x
= PyInt_FromLong(i
);
1132 else if (PyString_CheckExact(v
) &&
1133 PyString_CheckExact(w
)) {
1134 x
= string_concatenate(v
, w
, f
, next_instr
);
1135 /* string_concatenate consumed the ref to v */
1136 goto skip_decref_vx
;
1140 x
= PyNumber_Add(v
, w
);
1146 if (x
!= NULL
) continue;
1149 case BINARY_SUBTRACT
:
1152 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1153 /* INLINE: int - int */
1154 register long a
, b
, i
;
1155 a
= PyInt_AS_LONG(v
);
1156 b
= PyInt_AS_LONG(w
);
1158 if ((i
^a
) < 0 && (i
^~b
) < 0)
1160 x
= PyInt_FromLong(i
);
1164 x
= PyNumber_Subtract(v
, w
);
1169 if (x
!= NULL
) continue;
1175 if (PyList_CheckExact(v
) && PyInt_CheckExact(w
)) {
1176 /* INLINE: list[int] */
1177 Py_ssize_t i
= PyInt_AsSsize_t(w
);
1179 i
+= PyList_GET_SIZE(v
);
1180 if (i
>= 0 && i
< PyList_GET_SIZE(v
)) {
1181 x
= PyList_GET_ITEM(v
, i
);
1189 x
= PyObject_GetItem(v
, w
);
1193 if (x
!= NULL
) continue;
1199 x
= PyNumber_Lshift(v
, w
);
1203 if (x
!= NULL
) continue;
1209 x
= PyNumber_Rshift(v
, w
);
1213 if (x
!= NULL
) continue;
1219 x
= PyNumber_And(v
, w
);
1223 if (x
!= NULL
) continue;
1229 x
= PyNumber_Xor(v
, w
);
1233 if (x
!= NULL
) continue;
1239 x
= PyNumber_Or(v
, w
);
1243 if (x
!= NULL
) continue;
1249 err
= PyList_Append(v
, w
);
1253 PREDICT(JUMP_ABSOLUTE
);
1261 x
= PyNumber_InPlacePower(v
, w
, Py_None
);
1265 if (x
!= NULL
) continue;
1268 case INPLACE_MULTIPLY
:
1271 x
= PyNumber_InPlaceMultiply(v
, w
);
1275 if (x
!= NULL
) continue;
1278 case INPLACE_DIVIDE
:
1279 if (!_Py_QnewFlag
) {
1282 x
= PyNumber_InPlaceDivide(v
, w
);
1286 if (x
!= NULL
) continue;
1289 /* -Qnew is in effect: fall through to
1290 INPLACE_TRUE_DIVIDE */
1291 case INPLACE_TRUE_DIVIDE
:
1294 x
= PyNumber_InPlaceTrueDivide(v
, w
);
1298 if (x
!= NULL
) continue;
1301 case INPLACE_FLOOR_DIVIDE
:
1304 x
= PyNumber_InPlaceFloorDivide(v
, w
);
1308 if (x
!= NULL
) continue;
1311 case INPLACE_MODULO
:
1314 x
= PyNumber_InPlaceRemainder(v
, w
);
1318 if (x
!= NULL
) continue;
1324 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1325 /* INLINE: int + int */
1326 register long a
, b
, i
;
1327 a
= PyInt_AS_LONG(v
);
1328 b
= PyInt_AS_LONG(w
);
1330 if ((i
^a
) < 0 && (i
^b
) < 0)
1332 x
= PyInt_FromLong(i
);
1334 else if (PyString_CheckExact(v
) &&
1335 PyString_CheckExact(w
)) {
1336 x
= string_concatenate(v
, w
, f
, next_instr
);
1337 /* string_concatenate consumed the ref to v */
1342 x
= PyNumber_InPlaceAdd(v
, w
);
1348 if (x
!= NULL
) continue;
1351 case INPLACE_SUBTRACT
:
1354 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1355 /* INLINE: int - int */
1356 register long a
, b
, i
;
1357 a
= PyInt_AS_LONG(v
);
1358 b
= PyInt_AS_LONG(w
);
1360 if ((i
^a
) < 0 && (i
^~b
) < 0)
1362 x
= PyInt_FromLong(i
);
1366 x
= PyNumber_InPlaceSubtract(v
, w
);
1371 if (x
!= NULL
) continue;
1374 case INPLACE_LSHIFT
:
1377 x
= PyNumber_InPlaceLshift(v
, w
);
1381 if (x
!= NULL
) continue;
1384 case INPLACE_RSHIFT
:
1387 x
= PyNumber_InPlaceRshift(v
, w
);
1391 if (x
!= NULL
) continue;
1397 x
= PyNumber_InPlaceAnd(v
, w
);
1401 if (x
!= NULL
) continue;
1407 x
= PyNumber_InPlaceXor(v
, w
);
1411 if (x
!= NULL
) continue;
1417 x
= PyNumber_InPlaceOr(v
, w
);
1421 if (x
!= NULL
) continue;
1428 if ((opcode
-SLICE
) & 2)
1432 if ((opcode
-SLICE
) & 1)
1437 x
= apply_slice(u
, v
, w
);
1442 if (x
!= NULL
) continue;
1449 if ((opcode
-STORE_SLICE
) & 2)
1453 if ((opcode
-STORE_SLICE
) & 1)
1459 err
= assign_slice(u
, v
, w
, t
); /* u[v:w] = t */
1464 if (err
== 0) continue;
1467 case DELETE_SLICE
+0:
1468 case DELETE_SLICE
+1:
1469 case DELETE_SLICE
+2:
1470 case DELETE_SLICE
+3:
1471 if ((opcode
-DELETE_SLICE
) & 2)
1475 if ((opcode
-DELETE_SLICE
) & 1)
1480 err
= assign_slice(u
, v
, w
, (PyObject
*)NULL
);
1485 if (err
== 0) continue;
1494 err
= PyObject_SetItem(v
, w
, u
);
1498 if (err
== 0) continue;
1506 err
= PyObject_DelItem(v
, w
);
1509 if (err
== 0) continue;
1514 w
= PySys_GetObject("displayhook");
1516 PyErr_SetString(PyExc_RuntimeError
,
1517 "lost sys.displayhook");
1522 x
= PyTuple_Pack(1, v
);
1527 w
= PyEval_CallObject(w
, x
);
1538 /* fall through to PRINT_ITEM */
1542 if (stream
== NULL
|| stream
== Py_None
) {
1543 w
= PySys_GetObject("stdout");
1545 PyErr_SetString(PyExc_RuntimeError
,
1550 /* PyFile_SoftSpace() can exececute arbitrary code
1551 if sys.stdout is an instance with a __getattr__.
1552 If __getattr__ raises an exception, w will
1553 be freed, so we need to prevent that temporarily. */
1555 if (w
!= NULL
&& PyFile_SoftSpace(w
, 0))
1556 err
= PyFile_WriteString(" ", w
);
1558 err
= PyFile_WriteObject(v
, w
, Py_PRINT_RAW
);
1560 /* XXX move into writeobject() ? */
1561 if (PyString_Check(v
)) {
1562 char *s
= PyString_AS_STRING(v
);
1563 int len
= PyString_GET_SIZE(v
);
1565 !isspace(Py_CHARMASK(s
[len
-1])) ||
1567 PyFile_SoftSpace(w
, 1);
1569 #ifdef Py_USING_UNICODE
1570 else if (PyUnicode_Check(v
)) {
1571 Py_UNICODE
*s
= PyUnicode_AS_UNICODE(v
);
1572 int len
= PyUnicode_GET_SIZE(v
);
1574 !Py_UNICODE_ISSPACE(s
[len
-1]) ||
1576 PyFile_SoftSpace(w
, 1);
1580 PyFile_SoftSpace(w
, 1);
1590 case PRINT_NEWLINE_TO
:
1592 /* fall through to PRINT_NEWLINE */
1595 if (stream
== NULL
|| stream
== Py_None
) {
1596 w
= PySys_GetObject("stdout");
1598 PyErr_SetString(PyExc_RuntimeError
,
1602 err
= PyFile_WriteString("\n", w
);
1604 PyFile_SoftSpace(w
, 0);
1612 default: switch (opcode
) {
1618 u
= POP(); /* traceback */
1621 v
= POP(); /* value */
1624 w
= POP(); /* exc */
1625 case 0: /* Fallthrough */
1626 why
= do_raise(w
, v
, u
);
1629 PyErr_SetString(PyExc_SystemError
,
1630 "bad RAISE_VARARGS oparg");
1631 why
= WHY_EXCEPTION
;
1637 if ((x
= f
->f_locals
) != NULL
) {
1642 PyErr_SetString(PyExc_SystemError
, "no locals");
1648 goto fast_block_end
;
1652 f
->f_stacktop
= stack_pointer
;
1661 READ_TIMESTAMP(intr0
);
1662 err
= exec_statement(f
, u
, v
, w
);
1663 READ_TIMESTAMP(intr1
);
1671 PyTryBlock
*b
= PyFrame_BlockPop(f
);
1672 while (STACK_LEVEL() > b
->b_level
) {
1681 if (PyInt_Check(v
)) {
1682 why
= (enum why_code
) PyInt_AS_LONG(v
);
1683 assert(why
!= WHY_YIELD
);
1684 if (why
== WHY_RETURN
||
1685 why
== WHY_CONTINUE
)
1688 else if (PyExceptionClass_Check(v
) || PyString_Check(v
)) {
1691 PyErr_Restore(v
, w
, u
);
1695 else if (v
!= Py_None
) {
1696 PyErr_SetString(PyExc_SystemError
,
1697 "'finally' pops bad exception");
1698 why
= WHY_EXCEPTION
;
1708 x
= build_class(u
, v
, w
);
1716 w
= GETITEM(names
, oparg
);
1718 if ((x
= f
->f_locals
) != NULL
) {
1719 if (PyDict_CheckExact(x
))
1720 err
= PyDict_SetItem(x
, w
, v
);
1722 err
= PyObject_SetItem(x
, w
, v
);
1724 if (err
== 0) continue;
1727 PyErr_Format(PyExc_SystemError
,
1728 "no locals found when storing %s",
1733 w
= GETITEM(names
, oparg
);
1734 if ((x
= f
->f_locals
) != NULL
) {
1735 if ((err
= PyObject_DelItem(x
, w
)) != 0)
1736 format_exc_check_arg(PyExc_NameError
,
1740 PyErr_Format(PyExc_SystemError
,
1741 "no locals when deleting %s",
1745 PREDICTED_WITH_ARG(UNPACK_SEQUENCE
);
1746 case UNPACK_SEQUENCE
:
1748 if (PyTuple_CheckExact(v
) && PyTuple_GET_SIZE(v
) == oparg
) {
1749 PyObject
**items
= ((PyTupleObject
*)v
)->ob_item
;
1757 } else if (PyList_CheckExact(v
) && PyList_GET_SIZE(v
) == oparg
) {
1758 PyObject
**items
= ((PyListObject
*)v
)->ob_item
;
1764 } else if (unpack_iterable(v
, oparg
,
1765 stack_pointer
+ oparg
))
1766 stack_pointer
+= oparg
;
1768 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1769 PyErr_SetString(PyExc_TypeError
,
1770 "unpack non-sequence");
1771 why
= WHY_EXCEPTION
;
1777 w
= GETITEM(names
, oparg
);
1781 err
= PyObject_SetAttr(v
, w
, u
); /* v.w = u */
1784 if (err
== 0) continue;
1788 w
= GETITEM(names
, oparg
);
1790 err
= PyObject_SetAttr(v
, w
, (PyObject
*)NULL
);
1796 w
= GETITEM(names
, oparg
);
1798 err
= PyDict_SetItem(f
->f_globals
, w
, v
);
1800 if (err
== 0) continue;
1804 w
= GETITEM(names
, oparg
);
1805 if ((err
= PyDict_DelItem(f
->f_globals
, w
)) != 0)
1806 format_exc_check_arg(
1807 PyExc_NameError
, GLOBAL_NAME_ERROR_MSG
, w
);
1811 w
= GETITEM(names
, oparg
);
1812 if ((v
= f
->f_locals
) == NULL
) {
1813 PyErr_Format(PyExc_SystemError
,
1814 "no locals when loading %s",
1818 if (PyDict_CheckExact(v
)) {
1819 x
= PyDict_GetItem(v
, w
);
1823 x
= PyObject_GetItem(v
, w
);
1824 if (x
== NULL
&& PyErr_Occurred()) {
1825 if (!PyErr_ExceptionMatches(PyExc_KeyError
))
1831 x
= PyDict_GetItem(f
->f_globals
, w
);
1833 x
= PyDict_GetItem(f
->f_builtins
, w
);
1835 format_exc_check_arg(
1847 w
= GETITEM(names
, oparg
);
1848 if (PyString_CheckExact(w
)) {
1849 /* Inline the PyDict_GetItem() calls.
1850 WARNING: this is an extreme speed hack.
1851 Do not try this at home. */
1852 long hash
= ((PyStringObject
*)w
)->ob_shash
;
1855 d
= (PyDictObject
*)(f
->f_globals
);
1856 x
= d
->ma_lookup(d
, w
, hash
)->me_value
;
1862 d
= (PyDictObject
*)(f
->f_builtins
);
1863 x
= d
->ma_lookup(d
, w
, hash
)->me_value
;
1869 goto load_global_error
;
1872 /* This is the un-inlined version of the code above */
1873 x
= PyDict_GetItem(f
->f_globals
, w
);
1875 x
= PyDict_GetItem(f
->f_builtins
, w
);
1878 format_exc_check_arg(
1880 GLOBAL_NAME_ERROR_MSG
, w
);
1889 x
= GETLOCAL(oparg
);
1891 SETLOCAL(oparg
, NULL
);
1894 format_exc_check_arg(
1895 PyExc_UnboundLocalError
,
1896 UNBOUNDLOCAL_ERROR_MSG
,
1897 PyTuple_GetItem(co
->co_varnames
, oparg
)
1902 x
= freevars
[oparg
];
1905 if (x
!= NULL
) continue;
1909 x
= freevars
[oparg
];
1916 /* Don't stomp existing exception */
1917 if (PyErr_Occurred())
1919 if (oparg
< f
->f_ncells
) {
1920 v
= PyTuple_GetItem(co
->co_cellvars
,
1922 format_exc_check_arg(
1923 PyExc_UnboundLocalError
,
1924 UNBOUNDLOCAL_ERROR_MSG
,
1927 v
= PyTuple_GetItem(
1929 oparg
- f
->f_ncells
);
1930 format_exc_check_arg(
1932 UNBOUNDFREE_ERROR_MSG
,
1939 x
= freevars
[oparg
];
1945 x
= PyTuple_New(oparg
);
1947 for (; --oparg
>= 0;) {
1949 PyTuple_SET_ITEM(x
, oparg
, w
);
1957 x
= PyList_New(oparg
);
1959 for (; --oparg
>= 0;) {
1961 PyList_SET_ITEM(x
, oparg
, w
);
1971 if (x
!= NULL
) continue;
1975 w
= GETITEM(names
, oparg
);
1977 x
= PyObject_GetAttr(v
, w
);
1980 if (x
!= NULL
) continue;
1986 if (PyInt_CheckExact(w
) && PyInt_CheckExact(v
)) {
1987 /* INLINE: cmp(int, int) */
1990 a
= PyInt_AS_LONG(v
);
1991 b
= PyInt_AS_LONG(w
);
1993 case PyCmp_LT
: res
= a
< b
; break;
1994 case PyCmp_LE
: res
= a
<= b
; break;
1995 case PyCmp_EQ
: res
= a
== b
; break;
1996 case PyCmp_NE
: res
= a
!= b
; break;
1997 case PyCmp_GT
: res
= a
> b
; break;
1998 case PyCmp_GE
: res
= a
>= b
; break;
1999 case PyCmp_IS
: res
= v
== w
; break;
2000 case PyCmp_IS_NOT
: res
= v
!= w
; break;
2001 default: goto slow_compare
;
2003 x
= res
? Py_True
: Py_False
;
2008 x
= cmp_outcome(oparg
, v
, w
);
2013 if (x
== NULL
) break;
2014 PREDICT(JUMP_IF_FALSE
);
2015 PREDICT(JUMP_IF_TRUE
);
2019 w
= GETITEM(names
, oparg
);
2020 x
= PyDict_GetItemString(f
->f_builtins
, "__import__");
2022 PyErr_SetString(PyExc_ImportError
,
2023 "__import__ not found");
2028 if (PyInt_AsLong(u
) != -1 || PyErr_Occurred())
2032 f
->f_locals
== NULL
?
2033 Py_None
: f
->f_locals
,
2040 f
->f_locals
== NULL
?
2041 Py_None
: f
->f_locals
,
2050 READ_TIMESTAMP(intr0
);
2051 x
= PyEval_CallObject(x
, w
);
2052 READ_TIMESTAMP(intr1
);
2055 if (x
!= NULL
) continue;
2060 PyFrame_FastToLocals(f
);
2061 if ((x
= f
->f_locals
) == NULL
) {
2062 PyErr_SetString(PyExc_SystemError
,
2063 "no locals found during 'import *'");
2066 READ_TIMESTAMP(intr0
);
2067 err
= import_all_from(x
, v
);
2068 READ_TIMESTAMP(intr1
);
2069 PyFrame_LocalsToFast(f
, 0);
2071 if (err
== 0) continue;
2075 w
= GETITEM(names
, oparg
);
2077 READ_TIMESTAMP(intr0
);
2078 x
= import_from(v
, w
);
2079 READ_TIMESTAMP(intr1
);
2081 if (x
!= NULL
) continue;
2086 goto fast_next_opcode
;
2088 PREDICTED_WITH_ARG(JUMP_IF_FALSE
);
2093 goto fast_next_opcode
;
2095 if (w
== Py_False
) {
2097 goto fast_next_opcode
;
2099 err
= PyObject_IsTrue(w
);
2108 PREDICTED_WITH_ARG(JUMP_IF_TRUE
);
2111 if (w
== Py_False
) {
2113 goto fast_next_opcode
;
2117 goto fast_next_opcode
;
2119 err
= PyObject_IsTrue(w
);
2130 PREDICTED_WITH_ARG(JUMP_ABSOLUTE
);
2136 /* before: [obj]; after [getiter(obj)] */
2138 x
= PyObject_GetIter(v
);
2148 PREDICTED_WITH_ARG(FOR_ITER
);
2150 /* before: [iter]; after: [iter, iter()] *or* [] */
2152 x
= (*v
->ob_type
->tp_iternext
)(v
);
2155 PREDICT(STORE_FAST
);
2156 PREDICT(UNPACK_SEQUENCE
);
2159 if (PyErr_Occurred()) {
2160 if (!PyErr_ExceptionMatches(PyExc_StopIteration
))
2164 /* iterator ended normally */
2172 goto fast_block_end
;
2175 retval
= PyInt_FromLong(oparg
);
2177 goto fast_block_end
;
2182 PyFrame_BlockSetup(f
, opcode
, INSTR_OFFSET() + oparg
,
2188 /* TOP is the context.__exit__ bound method.
2189 Below that are 1-3 values indicating how/why
2190 we entered the finally clause:
2192 - (SECOND, THIRD) = (WHY_{RETURN,CONTINUE}), retval
2193 - SECOND = WHY_*; no retval below it
2194 - (SECOND, THIRD, FOURTH) = exc_info()
2195 In the last case, we must call
2196 TOP(SECOND, THIRD, FOURTH)
2197 otherwise we must call
2198 TOP(None, None, None)
2200 In addition, if the stack represents an exception,
2201 *and* the function call returns a 'true' value, we
2202 "zap" this information, to prevent END_FINALLY from
2203 re-raising the exception. (But non-local gotos
2204 should still be resumed.)
2209 if (PyInt_Check(u
) || u
== Py_None
) {
2210 u
= v
= w
= Py_None
;
2216 /* XXX Not the fastest way to call it... */
2217 x
= PyObject_CallFunctionObjArgs(x
, u
, v
, w
, NULL
);
2219 break; /* Go to error exit */
2220 if (u
!= Py_None
&& PyObject_IsTrue(x
)) {
2221 /* There was an exception and a true return */
2223 x
= TOP(); /* Again */
2232 /* Let END_FINALLY do its thing */
2246 x
= call_function(&sp
, oparg
, &intr0
, &intr1
);
2248 x
= call_function(&sp
, oparg
);
2257 case CALL_FUNCTION_VAR
:
2258 case CALL_FUNCTION_KW
:
2259 case CALL_FUNCTION_VAR_KW
:
2261 int na
= oparg
& 0xff;
2262 int nk
= (oparg
>>8) & 0xff;
2263 int flags
= (opcode
- CALL_FUNCTION
) & 3;
2264 int n
= na
+ 2 * nk
;
2265 PyObject
**pfunc
, *func
, **sp
;
2267 if (flags
& CALL_FLAG_VAR
)
2269 if (flags
& CALL_FLAG_KW
)
2271 pfunc
= stack_pointer
- n
- 1;
2274 if (PyMethod_Check(func
)
2275 && PyMethod_GET_SELF(func
) != NULL
) {
2276 PyObject
*self
= PyMethod_GET_SELF(func
);
2278 func
= PyMethod_GET_FUNCTION(func
);
2287 READ_TIMESTAMP(intr0
);
2288 x
= ext_do_call(func
, &sp
, flags
, na
, nk
);
2289 READ_TIMESTAMP(intr1
);
2293 while (stack_pointer
> pfunc
) {
2304 v
= POP(); /* code object */
2305 x
= PyFunction_New(v
, f
->f_globals
);
2307 /* XXX Maybe this should be a separate opcode? */
2308 if (x
!= NULL
&& oparg
> 0) {
2309 v
= PyTuple_New(oparg
);
2315 while (--oparg
>= 0) {
2317 PyTuple_SET_ITEM(v
, oparg
, w
);
2319 err
= PyFunction_SetDefaults(x
, v
);
2327 v
= POP(); /* code object */
2328 x
= PyFunction_New(v
, f
->f_globals
);
2332 err
= PyFunction_SetClosure(x
, v
);
2335 if (x
!= NULL
&& oparg
> 0) {
2336 v
= PyTuple_New(oparg
);
2342 while (--oparg
>= 0) {
2344 PyTuple_SET_ITEM(v
, oparg
, w
);
2346 err
= PyFunction_SetDefaults(x
, v
);
2360 x
= PySlice_New(u
, v
, w
);
2365 if (x
!= NULL
) continue;
2370 oparg
= oparg
<<16 | NEXTARG();
2371 goto dispatch_opcode
;
2375 "XXX lineno: %d, opcode: %d\n",
2376 PyCode_Addr2Line(f
->f_code
, f
->f_lasti
),
2378 PyErr_SetString(PyExc_SystemError
, "unknown opcode");
2379 why
= WHY_EXCEPTION
;
2390 READ_TIMESTAMP(inst1
);
2392 /* Quickly continue if no error occurred */
2394 if (why
== WHY_NOT
) {
2395 if (err
== 0 && x
!= NULL
) {
2397 /* This check is expensive! */
2398 if (PyErr_Occurred())
2400 "XXX undetected error\n");
2403 READ_TIMESTAMP(loop1
);
2404 continue; /* Normal, fast path */
2409 why
= WHY_EXCEPTION
;
2414 /* Double-check exception status */
2416 if (why
== WHY_EXCEPTION
|| why
== WHY_RERAISE
) {
2417 if (!PyErr_Occurred()) {
2418 PyErr_SetString(PyExc_SystemError
,
2419 "error return without exception set");
2420 why
= WHY_EXCEPTION
;
2425 /* This check is expensive! */
2426 if (PyErr_Occurred()) {
2428 sprintf(buf
, "Stack unwind with exception "
2429 "set and why=%d", why
);
2435 /* Log traceback info if this is a real exception */
2437 if (why
== WHY_EXCEPTION
) {
2438 PyTraceBack_Here(f
);
2440 if (tstate
->c_tracefunc
!= NULL
)
2441 call_exc_trace(tstate
->c_tracefunc
,
2442 tstate
->c_traceobj
, f
);
2445 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2447 if (why
== WHY_RERAISE
)
2448 why
= WHY_EXCEPTION
;
2450 /* Unwind stacks if a (pseudo) exception occurred */
2453 while (why
!= WHY_NOT
&& f
->f_iblock
> 0) {
2454 PyTryBlock
*b
= PyFrame_BlockPop(f
);
2456 assert(why
!= WHY_YIELD
);
2457 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_CONTINUE
) {
2458 /* For a continue inside a try block,
2459 don't pop the block for the loop. */
2460 PyFrame_BlockSetup(f
, b
->b_type
, b
->b_handler
,
2463 JUMPTO(PyInt_AS_LONG(retval
));
2468 while (STACK_LEVEL() > b
->b_level
) {
2472 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_BREAK
) {
2474 JUMPTO(b
->b_handler
);
2477 if (b
->b_type
== SETUP_FINALLY
||
2478 (b
->b_type
== SETUP_EXCEPT
&&
2479 why
== WHY_EXCEPTION
)) {
2480 if (why
== WHY_EXCEPTION
) {
2481 PyObject
*exc
, *val
, *tb
;
2482 PyErr_Fetch(&exc
, &val
, &tb
);
2487 /* Make the raw exception data
2488 available to the handler,
2489 so a program can emulate the
2490 Python main loop. Don't do
2491 this for 'finally'. */
2492 if (b
->b_type
== SETUP_EXCEPT
) {
2493 PyErr_NormalizeException(
2495 set_exc_info(tstate
,
2507 if (why
& (WHY_RETURN
| WHY_CONTINUE
))
2509 v
= PyInt_FromLong((long)why
);
2513 JUMPTO(b
->b_handler
);
2516 } /* unwind stack */
2518 /* End the loop if we still have an error (or return) */
2522 READ_TIMESTAMP(loop1
);
2526 assert(why
!= WHY_YIELD
);
2527 /* Pop remaining stack entries. */
2533 if (why
!= WHY_RETURN
)
2537 if (tstate
->use_tracing
) {
2538 if (tstate
->c_tracefunc
) {
2539 if (why
== WHY_RETURN
|| why
== WHY_YIELD
) {
2540 if (call_trace(tstate
->c_tracefunc
,
2541 tstate
->c_traceobj
, f
,
2542 PyTrace_RETURN
, retval
)) {
2545 why
= WHY_EXCEPTION
;
2548 else if (why
== WHY_EXCEPTION
) {
2549 call_trace_protected(tstate
->c_tracefunc
,
2550 tstate
->c_traceobj
, f
,
2551 PyTrace_RETURN
, NULL
);
2554 if (tstate
->c_profilefunc
) {
2555 if (why
== WHY_EXCEPTION
)
2556 call_trace_protected(tstate
->c_profilefunc
,
2557 tstate
->c_profileobj
, f
,
2558 PyTrace_RETURN
, NULL
);
2559 else if (call_trace(tstate
->c_profilefunc
,
2560 tstate
->c_profileobj
, f
,
2561 PyTrace_RETURN
, retval
)) {
2564 why
= WHY_EXCEPTION
;
2569 reset_exc_info(tstate
);
2573 Py_LeaveRecursiveCall();
2574 tstate
->frame
= f
->f_back
;
2579 /* This is gonna seem *real weird*, but if you put some other code between
2580 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
2581 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
2584 PyEval_EvalCodeEx(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
,
2585 PyObject
**args
, int argcount
, PyObject
**kws
, int kwcount
,
2586 PyObject
**defs
, int defcount
, PyObject
*closure
)
2588 register PyFrameObject
*f
;
2589 register PyObject
*retval
= NULL
;
2590 register PyObject
**fastlocals
, **freevars
;
2591 PyThreadState
*tstate
= PyThreadState_GET();
2594 if (globals
== NULL
) {
2595 PyErr_SetString(PyExc_SystemError
,
2596 "PyEval_EvalCodeEx: NULL globals");
2600 assert(globals
!= NULL
);
2601 f
= PyFrame_New(tstate
, co
, globals
, locals
);
2605 fastlocals
= f
->f_localsplus
;
2606 freevars
= f
->f_localsplus
+ f
->f_nlocals
;
2608 if (co
->co_argcount
> 0 ||
2609 co
->co_flags
& (CO_VARARGS
| CO_VARKEYWORDS
)) {
2612 PyObject
*kwdict
= NULL
;
2613 if (co
->co_flags
& CO_VARKEYWORDS
) {
2614 kwdict
= PyDict_New();
2617 i
= co
->co_argcount
;
2618 if (co
->co_flags
& CO_VARARGS
)
2620 SETLOCAL(i
, kwdict
);
2622 if (argcount
> co
->co_argcount
) {
2623 if (!(co
->co_flags
& CO_VARARGS
)) {
2624 PyErr_Format(PyExc_TypeError
,
2625 "%.200s() takes %s %d "
2626 "%sargument%s (%d given)",
2627 PyString_AsString(co
->co_name
),
2628 defcount
? "at most" : "exactly",
2630 kwcount
? "non-keyword " : "",
2631 co
->co_argcount
== 1 ? "" : "s",
2635 n
= co
->co_argcount
;
2637 for (i
= 0; i
< n
; i
++) {
2642 if (co
->co_flags
& CO_VARARGS
) {
2643 u
= PyTuple_New(argcount
- n
);
2646 SETLOCAL(co
->co_argcount
, u
);
2647 for (i
= n
; i
< argcount
; i
++) {
2650 PyTuple_SET_ITEM(u
, i
-n
, x
);
2653 for (i
= 0; i
< kwcount
; i
++) {
2654 PyObject
*keyword
= kws
[2*i
];
2655 PyObject
*value
= kws
[2*i
+ 1];
2657 if (keyword
== NULL
|| !PyString_Check(keyword
)) {
2658 PyErr_Format(PyExc_TypeError
,
2659 "%.200s() keywords must be strings",
2660 PyString_AsString(co
->co_name
));
2663 /* XXX slow -- speed up using dictionary? */
2664 for (j
= 0; j
< co
->co_argcount
; j
++) {
2665 PyObject
*nm
= PyTuple_GET_ITEM(
2666 co
->co_varnames
, j
);
2667 int cmp
= PyObject_RichCompareBool(
2668 keyword
, nm
, Py_EQ
);
2674 /* Check errors from Compare */
2675 if (PyErr_Occurred())
2677 if (j
>= co
->co_argcount
) {
2678 if (kwdict
== NULL
) {
2679 PyErr_Format(PyExc_TypeError
,
2680 "%.200s() got an unexpected "
2681 "keyword argument '%.400s'",
2682 PyString_AsString(co
->co_name
),
2683 PyString_AsString(keyword
));
2686 PyDict_SetItem(kwdict
, keyword
, value
);
2689 if (GETLOCAL(j
) != NULL
) {
2690 PyErr_Format(PyExc_TypeError
,
2691 "%.200s() got multiple "
2692 "values for keyword "
2693 "argument '%.400s'",
2694 PyString_AsString(co
->co_name
),
2695 PyString_AsString(keyword
));
2702 if (argcount
< co
->co_argcount
) {
2703 int m
= co
->co_argcount
- defcount
;
2704 for (i
= argcount
; i
< m
; i
++) {
2705 if (GETLOCAL(i
) == NULL
) {
2706 PyErr_Format(PyExc_TypeError
,
2707 "%.200s() takes %s %d "
2708 "%sargument%s (%d given)",
2709 PyString_AsString(co
->co_name
),
2710 ((co
->co_flags
& CO_VARARGS
) ||
2711 defcount
) ? "at least"
2713 m
, kwcount
? "non-keyword " : "",
2714 m
== 1 ? "" : "s", i
);
2722 for (; i
< defcount
; i
++) {
2723 if (GETLOCAL(m
+i
) == NULL
) {
2724 PyObject
*def
= defs
[i
];
2732 if (argcount
> 0 || kwcount
> 0) {
2733 PyErr_Format(PyExc_TypeError
,
2734 "%.200s() takes no arguments (%d given)",
2735 PyString_AsString(co
->co_name
),
2736 argcount
+ kwcount
);
2740 /* Allocate and initialize storage for cell vars, and copy free
2741 vars into frame. This isn't too efficient right now. */
2743 int i
= 0, j
= 0, nargs
, found
;
2744 char *cellname
, *argname
;
2747 nargs
= co
->co_argcount
;
2748 if (co
->co_flags
& CO_VARARGS
)
2750 if (co
->co_flags
& CO_VARKEYWORDS
)
2753 /* Initialize each cell var, taking into account
2754 cell vars that are initialized from arguments.
2756 Should arrange for the compiler to put cellvars
2757 that are arguments at the beginning of the cellvars
2758 list so that we can march over it more efficiently?
2760 for (i
= 0; i
< f
->f_ncells
; ++i
) {
2761 cellname
= PyString_AS_STRING(
2762 PyTuple_GET_ITEM(co
->co_cellvars
, i
));
2764 for (j
= 0; j
< nargs
; j
++) {
2765 argname
= PyString_AS_STRING(
2766 PyTuple_GET_ITEM(co
->co_varnames
, j
));
2767 if (strcmp(cellname
, argname
) == 0) {
2768 c
= PyCell_New(GETLOCAL(j
));
2771 GETLOCAL(f
->f_nlocals
+ i
) = c
;
2777 c
= PyCell_New(NULL
);
2780 SETLOCAL(f
->f_nlocals
+ i
, c
);
2784 if (f
->f_nfreevars
) {
2786 for (i
= 0; i
< f
->f_nfreevars
; ++i
) {
2787 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
2789 freevars
[f
->f_ncells
+ i
] = o
;
2793 if (co
->co_flags
& CO_GENERATOR
) {
2794 /* Don't need to keep the reference to f_back, it will be set
2795 * when the generator is resumed. */
2796 Py_XDECREF(f
->f_back
);
2799 PCALL(PCALL_GENERATOR
);
2801 /* Create a new generator that owns the ready to run frame
2802 * and return that as the value. */
2803 return PyGen_New(f
);
2806 retval
= PyEval_EvalFrameEx(f
,0);
2808 fail
: /* Jump here from prelude on failure */
2810 /* decref'ing the frame can cause __del__ methods to get invoked,
2811 which can call back into Python. While we're done with the
2812 current Python frame (f), the associated C stack is still in use,
2813 so recursion_depth must be boosted for the duration.
2815 assert(tstate
!= NULL
);
2816 ++tstate
->recursion_depth
;
2818 --tstate
->recursion_depth
;
2823 /* Implementation notes for set_exc_info() and reset_exc_info():
2825 - Below, 'exc_ZZZ' stands for 'exc_type', 'exc_value' and
2826 'exc_traceback'. These always travel together.
2828 - tstate->curexc_ZZZ is the "hot" exception that is set by
2829 PyErr_SetString(), cleared by PyErr_Clear(), and so on.
2831 - Once an exception is caught by an except clause, it is transferred
2832 from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info()
2833 can pick it up. This is the primary task of set_exc_info().
2835 - Now let me explain the complicated dance with frame->f_exc_ZZZ.
2837 Long ago, when none of this existed, there were just a few globals:
2838 one set corresponding to the "hot" exception, and one set
2839 corresponding to sys.exc_ZZZ. (Actually, the latter weren't C
2840 globals; they were simply stored as sys.exc_ZZZ. For backwards
2841 compatibility, they still are!) The problem was that in code like
2845 "something that may fail"
2846 except "some exception":
2847 "do something else first"
2848 "print the exception from sys.exc_ZZZ."
2850 if "do something else first" invoked something that raised and caught
2851 an exception, sys.exc_ZZZ were overwritten. That was a frequent
2852 cause of subtle bugs. I fixed this by changing the semantics as
2855 - Within one frame, sys.exc_ZZZ will hold the last exception caught
2858 - But initially, and as long as no exception is caught in a given
2859 frame, sys.exc_ZZZ will hold the last exception caught in the
2860 previous frame (or the frame before that, etc.).
2862 The first bullet fixed the bug in the above example. The second
2863 bullet was for backwards compatibility: it was (and is) common to
2864 have a function that is called when an exception is caught, and to
2865 have that function access the caught exception via sys.exc_ZZZ.
2866 (Example: traceback.print_exc()).
2868 At the same time I fixed the problem that sys.exc_ZZZ weren't
2869 thread-safe, by introducing sys.exc_info() which gets it from tstate;
2870 but that's really a separate improvement.
2872 The reset_exc_info() function in ceval.c restores the tstate->exc_ZZZ
2873 variables to what they were before the current frame was called. The
2874 set_exc_info() function saves them on the frame so that
2875 reset_exc_info() can restore them. The invariant is that
2876 frame->f_exc_ZZZ is NULL iff the current frame never caught an
2877 exception (where "catching" an exception applies only to successful
2878 except clauses); and if the current frame ever caught an exception,
2879 frame->f_exc_ZZZ is the exception that was stored in tstate->exc_ZZZ
2880 at the start of the current frame.
2885 set_exc_info(PyThreadState
*tstate
,
2886 PyObject
*type
, PyObject
*value
, PyObject
*tb
)
2888 PyFrameObject
*frame
;
2889 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
2891 frame
= tstate
->frame
;
2892 if (frame
->f_exc_type
== NULL
) {
2893 /* This frame didn't catch an exception before */
2894 /* Save previous exception of this thread in this frame */
2895 if (tstate
->exc_type
== NULL
) {
2897 tstate
->exc_type
= Py_None
;
2899 tmp_type
= frame
->f_exc_type
;
2900 tmp_value
= frame
->f_exc_value
;
2901 tmp_tb
= frame
->f_exc_traceback
;
2902 Py_XINCREF(tstate
->exc_type
);
2903 Py_XINCREF(tstate
->exc_value
);
2904 Py_XINCREF(tstate
->exc_traceback
);
2905 frame
->f_exc_type
= tstate
->exc_type
;
2906 frame
->f_exc_value
= tstate
->exc_value
;
2907 frame
->f_exc_traceback
= tstate
->exc_traceback
;
2908 Py_XDECREF(tmp_type
);
2909 Py_XDECREF(tmp_value
);
2912 /* Set new exception for this thread */
2913 tmp_type
= tstate
->exc_type
;
2914 tmp_value
= tstate
->exc_value
;
2915 tmp_tb
= tstate
->exc_traceback
;
2919 tstate
->exc_type
= type
;
2920 tstate
->exc_value
= value
;
2921 tstate
->exc_traceback
= tb
;
2922 Py_XDECREF(tmp_type
);
2923 Py_XDECREF(tmp_value
);
2925 /* For b/w compatibility */
2926 PySys_SetObject("exc_type", type
);
2927 PySys_SetObject("exc_value", value
);
2928 PySys_SetObject("exc_traceback", tb
);
2932 reset_exc_info(PyThreadState
*tstate
)
2934 PyFrameObject
*frame
;
2935 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
2936 frame
= tstate
->frame
;
2937 if (frame
->f_exc_type
!= NULL
) {
2938 /* This frame caught an exception */
2939 tmp_type
= tstate
->exc_type
;
2940 tmp_value
= tstate
->exc_value
;
2941 tmp_tb
= tstate
->exc_traceback
;
2942 Py_XINCREF(frame
->f_exc_type
);
2943 Py_XINCREF(frame
->f_exc_value
);
2944 Py_XINCREF(frame
->f_exc_traceback
);
2945 tstate
->exc_type
= frame
->f_exc_type
;
2946 tstate
->exc_value
= frame
->f_exc_value
;
2947 tstate
->exc_traceback
= frame
->f_exc_traceback
;
2948 Py_XDECREF(tmp_type
);
2949 Py_XDECREF(tmp_value
);
2951 /* For b/w compatibility */
2952 PySys_SetObject("exc_type", frame
->f_exc_type
);
2953 PySys_SetObject("exc_value", frame
->f_exc_value
);
2954 PySys_SetObject("exc_traceback", frame
->f_exc_traceback
);
2956 tmp_type
= frame
->f_exc_type
;
2957 tmp_value
= frame
->f_exc_value
;
2958 tmp_tb
= frame
->f_exc_traceback
;
2959 frame
->f_exc_type
= NULL
;
2960 frame
->f_exc_value
= NULL
;
2961 frame
->f_exc_traceback
= NULL
;
2962 Py_XDECREF(tmp_type
);
2963 Py_XDECREF(tmp_value
);
2967 /* Logic for the raise statement (too complicated for inlining).
2968 This *consumes* a reference count to each of its arguments. */
2969 static enum why_code
2970 do_raise(PyObject
*type
, PyObject
*value
, PyObject
*tb
)
2974 PyThreadState
*tstate
= PyThreadState_GET();
2975 type
= tstate
->exc_type
== NULL
? Py_None
: tstate
->exc_type
;
2976 value
= tstate
->exc_value
;
2977 tb
= tstate
->exc_traceback
;
2983 /* We support the following forms of raise:
2984 raise <class>, <classinstance>
2985 raise <class>, <argument tuple>
2987 raise <class>, <argument>
2988 raise <classinstance>, None
2989 raise <string>, <object>
2990 raise <string>, None
2992 An omitted second argument is the same as None.
2994 In addition, raise <tuple>, <anything> is the same as
2995 raising the tuple's first item (and it better have one!);
2996 this rule is applied recursively.
2998 Finally, an optional third argument can be supplied, which
2999 gives the traceback to be substituted (useful when
3000 re-raising an exception after examining it). */
3002 /* First, check the traceback argument, replacing None with
3004 if (tb
== Py_None
) {
3008 else if (tb
!= NULL
&& !PyTraceBack_Check(tb
)) {
3009 PyErr_SetString(PyExc_TypeError
,
3010 "raise: arg 3 must be a traceback or None");
3014 /* Next, replace a missing value with None */
3015 if (value
== NULL
) {
3020 /* Next, repeatedly, replace a tuple exception with its first item */
3021 while (PyTuple_Check(type
) && PyTuple_Size(type
) > 0) {
3022 PyObject
*tmp
= type
;
3023 type
= PyTuple_GET_ITEM(type
, 0);
3028 if (PyString_CheckExact(type
)) {
3029 /* Raising builtin string is deprecated but still allowed --
3030 * do nothing. Raising an instance of a new-style str
3031 * subclass is right out. */
3032 if (PyErr_Warn(PyExc_DeprecationWarning
,
3033 "raising a string exception is deprecated"))
3036 else if (PyExceptionClass_Check(type
))
3037 PyErr_NormalizeException(&type
, &value
, &tb
);
3039 else if (PyExceptionInstance_Check(type
)) {
3040 /* Raising an instance. The value should be a dummy. */
3041 if (value
!= Py_None
) {
3042 PyErr_SetString(PyExc_TypeError
,
3043 "instance exception may not have a separate value");
3047 /* Normalize to raise <class>, <instance> */
3050 type
= PyExceptionInstance_Class(type
);
3055 /* Not something you can raise. You get an exception
3056 anyway, just not what you specified :-) */
3057 PyErr_Format(PyExc_TypeError
,
3058 "exceptions must be classes, instances, or "
3059 "strings (deprecated), not %s",
3060 type
->ob_type
->tp_name
);
3063 PyErr_Restore(type
, value
, tb
);
3065 return WHY_EXCEPTION
;
3072 return WHY_EXCEPTION
;
3075 /* Iterate v argcnt times and store the results on the stack (via decreasing
3076 sp). Return 1 for success, 0 if error. */
3079 unpack_iterable(PyObject
*v
, int argcnt
, PyObject
**sp
)
3082 PyObject
*it
; /* iter(v) */
3087 it
= PyObject_GetIter(v
);
3091 for (; i
< argcnt
; i
++) {
3092 w
= PyIter_Next(it
);
3094 /* Iterator done, via error or exhaustion. */
3095 if (!PyErr_Occurred()) {
3096 PyErr_Format(PyExc_ValueError
,
3097 "need more than %d value%s to unpack",
3098 i
, i
== 1 ? "" : "s");
3105 /* We better have exhausted the iterator now. */
3106 w
= PyIter_Next(it
);
3108 if (PyErr_Occurred())
3114 PyErr_SetString(PyExc_ValueError
, "too many values to unpack");
3117 for (; i
> 0; i
--, sp
++)
3126 prtrace(PyObject
*v
, char *str
)
3129 if (PyObject_Print(v
, stdout
, 0) != 0)
3130 PyErr_Clear(); /* Don't know what else to do */
3137 call_exc_trace(Py_tracefunc func
, PyObject
*self
, PyFrameObject
*f
)
3139 PyObject
*type
, *value
, *traceback
, *arg
;
3141 PyErr_Fetch(&type
, &value
, &traceback
);
3142 if (value
== NULL
) {
3146 arg
= PyTuple_Pack(3, type
, value
, traceback
);
3148 PyErr_Restore(type
, value
, traceback
);
3151 err
= call_trace(func
, self
, f
, PyTrace_EXCEPTION
, arg
);
3154 PyErr_Restore(type
, value
, traceback
);
3158 Py_XDECREF(traceback
);
3163 call_trace_protected(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3164 int what
, PyObject
*arg
)
3166 PyObject
*type
, *value
, *traceback
;
3168 PyErr_Fetch(&type
, &value
, &traceback
);
3169 err
= call_trace(func
, obj
, frame
, what
, arg
);
3171 PyErr_Restore(type
, value
, traceback
);
3175 Py_XDECREF(traceback
);
3180 call_trace(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3181 int what
, PyObject
*arg
)
3183 register PyThreadState
*tstate
= frame
->f_tstate
;
3185 if (tstate
->tracing
)
3188 tstate
->use_tracing
= 0;
3189 result
= func(obj
, frame
, what
, arg
);
3190 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3191 || (tstate
->c_profilefunc
!= NULL
));
3197 _PyEval_CallTracing(PyObject
*func
, PyObject
*args
)
3199 PyFrameObject
*frame
= PyEval_GetFrame();
3200 PyThreadState
*tstate
= frame
->f_tstate
;
3201 int save_tracing
= tstate
->tracing
;
3202 int save_use_tracing
= tstate
->use_tracing
;
3205 tstate
->tracing
= 0;
3206 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3207 || (tstate
->c_profilefunc
!= NULL
));
3208 result
= PyObject_Call(func
, args
, NULL
);
3209 tstate
->tracing
= save_tracing
;
3210 tstate
->use_tracing
= save_use_tracing
;
3215 maybe_call_line_trace(Py_tracefunc func
, PyObject
*obj
,
3216 PyFrameObject
*frame
, int *instr_lb
, int *instr_ub
,
3219 /* The theory of SET_LINENO-less tracing.
3221 In a nutshell, we use the co_lnotab field of the code object
3222 to tell when execution has moved onto a different line.
3224 As mentioned above, the basic idea is so set things up so
3227 *instr_lb <= frame->f_lasti < *instr_ub
3229 is true so long as execution does not change lines.
3231 This is all fairly simple. Digging the information out of
3232 co_lnotab takes some work, but is conceptually clear.
3234 Somewhat harder to explain is why we don't *always* call the
3235 line trace function when the above test fails.
3245 which compiles to this:
3248 3 JUMP_IF_FALSE 9 (to 15)
3251 3 7 LOAD_CONST 1 (1)
3254 12 JUMP_FORWARD 6 (to 21)
3257 5 16 LOAD_CONST 2 (2)
3260 >> 21 LOAD_CONST 0 (None)
3263 If 'a' is false, execution will jump to instruction at offset
3264 15 and the co_lnotab will claim that execution has moved to
3265 line 3. This is at best misleading. In this case we could
3266 associate the POP_TOP with line 4, but that doesn't make
3267 sense in all cases (I think).
3269 What we do is only call the line trace function if the co_lnotab
3270 indicates we have jumped to the *start* of a line, i.e. if the
3271 current instruction offset matches the offset given for the
3272 start of a line by the co_lnotab.
3274 This also takes care of the situation where 'a' is true.
3275 Execution will jump from instruction offset 12 to offset 21.
3276 Then the co_lnotab would imply that execution has moved to line
3277 5, which is again misleading.
3279 Why do we set f_lineno when tracing? Well, consider the code
3280 above when 'a' is true. If stepping through this with 'n' in
3281 pdb, you would stop at line 1 with a "call" type event, then
3282 line events on lines 2 and 3, then a "return" type event -- but
3283 you would be shown line 5 during this event. This is a change
3284 from the behaviour in 2.2 and before, and I've found it
3285 confusing in practice. By setting and using f_lineno when
3286 tracing, one can report a line number different from that
3287 suggested by f_lasti on this one occasion where it's desirable.
3292 if ((frame
->f_lasti
< *instr_lb
|| frame
->f_lasti
>= *instr_ub
)) {
3293 PyCodeObject
* co
= frame
->f_code
;
3294 int size
, addr
, line
;
3297 size
= PyString_GET_SIZE(co
->co_lnotab
) / 2;
3298 p
= (unsigned char*)PyString_AS_STRING(co
->co_lnotab
);
3301 line
= co
->co_firstlineno
;
3303 /* possible optimization: if f->f_lasti == instr_ub
3304 (likely to be a common case) then we already know
3305 instr_lb -- if we stored the matching value of p
3306 somwhere we could skip the first while loop. */
3308 /* see comments in compile.c for the description of
3309 co_lnotab. A point to remember: increments to p
3310 should come in pairs -- although we don't care about
3311 the line increments here, treating them as byte
3312 increments gets confusing, to say the least. */
3315 if (addr
+ *p
> frame
->f_lasti
)
3318 if (*p
) *instr_lb
= addr
;
3323 if (addr
== frame
->f_lasti
) {
3324 frame
->f_lineno
= line
;
3325 result
= call_trace(func
, obj
, frame
,
3326 PyTrace_LINE
, Py_None
);
3330 while (--size
>= 0) {
3338 *instr_ub
= INT_MAX
;
3341 else if (frame
->f_lasti
<= *instr_prev
) {
3342 /* jumping back in the same line forces a trace event */
3343 result
= call_trace(func
, obj
, frame
,
3344 PyTrace_LINE
, Py_None
);
3346 *instr_prev
= frame
->f_lasti
;
3351 PyEval_SetProfile(Py_tracefunc func
, PyObject
*arg
)
3353 PyThreadState
*tstate
= PyThreadState_GET();
3354 PyObject
*temp
= tstate
->c_profileobj
;
3356 tstate
->c_profilefunc
= NULL
;
3357 tstate
->c_profileobj
= NULL
;
3358 /* Must make sure that tracing is not ignored if 'temp' is freed */
3359 tstate
->use_tracing
= tstate
->c_tracefunc
!= NULL
;
3361 tstate
->c_profilefunc
= func
;
3362 tstate
->c_profileobj
= arg
;
3363 /* Flag that tracing or profiling is turned on */
3364 tstate
->use_tracing
= (func
!= NULL
) || (tstate
->c_tracefunc
!= NULL
);
3368 PyEval_SetTrace(Py_tracefunc func
, PyObject
*arg
)
3370 PyThreadState
*tstate
= PyThreadState_GET();
3371 PyObject
*temp
= tstate
->c_traceobj
;
3373 tstate
->c_tracefunc
= NULL
;
3374 tstate
->c_traceobj
= NULL
;
3375 /* Must make sure that profiling is not ignored if 'temp' is freed */
3376 tstate
->use_tracing
= tstate
->c_profilefunc
!= NULL
;
3378 tstate
->c_tracefunc
= func
;
3379 tstate
->c_traceobj
= arg
;
3380 /* Flag that tracing or profiling is turned on */
3381 tstate
->use_tracing
= ((func
!= NULL
)
3382 || (tstate
->c_profilefunc
!= NULL
));
3386 PyEval_GetBuiltins(void)
3388 PyFrameObject
*current_frame
= PyEval_GetFrame();
3389 if (current_frame
== NULL
)
3390 return PyThreadState_GET()->interp
->builtins
;
3392 return current_frame
->f_builtins
;
3396 PyEval_GetLocals(void)
3398 PyFrameObject
*current_frame
= PyEval_GetFrame();
3399 if (current_frame
== NULL
)
3401 PyFrame_FastToLocals(current_frame
);
3402 return current_frame
->f_locals
;
3406 PyEval_GetGlobals(void)
3408 PyFrameObject
*current_frame
= PyEval_GetFrame();
3409 if (current_frame
== NULL
)
3412 return current_frame
->f_globals
;
3416 PyEval_GetFrame(void)
3418 PyThreadState
*tstate
= PyThreadState_GET();
3419 return _PyThreadState_GetFrame(tstate
);
3423 PyEval_GetRestricted(void)
3425 PyFrameObject
*current_frame
= PyEval_GetFrame();
3426 return current_frame
== NULL
? 0 : current_frame
->f_restricted
;
3430 PyEval_MergeCompilerFlags(PyCompilerFlags
*cf
)
3432 PyFrameObject
*current_frame
= PyEval_GetFrame();
3433 int result
= cf
->cf_flags
!= 0;
3435 if (current_frame
!= NULL
) {
3436 const int codeflags
= current_frame
->f_code
->co_flags
;
3437 const int compilerflags
= codeflags
& PyCF_MASK
;
3438 if (compilerflags
) {
3440 cf
->cf_flags
|= compilerflags
;
3442 #if 0 /* future keyword */
3443 if (codeflags
& CO_GENERATOR_ALLOWED
) {
3445 cf
->cf_flags
|= CO_GENERATOR_ALLOWED
;
3455 PyObject
*f
= PySys_GetObject("stdout");
3458 if (!PyFile_SoftSpace(f
, 0))
3460 return PyFile_WriteString("\n", f
);
3464 /* External interface to call any callable object.
3465 The arg must be a tuple or NULL. */
3467 #undef PyEval_CallObject
3468 /* for backward compatibility: export this interface */
3471 PyEval_CallObject(PyObject
*func
, PyObject
*arg
)
3473 return PyEval_CallObjectWithKeywords(func
, arg
, (PyObject
*)NULL
);
3475 #define PyEval_CallObject(func,arg) \
3476 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
3479 PyEval_CallObjectWithKeywords(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
3484 arg
= PyTuple_New(0);
3488 else if (!PyTuple_Check(arg
)) {
3489 PyErr_SetString(PyExc_TypeError
,
3490 "argument list must be a tuple");
3496 if (kw
!= NULL
&& !PyDict_Check(kw
)) {
3497 PyErr_SetString(PyExc_TypeError
,
3498 "keyword list must be a dictionary");
3503 result
= PyObject_Call(func
, arg
, kw
);
3509 PyEval_GetFuncName(PyObject
*func
)
3511 if (PyMethod_Check(func
))
3512 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func
));
3513 else if (PyFunction_Check(func
))
3514 return PyString_AsString(((PyFunctionObject
*)func
)->func_name
);
3515 else if (PyCFunction_Check(func
))
3516 return ((PyCFunctionObject
*)func
)->m_ml
->ml_name
;
3517 else if (PyClass_Check(func
))
3518 return PyString_AsString(((PyClassObject
*)func
)->cl_name
);
3519 else if (PyInstance_Check(func
)) {
3520 return PyString_AsString(
3521 ((PyInstanceObject
*)func
)->in_class
->cl_name
);
3523 return func
->ob_type
->tp_name
;
3528 PyEval_GetFuncDesc(PyObject
*func
)
3530 if (PyMethod_Check(func
))
3532 else if (PyFunction_Check(func
))
3534 else if (PyCFunction_Check(func
))
3536 else if (PyClass_Check(func
))
3537 return " constructor";
3538 else if (PyInstance_Check(func
)) {
3546 err_args(PyObject
*func
, int flags
, int nargs
)
3548 if (flags
& METH_NOARGS
)
3549 PyErr_Format(PyExc_TypeError
,
3550 "%.200s() takes no arguments (%d given)",
3551 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3554 PyErr_Format(PyExc_TypeError
,
3555 "%.200s() takes exactly one argument (%d given)",
3556 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3560 #define C_TRACE(x, call) \
3561 if (tstate->use_tracing && tstate->c_profilefunc) { \
3562 if (call_trace(tstate->c_profilefunc, \
3563 tstate->c_profileobj, \
3564 tstate->frame, PyTrace_C_CALL, \
3570 if (tstate->c_profilefunc != NULL) { \
3572 call_trace_protected(tstate->c_profilefunc, \
3573 tstate->c_profileobj, \
3574 tstate->frame, PyTrace_C_EXCEPTION, \
3576 /* XXX should pass (type, value, tb) */ \
3578 if (call_trace(tstate->c_profilefunc, \
3579 tstate->c_profileobj, \
3580 tstate->frame, PyTrace_C_RETURN, \
3593 call_function(PyObject
***pp_stack
, int oparg
3595 , uint64
* pintr0
, uint64
* pintr1
3599 int na
= oparg
& 0xff;
3600 int nk
= (oparg
>>8) & 0xff;
3601 int n
= na
+ 2 * nk
;
3602 PyObject
**pfunc
= (*pp_stack
) - n
- 1;
3603 PyObject
*func
= *pfunc
;
3606 /* Always dispatch PyCFunction first, because these are
3607 presumed to be the most frequent callable object.
3609 if (PyCFunction_Check(func
) && nk
== 0) {
3610 int flags
= PyCFunction_GET_FLAGS(func
);
3611 PyThreadState
*tstate
= PyThreadState_GET();
3613 PCALL(PCALL_CFUNCTION
);
3614 if (flags
& (METH_NOARGS
| METH_O
)) {
3615 PyCFunction meth
= PyCFunction_GET_FUNCTION(func
);
3616 PyObject
*self
= PyCFunction_GET_SELF(func
);
3617 if (flags
& METH_NOARGS
&& na
== 0) {
3618 C_TRACE(x
, (*meth
)(self
,NULL
));
3620 else if (flags
& METH_O
&& na
== 1) {
3621 PyObject
*arg
= EXT_POP(*pp_stack
);
3622 C_TRACE(x
, (*meth
)(self
,arg
));
3626 err_args(func
, flags
, na
);
3632 callargs
= load_args(pp_stack
, na
);
3633 READ_TIMESTAMP(*pintr0
);
3634 C_TRACE(x
, PyCFunction_Call(func
,callargs
,NULL
));
3635 READ_TIMESTAMP(*pintr1
);
3636 Py_XDECREF(callargs
);
3639 if (PyMethod_Check(func
) && PyMethod_GET_SELF(func
) != NULL
) {
3640 /* optimize access to bound methods */
3641 PyObject
*self
= PyMethod_GET_SELF(func
);
3642 PCALL(PCALL_METHOD
);
3643 PCALL(PCALL_BOUND_METHOD
);
3645 func
= PyMethod_GET_FUNCTION(func
);
3653 READ_TIMESTAMP(*pintr0
);
3654 if (PyFunction_Check(func
))
3655 x
= fast_function(func
, pp_stack
, n
, na
, nk
);
3657 x
= do_call(func
, pp_stack
, na
, nk
);
3658 READ_TIMESTAMP(*pintr1
);
3662 /* Clear the stack of the function object and the arguments,
3663 in case they weren't consumed already.
3664 XXX(twouters) when are they not consumed already?
3666 while ((*pp_stack
) > pfunc
) {
3667 w
= EXT_POP(*pp_stack
);
3674 /* The fast_function() function optimize calls for which no argument
3675 tuple is necessary; the objects are passed directly from the stack.
3676 For the simplest case -- a function that takes only positional
3677 arguments and is called with only positional arguments -- it
3678 inlines the most primitive frame setup code from
3679 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
3680 done before evaluating the frame.
3684 fast_function(PyObject
*func
, PyObject
***pp_stack
, int n
, int na
, int nk
)
3686 PyCodeObject
*co
= (PyCodeObject
*)PyFunction_GET_CODE(func
);
3687 PyObject
*globals
= PyFunction_GET_GLOBALS(func
);
3688 PyObject
*argdefs
= PyFunction_GET_DEFAULTS(func
);
3689 PyObject
**d
= NULL
;
3692 PCALL(PCALL_FUNCTION
);
3693 PCALL(PCALL_FAST_FUNCTION
);
3694 if (argdefs
== NULL
&& co
->co_argcount
== n
&& nk
==0 &&
3695 co
->co_flags
== (CO_OPTIMIZED
| CO_NEWLOCALS
| CO_NOFREE
)) {
3697 PyObject
*retval
= NULL
;
3698 PyThreadState
*tstate
= PyThreadState_GET();
3699 PyObject
**fastlocals
, **stack
;
3702 PCALL(PCALL_FASTER_FUNCTION
);
3703 assert(globals
!= NULL
);
3704 /* XXX Perhaps we should create a specialized
3705 PyFrame_New() that doesn't take locals, but does
3706 take builtins without sanity checking them.
3708 f
= PyFrame_New(tstate
, co
, globals
, NULL
);
3712 fastlocals
= f
->f_localsplus
;
3713 stack
= (*pp_stack
) - n
;
3715 for (i
= 0; i
< n
; i
++) {
3717 fastlocals
[i
] = *stack
++;
3719 retval
= PyEval_EvalFrameEx(f
,0);
3720 assert(tstate
!= NULL
);
3721 ++tstate
->recursion_depth
;
3723 --tstate
->recursion_depth
;
3726 if (argdefs
!= NULL
) {
3727 d
= &PyTuple_GET_ITEM(argdefs
, 0);
3728 nd
= ((PyTupleObject
*)argdefs
)->ob_size
;
3730 return PyEval_EvalCodeEx(co
, globals
,
3731 (PyObject
*)NULL
, (*pp_stack
)-n
, na
,
3732 (*pp_stack
)-2*nk
, nk
, d
, nd
,
3733 PyFunction_GET_CLOSURE(func
));
3737 update_keyword_args(PyObject
*orig_kwdict
, int nk
, PyObject
***pp_stack
,
3740 PyObject
*kwdict
= NULL
;
3741 if (orig_kwdict
== NULL
)
3742 kwdict
= PyDict_New();
3744 kwdict
= PyDict_Copy(orig_kwdict
);
3745 Py_DECREF(orig_kwdict
);
3751 PyObject
*value
= EXT_POP(*pp_stack
);
3752 PyObject
*key
= EXT_POP(*pp_stack
);
3753 if (PyDict_GetItem(kwdict
, key
) != NULL
) {
3754 PyErr_Format(PyExc_TypeError
,
3755 "%.200s%s got multiple values "
3756 "for keyword argument '%.200s'",
3757 PyEval_GetFuncName(func
),
3758 PyEval_GetFuncDesc(func
),
3759 PyString_AsString(key
));
3765 err
= PyDict_SetItem(kwdict
, key
, value
);
3777 update_star_args(int nstack
, int nstar
, PyObject
*stararg
,
3778 PyObject
***pp_stack
)
3780 PyObject
*callargs
, *w
;
3782 callargs
= PyTuple_New(nstack
+ nstar
);
3783 if (callargs
== NULL
) {
3788 for (i
= 0; i
< nstar
; i
++) {
3789 PyObject
*a
= PyTuple_GET_ITEM(stararg
, i
);
3791 PyTuple_SET_ITEM(callargs
, nstack
+ i
, a
);
3794 while (--nstack
>= 0) {
3795 w
= EXT_POP(*pp_stack
);
3796 PyTuple_SET_ITEM(callargs
, nstack
, w
);
3802 load_args(PyObject
***pp_stack
, int na
)
3804 PyObject
*args
= PyTuple_New(na
);
3810 w
= EXT_POP(*pp_stack
);
3811 PyTuple_SET_ITEM(args
, na
, w
);
3817 do_call(PyObject
*func
, PyObject
***pp_stack
, int na
, int nk
)
3819 PyObject
*callargs
= NULL
;
3820 PyObject
*kwdict
= NULL
;
3821 PyObject
*result
= NULL
;
3824 kwdict
= update_keyword_args(NULL
, nk
, pp_stack
, func
);
3828 callargs
= load_args(pp_stack
, na
);
3829 if (callargs
== NULL
)
3832 /* At this point, we have to look at the type of func to
3833 update the call stats properly. Do it here so as to avoid
3834 exposing the call stats machinery outside ceval.c
3836 if (PyFunction_Check(func
))
3837 PCALL(PCALL_FUNCTION
);
3838 else if (PyMethod_Check(func
))
3839 PCALL(PCALL_METHOD
);
3840 else if (PyType_Check(func
))
3845 result
= PyObject_Call(func
, callargs
, kwdict
);
3847 Py_XDECREF(callargs
);
3853 ext_do_call(PyObject
*func
, PyObject
***pp_stack
, int flags
, int na
, int nk
)
3856 PyObject
*callargs
= NULL
;
3857 PyObject
*stararg
= NULL
;
3858 PyObject
*kwdict
= NULL
;
3859 PyObject
*result
= NULL
;
3861 if (flags
& CALL_FLAG_KW
) {
3862 kwdict
= EXT_POP(*pp_stack
);
3863 if (!(kwdict
&& PyDict_Check(kwdict
))) {
3864 PyErr_Format(PyExc_TypeError
,
3865 "%s%s argument after ** "
3866 "must be a dictionary",
3867 PyEval_GetFuncName(func
),
3868 PyEval_GetFuncDesc(func
));
3872 if (flags
& CALL_FLAG_VAR
) {
3873 stararg
= EXT_POP(*pp_stack
);
3874 if (!PyTuple_Check(stararg
)) {
3876 t
= PySequence_Tuple(stararg
);
3878 if (PyErr_ExceptionMatches(PyExc_TypeError
)) {
3879 PyErr_Format(PyExc_TypeError
,
3880 "%s%s argument after * "
3881 "must be a sequence",
3882 PyEval_GetFuncName(func
),
3883 PyEval_GetFuncDesc(func
));
3890 nstar
= PyTuple_GET_SIZE(stararg
);
3893 kwdict
= update_keyword_args(kwdict
, nk
, pp_stack
, func
);
3897 callargs
= update_star_args(na
, nstar
, stararg
, pp_stack
);
3898 if (callargs
== NULL
)
3901 /* At this point, we have to look at the type of func to
3902 update the call stats properly. Do it here so as to avoid
3903 exposing the call stats machinery outside ceval.c
3905 if (PyFunction_Check(func
))
3906 PCALL(PCALL_FUNCTION
);
3907 else if (PyMethod_Check(func
))
3908 PCALL(PCALL_METHOD
);
3909 else if (PyType_Check(func
))
3914 result
= PyObject_Call(func
, callargs
, kwdict
);
3916 Py_XDECREF(callargs
);
3918 Py_XDECREF(stararg
);
3922 /* Extract a slice index from a PyInt or PyLong or an object with the
3923 nb_index slot defined, and store in *pi.
3924 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
3925 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
3926 Return 0 on error, 1 on success.
3928 /* Note: If v is NULL, return success without storing into *pi. This
3929 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
3930 called by the SLICE opcode with v and/or w equal to NULL.
3933 _PyEval_SliceIndex(PyObject
*v
, Py_ssize_t
*pi
)
3937 if (PyInt_Check(v
)) {
3938 x
= PyInt_AsLong(v
);
3940 else if (v
->ob_type
->tp_as_number
&&
3941 PyType_HasFeature(v
->ob_type
, Py_TPFLAGS_HAVE_INDEX
)
3942 && v
->ob_type
->tp_as_number
->nb_index
) {
3943 x
= v
->ob_type
->tp_as_number
->nb_index(v
);
3944 if (x
== -1 && PyErr_Occurred())
3948 PyErr_SetString(PyExc_TypeError
,
3949 "slice indices must be integers or "
3950 "None or have an __index__ method");
3959 #define ISINDEX(x) ((x) == NULL || PyInt_Check(x) || PyLong_Check(x) || \
3960 ((x)->ob_type->tp_as_number && \
3961 PyType_HasFeature((x)->ob_type, Py_TPFLAGS_HAVE_INDEX) \
3962 && (x)->ob_type->tp_as_number->nb_index))
3965 apply_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
) /* return u[v:w] */
3967 PyTypeObject
*tp
= u
->ob_type
;
3968 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
3970 if (sq
&& sq
->sq_slice
&& ISINDEX(v
) && ISINDEX(w
)) {
3971 Py_ssize_t ilow
= 0, ihigh
= PY_SSIZE_T_MAX
;
3972 if (!_PyEval_SliceIndex(v
, &ilow
))
3974 if (!_PyEval_SliceIndex(w
, &ihigh
))
3976 return PySequence_GetSlice(u
, ilow
, ihigh
);
3979 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
3980 if (slice
!= NULL
) {
3981 PyObject
*res
= PyObject_GetItem(u
, slice
);
3991 assign_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
, PyObject
*x
)
3994 PyTypeObject
*tp
= u
->ob_type
;
3995 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
3997 if (sq
&& sq
->sq_slice
&& ISINDEX(v
) && ISINDEX(w
)) {
3998 Py_ssize_t ilow
= 0, ihigh
= PY_SSIZE_T_MAX
;
3999 if (!_PyEval_SliceIndex(v
, &ilow
))
4001 if (!_PyEval_SliceIndex(w
, &ihigh
))
4004 return PySequence_DelSlice(u
, ilow
, ihigh
);
4006 return PySequence_SetSlice(u
, ilow
, ihigh
, x
);
4009 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
4010 if (slice
!= NULL
) {
4013 res
= PyObject_SetItem(u
, slice
, x
);
4015 res
= PyObject_DelItem(u
, slice
);
4025 cmp_outcome(int op
, register PyObject
*v
, register PyObject
*w
)
4036 res
= PySequence_Contains(w
, v
);
4041 res
= PySequence_Contains(w
, v
);
4046 case PyCmp_EXC_MATCH
:
4047 res
= PyErr_GivenExceptionMatches(v
, w
);
4050 return PyObject_RichCompare(v
, w
, op
);
4052 v
= res
? Py_True
: Py_False
;
4058 import_from(PyObject
*v
, PyObject
*name
)
4062 x
= PyObject_GetAttr(v
, name
);
4063 if (x
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
4064 PyErr_Format(PyExc_ImportError
,
4065 "cannot import name %.230s",
4066 PyString_AsString(name
));
4072 import_all_from(PyObject
*locals
, PyObject
*v
)
4074 PyObject
*all
= PyObject_GetAttrString(v
, "__all__");
4075 PyObject
*dict
, *name
, *value
;
4076 int skip_leading_underscores
= 0;
4080 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4081 return -1; /* Unexpected error */
4083 dict
= PyObject_GetAttrString(v
, "__dict__");
4085 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4087 PyErr_SetString(PyExc_ImportError
,
4088 "from-import-* object has no __dict__ and no __all__");
4091 all
= PyMapping_Keys(dict
);
4095 skip_leading_underscores
= 1;
4098 for (pos
= 0, err
= 0; ; pos
++) {
4099 name
= PySequence_GetItem(all
, pos
);
4101 if (!PyErr_ExceptionMatches(PyExc_IndexError
))
4107 if (skip_leading_underscores
&&
4108 PyString_Check(name
) &&
4109 PyString_AS_STRING(name
)[0] == '_')
4114 value
= PyObject_GetAttr(v
, name
);
4118 err
= PyDict_SetItem(locals
, name
, value
);
4129 build_class(PyObject
*methods
, PyObject
*bases
, PyObject
*name
)
4131 PyObject
*metaclass
= NULL
, *result
, *base
;
4133 if (PyDict_Check(methods
))
4134 metaclass
= PyDict_GetItemString(methods
, "__metaclass__");
4135 if (metaclass
!= NULL
)
4136 Py_INCREF(metaclass
);
4137 else if (PyTuple_Check(bases
) && PyTuple_GET_SIZE(bases
) > 0) {
4138 base
= PyTuple_GET_ITEM(bases
, 0);
4139 metaclass
= PyObject_GetAttrString(base
, "__class__");
4140 if (metaclass
== NULL
) {
4142 metaclass
= (PyObject
*)base
->ob_type
;
4143 Py_INCREF(metaclass
);
4147 PyObject
*g
= PyEval_GetGlobals();
4148 if (g
!= NULL
&& PyDict_Check(g
))
4149 metaclass
= PyDict_GetItemString(g
, "__metaclass__");
4150 if (metaclass
== NULL
)
4151 metaclass
= (PyObject
*) &PyClass_Type
;
4152 Py_INCREF(metaclass
);
4154 result
= PyObject_CallFunction(metaclass
, "OOO", name
, bases
, methods
);
4155 Py_DECREF(metaclass
);
4156 if (result
== NULL
&& PyErr_ExceptionMatches(PyExc_TypeError
)) {
4157 /* A type error here likely means that the user passed
4158 in a base that was not a class (such the random module
4159 instead of the random.random type). Help them out with
4160 by augmenting the error message with more information.*/
4162 PyObject
*ptype
, *pvalue
, *ptraceback
;
4164 PyErr_Fetch(&ptype
, &pvalue
, &ptraceback
);
4165 if (PyString_Check(pvalue
)) {
4167 newmsg
= PyString_FromFormat(
4168 "Error when calling the metaclass bases\n %s",
4169 PyString_AS_STRING(pvalue
));
4170 if (newmsg
!= NULL
) {
4175 PyErr_Restore(ptype
, pvalue
, ptraceback
);
4181 exec_statement(PyFrameObject
*f
, PyObject
*prog
, PyObject
*globals
,
4188 if (PyTuple_Check(prog
) && globals
== Py_None
&& locals
== Py_None
&&
4189 ((n
= PyTuple_Size(prog
)) == 2 || n
== 3)) {
4190 /* Backward compatibility hack */
4191 globals
= PyTuple_GetItem(prog
, 1);
4193 locals
= PyTuple_GetItem(prog
, 2);
4194 prog
= PyTuple_GetItem(prog
, 0);
4196 if (globals
== Py_None
) {
4197 globals
= PyEval_GetGlobals();
4198 if (locals
== Py_None
) {
4199 locals
= PyEval_GetLocals();
4203 else if (locals
== Py_None
)
4205 if (!PyString_Check(prog
) &&
4206 !PyUnicode_Check(prog
) &&
4207 !PyCode_Check(prog
) &&
4208 !PyFile_Check(prog
)) {
4209 PyErr_SetString(PyExc_TypeError
,
4210 "exec: arg 1 must be a string, file, or code object");
4213 if (!PyDict_Check(globals
)) {
4214 PyErr_SetString(PyExc_TypeError
,
4215 "exec: arg 2 must be a dictionary or None");
4218 if (!PyMapping_Check(locals
)) {
4219 PyErr_SetString(PyExc_TypeError
,
4220 "exec: arg 3 must be a mapping or None");
4223 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
)
4224 PyDict_SetItemString(globals
, "__builtins__", f
->f_builtins
);
4225 if (PyCode_Check(prog
)) {
4226 if (PyCode_GetNumFree((PyCodeObject
*)prog
) > 0) {
4227 PyErr_SetString(PyExc_TypeError
,
4228 "code object passed to exec may not contain free variables");
4231 v
= PyEval_EvalCode((PyCodeObject
*) prog
, globals
, locals
);
4233 else if (PyFile_Check(prog
)) {
4234 FILE *fp
= PyFile_AsFile(prog
);
4235 char *name
= PyString_AsString(PyFile_Name(prog
));
4238 if (PyEval_MergeCompilerFlags(&cf
))
4239 v
= PyRun_FileFlags(fp
, name
, Py_file_input
, globals
,
4242 v
= PyRun_File(fp
, name
, Py_file_input
, globals
,
4246 PyObject
*tmp
= NULL
;
4250 #ifdef Py_USING_UNICODE
4251 if (PyUnicode_Check(prog
)) {
4252 tmp
= PyUnicode_AsUTF8String(prog
);
4256 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
4259 if (PyString_AsStringAndSize(prog
, &str
, NULL
))
4261 if (PyEval_MergeCompilerFlags(&cf
))
4262 v
= PyRun_StringFlags(str
, Py_file_input
, globals
,
4265 v
= PyRun_String(str
, Py_file_input
, globals
, locals
);
4269 PyFrame_LocalsToFast(f
, 0);
4277 format_exc_check_arg(PyObject
*exc
, char *format_str
, PyObject
*obj
)
4284 obj_str
= PyString_AsString(obj
);
4288 PyErr_Format(exc
, format_str
, obj_str
);
4292 string_concatenate(PyObject
*v
, PyObject
*w
,
4293 PyFrameObject
*f
, unsigned char *next_instr
)
4295 /* This function implements 'variable += expr' when both arguments
4298 if (v
->ob_refcnt
== 2) {
4299 /* In the common case, there are 2 references to the value
4300 * stored in 'variable' when the += is performed: one on the
4301 * value stack (in 'v') and one still stored in the 'variable'.
4302 * We try to delete the variable now to reduce the refcnt to 1.
4304 switch (*next_instr
) {
4307 int oparg
= PEEKARG();
4308 PyObject
**fastlocals
= f
->f_localsplus
;
4309 if (GETLOCAL(oparg
) == v
)
4310 SETLOCAL(oparg
, NULL
);
4315 PyObject
**freevars
= f
->f_localsplus
+ f
->f_nlocals
;
4316 PyObject
*c
= freevars
[PEEKARG()];
4317 if (PyCell_GET(c
) == v
)
4318 PyCell_Set(c
, NULL
);
4323 PyObject
*names
= f
->f_code
->co_names
;
4324 PyObject
*name
= GETITEM(names
, PEEKARG());
4325 PyObject
*locals
= f
->f_locals
;
4326 if (PyDict_CheckExact(locals
) &&
4327 PyDict_GetItem(locals
, name
) == v
) {
4328 if (PyDict_DelItem(locals
, name
) != 0) {
4337 if (v
->ob_refcnt
== 1 && !PyString_CHECK_INTERNED(v
)) {
4338 /* Now we own the last reference to 'v', so we can resize it
4341 int v_len
= PyString_GET_SIZE(v
);
4342 int w_len
= PyString_GET_SIZE(w
);
4343 if (_PyString_Resize(&v
, v_len
+ w_len
) != 0) {
4344 /* XXX if _PyString_Resize() fails, 'v' has been
4345 * deallocated so it cannot be put back into 'variable'.
4346 * The MemoryError is raised when there is no value in
4347 * 'variable', which might (very remotely) be a cause
4348 * of incompatibilities.
4352 /* copy 'w' into the newly allocated area of 'v' */
4353 memcpy(PyString_AS_STRING(v
) + v_len
,
4354 PyString_AS_STRING(w
), w_len
);
4358 /* When in-place resizing is not an option. */
4359 PyString_Concat(&v
, w
);
4364 #ifdef DYNAMIC_EXECUTION_PROFILE
4367 getarray(long a
[256])
4370 PyObject
*l
= PyList_New(256);
4371 if (l
== NULL
) return NULL
;
4372 for (i
= 0; i
< 256; i
++) {
4373 PyObject
*x
= PyInt_FromLong(a
[i
]);
4378 PyList_SetItem(l
, i
, x
);
4380 for (i
= 0; i
< 256; i
++)
4386 _Py_GetDXProfile(PyObject
*self
, PyObject
*args
)
4389 return getarray(dxp
);
4392 PyObject
*l
= PyList_New(257);
4393 if (l
== NULL
) return NULL
;
4394 for (i
= 0; i
< 257; i
++) {
4395 PyObject
*x
= getarray(dxpairs
[i
]);
4400 PyList_SetItem(l
, i
, x
);