2 /* Execute compiled code */
5 XXX speed up searching for keywords by using a dictionary
9 /* enable more aggressive intra-module optimizations, where available */
10 #define PY_LOCAL_AGGRESSIVE
15 #include "frameobject.h"
18 #include "structmember.h"
24 #define READ_TIMESTAMP(var)
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 platform,
32 irrespective of OS. POWER? Who knows :-) */
34 #define READ_TIMESTAMP(var) ppc_getcounter(&var)
37 ppc_getcounter(uint64
*v
)
39 register unsigned long tbu
, tb
, tbu2
;
42 asm volatile ("mftbu %0" : "=r" (tbu
) );
43 asm volatile ("mftb %0" : "=r" (tb
) );
44 asm volatile ("mftbu %0" : "=r" (tbu2
));
45 if (__builtin_expect(tbu
!= tbu2
, 0)) goto loop
;
47 /* The slightly peculiar way of writing the next lines is
48 compiled better by GCC than any other way I tried. */
49 ((long*)(v
))[0] = tbu
;
53 #else /* this is for linux/x86 (and probably any other GCC/x86 combo) */
55 #define READ_TIMESTAMP(val) \
56 __asm__ __volatile__("rdtsc" : "=A" (val))
60 void dump_tsc(int opcode
, int ticked
, uint64 inst0
, uint64 inst1
,
61 uint64 loop0
, uint64 loop1
, uint64 intr0
, uint64 intr1
)
63 uint64 intr
, inst
, loop
;
64 PyThreadState
*tstate
= PyThreadState_Get();
65 if (!tstate
->interp
->tscdump
)
68 inst
= inst1
- inst0
- intr
;
69 loop
= loop1
- loop0
- intr
;
70 fprintf(stderr
, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
71 opcode
, ticked
, inst
, loop
);
76 /* Turn this on if your compiler chokes on the big switch: */
77 /* #define CASE_TOO_BIG 1 */
80 /* For debugging the interpreter: */
81 #define LLTRACE 1 /* Low-level trace feature */
82 #define CHECKEXC 1 /* Double-check exception checking */
85 typedef PyObject
*(*callproc
)(PyObject
*, PyObject
*, PyObject
*);
87 /* Forward declarations */
89 static PyObject
* call_function(PyObject
***, int, uint64
*, uint64
*);
91 static PyObject
* call_function(PyObject
***, int);
93 static PyObject
* fast_function(PyObject
*, PyObject
***, int, int, int);
94 static PyObject
* do_call(PyObject
*, PyObject
***, int, int);
95 static PyObject
* ext_do_call(PyObject
*, PyObject
***, int, int, int);
96 static PyObject
* update_keyword_args(PyObject
*, int, PyObject
***,PyObject
*);
97 static PyObject
* update_star_args(int, int, PyObject
*, PyObject
***);
98 static PyObject
* load_args(PyObject
***, int);
99 #define CALL_FLAG_VAR 1
100 #define CALL_FLAG_KW 2
104 static int prtrace(PyObject
*, char *);
106 static int call_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*,
108 static void call_trace_protected(Py_tracefunc
, PyObject
*,
109 PyFrameObject
*, int, PyObject
*);
110 static void call_exc_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*);
111 static int maybe_call_line_trace(Py_tracefunc
, PyObject
*,
112 PyFrameObject
*, int *, int *, int *);
114 static PyObject
* apply_slice(PyObject
*, PyObject
*, PyObject
*);
115 static int assign_slice(PyObject
*, PyObject
*,
116 PyObject
*, PyObject
*);
117 static PyObject
* cmp_outcome(int, PyObject
*, PyObject
*);
118 static PyObject
* import_from(PyObject
*, PyObject
*);
119 static int import_all_from(PyObject
*, PyObject
*);
120 static PyObject
* build_class(PyObject
*, PyObject
*, PyObject
*);
121 static int exec_statement(PyFrameObject
*,
122 PyObject
*, PyObject
*, PyObject
*);
123 static void set_exc_info(PyThreadState
*, PyObject
*, PyObject
*, PyObject
*);
124 static void reset_exc_info(PyThreadState
*);
125 static void format_exc_check_arg(PyObject
*, char *, PyObject
*);
126 static PyObject
* string_concatenate(PyObject
*, PyObject
*,
127 PyFrameObject
*, unsigned char *);
129 #define NAME_ERROR_MSG \
130 "name '%.200s' is not defined"
131 #define GLOBAL_NAME_ERROR_MSG \
132 "global name '%.200s' is not defined"
133 #define UNBOUNDLOCAL_ERROR_MSG \
134 "local variable '%.200s' referenced before assignment"
135 #define UNBOUNDFREE_ERROR_MSG \
136 "free variable '%.200s' referenced before assignment" \
137 " in enclosing scope"
139 /* Dynamic execution profile */
140 #ifdef DYNAMIC_EXECUTION_PROFILE
142 static long dxpairs
[257][256];
143 #define dxp dxpairs[256]
145 static long dxp
[256];
149 /* Function call profile */
152 static int pcall
[PCALL_NUM
];
155 #define PCALL_FUNCTION 1
156 #define PCALL_FAST_FUNCTION 2
157 #define PCALL_FASTER_FUNCTION 3
158 #define PCALL_METHOD 4
159 #define PCALL_BOUND_METHOD 5
160 #define PCALL_CFUNCTION 6
162 #define PCALL_GENERATOR 8
163 #define PCALL_OTHER 9
166 /* Notes about the statistics
170 FAST_FUNCTION means no argument tuple needs to be created.
171 FASTER_FUNCTION means that the fast-path frame setup code is used.
173 If there is a method call where the call can be optimized by changing
174 the argument tuple and calling the function directly, it gets recorded
177 As a result, the relationship among the statistics appears to be
178 PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
179 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
180 PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
181 PCALL_METHOD > PCALL_BOUND_METHOD
184 #define PCALL(POS) pcall[POS]++
187 PyEval_GetCallStats(PyObject
*self
)
189 return Py_BuildValue("iiiiiiiiiii",
190 pcall
[0], pcall
[1], pcall
[2], pcall
[3],
191 pcall
[4], pcall
[5], pcall
[6], pcall
[7],
192 pcall
[8], pcall
[9], pcall
[10]);
198 PyEval_GetCallStats(PyObject
*self
)
211 #include "pythread.h"
213 static PyThread_type_lock interpreter_lock
= 0; /* This is the GIL */
214 static long main_thread
= 0;
217 PyEval_ThreadsInitialized(void)
219 return interpreter_lock
!= 0;
223 PyEval_InitThreads(void)
225 if (interpreter_lock
)
227 interpreter_lock
= PyThread_allocate_lock();
228 PyThread_acquire_lock(interpreter_lock
, 1);
229 main_thread
= PyThread_get_thread_ident();
233 PyEval_AcquireLock(void)
235 PyThread_acquire_lock(interpreter_lock
, 1);
239 PyEval_ReleaseLock(void)
241 PyThread_release_lock(interpreter_lock
);
245 PyEval_AcquireThread(PyThreadState
*tstate
)
248 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
249 /* Check someone has called PyEval_InitThreads() to create the lock */
250 assert(interpreter_lock
);
251 PyThread_acquire_lock(interpreter_lock
, 1);
252 if (PyThreadState_Swap(tstate
) != NULL
)
254 "PyEval_AcquireThread: non-NULL old thread state");
258 PyEval_ReleaseThread(PyThreadState
*tstate
)
261 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
262 if (PyThreadState_Swap(NULL
) != tstate
)
263 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
264 PyThread_release_lock(interpreter_lock
);
267 /* This function is called from PyOS_AfterFork to ensure that newly
268 created child processes don't hold locks referring to threads which
269 are not running in the child process. (This could also be done using
270 pthread_atfork mechanism, at least for the pthreads implementation.) */
273 PyEval_ReInitThreads(void)
275 if (!interpreter_lock
)
277 /*XXX Can't use PyThread_free_lock here because it does too
278 much error-checking. Doing this cleanly would require
279 adding a new function to each thread_*.h. Instead, just
280 create a new lock and waste a little bit of memory */
281 interpreter_lock
= PyThread_allocate_lock();
282 PyThread_acquire_lock(interpreter_lock
, 1);
283 main_thread
= PyThread_get_thread_ident();
287 /* Functions save_thread and restore_thread are always defined so
288 dynamically loaded modules needn't be compiled separately for use
289 with and without threads: */
292 PyEval_SaveThread(void)
294 PyThreadState
*tstate
= PyThreadState_Swap(NULL
);
296 Py_FatalError("PyEval_SaveThread: NULL tstate");
298 if (interpreter_lock
)
299 PyThread_release_lock(interpreter_lock
);
305 PyEval_RestoreThread(PyThreadState
*tstate
)
308 Py_FatalError("PyEval_RestoreThread: NULL tstate");
310 if (interpreter_lock
) {
312 PyThread_acquire_lock(interpreter_lock
, 1);
316 PyThreadState_Swap(tstate
);
320 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
321 signal handlers or Mac I/O completion routines) can schedule calls
322 to a function to be called synchronously.
323 The synchronous function is called with one void* argument.
324 It should return 0 for success or -1 for failure -- failure should
325 be accompanied by an exception.
327 If registry succeeds, the registry function returns 0; if it fails
328 (e.g. due to too many pending calls) it returns -1 (without setting
329 an exception condition).
331 Note that because registry may occur from within signal handlers,
332 or other asynchronous events, calling malloc() is unsafe!
335 Any thread can schedule pending calls, but only the main thread
339 XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE!
340 There are two possible race conditions:
341 (1) nested asynchronous registry calls;
342 (2) registry calls made while pending calls are being processed.
343 While (1) is very unlikely, (2) is a real possibility.
344 The current code is safe against (2), but not against (1).
345 The safety against (2) is derived from the fact that only one
346 thread (the main thread) ever takes things out of the queue.
348 XXX Darn! With the advent of thread state, we should have an array
349 of pending calls per thread in the thread state! Later...
352 #define NPENDINGCALLS 32
356 } pendingcalls
[NPENDINGCALLS
];
357 static volatile int pendingfirst
= 0;
358 static volatile int pendinglast
= 0;
359 static volatile int things_to_do
= 0;
362 Py_AddPendingCall(int (*func
)(void *), void *arg
)
364 static volatile int busy
= 0;
366 /* XXX Begin critical section */
367 /* XXX If you want this to be safe against nested
368 XXX asynchronous calls, you'll have to work harder! */
373 j
= (i
+ 1) % NPENDINGCALLS
;
374 if (j
== pendingfirst
) {
376 return -1; /* Queue full */
378 pendingcalls
[i
].func
= func
;
379 pendingcalls
[i
].arg
= arg
;
383 things_to_do
= 1; /* Signal main loop */
385 /* XXX End critical section */
390 Py_MakePendingCalls(void)
394 if (main_thread
&& PyThread_get_thread_ident() != main_thread
)
406 if (i
== pendinglast
)
407 break; /* Queue empty */
408 func
= pendingcalls
[i
].func
;
409 arg
= pendingcalls
[i
].arg
;
410 pendingfirst
= (i
+ 1) % NPENDINGCALLS
;
413 things_to_do
= 1; /* We're not done yet */
422 /* The interpreter's recursion limit */
424 #ifndef Py_DEFAULT_RECURSION_LIMIT
425 #define Py_DEFAULT_RECURSION_LIMIT 1000
427 static int recursion_limit
= Py_DEFAULT_RECURSION_LIMIT
;
428 int _Py_CheckRecursionLimit
= Py_DEFAULT_RECURSION_LIMIT
;
431 Py_GetRecursionLimit(void)
433 return recursion_limit
;
437 Py_SetRecursionLimit(int new_limit
)
439 recursion_limit
= new_limit
;
440 _Py_CheckRecursionLimit
= recursion_limit
;
443 /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
444 if the recursion_depth reaches _Py_CheckRecursionLimit.
445 If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
446 to guarantee that _Py_CheckRecursiveCall() is regularly called.
447 Without USE_STACKCHECK, there is no need for this. */
449 _Py_CheckRecursiveCall(char *where
)
451 PyThreadState
*tstate
= PyThreadState_GET();
453 #ifdef USE_STACKCHECK
454 if (PyOS_CheckStack()) {
455 --tstate
->recursion_depth
;
456 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
460 if (tstate
->recursion_depth
> recursion_limit
) {
461 --tstate
->recursion_depth
;
462 PyErr_Format(PyExc_RuntimeError
,
463 "maximum recursion depth exceeded%s",
467 _Py_CheckRecursionLimit
= recursion_limit
;
471 /* Status code for main loop (reason for stack unwind) */
473 WHY_NOT
= 0x0001, /* No error */
474 WHY_EXCEPTION
= 0x0002, /* Exception occurred */
475 WHY_RERAISE
= 0x0004, /* Exception re-raised by 'finally' */
476 WHY_RETURN
= 0x0008, /* 'return' statement */
477 WHY_BREAK
= 0x0010, /* 'break' statement */
478 WHY_CONTINUE
= 0x0020, /* 'continue' statement */
479 WHY_YIELD
= 0x0040 /* 'yield' operator */
482 static enum why_code
do_raise(PyObject
*, PyObject
*, PyObject
*);
483 static int unpack_iterable(PyObject
*, int, PyObject
**);
485 /* for manipulating the thread switch and periodic "stuff" - used to be
486 per thread, now just a pair o' globals */
487 int _Py_CheckInterval
= 100;
488 volatile int _Py_Ticker
= 100;
491 PyEval_EvalCode(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
)
493 return PyEval_EvalCodeEx(co
,
495 (PyObject
**)NULL
, 0,
496 (PyObject
**)NULL
, 0,
497 (PyObject
**)NULL
, 0,
502 /* Interpreter main loop */
505 PyEval_EvalFrame(PyFrameObject
*f
) {
506 /* This is for backward compatibility with extension modules that
507 used this API; core interpreter code should call PyEval_EvalFrameEx() */
508 return PyEval_EvalFrameEx(f
, 0);
512 PyEval_EvalFrameEx(PyFrameObject
*f
, int throwflag
)
517 register PyObject
**stack_pointer
; /* Next free slot in value stack */
518 register unsigned char *next_instr
;
519 register int opcode
; /* Current opcode */
520 register int oparg
; /* Current opcode argument, if any */
521 register enum why_code why
; /* Reason for block stack unwind */
522 register int err
; /* Error status -- nonzero if error */
523 register PyObject
*x
; /* Result object -- NULL if error */
524 register PyObject
*v
; /* Temporary objects popped off stack */
525 register PyObject
*w
;
526 register PyObject
*u
;
527 register PyObject
*t
;
528 register PyObject
*stream
= NULL
; /* for PRINT opcodes */
529 register PyObject
**fastlocals
, **freevars
;
530 PyObject
*retval
= NULL
; /* Return value */
531 PyThreadState
*tstate
= PyThreadState_GET();
534 /* when tracing we set things up so that
536 not (instr_lb <= current_bytecode_offset < instr_ub)
538 is true when the line being executed has changed. The
539 initial values are such as to make this false the first
540 time it is tested. */
541 int instr_ub
= -1, instr_lb
= 0, instr_prev
= -1;
543 unsigned char *first_instr
;
546 #if defined(Py_DEBUG) || defined(LLTRACE)
547 /* Make it easier to find out where we are with a debugger */
551 /* Tuple access macros */
554 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
556 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
560 /* Use Pentium timestamp counter to mark certain events:
561 inst0 -- beginning of switch statement for opcode dispatch
562 inst1 -- end of switch statement (may be skipped)
563 loop0 -- the top of the mainloop
564 loop1 -- place where control returns again to top of mainloop
566 intr1 -- beginning of long interruption
567 intr2 -- end of long interruption
569 Many opcodes call out to helper C functions. In some cases, the
570 time in those functions should be counted towards the time for the
571 opcode, but not in all cases. For example, a CALL_FUNCTION opcode
572 calls another Python function; there's no point in charge all the
573 bytecode executed by the called function to the caller.
575 It's hard to make a useful judgement statically. In the presence
576 of operator overloading, it's impossible to tell if a call will
577 execute new Python code or not.
579 It's a case-by-case judgement. I'll use intr1 for the following
585 CALL_FUNCTION (and friends)
588 uint64 inst0
, inst1
, loop0
, loop1
, intr0
= 0, intr1
= 0;
591 READ_TIMESTAMP(inst0
);
592 READ_TIMESTAMP(inst1
);
593 READ_TIMESTAMP(loop0
);
594 READ_TIMESTAMP(loop1
);
596 /* shut up the compiler */
600 /* Code access macros */
602 #define INSTR_OFFSET() ((int)(next_instr - first_instr))
603 #define NEXTOP() (*next_instr++)
604 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
605 #define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
606 #define JUMPTO(x) (next_instr = first_instr + (x))
607 #define JUMPBY(x) (next_instr += (x))
609 /* OpCode prediction macros
610 Some opcodes tend to come in pairs thus making it possible to predict
611 the second code when the first is run. For example, COMPARE_OP is often
612 followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, those opcodes are often
613 followed by a POP_TOP.
615 Verifying the prediction costs a single high-speed test of register
616 variable against a constant. If the pairing was good, then the
617 processor has a high likelihood of making its own successful branch
618 prediction which results in a nearly zero overhead transition to the
621 A successful prediction saves a trip through the eval-loop including
622 its two unpredictable branches, the HASARG test and the switch-case.
624 If collecting opcode statistics, turn off prediction so that
625 statistics are accurately maintained (the predictions bypass
626 the opcode frequency counter updates).
629 #ifdef DYNAMIC_EXECUTION_PROFILE
630 #define PREDICT(op) if (0) goto PRED_##op
632 #define PREDICT(op) if (*next_instr == op) goto PRED_##op
635 #define PREDICTED(op) PRED_##op: next_instr++
636 #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
638 /* Stack manipulation macros */
640 /* The stack can grow at most MAXINT deep, as co_nlocals and
641 co_stacksize are ints. */
642 #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
643 #define EMPTY() (STACK_LEVEL() == 0)
644 #define TOP() (stack_pointer[-1])
645 #define SECOND() (stack_pointer[-2])
646 #define THIRD() (stack_pointer[-3])
647 #define FOURTH() (stack_pointer[-4])
648 #define SET_TOP(v) (stack_pointer[-1] = (v))
649 #define SET_SECOND(v) (stack_pointer[-2] = (v))
650 #define SET_THIRD(v) (stack_pointer[-3] = (v))
651 #define SET_FOURTH(v) (stack_pointer[-4] = (v))
652 #define BASIC_STACKADJ(n) (stack_pointer += n)
653 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
654 #define BASIC_POP() (*--stack_pointer)
657 #define PUSH(v) { (void)(BASIC_PUSH(v), \
658 lltrace && prtrace(TOP(), "push")); \
659 assert(STACK_LEVEL() <= co->co_stacksize); }
660 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP())
661 #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
662 lltrace && prtrace(TOP(), "stackadj")); \
663 assert(STACK_LEVEL() <= co->co_stacksize); }
664 #define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], "ext_pop"), *--(STACK_POINTER))
666 #define PUSH(v) BASIC_PUSH(v)
667 #define POP() BASIC_POP()
668 #define STACKADJ(n) BASIC_STACKADJ(n)
669 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
672 /* Local variable macros */
674 #define GETLOCAL(i) (fastlocals[i])
676 /* The SETLOCAL() macro must not DECREF the local variable in-place and
677 then store the new value; it must copy the old value to a temporary
678 value, then store the new value, and then DECREF the temporary value.
679 This is because it is possible that during the DECREF the frame is
680 accessed by other code (e.g. a __del__ method or gc.collect()) and the
681 variable would be pointing to already-freed memory. */
682 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
683 GETLOCAL(i) = value; \
684 Py_XDECREF(tmp); } while (0)
692 if (Py_EnterRecursiveCall(""))
697 if (tstate
->use_tracing
) {
698 if (tstate
->c_tracefunc
!= NULL
) {
699 /* tstate->c_tracefunc, if defined, is a
700 function that will be called on *every* entry
701 to a code block. Its return value, if not
702 None, is a function that will be called at
703 the start of each executed line of code.
704 (Actually, the function must return itself
705 in order to continue tracing.) The trace
706 functions are called with three arguments:
707 a pointer to the current frame, a string
708 indicating why the function is called, and
709 an argument which depends on the situation.
710 The global trace function is also called
711 whenever an exception is detected. */
712 if (call_trace(tstate
->c_tracefunc
, tstate
->c_traceobj
,
713 f
, PyTrace_CALL
, Py_None
)) {
714 /* Trace function raised an error */
715 goto exit_eval_frame
;
718 if (tstate
->c_profilefunc
!= NULL
) {
719 /* Similar for c_profilefunc, except it needn't
720 return itself and isn't called for "line" events */
721 if (call_trace(tstate
->c_profilefunc
,
722 tstate
->c_profileobj
,
723 f
, PyTrace_CALL
, Py_None
)) {
724 /* Profile function raised an error */
725 goto exit_eval_frame
;
731 names
= co
->co_names
;
732 consts
= co
->co_consts
;
733 fastlocals
= f
->f_localsplus
;
734 freevars
= f
->f_localsplus
+ co
->co_nlocals
;
735 first_instr
= (unsigned char*) PyString_AS_STRING(co
->co_code
);
736 /* An explanation is in order for the next line.
738 f->f_lasti now refers to the index of the last instruction
739 executed. You might think this was obvious from the name, but
740 this wasn't always true before 2.3! PyFrame_New now sets
741 f->f_lasti to -1 (i.e. the index *before* the first instruction)
742 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
745 When the PREDICT() macros are enabled, some opcode pairs follow in
746 direct succession without updating f->f_lasti. A successful
747 prediction effectively links the two codes together as if they
748 were a single new opcode; accordingly,f->f_lasti will point to
749 the first code in the pair (for instance, GET_ITER followed by
750 FOR_ITER is effectively a single opcode and f->f_lasti will point
751 at to the beginning of the combined pair.)
753 next_instr
= first_instr
+ f
->f_lasti
+ 1;
754 stack_pointer
= f
->f_stacktop
;
755 assert(stack_pointer
!= NULL
);
756 f
->f_stacktop
= NULL
; /* remains NULL unless yield suspends frame */
759 lltrace
= PyDict_GetItemString(f
->f_globals
, "__lltrace__") != NULL
;
761 #if defined(Py_DEBUG) || defined(LLTRACE)
762 filename
= PyString_AsString(co
->co_filename
);
767 x
= Py_None
; /* Not a reference, just anything non-NULL */
770 if (throwflag
) { /* support for generator.throw() */
778 /* Almost surely, the opcode executed a break
779 or a continue, preventing inst1 from being set
780 on the way out of the loop.
782 READ_TIMESTAMP(inst1
);
785 dump_tsc(opcode
, ticked
, inst0
, inst1
, loop0
, loop1
,
791 READ_TIMESTAMP(loop0
);
793 assert(stack_pointer
>= f
->f_valuestack
); /* else underflow */
794 assert(STACK_LEVEL() <= co
->co_stacksize
); /* else overflow */
796 /* Do periodic things. Doing this every time through
797 the loop would add too much overhead, so we do it
798 only every Nth instruction. We also do it if
799 ``things_to_do'' is set, i.e. when an asynchronous
800 event needs attention (e.g. a signal handler or
801 async I/O handler); see Py_AddPendingCall() and
802 Py_MakePendingCalls() above. */
804 if (--_Py_Ticker
< 0) {
805 if (*next_instr
== SETUP_FINALLY
) {
806 /* Make the last opcode before
807 a try: finally: block uninterruptable. */
808 goto fast_next_opcode
;
810 _Py_Ticker
= _Py_CheckInterval
;
811 tstate
->tick_counter
++;
816 if (Py_MakePendingCalls() < 0) {
821 /* MakePendingCalls() didn't succeed.
822 Force early re-execution of this
823 "periodic" code, possibly after
828 if (interpreter_lock
) {
829 /* Give another thread a chance */
831 if (PyThreadState_Swap(NULL
) != tstate
)
832 Py_FatalError("ceval: tstate mix-up");
833 PyThread_release_lock(interpreter_lock
);
835 /* Other threads may run now */
837 PyThread_acquire_lock(interpreter_lock
, 1);
838 if (PyThreadState_Swap(tstate
) != NULL
)
839 Py_FatalError("ceval: orphan tstate");
841 /* Check for thread interrupts */
843 if (tstate
->async_exc
!= NULL
) {
844 x
= tstate
->async_exc
;
845 tstate
->async_exc
= NULL
;
856 f
->f_lasti
= INSTR_OFFSET();
858 /* line-by-line tracing support */
860 if (tstate
->c_tracefunc
!= NULL
&& !tstate
->tracing
) {
861 /* see maybe_call_line_trace
862 for expository comments */
863 f
->f_stacktop
= stack_pointer
;
865 err
= maybe_call_line_trace(tstate
->c_tracefunc
,
867 f
, &instr_lb
, &instr_ub
,
869 /* Reload possibly changed frame fields */
871 if (f
->f_stacktop
!= NULL
) {
872 stack_pointer
= f
->f_stacktop
;
873 f
->f_stacktop
= NULL
;
876 /* trace function raised an exception */
881 /* Extract opcode and argument */
884 oparg
= 0; /* allows oparg to be stored in a register because
885 it doesn't have to be remembered across a full loop */
889 #ifdef DYNAMIC_EXECUTION_PROFILE
891 dxpairs
[lastopcode
][opcode
]++;
898 /* Instruction tracing */
901 if (HAS_ARG(opcode
)) {
902 printf("%d: %d, %d\n",
903 f
->f_lasti
, opcode
, oparg
);
912 /* Main switch on opcode */
913 READ_TIMESTAMP(inst0
);
918 It is essential that any operation that fails sets either
919 x to NULL, err to nonzero, or why to anything but WHY_NOT,
920 and that no operation that succeeds does this! */
922 /* case STOP_CODE: this is an error! */
925 goto fast_next_opcode
;
932 goto fast_next_opcode
;
934 format_exc_check_arg(PyExc_UnboundLocalError
,
935 UNBOUNDLOCAL_ERROR_MSG
,
936 PyTuple_GetItem(co
->co_varnames
, oparg
));
940 x
= GETITEM(consts
, oparg
);
943 goto fast_next_opcode
;
945 PREDICTED_WITH_ARG(STORE_FAST
);
949 goto fast_next_opcode
;
955 goto fast_next_opcode
;
962 goto fast_next_opcode
;
971 goto fast_next_opcode
;
982 goto fast_next_opcode
;
988 goto fast_next_opcode
;
999 goto fast_next_opcode
;
1000 } else if (oparg
== 3) {
1011 goto fast_next_opcode
;
1013 Py_FatalError("invalid argument to DUP_TOPX"
1014 " (bytecode corruption?)");
1017 case UNARY_POSITIVE
:
1019 x
= PyNumber_Positive(v
);
1022 if (x
!= NULL
) continue;
1025 case UNARY_NEGATIVE
:
1027 x
= PyNumber_Negative(v
);
1030 if (x
!= NULL
) continue;
1035 err
= PyObject_IsTrue(v
);
1043 Py_INCREF(Py_False
);
1053 x
= PyObject_Repr(v
);
1056 if (x
!= NULL
) continue;
1061 x
= PyNumber_Invert(v
);
1064 if (x
!= NULL
) continue;
1070 x
= PyNumber_Power(v
, w
, Py_None
);
1074 if (x
!= NULL
) continue;
1077 case BINARY_MULTIPLY
:
1080 x
= PyNumber_Multiply(v
, w
);
1084 if (x
!= NULL
) continue;
1088 if (!_Py_QnewFlag
) {
1091 x
= PyNumber_Divide(v
, w
);
1095 if (x
!= NULL
) continue;
1098 /* -Qnew is in effect: fall through to
1099 BINARY_TRUE_DIVIDE */
1100 case BINARY_TRUE_DIVIDE
:
1103 x
= PyNumber_TrueDivide(v
, w
);
1107 if (x
!= NULL
) continue;
1110 case BINARY_FLOOR_DIVIDE
:
1113 x
= PyNumber_FloorDivide(v
, w
);
1117 if (x
!= NULL
) continue;
1123 x
= PyNumber_Remainder(v
, w
);
1127 if (x
!= NULL
) continue;
1133 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1134 /* INLINE: int + int */
1135 register long a
, b
, i
;
1136 a
= PyInt_AS_LONG(v
);
1137 b
= PyInt_AS_LONG(w
);
1139 if ((i
^a
) < 0 && (i
^b
) < 0)
1141 x
= PyInt_FromLong(i
);
1143 else if (PyString_CheckExact(v
) &&
1144 PyString_CheckExact(w
)) {
1145 x
= string_concatenate(v
, w
, f
, next_instr
);
1146 /* string_concatenate consumed the ref to v */
1147 goto skip_decref_vx
;
1151 x
= PyNumber_Add(v
, w
);
1157 if (x
!= NULL
) continue;
1160 case BINARY_SUBTRACT
:
1163 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1164 /* INLINE: int - int */
1165 register long a
, b
, i
;
1166 a
= PyInt_AS_LONG(v
);
1167 b
= PyInt_AS_LONG(w
);
1169 if ((i
^a
) < 0 && (i
^~b
) < 0)
1171 x
= PyInt_FromLong(i
);
1175 x
= PyNumber_Subtract(v
, w
);
1180 if (x
!= NULL
) continue;
1186 if (PyList_CheckExact(v
) && PyInt_CheckExact(w
)) {
1187 /* INLINE: list[int] */
1188 Py_ssize_t i
= PyInt_AsSsize_t(w
);
1190 i
+= PyList_GET_SIZE(v
);
1191 if (i
>= 0 && i
< PyList_GET_SIZE(v
)) {
1192 x
= PyList_GET_ITEM(v
, i
);
1200 x
= PyObject_GetItem(v
, w
);
1204 if (x
!= NULL
) continue;
1210 x
= PyNumber_Lshift(v
, w
);
1214 if (x
!= NULL
) continue;
1220 x
= PyNumber_Rshift(v
, w
);
1224 if (x
!= NULL
) continue;
1230 x
= PyNumber_And(v
, w
);
1234 if (x
!= NULL
) continue;
1240 x
= PyNumber_Xor(v
, w
);
1244 if (x
!= NULL
) continue;
1250 x
= PyNumber_Or(v
, w
);
1254 if (x
!= NULL
) continue;
1260 err
= PyList_Append(v
, w
);
1264 PREDICT(JUMP_ABSOLUTE
);
1272 x
= PyNumber_InPlacePower(v
, w
, Py_None
);
1276 if (x
!= NULL
) continue;
1279 case INPLACE_MULTIPLY
:
1282 x
= PyNumber_InPlaceMultiply(v
, w
);
1286 if (x
!= NULL
) continue;
1289 case INPLACE_DIVIDE
:
1290 if (!_Py_QnewFlag
) {
1293 x
= PyNumber_InPlaceDivide(v
, w
);
1297 if (x
!= NULL
) continue;
1300 /* -Qnew is in effect: fall through to
1301 INPLACE_TRUE_DIVIDE */
1302 case INPLACE_TRUE_DIVIDE
:
1305 x
= PyNumber_InPlaceTrueDivide(v
, w
);
1309 if (x
!= NULL
) continue;
1312 case INPLACE_FLOOR_DIVIDE
:
1315 x
= PyNumber_InPlaceFloorDivide(v
, w
);
1319 if (x
!= NULL
) continue;
1322 case INPLACE_MODULO
:
1325 x
= PyNumber_InPlaceRemainder(v
, w
);
1329 if (x
!= NULL
) continue;
1335 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1336 /* INLINE: int + int */
1337 register long a
, b
, i
;
1338 a
= PyInt_AS_LONG(v
);
1339 b
= PyInt_AS_LONG(w
);
1341 if ((i
^a
) < 0 && (i
^b
) < 0)
1343 x
= PyInt_FromLong(i
);
1345 else if (PyString_CheckExact(v
) &&
1346 PyString_CheckExact(w
)) {
1347 x
= string_concatenate(v
, w
, f
, next_instr
);
1348 /* string_concatenate consumed the ref to v */
1353 x
= PyNumber_InPlaceAdd(v
, w
);
1359 if (x
!= NULL
) continue;
1362 case INPLACE_SUBTRACT
:
1365 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1366 /* INLINE: int - int */
1367 register long a
, b
, i
;
1368 a
= PyInt_AS_LONG(v
);
1369 b
= PyInt_AS_LONG(w
);
1371 if ((i
^a
) < 0 && (i
^~b
) < 0)
1373 x
= PyInt_FromLong(i
);
1377 x
= PyNumber_InPlaceSubtract(v
, w
);
1382 if (x
!= NULL
) continue;
1385 case INPLACE_LSHIFT
:
1388 x
= PyNumber_InPlaceLshift(v
, w
);
1392 if (x
!= NULL
) continue;
1395 case INPLACE_RSHIFT
:
1398 x
= PyNumber_InPlaceRshift(v
, w
);
1402 if (x
!= NULL
) continue;
1408 x
= PyNumber_InPlaceAnd(v
, w
);
1412 if (x
!= NULL
) continue;
1418 x
= PyNumber_InPlaceXor(v
, w
);
1422 if (x
!= NULL
) continue;
1428 x
= PyNumber_InPlaceOr(v
, w
);
1432 if (x
!= NULL
) continue;
1439 if ((opcode
-SLICE
) & 2)
1443 if ((opcode
-SLICE
) & 1)
1448 x
= apply_slice(u
, v
, w
);
1453 if (x
!= NULL
) continue;
1460 if ((opcode
-STORE_SLICE
) & 2)
1464 if ((opcode
-STORE_SLICE
) & 1)
1470 err
= assign_slice(u
, v
, w
, t
); /* u[v:w] = t */
1475 if (err
== 0) continue;
1478 case DELETE_SLICE
+0:
1479 case DELETE_SLICE
+1:
1480 case DELETE_SLICE
+2:
1481 case DELETE_SLICE
+3:
1482 if ((opcode
-DELETE_SLICE
) & 2)
1486 if ((opcode
-DELETE_SLICE
) & 1)
1491 err
= assign_slice(u
, v
, w
, (PyObject
*)NULL
);
1496 if (err
== 0) continue;
1505 err
= PyObject_SetItem(v
, w
, u
);
1509 if (err
== 0) continue;
1517 err
= PyObject_DelItem(v
, w
);
1520 if (err
== 0) continue;
1525 w
= PySys_GetObject("displayhook");
1527 PyErr_SetString(PyExc_RuntimeError
,
1528 "lost sys.displayhook");
1533 x
= PyTuple_Pack(1, v
);
1538 w
= PyEval_CallObject(w
, x
);
1549 /* fall through to PRINT_ITEM */
1553 if (stream
== NULL
|| stream
== Py_None
) {
1554 w
= PySys_GetObject("stdout");
1556 PyErr_SetString(PyExc_RuntimeError
,
1561 /* PyFile_SoftSpace() can exececute arbitrary code
1562 if sys.stdout is an instance with a __getattr__.
1563 If __getattr__ raises an exception, w will
1564 be freed, so we need to prevent that temporarily. */
1566 if (w
!= NULL
&& PyFile_SoftSpace(w
, 0))
1567 err
= PyFile_WriteString(" ", w
);
1569 err
= PyFile_WriteObject(v
, w
, Py_PRINT_RAW
);
1571 /* XXX move into writeobject() ? */
1572 if (PyString_Check(v
)) {
1573 char *s
= PyString_AS_STRING(v
);
1574 Py_ssize_t len
= PyString_GET_SIZE(v
);
1576 !isspace(Py_CHARMASK(s
[len
-1])) ||
1578 PyFile_SoftSpace(w
, 1);
1580 #ifdef Py_USING_UNICODE
1581 else if (PyUnicode_Check(v
)) {
1582 Py_UNICODE
*s
= PyUnicode_AS_UNICODE(v
);
1583 Py_ssize_t len
= PyUnicode_GET_SIZE(v
);
1585 !Py_UNICODE_ISSPACE(s
[len
-1]) ||
1587 PyFile_SoftSpace(w
, 1);
1591 PyFile_SoftSpace(w
, 1);
1601 case PRINT_NEWLINE_TO
:
1603 /* fall through to PRINT_NEWLINE */
1606 if (stream
== NULL
|| stream
== Py_None
) {
1607 w
= PySys_GetObject("stdout");
1609 PyErr_SetString(PyExc_RuntimeError
,
1613 err
= PyFile_WriteString("\n", w
);
1615 PyFile_SoftSpace(w
, 0);
1623 default: switch (opcode
) {
1629 u
= POP(); /* traceback */
1632 v
= POP(); /* value */
1635 w
= POP(); /* exc */
1636 case 0: /* Fallthrough */
1637 why
= do_raise(w
, v
, u
);
1640 PyErr_SetString(PyExc_SystemError
,
1641 "bad RAISE_VARARGS oparg");
1642 why
= WHY_EXCEPTION
;
1648 if ((x
= f
->f_locals
) != NULL
) {
1653 PyErr_SetString(PyExc_SystemError
, "no locals");
1659 goto fast_block_end
;
1663 f
->f_stacktop
= stack_pointer
;
1672 READ_TIMESTAMP(intr0
);
1673 err
= exec_statement(f
, u
, v
, w
);
1674 READ_TIMESTAMP(intr1
);
1682 PyTryBlock
*b
= PyFrame_BlockPop(f
);
1683 while (STACK_LEVEL() > b
->b_level
) {
1692 if (PyInt_Check(v
)) {
1693 why
= (enum why_code
) PyInt_AS_LONG(v
);
1694 assert(why
!= WHY_YIELD
);
1695 if (why
== WHY_RETURN
||
1696 why
== WHY_CONTINUE
)
1699 else if (PyExceptionClass_Check(v
) || PyString_Check(v
)) {
1702 PyErr_Restore(v
, w
, u
);
1706 else if (v
!= Py_None
) {
1707 PyErr_SetString(PyExc_SystemError
,
1708 "'finally' pops bad exception");
1709 why
= WHY_EXCEPTION
;
1719 x
= build_class(u
, v
, w
);
1727 w
= GETITEM(names
, oparg
);
1729 if ((x
= f
->f_locals
) != NULL
) {
1730 if (PyDict_CheckExact(x
))
1731 err
= PyDict_SetItem(x
, w
, v
);
1733 err
= PyObject_SetItem(x
, w
, v
);
1735 if (err
== 0) continue;
1738 PyErr_Format(PyExc_SystemError
,
1739 "no locals found when storing %s",
1744 w
= GETITEM(names
, oparg
);
1745 if ((x
= f
->f_locals
) != NULL
) {
1746 if ((err
= PyObject_DelItem(x
, w
)) != 0)
1747 format_exc_check_arg(PyExc_NameError
,
1751 PyErr_Format(PyExc_SystemError
,
1752 "no locals when deleting %s",
1756 PREDICTED_WITH_ARG(UNPACK_SEQUENCE
);
1757 case UNPACK_SEQUENCE
:
1759 if (PyTuple_CheckExact(v
) && PyTuple_GET_SIZE(v
) == oparg
) {
1760 PyObject
**items
= ((PyTupleObject
*)v
)->ob_item
;
1768 } else if (PyList_CheckExact(v
) && PyList_GET_SIZE(v
) == oparg
) {
1769 PyObject
**items
= ((PyListObject
*)v
)->ob_item
;
1775 } else if (unpack_iterable(v
, oparg
,
1776 stack_pointer
+ oparg
)) {
1777 stack_pointer
+= oparg
;
1779 /* unpack_iterable() raised an exception */
1780 why
= WHY_EXCEPTION
;
1786 w
= GETITEM(names
, oparg
);
1790 err
= PyObject_SetAttr(v
, w
, u
); /* v.w = u */
1793 if (err
== 0) continue;
1797 w
= GETITEM(names
, oparg
);
1799 err
= PyObject_SetAttr(v
, w
, (PyObject
*)NULL
);
1805 w
= GETITEM(names
, oparg
);
1807 err
= PyDict_SetItem(f
->f_globals
, w
, v
);
1809 if (err
== 0) continue;
1813 w
= GETITEM(names
, oparg
);
1814 if ((err
= PyDict_DelItem(f
->f_globals
, w
)) != 0)
1815 format_exc_check_arg(
1816 PyExc_NameError
, GLOBAL_NAME_ERROR_MSG
, w
);
1820 w
= GETITEM(names
, oparg
);
1821 if ((v
= f
->f_locals
) == NULL
) {
1822 PyErr_Format(PyExc_SystemError
,
1823 "no locals when loading %s",
1827 if (PyDict_CheckExact(v
)) {
1828 x
= PyDict_GetItem(v
, w
);
1832 x
= PyObject_GetItem(v
, w
);
1833 if (x
== NULL
&& PyErr_Occurred()) {
1834 if (!PyErr_ExceptionMatches(PyExc_KeyError
))
1840 x
= PyDict_GetItem(f
->f_globals
, w
);
1842 x
= PyDict_GetItem(f
->f_builtins
, w
);
1844 format_exc_check_arg(
1856 w
= GETITEM(names
, oparg
);
1857 if (PyString_CheckExact(w
)) {
1858 /* Inline the PyDict_GetItem() calls.
1859 WARNING: this is an extreme speed hack.
1860 Do not try this at home. */
1861 long hash
= ((PyStringObject
*)w
)->ob_shash
;
1865 d
= (PyDictObject
*)(f
->f_globals
);
1866 e
= d
->ma_lookup(d
, w
, hash
);
1877 d
= (PyDictObject
*)(f
->f_builtins
);
1878 e
= d
->ma_lookup(d
, w
, hash
);
1889 goto load_global_error
;
1892 /* This is the un-inlined version of the code above */
1893 x
= PyDict_GetItem(f
->f_globals
, w
);
1895 x
= PyDict_GetItem(f
->f_builtins
, w
);
1898 format_exc_check_arg(
1900 GLOBAL_NAME_ERROR_MSG
, w
);
1909 x
= GETLOCAL(oparg
);
1911 SETLOCAL(oparg
, NULL
);
1914 format_exc_check_arg(
1915 PyExc_UnboundLocalError
,
1916 UNBOUNDLOCAL_ERROR_MSG
,
1917 PyTuple_GetItem(co
->co_varnames
, oparg
)
1922 x
= freevars
[oparg
];
1925 if (x
!= NULL
) continue;
1929 x
= freevars
[oparg
];
1936 /* Don't stomp existing exception */
1937 if (PyErr_Occurred())
1939 if (oparg
< PyTuple_GET_SIZE(co
->co_cellvars
)) {
1940 v
= PyTuple_GET_ITEM(co
->co_cellvars
,
1942 format_exc_check_arg(
1943 PyExc_UnboundLocalError
,
1944 UNBOUNDLOCAL_ERROR_MSG
,
1947 v
= PyTuple_GET_ITEM(
1949 oparg
- PyTuple_GET_SIZE(co
->co_cellvars
));
1950 format_exc_check_arg(
1952 UNBOUNDFREE_ERROR_MSG
,
1959 x
= freevars
[oparg
];
1965 x
= PyTuple_New(oparg
);
1967 for (; --oparg
>= 0;) {
1969 PyTuple_SET_ITEM(x
, oparg
, w
);
1977 x
= PyList_New(oparg
);
1979 for (; --oparg
>= 0;) {
1981 PyList_SET_ITEM(x
, oparg
, w
);
1991 if (x
!= NULL
) continue;
1995 w
= GETITEM(names
, oparg
);
1997 x
= PyObject_GetAttr(v
, w
);
2000 if (x
!= NULL
) continue;
2006 if (PyInt_CheckExact(w
) && PyInt_CheckExact(v
)) {
2007 /* INLINE: cmp(int, int) */
2010 a
= PyInt_AS_LONG(v
);
2011 b
= PyInt_AS_LONG(w
);
2013 case PyCmp_LT
: res
= a
< b
; break;
2014 case PyCmp_LE
: res
= a
<= b
; break;
2015 case PyCmp_EQ
: res
= a
== b
; break;
2016 case PyCmp_NE
: res
= a
!= b
; break;
2017 case PyCmp_GT
: res
= a
> b
; break;
2018 case PyCmp_GE
: res
= a
>= b
; break;
2019 case PyCmp_IS
: res
= v
== w
; break;
2020 case PyCmp_IS_NOT
: res
= v
!= w
; break;
2021 default: goto slow_compare
;
2023 x
= res
? Py_True
: Py_False
;
2028 x
= cmp_outcome(oparg
, v
, w
);
2033 if (x
== NULL
) break;
2034 PREDICT(JUMP_IF_FALSE
);
2035 PREDICT(JUMP_IF_TRUE
);
2039 w
= GETITEM(names
, oparg
);
2040 x
= PyDict_GetItemString(f
->f_builtins
, "__import__");
2042 PyErr_SetString(PyExc_ImportError
,
2043 "__import__ not found");
2048 if (PyInt_AsLong(u
) != -1 || PyErr_Occurred())
2052 f
->f_locals
== NULL
?
2053 Py_None
: f
->f_locals
,
2060 f
->f_locals
== NULL
?
2061 Py_None
: f
->f_locals
,
2070 READ_TIMESTAMP(intr0
);
2071 x
= PyEval_CallObject(x
, w
);
2072 READ_TIMESTAMP(intr1
);
2075 if (x
!= NULL
) continue;
2080 PyFrame_FastToLocals(f
);
2081 if ((x
= f
->f_locals
) == NULL
) {
2082 PyErr_SetString(PyExc_SystemError
,
2083 "no locals found during 'import *'");
2086 READ_TIMESTAMP(intr0
);
2087 err
= import_all_from(x
, v
);
2088 READ_TIMESTAMP(intr1
);
2089 PyFrame_LocalsToFast(f
, 0);
2091 if (err
== 0) continue;
2095 w
= GETITEM(names
, oparg
);
2097 READ_TIMESTAMP(intr0
);
2098 x
= import_from(v
, w
);
2099 READ_TIMESTAMP(intr1
);
2101 if (x
!= NULL
) continue;
2106 goto fast_next_opcode
;
2108 PREDICTED_WITH_ARG(JUMP_IF_FALSE
);
2113 goto fast_next_opcode
;
2115 if (w
== Py_False
) {
2117 goto fast_next_opcode
;
2119 err
= PyObject_IsTrue(w
);
2128 PREDICTED_WITH_ARG(JUMP_IF_TRUE
);
2131 if (w
== Py_False
) {
2133 goto fast_next_opcode
;
2137 goto fast_next_opcode
;
2139 err
= PyObject_IsTrue(w
);
2150 PREDICTED_WITH_ARG(JUMP_ABSOLUTE
);
2156 /* before: [obj]; after [getiter(obj)] */
2158 x
= PyObject_GetIter(v
);
2168 PREDICTED_WITH_ARG(FOR_ITER
);
2170 /* before: [iter]; after: [iter, iter()] *or* [] */
2172 x
= (*v
->ob_type
->tp_iternext
)(v
);
2175 PREDICT(STORE_FAST
);
2176 PREDICT(UNPACK_SEQUENCE
);
2179 if (PyErr_Occurred()) {
2180 if (!PyErr_ExceptionMatches(PyExc_StopIteration
))
2184 /* iterator ended normally */
2192 goto fast_block_end
;
2195 retval
= PyInt_FromLong(oparg
);
2201 goto fast_block_end
;
2206 /* NOTE: If you add any new block-setup opcodes that are
2207 not try/except/finally handlers, you may need to
2208 update the PyGen_NeedsFinalizing() function. */
2210 PyFrame_BlockSetup(f
, opcode
, INSTR_OFFSET() + oparg
,
2216 /* TOP is the context.__exit__ bound method.
2217 Below that are 1-3 values indicating how/why
2218 we entered the finally clause:
2220 - (SECOND, THIRD) = (WHY_{RETURN,CONTINUE}), retval
2221 - SECOND = WHY_*; no retval below it
2222 - (SECOND, THIRD, FOURTH) = exc_info()
2223 In the last case, we must call
2224 TOP(SECOND, THIRD, FOURTH)
2225 otherwise we must call
2226 TOP(None, None, None)
2228 In addition, if the stack represents an exception,
2229 *and* the function call returns a 'true' value, we
2230 "zap" this information, to prevent END_FINALLY from
2231 re-raising the exception. (But non-local gotos
2232 should still be resumed.)
2237 if (PyInt_Check(u
) || u
== Py_None
) {
2238 u
= v
= w
= Py_None
;
2244 /* XXX Not the fastest way to call it... */
2245 x
= PyObject_CallFunctionObjArgs(x
, u
, v
, w
, NULL
);
2247 break; /* Go to error exit */
2248 if (u
!= Py_None
&& PyObject_IsTrue(x
)) {
2249 /* There was an exception and a true return */
2251 x
= TOP(); /* Again */
2260 /* Let END_FINALLY do its thing */
2274 x
= call_function(&sp
, oparg
, &intr0
, &intr1
);
2276 x
= call_function(&sp
, oparg
);
2285 case CALL_FUNCTION_VAR
:
2286 case CALL_FUNCTION_KW
:
2287 case CALL_FUNCTION_VAR_KW
:
2289 int na
= oparg
& 0xff;
2290 int nk
= (oparg
>>8) & 0xff;
2291 int flags
= (opcode
- CALL_FUNCTION
) & 3;
2292 int n
= na
+ 2 * nk
;
2293 PyObject
**pfunc
, *func
, **sp
;
2295 if (flags
& CALL_FLAG_VAR
)
2297 if (flags
& CALL_FLAG_KW
)
2299 pfunc
= stack_pointer
- n
- 1;
2302 if (PyMethod_Check(func
)
2303 && PyMethod_GET_SELF(func
) != NULL
) {
2304 PyObject
*self
= PyMethod_GET_SELF(func
);
2306 func
= PyMethod_GET_FUNCTION(func
);
2315 READ_TIMESTAMP(intr0
);
2316 x
= ext_do_call(func
, &sp
, flags
, na
, nk
);
2317 READ_TIMESTAMP(intr1
);
2321 while (stack_pointer
> pfunc
) {
2332 v
= POP(); /* code object */
2333 x
= PyFunction_New(v
, f
->f_globals
);
2335 /* XXX Maybe this should be a separate opcode? */
2336 if (x
!= NULL
&& oparg
> 0) {
2337 v
= PyTuple_New(oparg
);
2343 while (--oparg
>= 0) {
2345 PyTuple_SET_ITEM(v
, oparg
, w
);
2347 err
= PyFunction_SetDefaults(x
, v
);
2355 v
= POP(); /* code object */
2356 x
= PyFunction_New(v
, f
->f_globals
);
2360 err
= PyFunction_SetClosure(x
, v
);
2363 if (x
!= NULL
&& oparg
> 0) {
2364 v
= PyTuple_New(oparg
);
2370 while (--oparg
>= 0) {
2372 PyTuple_SET_ITEM(v
, oparg
, w
);
2374 err
= PyFunction_SetDefaults(x
, v
);
2388 x
= PySlice_New(u
, v
, w
);
2393 if (x
!= NULL
) continue;
2398 oparg
= oparg
<<16 | NEXTARG();
2399 goto dispatch_opcode
;
2403 "XXX lineno: %d, opcode: %d\n",
2404 PyCode_Addr2Line(f
->f_code
, f
->f_lasti
),
2406 PyErr_SetString(PyExc_SystemError
, "unknown opcode");
2407 why
= WHY_EXCEPTION
;
2418 READ_TIMESTAMP(inst1
);
2420 /* Quickly continue if no error occurred */
2422 if (why
== WHY_NOT
) {
2423 if (err
== 0 && x
!= NULL
) {
2425 /* This check is expensive! */
2426 if (PyErr_Occurred())
2428 "XXX undetected error\n");
2431 READ_TIMESTAMP(loop1
);
2432 continue; /* Normal, fast path */
2437 why
= WHY_EXCEPTION
;
2442 /* Double-check exception status */
2444 if (why
== WHY_EXCEPTION
|| why
== WHY_RERAISE
) {
2445 if (!PyErr_Occurred()) {
2446 PyErr_SetString(PyExc_SystemError
,
2447 "error return without exception set");
2448 why
= WHY_EXCEPTION
;
2453 /* This check is expensive! */
2454 if (PyErr_Occurred()) {
2456 sprintf(buf
, "Stack unwind with exception "
2457 "set and why=%d", why
);
2463 /* Log traceback info if this is a real exception */
2465 if (why
== WHY_EXCEPTION
) {
2466 PyTraceBack_Here(f
);
2468 if (tstate
->c_tracefunc
!= NULL
)
2469 call_exc_trace(tstate
->c_tracefunc
,
2470 tstate
->c_traceobj
, f
);
2473 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2475 if (why
== WHY_RERAISE
)
2476 why
= WHY_EXCEPTION
;
2478 /* Unwind stacks if a (pseudo) exception occurred */
2481 while (why
!= WHY_NOT
&& f
->f_iblock
> 0) {
2482 PyTryBlock
*b
= PyFrame_BlockPop(f
);
2484 assert(why
!= WHY_YIELD
);
2485 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_CONTINUE
) {
2486 /* For a continue inside a try block,
2487 don't pop the block for the loop. */
2488 PyFrame_BlockSetup(f
, b
->b_type
, b
->b_handler
,
2491 JUMPTO(PyInt_AS_LONG(retval
));
2496 while (STACK_LEVEL() > b
->b_level
) {
2500 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_BREAK
) {
2502 JUMPTO(b
->b_handler
);
2505 if (b
->b_type
== SETUP_FINALLY
||
2506 (b
->b_type
== SETUP_EXCEPT
&&
2507 why
== WHY_EXCEPTION
)) {
2508 if (why
== WHY_EXCEPTION
) {
2509 PyObject
*exc
, *val
, *tb
;
2510 PyErr_Fetch(&exc
, &val
, &tb
);
2515 /* Make the raw exception data
2516 available to the handler,
2517 so a program can emulate the
2518 Python main loop. Don't do
2519 this for 'finally'. */
2520 if (b
->b_type
== SETUP_EXCEPT
) {
2521 PyErr_NormalizeException(
2523 set_exc_info(tstate
,
2535 if (why
& (WHY_RETURN
| WHY_CONTINUE
))
2537 v
= PyInt_FromLong((long)why
);
2541 JUMPTO(b
->b_handler
);
2544 } /* unwind stack */
2546 /* End the loop if we still have an error (or return) */
2550 READ_TIMESTAMP(loop1
);
2554 assert(why
!= WHY_YIELD
);
2555 /* Pop remaining stack entries. */
2561 if (why
!= WHY_RETURN
)
2565 if (tstate
->use_tracing
) {
2566 if (tstate
->c_tracefunc
) {
2567 if (why
== WHY_RETURN
|| why
== WHY_YIELD
) {
2568 if (call_trace(tstate
->c_tracefunc
,
2569 tstate
->c_traceobj
, f
,
2570 PyTrace_RETURN
, retval
)) {
2573 why
= WHY_EXCEPTION
;
2576 else if (why
== WHY_EXCEPTION
) {
2577 call_trace_protected(tstate
->c_tracefunc
,
2578 tstate
->c_traceobj
, f
,
2579 PyTrace_RETURN
, NULL
);
2582 if (tstate
->c_profilefunc
) {
2583 if (why
== WHY_EXCEPTION
)
2584 call_trace_protected(tstate
->c_profilefunc
,
2585 tstate
->c_profileobj
, f
,
2586 PyTrace_RETURN
, NULL
);
2587 else if (call_trace(tstate
->c_profilefunc
,
2588 tstate
->c_profileobj
, f
,
2589 PyTrace_RETURN
, retval
)) {
2592 why
= WHY_EXCEPTION
;
2597 if (tstate
->frame
->f_exc_type
!= NULL
)
2598 reset_exc_info(tstate
);
2600 assert(tstate
->frame
->f_exc_value
== NULL
);
2601 assert(tstate
->frame
->f_exc_traceback
== NULL
);
2606 Py_LeaveRecursiveCall();
2607 tstate
->frame
= f
->f_back
;
2612 /* This is gonna seem *real weird*, but if you put some other code between
2613 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
2614 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
2617 PyEval_EvalCodeEx(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
,
2618 PyObject
**args
, int argcount
, PyObject
**kws
, int kwcount
,
2619 PyObject
**defs
, int defcount
, PyObject
*closure
)
2621 register PyFrameObject
*f
;
2622 register PyObject
*retval
= NULL
;
2623 register PyObject
**fastlocals
, **freevars
;
2624 PyThreadState
*tstate
= PyThreadState_GET();
2627 if (globals
== NULL
) {
2628 PyErr_SetString(PyExc_SystemError
,
2629 "PyEval_EvalCodeEx: NULL globals");
2633 assert(tstate
!= NULL
);
2634 assert(globals
!= NULL
);
2635 f
= PyFrame_New(tstate
, co
, globals
, locals
);
2639 fastlocals
= f
->f_localsplus
;
2640 freevars
= f
->f_localsplus
+ co
->co_nlocals
;
2642 if (co
->co_argcount
> 0 ||
2643 co
->co_flags
& (CO_VARARGS
| CO_VARKEYWORDS
)) {
2646 PyObject
*kwdict
= NULL
;
2647 if (co
->co_flags
& CO_VARKEYWORDS
) {
2648 kwdict
= PyDict_New();
2651 i
= co
->co_argcount
;
2652 if (co
->co_flags
& CO_VARARGS
)
2654 SETLOCAL(i
, kwdict
);
2656 if (argcount
> co
->co_argcount
) {
2657 if (!(co
->co_flags
& CO_VARARGS
)) {
2658 PyErr_Format(PyExc_TypeError
,
2659 "%.200s() takes %s %d "
2660 "%sargument%s (%d given)",
2661 PyString_AsString(co
->co_name
),
2662 defcount
? "at most" : "exactly",
2664 kwcount
? "non-keyword " : "",
2665 co
->co_argcount
== 1 ? "" : "s",
2669 n
= co
->co_argcount
;
2671 for (i
= 0; i
< n
; i
++) {
2676 if (co
->co_flags
& CO_VARARGS
) {
2677 u
= PyTuple_New(argcount
- n
);
2680 SETLOCAL(co
->co_argcount
, u
);
2681 for (i
= n
; i
< argcount
; i
++) {
2684 PyTuple_SET_ITEM(u
, i
-n
, x
);
2687 for (i
= 0; i
< kwcount
; i
++) {
2688 PyObject
*keyword
= kws
[2*i
];
2689 PyObject
*value
= kws
[2*i
+ 1];
2691 if (keyword
== NULL
|| !PyString_Check(keyword
)) {
2692 PyErr_Format(PyExc_TypeError
,
2693 "%.200s() keywords must be strings",
2694 PyString_AsString(co
->co_name
));
2697 /* XXX slow -- speed up using dictionary? */
2698 for (j
= 0; j
< co
->co_argcount
; j
++) {
2699 PyObject
*nm
= PyTuple_GET_ITEM(
2700 co
->co_varnames
, j
);
2701 int cmp
= PyObject_RichCompareBool(
2702 keyword
, nm
, Py_EQ
);
2708 /* Check errors from Compare */
2709 if (PyErr_Occurred())
2711 if (j
>= co
->co_argcount
) {
2712 if (kwdict
== NULL
) {
2713 PyErr_Format(PyExc_TypeError
,
2714 "%.200s() got an unexpected "
2715 "keyword argument '%.400s'",
2716 PyString_AsString(co
->co_name
),
2717 PyString_AsString(keyword
));
2720 PyDict_SetItem(kwdict
, keyword
, value
);
2723 if (GETLOCAL(j
) != NULL
) {
2724 PyErr_Format(PyExc_TypeError
,
2725 "%.200s() got multiple "
2726 "values for keyword "
2727 "argument '%.400s'",
2728 PyString_AsString(co
->co_name
),
2729 PyString_AsString(keyword
));
2736 if (argcount
< co
->co_argcount
) {
2737 int m
= co
->co_argcount
- defcount
;
2738 for (i
= argcount
; i
< m
; i
++) {
2739 if (GETLOCAL(i
) == NULL
) {
2740 PyErr_Format(PyExc_TypeError
,
2741 "%.200s() takes %s %d "
2742 "%sargument%s (%d given)",
2743 PyString_AsString(co
->co_name
),
2744 ((co
->co_flags
& CO_VARARGS
) ||
2745 defcount
) ? "at least"
2747 m
, kwcount
? "non-keyword " : "",
2748 m
== 1 ? "" : "s", i
);
2756 for (; i
< defcount
; i
++) {
2757 if (GETLOCAL(m
+i
) == NULL
) {
2758 PyObject
*def
= defs
[i
];
2766 if (argcount
> 0 || kwcount
> 0) {
2767 PyErr_Format(PyExc_TypeError
,
2768 "%.200s() takes no arguments (%d given)",
2769 PyString_AsString(co
->co_name
),
2770 argcount
+ kwcount
);
2774 /* Allocate and initialize storage for cell vars, and copy free
2775 vars into frame. This isn't too efficient right now. */
2776 if (PyTuple_GET_SIZE(co
->co_cellvars
)) {
2777 int i
, j
, nargs
, found
;
2778 char *cellname
, *argname
;
2781 nargs
= co
->co_argcount
;
2782 if (co
->co_flags
& CO_VARARGS
)
2784 if (co
->co_flags
& CO_VARKEYWORDS
)
2787 /* Initialize each cell var, taking into account
2788 cell vars that are initialized from arguments.
2790 Should arrange for the compiler to put cellvars
2791 that are arguments at the beginning of the cellvars
2792 list so that we can march over it more efficiently?
2794 for (i
= 0; i
< PyTuple_GET_SIZE(co
->co_cellvars
); ++i
) {
2795 cellname
= PyString_AS_STRING(
2796 PyTuple_GET_ITEM(co
->co_cellvars
, i
));
2798 for (j
= 0; j
< nargs
; j
++) {
2799 argname
= PyString_AS_STRING(
2800 PyTuple_GET_ITEM(co
->co_varnames
, j
));
2801 if (strcmp(cellname
, argname
) == 0) {
2802 c
= PyCell_New(GETLOCAL(j
));
2805 GETLOCAL(co
->co_nlocals
+ i
) = c
;
2811 c
= PyCell_New(NULL
);
2814 SETLOCAL(co
->co_nlocals
+ i
, c
);
2818 if (PyTuple_GET_SIZE(co
->co_freevars
)) {
2820 for (i
= 0; i
< PyTuple_GET_SIZE(co
->co_freevars
); ++i
) {
2821 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
2823 freevars
[PyTuple_GET_SIZE(co
->co_cellvars
) + i
] = o
;
2827 if (co
->co_flags
& CO_GENERATOR
) {
2828 /* Don't need to keep the reference to f_back, it will be set
2829 * when the generator is resumed. */
2830 Py_XDECREF(f
->f_back
);
2833 PCALL(PCALL_GENERATOR
);
2835 /* Create a new generator that owns the ready to run frame
2836 * and return that as the value. */
2837 return PyGen_New(f
);
2840 retval
= PyEval_EvalFrameEx(f
,0);
2842 fail
: /* Jump here from prelude on failure */
2844 /* decref'ing the frame can cause __del__ methods to get invoked,
2845 which can call back into Python. While we're done with the
2846 current Python frame (f), the associated C stack is still in use,
2847 so recursion_depth must be boosted for the duration.
2849 assert(tstate
!= NULL
);
2850 ++tstate
->recursion_depth
;
2852 --tstate
->recursion_depth
;
2857 /* Implementation notes for set_exc_info() and reset_exc_info():
2859 - Below, 'exc_ZZZ' stands for 'exc_type', 'exc_value' and
2860 'exc_traceback'. These always travel together.
2862 - tstate->curexc_ZZZ is the "hot" exception that is set by
2863 PyErr_SetString(), cleared by PyErr_Clear(), and so on.
2865 - Once an exception is caught by an except clause, it is transferred
2866 from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info()
2867 can pick it up. This is the primary task of set_exc_info().
2868 XXX That can't be right: set_exc_info() doesn't look at tstate->curexc_ZZZ.
2870 - Now let me explain the complicated dance with frame->f_exc_ZZZ.
2872 Long ago, when none of this existed, there were just a few globals:
2873 one set corresponding to the "hot" exception, and one set
2874 corresponding to sys.exc_ZZZ. (Actually, the latter weren't C
2875 globals; they were simply stored as sys.exc_ZZZ. For backwards
2876 compatibility, they still are!) The problem was that in code like
2880 "something that may fail"
2881 except "some exception":
2882 "do something else first"
2883 "print the exception from sys.exc_ZZZ."
2885 if "do something else first" invoked something that raised and caught
2886 an exception, sys.exc_ZZZ were overwritten. That was a frequent
2887 cause of subtle bugs. I fixed this by changing the semantics as
2890 - Within one frame, sys.exc_ZZZ will hold the last exception caught
2893 - But initially, and as long as no exception is caught in a given
2894 frame, sys.exc_ZZZ will hold the last exception caught in the
2895 previous frame (or the frame before that, etc.).
2897 The first bullet fixed the bug in the above example. The second
2898 bullet was for backwards compatibility: it was (and is) common to
2899 have a function that is called when an exception is caught, and to
2900 have that function access the caught exception via sys.exc_ZZZ.
2901 (Example: traceback.print_exc()).
2903 At the same time I fixed the problem that sys.exc_ZZZ weren't
2904 thread-safe, by introducing sys.exc_info() which gets it from tstate;
2905 but that's really a separate improvement.
2907 The reset_exc_info() function in ceval.c restores the tstate->exc_ZZZ
2908 variables to what they were before the current frame was called. The
2909 set_exc_info() function saves them on the frame so that
2910 reset_exc_info() can restore them. The invariant is that
2911 frame->f_exc_ZZZ is NULL iff the current frame never caught an
2912 exception (where "catching" an exception applies only to successful
2913 except clauses); and if the current frame ever caught an exception,
2914 frame->f_exc_ZZZ is the exception that was stored in tstate->exc_ZZZ
2915 at the start of the current frame.
2920 set_exc_info(PyThreadState
*tstate
,
2921 PyObject
*type
, PyObject
*value
, PyObject
*tb
)
2923 PyFrameObject
*frame
= tstate
->frame
;
2924 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
2926 assert(type
!= NULL
);
2927 assert(frame
!= NULL
);
2928 if (frame
->f_exc_type
== NULL
) {
2929 assert(frame
->f_exc_value
== NULL
);
2930 assert(frame
->f_exc_traceback
== NULL
);
2931 /* This frame didn't catch an exception before. */
2932 /* Save previous exception of this thread in this frame. */
2933 if (tstate
->exc_type
== NULL
) {
2934 /* XXX Why is this set to Py_None? */
2936 tstate
->exc_type
= Py_None
;
2938 Py_INCREF(tstate
->exc_type
);
2939 Py_XINCREF(tstate
->exc_value
);
2940 Py_XINCREF(tstate
->exc_traceback
);
2941 frame
->f_exc_type
= tstate
->exc_type
;
2942 frame
->f_exc_value
= tstate
->exc_value
;
2943 frame
->f_exc_traceback
= tstate
->exc_traceback
;
2945 /* Set new exception for this thread. */
2946 tmp_type
= tstate
->exc_type
;
2947 tmp_value
= tstate
->exc_value
;
2948 tmp_tb
= tstate
->exc_traceback
;
2952 tstate
->exc_type
= type
;
2953 tstate
->exc_value
= value
;
2954 tstate
->exc_traceback
= tb
;
2955 Py_XDECREF(tmp_type
);
2956 Py_XDECREF(tmp_value
);
2958 /* For b/w compatibility */
2959 PySys_SetObject("exc_type", type
);
2960 PySys_SetObject("exc_value", value
);
2961 PySys_SetObject("exc_traceback", tb
);
2965 reset_exc_info(PyThreadState
*tstate
)
2967 PyFrameObject
*frame
;
2968 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
2970 /* It's a precondition that the thread state's frame caught an
2971 * exception -- verify in a debug build.
2973 assert(tstate
!= NULL
);
2974 frame
= tstate
->frame
;
2975 assert(frame
!= NULL
);
2976 assert(frame
->f_exc_type
!= NULL
);
2978 /* Copy the frame's exception info back to the thread state. */
2979 tmp_type
= tstate
->exc_type
;
2980 tmp_value
= tstate
->exc_value
;
2981 tmp_tb
= tstate
->exc_traceback
;
2982 Py_INCREF(frame
->f_exc_type
);
2983 Py_XINCREF(frame
->f_exc_value
);
2984 Py_XINCREF(frame
->f_exc_traceback
);
2985 tstate
->exc_type
= frame
->f_exc_type
;
2986 tstate
->exc_value
= frame
->f_exc_value
;
2987 tstate
->exc_traceback
= frame
->f_exc_traceback
;
2988 Py_XDECREF(tmp_type
);
2989 Py_XDECREF(tmp_value
);
2992 /* For b/w compatibility */
2993 PySys_SetObject("exc_type", frame
->f_exc_type
);
2994 PySys_SetObject("exc_value", frame
->f_exc_value
);
2995 PySys_SetObject("exc_traceback", frame
->f_exc_traceback
);
2997 /* Clear the frame's exception info. */
2998 tmp_type
= frame
->f_exc_type
;
2999 tmp_value
= frame
->f_exc_value
;
3000 tmp_tb
= frame
->f_exc_traceback
;
3001 frame
->f_exc_type
= NULL
;
3002 frame
->f_exc_value
= NULL
;
3003 frame
->f_exc_traceback
= NULL
;
3004 Py_DECREF(tmp_type
);
3005 Py_XDECREF(tmp_value
);
3009 /* Logic for the raise statement (too complicated for inlining).
3010 This *consumes* a reference count to each of its arguments. */
3011 static enum why_code
3012 do_raise(PyObject
*type
, PyObject
*value
, PyObject
*tb
)
3016 PyThreadState
*tstate
= PyThreadState_GET();
3017 type
= tstate
->exc_type
== NULL
? Py_None
: tstate
->exc_type
;
3018 value
= tstate
->exc_value
;
3019 tb
= tstate
->exc_traceback
;
3025 /* We support the following forms of raise:
3026 raise <class>, <classinstance>
3027 raise <class>, <argument tuple>
3029 raise <class>, <argument>
3030 raise <classinstance>, None
3031 raise <string>, <object>
3032 raise <string>, None
3034 An omitted second argument is the same as None.
3036 In addition, raise <tuple>, <anything> is the same as
3037 raising the tuple's first item (and it better have one!);
3038 this rule is applied recursively.
3040 Finally, an optional third argument can be supplied, which
3041 gives the traceback to be substituted (useful when
3042 re-raising an exception after examining it). */
3044 /* First, check the traceback argument, replacing None with
3046 if (tb
== Py_None
) {
3050 else if (tb
!= NULL
&& !PyTraceBack_Check(tb
)) {
3051 PyErr_SetString(PyExc_TypeError
,
3052 "raise: arg 3 must be a traceback or None");
3056 /* Next, replace a missing value with None */
3057 if (value
== NULL
) {
3062 /* Next, repeatedly, replace a tuple exception with its first item */
3063 while (PyTuple_Check(type
) && PyTuple_Size(type
) > 0) {
3064 PyObject
*tmp
= type
;
3065 type
= PyTuple_GET_ITEM(type
, 0);
3070 if (PyExceptionClass_Check(type
))
3071 PyErr_NormalizeException(&type
, &value
, &tb
);
3073 else if (PyExceptionInstance_Check(type
)) {
3074 /* Raising an instance. The value should be a dummy. */
3075 if (value
!= Py_None
) {
3076 PyErr_SetString(PyExc_TypeError
,
3077 "instance exception may not have a separate value");
3081 /* Normalize to raise <class>, <instance> */
3084 type
= PyExceptionInstance_Class(type
);
3089 /* Not something you can raise. You get an exception
3090 anyway, just not what you specified :-) */
3091 PyErr_Format(PyExc_TypeError
,
3092 "exceptions must be classes or instances, not %s",
3093 type
->ob_type
->tp_name
);
3096 PyErr_Restore(type
, value
, tb
);
3098 return WHY_EXCEPTION
;
3105 return WHY_EXCEPTION
;
3108 /* Iterate v argcnt times and store the results on the stack (via decreasing
3109 sp). Return 1 for success, 0 if error. */
3112 unpack_iterable(PyObject
*v
, int argcnt
, PyObject
**sp
)
3115 PyObject
*it
; /* iter(v) */
3120 it
= PyObject_GetIter(v
);
3124 for (; i
< argcnt
; i
++) {
3125 w
= PyIter_Next(it
);
3127 /* Iterator done, via error or exhaustion. */
3128 if (!PyErr_Occurred()) {
3129 PyErr_Format(PyExc_ValueError
,
3130 "need more than %d value%s to unpack",
3131 i
, i
== 1 ? "" : "s");
3138 /* We better have exhausted the iterator now. */
3139 w
= PyIter_Next(it
);
3141 if (PyErr_Occurred())
3147 PyErr_SetString(PyExc_ValueError
, "too many values to unpack");
3150 for (; i
> 0; i
--, sp
++)
3159 prtrace(PyObject
*v
, char *str
)
3162 if (PyObject_Print(v
, stdout
, 0) != 0)
3163 PyErr_Clear(); /* Don't know what else to do */
3170 call_exc_trace(Py_tracefunc func
, PyObject
*self
, PyFrameObject
*f
)
3172 PyObject
*type
, *value
, *traceback
, *arg
;
3174 PyErr_Fetch(&type
, &value
, &traceback
);
3175 if (value
== NULL
) {
3179 arg
= PyTuple_Pack(3, type
, value
, traceback
);
3181 PyErr_Restore(type
, value
, traceback
);
3184 err
= call_trace(func
, self
, f
, PyTrace_EXCEPTION
, arg
);
3187 PyErr_Restore(type
, value
, traceback
);
3191 Py_XDECREF(traceback
);
3196 call_trace_protected(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3197 int what
, PyObject
*arg
)
3199 PyObject
*type
, *value
, *traceback
;
3201 PyErr_Fetch(&type
, &value
, &traceback
);
3202 err
= call_trace(func
, obj
, frame
, what
, arg
);
3204 PyErr_Restore(type
, value
, traceback
);
3208 Py_XDECREF(traceback
);
3213 call_trace(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3214 int what
, PyObject
*arg
)
3216 register PyThreadState
*tstate
= frame
->f_tstate
;
3218 if (tstate
->tracing
)
3221 tstate
->use_tracing
= 0;
3222 result
= func(obj
, frame
, what
, arg
);
3223 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3224 || (tstate
->c_profilefunc
!= NULL
));
3230 _PyEval_CallTracing(PyObject
*func
, PyObject
*args
)
3232 PyFrameObject
*frame
= PyEval_GetFrame();
3233 PyThreadState
*tstate
= frame
->f_tstate
;
3234 int save_tracing
= tstate
->tracing
;
3235 int save_use_tracing
= tstate
->use_tracing
;
3238 tstate
->tracing
= 0;
3239 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3240 || (tstate
->c_profilefunc
!= NULL
));
3241 result
= PyObject_Call(func
, args
, NULL
);
3242 tstate
->tracing
= save_tracing
;
3243 tstate
->use_tracing
= save_use_tracing
;
3248 maybe_call_line_trace(Py_tracefunc func
, PyObject
*obj
,
3249 PyFrameObject
*frame
, int *instr_lb
, int *instr_ub
,
3254 /* If the last instruction executed isn't in the current
3255 instruction window, reset the window. If the last
3256 instruction happens to fall at the start of a line or if it
3257 represents a jump backwards, call the trace function.
3259 if ((frame
->f_lasti
< *instr_lb
|| frame
->f_lasti
>= *instr_ub
)) {
3263 line
= PyCode_CheckLineNumber(frame
->f_code
, frame
->f_lasti
,
3266 frame
->f_lineno
= line
;
3267 result
= call_trace(func
, obj
, frame
,
3268 PyTrace_LINE
, Py_None
);
3270 *instr_lb
= bounds
.ap_lower
;
3271 *instr_ub
= bounds
.ap_upper
;
3273 else if (frame
->f_lasti
<= *instr_prev
) {
3274 result
= call_trace(func
, obj
, frame
, PyTrace_LINE
, Py_None
);
3276 *instr_prev
= frame
->f_lasti
;
3281 PyEval_SetProfile(Py_tracefunc func
, PyObject
*arg
)
3283 PyThreadState
*tstate
= PyThreadState_GET();
3284 PyObject
*temp
= tstate
->c_profileobj
;
3286 tstate
->c_profilefunc
= NULL
;
3287 tstate
->c_profileobj
= NULL
;
3288 /* Must make sure that tracing is not ignored if 'temp' is freed */
3289 tstate
->use_tracing
= tstate
->c_tracefunc
!= NULL
;
3291 tstate
->c_profilefunc
= func
;
3292 tstate
->c_profileobj
= arg
;
3293 /* Flag that tracing or profiling is turned on */
3294 tstate
->use_tracing
= (func
!= NULL
) || (tstate
->c_tracefunc
!= NULL
);
3298 PyEval_SetTrace(Py_tracefunc func
, PyObject
*arg
)
3300 PyThreadState
*tstate
= PyThreadState_GET();
3301 PyObject
*temp
= tstate
->c_traceobj
;
3303 tstate
->c_tracefunc
= NULL
;
3304 tstate
->c_traceobj
= NULL
;
3305 /* Must make sure that profiling is not ignored if 'temp' is freed */
3306 tstate
->use_tracing
= tstate
->c_profilefunc
!= NULL
;
3308 tstate
->c_tracefunc
= func
;
3309 tstate
->c_traceobj
= arg
;
3310 /* Flag that tracing or profiling is turned on */
3311 tstate
->use_tracing
= ((func
!= NULL
)
3312 || (tstate
->c_profilefunc
!= NULL
));
3316 PyEval_GetBuiltins(void)
3318 PyFrameObject
*current_frame
= PyEval_GetFrame();
3319 if (current_frame
== NULL
)
3320 return PyThreadState_GET()->interp
->builtins
;
3322 return current_frame
->f_builtins
;
3326 PyEval_GetLocals(void)
3328 PyFrameObject
*current_frame
= PyEval_GetFrame();
3329 if (current_frame
== NULL
)
3331 PyFrame_FastToLocals(current_frame
);
3332 return current_frame
->f_locals
;
3336 PyEval_GetGlobals(void)
3338 PyFrameObject
*current_frame
= PyEval_GetFrame();
3339 if (current_frame
== NULL
)
3342 return current_frame
->f_globals
;
3346 PyEval_GetFrame(void)
3348 PyThreadState
*tstate
= PyThreadState_GET();
3349 return _PyThreadState_GetFrame(tstate
);
3353 PyEval_GetRestricted(void)
3355 PyFrameObject
*current_frame
= PyEval_GetFrame();
3356 return current_frame
== NULL
? 0 : PyFrame_IsRestricted(current_frame
);
3360 PyEval_MergeCompilerFlags(PyCompilerFlags
*cf
)
3362 PyFrameObject
*current_frame
= PyEval_GetFrame();
3363 int result
= cf
->cf_flags
!= 0;
3365 if (current_frame
!= NULL
) {
3366 const int codeflags
= current_frame
->f_code
->co_flags
;
3367 const int compilerflags
= codeflags
& PyCF_MASK
;
3368 if (compilerflags
) {
3370 cf
->cf_flags
|= compilerflags
;
3372 #if 0 /* future keyword */
3373 if (codeflags
& CO_GENERATOR_ALLOWED
) {
3375 cf
->cf_flags
|= CO_GENERATOR_ALLOWED
;
3385 PyObject
*f
= PySys_GetObject("stdout");
3388 if (!PyFile_SoftSpace(f
, 0))
3390 return PyFile_WriteString("\n", f
);
3394 /* External interface to call any callable object.
3395 The arg must be a tuple or NULL. */
3397 #undef PyEval_CallObject
3398 /* for backward compatibility: export this interface */
3401 PyEval_CallObject(PyObject
*func
, PyObject
*arg
)
3403 return PyEval_CallObjectWithKeywords(func
, arg
, (PyObject
*)NULL
);
3405 #define PyEval_CallObject(func,arg) \
3406 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
3409 PyEval_CallObjectWithKeywords(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
3414 arg
= PyTuple_New(0);
3418 else if (!PyTuple_Check(arg
)) {
3419 PyErr_SetString(PyExc_TypeError
,
3420 "argument list must be a tuple");
3426 if (kw
!= NULL
&& !PyDict_Check(kw
)) {
3427 PyErr_SetString(PyExc_TypeError
,
3428 "keyword list must be a dictionary");
3433 result
= PyObject_Call(func
, arg
, kw
);
3439 PyEval_GetFuncName(PyObject
*func
)
3441 if (PyMethod_Check(func
))
3442 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func
));
3443 else if (PyFunction_Check(func
))
3444 return PyString_AsString(((PyFunctionObject
*)func
)->func_name
);
3445 else if (PyCFunction_Check(func
))
3446 return ((PyCFunctionObject
*)func
)->m_ml
->ml_name
;
3447 else if (PyClass_Check(func
))
3448 return PyString_AsString(((PyClassObject
*)func
)->cl_name
);
3449 else if (PyInstance_Check(func
)) {
3450 return PyString_AsString(
3451 ((PyInstanceObject
*)func
)->in_class
->cl_name
);
3453 return func
->ob_type
->tp_name
;
3458 PyEval_GetFuncDesc(PyObject
*func
)
3460 if (PyMethod_Check(func
))
3462 else if (PyFunction_Check(func
))
3464 else if (PyCFunction_Check(func
))
3466 else if (PyClass_Check(func
))
3467 return " constructor";
3468 else if (PyInstance_Check(func
)) {
3476 err_args(PyObject
*func
, int flags
, int nargs
)
3478 if (flags
& METH_NOARGS
)
3479 PyErr_Format(PyExc_TypeError
,
3480 "%.200s() takes no arguments (%d given)",
3481 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3484 PyErr_Format(PyExc_TypeError
,
3485 "%.200s() takes exactly one argument (%d given)",
3486 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3490 #define C_TRACE(x, call) \
3491 if (tstate->use_tracing && tstate->c_profilefunc) { \
3492 if (call_trace(tstate->c_profilefunc, \
3493 tstate->c_profileobj, \
3494 tstate->frame, PyTrace_C_CALL, \
3500 if (tstate->c_profilefunc != NULL) { \
3502 call_trace_protected(tstate->c_profilefunc, \
3503 tstate->c_profileobj, \
3504 tstate->frame, PyTrace_C_EXCEPTION, \
3506 /* XXX should pass (type, value, tb) */ \
3508 if (call_trace(tstate->c_profilefunc, \
3509 tstate->c_profileobj, \
3510 tstate->frame, PyTrace_C_RETURN, \
3523 call_function(PyObject
***pp_stack
, int oparg
3525 , uint64
* pintr0
, uint64
* pintr1
3529 int na
= oparg
& 0xff;
3530 int nk
= (oparg
>>8) & 0xff;
3531 int n
= na
+ 2 * nk
;
3532 PyObject
**pfunc
= (*pp_stack
) - n
- 1;
3533 PyObject
*func
= *pfunc
;
3536 /* Always dispatch PyCFunction first, because these are
3537 presumed to be the most frequent callable object.
3539 if (PyCFunction_Check(func
) && nk
== 0) {
3540 int flags
= PyCFunction_GET_FLAGS(func
);
3541 PyThreadState
*tstate
= PyThreadState_GET();
3543 PCALL(PCALL_CFUNCTION
);
3544 if (flags
& (METH_NOARGS
| METH_O
)) {
3545 PyCFunction meth
= PyCFunction_GET_FUNCTION(func
);
3546 PyObject
*self
= PyCFunction_GET_SELF(func
);
3547 if (flags
& METH_NOARGS
&& na
== 0) {
3548 C_TRACE(x
, (*meth
)(self
,NULL
));
3550 else if (flags
& METH_O
&& na
== 1) {
3551 PyObject
*arg
= EXT_POP(*pp_stack
);
3552 C_TRACE(x
, (*meth
)(self
,arg
));
3556 err_args(func
, flags
, na
);
3562 callargs
= load_args(pp_stack
, na
);
3563 READ_TIMESTAMP(*pintr0
);
3564 C_TRACE(x
, PyCFunction_Call(func
,callargs
,NULL
));
3565 READ_TIMESTAMP(*pintr1
);
3566 Py_XDECREF(callargs
);
3569 if (PyMethod_Check(func
) && PyMethod_GET_SELF(func
) != NULL
) {
3570 /* optimize access to bound methods */
3571 PyObject
*self
= PyMethod_GET_SELF(func
);
3572 PCALL(PCALL_METHOD
);
3573 PCALL(PCALL_BOUND_METHOD
);
3575 func
= PyMethod_GET_FUNCTION(func
);
3583 READ_TIMESTAMP(*pintr0
);
3584 if (PyFunction_Check(func
))
3585 x
= fast_function(func
, pp_stack
, n
, na
, nk
);
3587 x
= do_call(func
, pp_stack
, na
, nk
);
3588 READ_TIMESTAMP(*pintr1
);
3592 /* Clear the stack of the function object. Also removes
3593 the arguments in case they weren't consumed already
3594 (fast_function() and err_args() leave them on the stack).
3596 while ((*pp_stack
) > pfunc
) {
3597 w
= EXT_POP(*pp_stack
);
3604 /* The fast_function() function optimize calls for which no argument
3605 tuple is necessary; the objects are passed directly from the stack.
3606 For the simplest case -- a function that takes only positional
3607 arguments and is called with only positional arguments -- it
3608 inlines the most primitive frame setup code from
3609 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
3610 done before evaluating the frame.
3614 fast_function(PyObject
*func
, PyObject
***pp_stack
, int n
, int na
, int nk
)
3616 PyCodeObject
*co
= (PyCodeObject
*)PyFunction_GET_CODE(func
);
3617 PyObject
*globals
= PyFunction_GET_GLOBALS(func
);
3618 PyObject
*argdefs
= PyFunction_GET_DEFAULTS(func
);
3619 PyObject
**d
= NULL
;
3622 PCALL(PCALL_FUNCTION
);
3623 PCALL(PCALL_FAST_FUNCTION
);
3624 if (argdefs
== NULL
&& co
->co_argcount
== n
&& nk
==0 &&
3625 co
->co_flags
== (CO_OPTIMIZED
| CO_NEWLOCALS
| CO_NOFREE
)) {
3627 PyObject
*retval
= NULL
;
3628 PyThreadState
*tstate
= PyThreadState_GET();
3629 PyObject
**fastlocals
, **stack
;
3632 PCALL(PCALL_FASTER_FUNCTION
);
3633 assert(globals
!= NULL
);
3634 /* XXX Perhaps we should create a specialized
3635 PyFrame_New() that doesn't take locals, but does
3636 take builtins without sanity checking them.
3638 assert(tstate
!= NULL
);
3639 f
= PyFrame_New(tstate
, co
, globals
, NULL
);
3643 fastlocals
= f
->f_localsplus
;
3644 stack
= (*pp_stack
) - n
;
3646 for (i
= 0; i
< n
; i
++) {
3648 fastlocals
[i
] = *stack
++;
3650 retval
= PyEval_EvalFrameEx(f
,0);
3651 ++tstate
->recursion_depth
;
3653 --tstate
->recursion_depth
;
3656 if (argdefs
!= NULL
) {
3657 d
= &PyTuple_GET_ITEM(argdefs
, 0);
3658 nd
= Py_Size(argdefs
);
3660 return PyEval_EvalCodeEx(co
, globals
,
3661 (PyObject
*)NULL
, (*pp_stack
)-n
, na
,
3662 (*pp_stack
)-2*nk
, nk
, d
, nd
,
3663 PyFunction_GET_CLOSURE(func
));
3667 update_keyword_args(PyObject
*orig_kwdict
, int nk
, PyObject
***pp_stack
,
3670 PyObject
*kwdict
= NULL
;
3671 if (orig_kwdict
== NULL
)
3672 kwdict
= PyDict_New();
3674 kwdict
= PyDict_Copy(orig_kwdict
);
3675 Py_DECREF(orig_kwdict
);
3681 PyObject
*value
= EXT_POP(*pp_stack
);
3682 PyObject
*key
= EXT_POP(*pp_stack
);
3683 if (PyDict_GetItem(kwdict
, key
) != NULL
) {
3684 PyErr_Format(PyExc_TypeError
,
3685 "%.200s%s got multiple values "
3686 "for keyword argument '%.200s'",
3687 PyEval_GetFuncName(func
),
3688 PyEval_GetFuncDesc(func
),
3689 PyString_AsString(key
));
3695 err
= PyDict_SetItem(kwdict
, key
, value
);
3707 update_star_args(int nstack
, int nstar
, PyObject
*stararg
,
3708 PyObject
***pp_stack
)
3710 PyObject
*callargs
, *w
;
3712 callargs
= PyTuple_New(nstack
+ nstar
);
3713 if (callargs
== NULL
) {
3718 for (i
= 0; i
< nstar
; i
++) {
3719 PyObject
*a
= PyTuple_GET_ITEM(stararg
, i
);
3721 PyTuple_SET_ITEM(callargs
, nstack
+ i
, a
);
3724 while (--nstack
>= 0) {
3725 w
= EXT_POP(*pp_stack
);
3726 PyTuple_SET_ITEM(callargs
, nstack
, w
);
3732 load_args(PyObject
***pp_stack
, int na
)
3734 PyObject
*args
= PyTuple_New(na
);
3740 w
= EXT_POP(*pp_stack
);
3741 PyTuple_SET_ITEM(args
, na
, w
);
3747 do_call(PyObject
*func
, PyObject
***pp_stack
, int na
, int nk
)
3749 PyObject
*callargs
= NULL
;
3750 PyObject
*kwdict
= NULL
;
3751 PyObject
*result
= NULL
;
3754 kwdict
= update_keyword_args(NULL
, nk
, pp_stack
, func
);
3758 callargs
= load_args(pp_stack
, na
);
3759 if (callargs
== NULL
)
3762 /* At this point, we have to look at the type of func to
3763 update the call stats properly. Do it here so as to avoid
3764 exposing the call stats machinery outside ceval.c
3766 if (PyFunction_Check(func
))
3767 PCALL(PCALL_FUNCTION
);
3768 else if (PyMethod_Check(func
))
3769 PCALL(PCALL_METHOD
);
3770 else if (PyType_Check(func
))
3775 result
= PyObject_Call(func
, callargs
, kwdict
);
3777 Py_XDECREF(callargs
);
3783 ext_do_call(PyObject
*func
, PyObject
***pp_stack
, int flags
, int na
, int nk
)
3786 PyObject
*callargs
= NULL
;
3787 PyObject
*stararg
= NULL
;
3788 PyObject
*kwdict
= NULL
;
3789 PyObject
*result
= NULL
;
3791 if (flags
& CALL_FLAG_KW
) {
3792 kwdict
= EXT_POP(*pp_stack
);
3793 if (!PyDict_Check(kwdict
)) {
3798 if (PyDict_Update(d
, kwdict
) != 0) {
3800 /* PyDict_Update raises attribute
3801 * error (percolated from an attempt
3802 * to get 'keys' attribute) instead of
3803 * a type error if its second argument
3806 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
3807 PyErr_Format(PyExc_TypeError
,
3808 "%.200s%.200s argument after ** "
3809 "must be a mapping, not %.200s",
3810 PyEval_GetFuncName(func
),
3811 PyEval_GetFuncDesc(func
),
3812 kwdict
->ob_type
->tp_name
);
3820 if (flags
& CALL_FLAG_VAR
) {
3821 stararg
= EXT_POP(*pp_stack
);
3822 if (!PyTuple_Check(stararg
)) {
3824 t
= PySequence_Tuple(stararg
);
3826 if (PyErr_ExceptionMatches(PyExc_TypeError
)) {
3827 PyErr_Format(PyExc_TypeError
,
3828 "%.200s%.200s argument after * "
3829 "must be a sequence, not %200s",
3830 PyEval_GetFuncName(func
),
3831 PyEval_GetFuncDesc(func
),
3832 stararg
->ob_type
->tp_name
);
3839 nstar
= PyTuple_GET_SIZE(stararg
);
3842 kwdict
= update_keyword_args(kwdict
, nk
, pp_stack
, func
);
3846 callargs
= update_star_args(na
, nstar
, stararg
, pp_stack
);
3847 if (callargs
== NULL
)
3850 /* At this point, we have to look at the type of func to
3851 update the call stats properly. Do it here so as to avoid
3852 exposing the call stats machinery outside ceval.c
3854 if (PyFunction_Check(func
))
3855 PCALL(PCALL_FUNCTION
);
3856 else if (PyMethod_Check(func
))
3857 PCALL(PCALL_METHOD
);
3858 else if (PyType_Check(func
))
3863 result
= PyObject_Call(func
, callargs
, kwdict
);
3865 Py_XDECREF(callargs
);
3867 Py_XDECREF(stararg
);
3871 /* Extract a slice index from a PyInt or PyLong or an object with the
3872 nb_index slot defined, and store in *pi.
3873 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
3874 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
3875 Return 0 on error, 1 on success.
3877 /* Note: If v is NULL, return success without storing into *pi. This
3878 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
3879 called by the SLICE opcode with v and/or w equal to NULL.
3882 _PyEval_SliceIndex(PyObject
*v
, Py_ssize_t
*pi
)
3886 if (PyInt_Check(v
)) {
3887 /* XXX(nnorwitz): I think PyInt_AS_LONG is correct,
3888 however, it looks like it should be AsSsize_t.
3889 There should be a comment here explaining why.
3891 x
= PyInt_AS_LONG(v
);
3893 else if (PyIndex_Check(v
)) {
3894 x
= PyNumber_AsSsize_t(v
, NULL
);
3895 if (x
== -1 && PyErr_Occurred())
3899 PyErr_SetString(PyExc_TypeError
,
3900 "slice indices must be integers or "
3901 "None or have an __index__ method");
3910 #define ISINDEX(x) ((x) == NULL || \
3911 PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
3914 apply_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
) /* return u[v:w] */
3916 PyTypeObject
*tp
= u
->ob_type
;
3917 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
3919 if (sq
&& sq
->sq_slice
&& ISINDEX(v
) && ISINDEX(w
)) {
3920 Py_ssize_t ilow
= 0, ihigh
= PY_SSIZE_T_MAX
;
3921 if (!_PyEval_SliceIndex(v
, &ilow
))
3923 if (!_PyEval_SliceIndex(w
, &ihigh
))
3925 return PySequence_GetSlice(u
, ilow
, ihigh
);
3928 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
3929 if (slice
!= NULL
) {
3930 PyObject
*res
= PyObject_GetItem(u
, slice
);
3940 assign_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
, PyObject
*x
)
3943 PyTypeObject
*tp
= u
->ob_type
;
3944 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
3946 if (sq
&& sq
->sq_ass_slice
&& ISINDEX(v
) && ISINDEX(w
)) {
3947 Py_ssize_t ilow
= 0, ihigh
= PY_SSIZE_T_MAX
;
3948 if (!_PyEval_SliceIndex(v
, &ilow
))
3950 if (!_PyEval_SliceIndex(w
, &ihigh
))
3953 return PySequence_DelSlice(u
, ilow
, ihigh
);
3955 return PySequence_SetSlice(u
, ilow
, ihigh
, x
);
3958 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
3959 if (slice
!= NULL
) {
3962 res
= PyObject_SetItem(u
, slice
, x
);
3964 res
= PyObject_DelItem(u
, slice
);
3974 cmp_outcome(int op
, register PyObject
*v
, register PyObject
*w
)
3985 res
= PySequence_Contains(w
, v
);
3990 res
= PySequence_Contains(w
, v
);
3995 case PyCmp_EXC_MATCH
:
3996 if (PyTuple_Check(w
)) {
3997 Py_ssize_t i
, length
;
3998 length
= PyTuple_Size(w
);
3999 for (i
= 0; i
< length
; i
+= 1) {
4000 PyObject
*exc
= PyTuple_GET_ITEM(w
, i
);
4001 if (PyString_Check(exc
)) {
4003 ret_val
= PyErr_WarnEx(
4004 PyExc_DeprecationWarning
,
4005 "catching of string "
4014 if (PyString_Check(w
)) {
4016 ret_val
= PyErr_WarnEx(
4017 PyExc_DeprecationWarning
,
4018 "catching of string "
4019 "exceptions is deprecated",
4025 res
= PyErr_GivenExceptionMatches(v
, w
);
4028 return PyObject_RichCompare(v
, w
, op
);
4030 v
= res
? Py_True
: Py_False
;
4036 import_from(PyObject
*v
, PyObject
*name
)
4040 x
= PyObject_GetAttr(v
, name
);
4041 if (x
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
4042 PyErr_Format(PyExc_ImportError
,
4043 "cannot import name %.230s",
4044 PyString_AsString(name
));
4050 import_all_from(PyObject
*locals
, PyObject
*v
)
4052 PyObject
*all
= PyObject_GetAttrString(v
, "__all__");
4053 PyObject
*dict
, *name
, *value
;
4054 int skip_leading_underscores
= 0;
4058 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4059 return -1; /* Unexpected error */
4061 dict
= PyObject_GetAttrString(v
, "__dict__");
4063 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4065 PyErr_SetString(PyExc_ImportError
,
4066 "from-import-* object has no __dict__ and no __all__");
4069 all
= PyMapping_Keys(dict
);
4073 skip_leading_underscores
= 1;
4076 for (pos
= 0, err
= 0; ; pos
++) {
4077 name
= PySequence_GetItem(all
, pos
);
4079 if (!PyErr_ExceptionMatches(PyExc_IndexError
))
4085 if (skip_leading_underscores
&&
4086 PyString_Check(name
) &&
4087 PyString_AS_STRING(name
)[0] == '_')
4092 value
= PyObject_GetAttr(v
, name
);
4095 else if (PyDict_CheckExact(locals
))
4096 err
= PyDict_SetItem(locals
, name
, value
);
4098 err
= PyObject_SetItem(locals
, name
, value
);
4109 build_class(PyObject
*methods
, PyObject
*bases
, PyObject
*name
)
4111 PyObject
*metaclass
= NULL
, *result
, *base
;
4113 if (PyDict_Check(methods
))
4114 metaclass
= PyDict_GetItemString(methods
, "__metaclass__");
4115 if (metaclass
!= NULL
)
4116 Py_INCREF(metaclass
);
4117 else if (PyTuple_Check(bases
) && PyTuple_GET_SIZE(bases
) > 0) {
4118 base
= PyTuple_GET_ITEM(bases
, 0);
4119 metaclass
= PyObject_GetAttrString(base
, "__class__");
4120 if (metaclass
== NULL
) {
4122 metaclass
= (PyObject
*)base
->ob_type
;
4123 Py_INCREF(metaclass
);
4127 PyObject
*g
= PyEval_GetGlobals();
4128 if (g
!= NULL
&& PyDict_Check(g
))
4129 metaclass
= PyDict_GetItemString(g
, "__metaclass__");
4130 if (metaclass
== NULL
)
4131 metaclass
= (PyObject
*) &PyClass_Type
;
4132 Py_INCREF(metaclass
);
4134 result
= PyObject_CallFunctionObjArgs(metaclass
, name
, bases
, methods
,
4136 Py_DECREF(metaclass
);
4137 if (result
== NULL
&& PyErr_ExceptionMatches(PyExc_TypeError
)) {
4138 /* A type error here likely means that the user passed
4139 in a base that was not a class (such the random module
4140 instead of the random.random type). Help them out with
4141 by augmenting the error message with more information.*/
4143 PyObject
*ptype
, *pvalue
, *ptraceback
;
4145 PyErr_Fetch(&ptype
, &pvalue
, &ptraceback
);
4146 if (PyString_Check(pvalue
)) {
4148 newmsg
= PyString_FromFormat(
4149 "Error when calling the metaclass bases\n"
4151 PyString_AS_STRING(pvalue
));
4152 if (newmsg
!= NULL
) {
4157 PyErr_Restore(ptype
, pvalue
, ptraceback
);
4163 exec_statement(PyFrameObject
*f
, PyObject
*prog
, PyObject
*globals
,
4170 if (PyTuple_Check(prog
) && globals
== Py_None
&& locals
== Py_None
&&
4171 ((n
= PyTuple_Size(prog
)) == 2 || n
== 3)) {
4172 /* Backward compatibility hack */
4173 globals
= PyTuple_GetItem(prog
, 1);
4175 locals
= PyTuple_GetItem(prog
, 2);
4176 prog
= PyTuple_GetItem(prog
, 0);
4178 if (globals
== Py_None
) {
4179 globals
= PyEval_GetGlobals();
4180 if (locals
== Py_None
) {
4181 locals
= PyEval_GetLocals();
4184 if (!globals
|| !locals
) {
4185 PyErr_SetString(PyExc_SystemError
,
4186 "globals and locals cannot be NULL");
4190 else if (locals
== Py_None
)
4192 if (!PyString_Check(prog
) &&
4193 !PyUnicode_Check(prog
) &&
4194 !PyCode_Check(prog
) &&
4195 !PyFile_Check(prog
)) {
4196 PyErr_SetString(PyExc_TypeError
,
4197 "exec: arg 1 must be a string, file, or code object");
4200 if (!PyDict_Check(globals
)) {
4201 PyErr_SetString(PyExc_TypeError
,
4202 "exec: arg 2 must be a dictionary or None");
4205 if (!PyMapping_Check(locals
)) {
4206 PyErr_SetString(PyExc_TypeError
,
4207 "exec: arg 3 must be a mapping or None");
4210 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
)
4211 PyDict_SetItemString(globals
, "__builtins__", f
->f_builtins
);
4212 if (PyCode_Check(prog
)) {
4213 if (PyCode_GetNumFree((PyCodeObject
*)prog
) > 0) {
4214 PyErr_SetString(PyExc_TypeError
,
4215 "code object passed to exec may not contain free variables");
4218 v
= PyEval_EvalCode((PyCodeObject
*) prog
, globals
, locals
);
4220 else if (PyFile_Check(prog
)) {
4221 FILE *fp
= PyFile_AsFile(prog
);
4222 char *name
= PyString_AsString(PyFile_Name(prog
));
4227 if (PyEval_MergeCompilerFlags(&cf
))
4228 v
= PyRun_FileFlags(fp
, name
, Py_file_input
, globals
,
4231 v
= PyRun_File(fp
, name
, Py_file_input
, globals
,
4235 PyObject
*tmp
= NULL
;
4239 #ifdef Py_USING_UNICODE
4240 if (PyUnicode_Check(prog
)) {
4241 tmp
= PyUnicode_AsUTF8String(prog
);
4245 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
4248 if (PyString_AsStringAndSize(prog
, &str
, NULL
))
4250 if (PyEval_MergeCompilerFlags(&cf
))
4251 v
= PyRun_StringFlags(str
, Py_file_input
, globals
,
4254 v
= PyRun_String(str
, Py_file_input
, globals
, locals
);
4258 PyFrame_LocalsToFast(f
, 0);
4266 format_exc_check_arg(PyObject
*exc
, char *format_str
, PyObject
*obj
)
4273 obj_str
= PyString_AsString(obj
);
4277 PyErr_Format(exc
, format_str
, obj_str
);
4281 string_concatenate(PyObject
*v
, PyObject
*w
,
4282 PyFrameObject
*f
, unsigned char *next_instr
)
4284 /* This function implements 'variable += expr' when both arguments
4286 Py_ssize_t v_len
= PyString_GET_SIZE(v
);
4287 Py_ssize_t w_len
= PyString_GET_SIZE(w
);
4288 Py_ssize_t new_len
= v_len
+ w_len
;
4290 PyErr_SetString(PyExc_OverflowError
,
4291 "strings are too large to concat");
4295 if (v
->ob_refcnt
== 2) {
4296 /* In the common case, there are 2 references to the value
4297 * stored in 'variable' when the += is performed: one on the
4298 * value stack (in 'v') and one still stored in the 'variable'.
4299 * We try to delete the variable now to reduce the refcnt to 1.
4301 switch (*next_instr
) {
4304 int oparg
= PEEKARG();
4305 PyObject
**fastlocals
= f
->f_localsplus
;
4306 if (GETLOCAL(oparg
) == v
)
4307 SETLOCAL(oparg
, NULL
);
4312 PyObject
**freevars
= f
->f_localsplus
+ f
->f_code
->co_nlocals
;
4313 PyObject
*c
= freevars
[PEEKARG()];
4314 if (PyCell_GET(c
) == v
)
4315 PyCell_Set(c
, NULL
);
4320 PyObject
*names
= f
->f_code
->co_names
;
4321 PyObject
*name
= GETITEM(names
, PEEKARG());
4322 PyObject
*locals
= f
->f_locals
;
4323 if (PyDict_CheckExact(locals
) &&
4324 PyDict_GetItem(locals
, name
) == v
) {
4325 if (PyDict_DelItem(locals
, name
) != 0) {
4334 if (v
->ob_refcnt
== 1 && !PyString_CHECK_INTERNED(v
)) {
4335 /* Now we own the last reference to 'v', so we can resize it
4338 if (_PyString_Resize(&v
, new_len
) != 0) {
4339 /* XXX if _PyString_Resize() fails, 'v' has been
4340 * deallocated so it cannot be put back into 'variable'.
4341 * The MemoryError is raised when there is no value in
4342 * 'variable', which might (very remotely) be a cause
4343 * of incompatibilities.
4347 /* copy 'w' into the newly allocated area of 'v' */
4348 memcpy(PyString_AS_STRING(v
) + v_len
,
4349 PyString_AS_STRING(w
), w_len
);
4353 /* When in-place resizing is not an option. */
4354 PyString_Concat(&v
, w
);
4359 #ifdef DYNAMIC_EXECUTION_PROFILE
4362 getarray(long a
[256])
4365 PyObject
*l
= PyList_New(256);
4366 if (l
== NULL
) return NULL
;
4367 for (i
= 0; i
< 256; i
++) {
4368 PyObject
*x
= PyInt_FromLong(a
[i
]);
4373 PyList_SetItem(l
, i
, x
);
4375 for (i
= 0; i
< 256; i
++)
4381 _Py_GetDXProfile(PyObject
*self
, PyObject
*args
)
4384 return getarray(dxp
);
4387 PyObject
*l
= PyList_New(257);
4388 if (l
== NULL
) return NULL
;
4389 for (i
= 0; i
< 257; i
++) {
4390 PyObject
*x
= getarray(dxpairs
[i
]);
4395 PyList_SetItem(l
, i
, x
);