2 /* Execute compiled code */
5 XXX speed up searching for keywords by using a dictionary
12 #include "frameobject.h"
15 #include "structmember.h"
23 /* Turn this on if your compiler chokes on the big switch: */
24 /* #define CASE_TOO_BIG 1 */
27 /* For debugging the interpreter: */
28 #define LLTRACE 1 /* Low-level trace feature */
29 #define CHECKEXC 1 /* Double-check exception checking */
32 typedef PyObject
*(*callproc
)(PyObject
*, PyObject
*, PyObject
*);
34 /* Forward declarations */
35 static PyObject
*eval_frame(PyFrameObject
*);
36 static PyObject
*call_function(PyObject
***, int);
37 static PyObject
*fast_function(PyObject
*, PyObject
***, int, int, int);
38 static PyObject
*do_call(PyObject
*, PyObject
***, int, int);
39 static PyObject
*ext_do_call(PyObject
*, PyObject
***, int, int, int);
40 static PyObject
*update_keyword_args(PyObject
*, int, PyObject
***,PyObject
*);
41 static PyObject
*update_star_args(int, int, PyObject
*, PyObject
***);
42 static PyObject
*load_args(PyObject
***, int);
43 #define CALL_FLAG_VAR 1
44 #define CALL_FLAG_KW 2
47 static int prtrace(PyObject
*, char *);
49 static int call_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*,
51 static void call_trace_protected(Py_tracefunc
, PyObject
*,
52 PyFrameObject
*, int);
53 static void call_exc_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*);
54 static int maybe_call_line_trace(Py_tracefunc
, PyObject
*,
55 PyFrameObject
*, int *, int *);
57 static PyObject
*apply_slice(PyObject
*, PyObject
*, PyObject
*);
58 static int assign_slice(PyObject
*, PyObject
*,
59 PyObject
*, PyObject
*);
60 static PyObject
*cmp_outcome(int, PyObject
*, PyObject
*);
61 static PyObject
*import_from(PyObject
*, PyObject
*);
62 static int import_all_from(PyObject
*, PyObject
*);
63 static PyObject
*build_class(PyObject
*, PyObject
*, PyObject
*);
64 static int exec_statement(PyFrameObject
*,
65 PyObject
*, PyObject
*, PyObject
*);
66 static void set_exc_info(PyThreadState
*, PyObject
*, PyObject
*, PyObject
*);
67 static void reset_exc_info(PyThreadState
*);
68 static void format_exc_check_arg(PyObject
*, char *, PyObject
*);
70 #define NAME_ERROR_MSG \
71 "name '%.200s' is not defined"
72 #define GLOBAL_NAME_ERROR_MSG \
73 "global name '%.200s' is not defined"
74 #define UNBOUNDLOCAL_ERROR_MSG \
75 "local variable '%.200s' referenced before assignment"
76 #define UNBOUNDFREE_ERROR_MSG \
77 "free variable '%.200s' referenced before assignment" \
80 /* Dynamic execution profile */
81 #ifdef DYNAMIC_EXECUTION_PROFILE
83 static long dxpairs
[257][256];
84 #define dxp dxpairs[256]
90 /* Function call profile */
93 static int pcall
[PCALL_NUM
];
96 #define PCALL_FUNCTION 1
97 #define PCALL_FAST_FUNCTION 2
98 #define PCALL_FASTER_FUNCTION 3
99 #define PCALL_METHOD 4
100 #define PCALL_BOUND_METHOD 5
101 #define PCALL_CFUNCTION 6
103 #define PCALL_GENERATOR 8
104 #define PCALL_OTHER 9
107 /* Notes about the statistics
111 FAST_FUNCTION means no argument tuple needs to be created.
112 FASTER_FUNCTION means that the fast-path frame setup code is used.
114 If there is a method call where the call can be optimized by changing
115 the argument tuple and calling the function directly, it gets recorded
118 As a result, the relationship among the statistics appears to be
119 PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
120 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
121 PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
122 PCALL_METHOD > PCALL_BOUND_METHOD
125 #define PCALL(POS) pcall[POS]++
128 PyEval_GetCallStats(PyObject
*self
)
130 return Py_BuildValue("iiiiiiiiii",
131 pcall
[0], pcall
[1], pcall
[2], pcall
[3],
132 pcall
[4], pcall
[5], pcall
[6], pcall
[7],
139 PyEval_GetCallStats(PyObject
*self
)
146 static PyTypeObject gentype
;
150 /* The gi_ prefix is intended to remind of generator-iterator. */
152 PyFrameObject
*gi_frame
;
154 /* True if generator is being executed. */
157 /* List of weak reference. */
158 PyObject
*gi_weakreflist
;
162 gen_new(PyFrameObject
*f
)
164 genobject
*gen
= PyObject_GC_New(genobject
, &gentype
);
171 gen
->gi_weakreflist
= NULL
;
172 _PyObject_GC_TRACK(gen
);
173 return (PyObject
*)gen
;
177 gen_traverse(genobject
*gen
, visitproc visit
, void *arg
)
179 return visit((PyObject
*)gen
->gi_frame
, arg
);
183 gen_dealloc(genobject
*gen
)
185 _PyObject_GC_UNTRACK(gen
);
186 if (gen
->gi_weakreflist
!= NULL
)
187 PyObject_ClearWeakRefs((PyObject
*) gen
);
188 Py_DECREF(gen
->gi_frame
);
189 PyObject_GC_Del(gen
);
193 gen_iternext(genobject
*gen
)
195 PyThreadState
*tstate
= PyThreadState_GET();
196 PyFrameObject
*f
= gen
->gi_frame
;
199 if (gen
->gi_running
) {
200 PyErr_SetString(PyExc_ValueError
,
201 "generator already executing");
204 if (f
->f_stacktop
== NULL
)
207 /* Generators always return to their most recent caller, not
208 * necessarily their creator. */
209 Py_XINCREF(tstate
->frame
);
210 assert(f
->f_back
== NULL
);
211 f
->f_back
= tstate
->frame
;
214 result
= eval_frame(f
);
217 /* Don't keep the reference to f_back any longer than necessary. It
218 * may keep a chain of frames alive or it could create a reference
220 Py_XDECREF(f
->f_back
);
223 /* If the generator just returned (as opposed to yielding), signal
224 * that the generator is exhausted. */
225 if (result
== Py_None
&& f
->f_stacktop
== NULL
) {
234 gen_getiter(PyObject
*gen
)
240 static PyMemberDef gen_memberlist
[] = {
241 {"gi_frame", T_OBJECT
, offsetof(genobject
, gi_frame
), RO
},
242 {"gi_running", T_INT
, offsetof(genobject
, gi_running
), RO
},
243 {NULL
} /* Sentinel */
246 static PyTypeObject gentype
= {
247 PyObject_HEAD_INIT(&PyType_Type
)
249 "generator", /* tp_name */
250 sizeof(genobject
), /* tp_basicsize */
253 (destructor
)gen_dealloc
, /* tp_dealloc */
259 0, /* tp_as_number */
260 0, /* tp_as_sequence */
261 0, /* tp_as_mapping */
265 PyObject_GenericGetAttr
, /* tp_getattro */
267 0, /* tp_as_buffer */
268 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
270 (traverseproc
)gen_traverse
, /* tp_traverse */
272 0, /* tp_richcompare */
273 offsetof(genobject
, gi_weakreflist
), /* tp_weaklistoffset */
274 (getiterfunc
)gen_getiter
, /* tp_iter */
275 (iternextfunc
)gen_iternext
, /* tp_iternext */
277 gen_memberlist
, /* tp_members */
286 #ifndef DONT_HAVE_ERRNO_H
289 #include "pythread.h"
291 extern int _PyThread_Started
; /* Flag for Py_Exit */
293 static PyThread_type_lock interpreter_lock
= 0; /* This is the GIL */
294 static long main_thread
= 0;
297 PyEval_InitThreads(void)
299 if (interpreter_lock
)
301 _PyThread_Started
= 1;
302 interpreter_lock
= PyThread_allocate_lock();
303 PyThread_acquire_lock(interpreter_lock
, 1);
304 main_thread
= PyThread_get_thread_ident();
308 PyEval_AcquireLock(void)
310 PyThread_acquire_lock(interpreter_lock
, 1);
314 PyEval_ReleaseLock(void)
316 PyThread_release_lock(interpreter_lock
);
320 PyEval_AcquireThread(PyThreadState
*tstate
)
323 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
324 /* Check someone has called PyEval_InitThreads() to create the lock */
325 assert(interpreter_lock
);
326 PyThread_acquire_lock(interpreter_lock
, 1);
327 if (PyThreadState_Swap(tstate
) != NULL
)
329 "PyEval_AcquireThread: non-NULL old thread state");
333 PyEval_ReleaseThread(PyThreadState
*tstate
)
336 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
337 if (PyThreadState_Swap(NULL
) != tstate
)
338 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
339 PyThread_release_lock(interpreter_lock
);
342 /* This function is called from PyOS_AfterFork to ensure that newly
343 created child processes don't hold locks referring to threads which
344 are not running in the child process. (This could also be done using
345 pthread_atfork mechanism, at least for the pthreads implementation.) */
348 PyEval_ReInitThreads(void)
350 if (!interpreter_lock
)
352 /*XXX Can't use PyThread_free_lock here because it does too
353 much error-checking. Doing this cleanly would require
354 adding a new function to each thread_*.h. Instead, just
355 create a new lock and waste a little bit of memory */
356 interpreter_lock
= PyThread_allocate_lock();
357 PyThread_acquire_lock(interpreter_lock
, 1);
358 main_thread
= PyThread_get_thread_ident();
362 /* Functions save_thread and restore_thread are always defined so
363 dynamically loaded modules needn't be compiled separately for use
364 with and without threads: */
367 PyEval_SaveThread(void)
369 PyThreadState
*tstate
= PyThreadState_Swap(NULL
);
371 Py_FatalError("PyEval_SaveThread: NULL tstate");
373 if (interpreter_lock
)
374 PyThread_release_lock(interpreter_lock
);
380 PyEval_RestoreThread(PyThreadState
*tstate
)
383 Py_FatalError("PyEval_RestoreThread: NULL tstate");
385 if (interpreter_lock
) {
387 PyThread_acquire_lock(interpreter_lock
, 1);
391 PyThreadState_Swap(tstate
);
395 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
396 signal handlers or Mac I/O completion routines) can schedule calls
397 to a function to be called synchronously.
398 The synchronous function is called with one void* argument.
399 It should return 0 for success or -1 for failure -- failure should
400 be accompanied by an exception.
402 If registry succeeds, the registry function returns 0; if it fails
403 (e.g. due to too many pending calls) it returns -1 (without setting
404 an exception condition).
406 Note that because registry may occur from within signal handlers,
407 or other asynchronous events, calling malloc() is unsafe!
410 Any thread can schedule pending calls, but only the main thread
414 XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE!
415 There are two possible race conditions:
416 (1) nested asynchronous registry calls;
417 (2) registry calls made while pending calls are being processed.
418 While (1) is very unlikely, (2) is a real possibility.
419 The current code is safe against (2), but not against (1).
420 The safety against (2) is derived from the fact that only one
421 thread (the main thread) ever takes things out of the queue.
423 XXX Darn! With the advent of thread state, we should have an array
424 of pending calls per thread in the thread state! Later...
427 #define NPENDINGCALLS 32
431 } pendingcalls
[NPENDINGCALLS
];
432 static volatile int pendingfirst
= 0;
433 static volatile int pendinglast
= 0;
434 static volatile int things_to_do
= 0;
437 Py_AddPendingCall(int (*func
)(void *), void *arg
)
441 /* XXX Begin critical section */
442 /* XXX If you want this to be safe against nested
443 XXX asynchronous calls, you'll have to work harder! */
448 j
= (i
+ 1) % NPENDINGCALLS
;
449 if (j
== pendingfirst
) {
451 return -1; /* Queue full */
453 pendingcalls
[i
].func
= func
;
454 pendingcalls
[i
].arg
= arg
;
458 things_to_do
= 1; /* Signal main loop */
460 /* XXX End critical section */
465 Py_MakePendingCalls(void)
469 if (main_thread
&& PyThread_get_thread_ident() != main_thread
)
481 if (i
== pendinglast
)
482 break; /* Queue empty */
483 func
= pendingcalls
[i
].func
;
484 arg
= pendingcalls
[i
].arg
;
485 pendingfirst
= (i
+ 1) % NPENDINGCALLS
;
488 things_to_do
= 1; /* We're not done yet */
497 /* The interpreter's recursion limit */
499 static int recursion_limit
= 1000;
502 Py_GetRecursionLimit(void)
504 return recursion_limit
;
508 Py_SetRecursionLimit(int new_limit
)
510 recursion_limit
= new_limit
;
513 /* Status code for main loop (reason for stack unwind) */
516 WHY_NOT
, /* No error */
517 WHY_EXCEPTION
, /* Exception occurred */
518 WHY_RERAISE
, /* Exception re-raised by 'finally' */
519 WHY_RETURN
, /* 'return' statement */
520 WHY_BREAK
, /* 'break' statement */
521 WHY_CONTINUE
, /* 'continue' statement */
522 WHY_YIELD
/* 'yield' operator */
525 static enum why_code
do_raise(PyObject
*, PyObject
*, PyObject
*);
526 static int unpack_iterable(PyObject
*, int, PyObject
**);
528 /* for manipulating the thread switch and periodic "stuff" - used to be
529 per thread, now just a pair o' globals */
530 int _Py_CheckInterval
= 100;
531 volatile int _Py_Ticker
= 100;
534 PyEval_EvalCode(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
)
536 /* XXX raise SystemError if globals is NULL */
537 return PyEval_EvalCodeEx(co
,
539 (PyObject
**)NULL
, 0,
540 (PyObject
**)NULL
, 0,
541 (PyObject
**)NULL
, 0,
546 /* Interpreter main loop */
549 eval_frame(PyFrameObject
*f
)
554 PyObject
**stack_pointer
; /* Next free slot in value stack */
555 register unsigned char *next_instr
;
556 register int opcode
=0; /* Current opcode */
557 register int oparg
=0; /* Current opcode argument, if any */
558 register enum why_code why
; /* Reason for block stack unwind */
559 register int err
; /* Error status -- nonzero if error */
560 register PyObject
*x
; /* Result object -- NULL if error */
561 register PyObject
*v
; /* Temporary objects popped off stack */
562 register PyObject
*w
;
563 register PyObject
*u
;
564 register PyObject
*t
;
565 register PyObject
*stream
= NULL
; /* for PRINT opcodes */
566 register PyObject
**fastlocals
, **freevars
;
567 PyObject
*retval
= NULL
; /* Return value */
568 PyThreadState
*tstate
= PyThreadState_GET();
571 /* when tracing we set things up so that
573 not (instr_lb <= current_bytecode_offset < instr_ub)
575 is true when the line being executed has changed. The
576 initial values are such as to make this false the first
577 time it is tested. */
578 int instr_ub
= -1, instr_lb
= 0;
580 unsigned char *first_instr
;
586 #if defined(Py_DEBUG) || defined(LLTRACE)
587 /* Make it easier to find out where we are with a debugger */
591 /* Tuple access macros */
594 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
596 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
599 /* Code access macros */
601 #define INSTR_OFFSET() (next_instr - first_instr)
602 #define NEXTOP() (*next_instr++)
603 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
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.
623 #define PREDICT(op) if (*next_instr == op) goto PRED_##op
624 #define PREDICTED(op) PRED_##op: next_instr++
625 #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = (next_instr[2]<<8) + \
626 next_instr[1]; next_instr += 3
628 /* Stack manipulation macros */
630 #define STACK_LEVEL() (stack_pointer - f->f_valuestack)
631 #define EMPTY() (STACK_LEVEL() == 0)
632 #define TOP() (stack_pointer[-1])
633 #define SECOND() (stack_pointer[-2])
634 #define THIRD() (stack_pointer[-3])
635 #define FOURTH() (stack_pointer[-4])
636 #define SET_TOP(v) (stack_pointer[-1] = (v))
637 #define SET_SECOND(v) (stack_pointer[-2] = (v))
638 #define SET_THIRD(v) (stack_pointer[-3] = (v))
639 #define SET_FOURTH(v) (stack_pointer[-4] = (v))
640 #define BASIC_STACKADJ(n) (stack_pointer += n)
641 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
642 #define BASIC_POP() (*--stack_pointer)
645 #define PUSH(v) { (void)(BASIC_PUSH(v), \
646 lltrace && prtrace(TOP(), "push")); \
647 assert(STACK_LEVEL() <= f->f_stacksize); }
648 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP())
649 #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
650 lltrace && prtrace(TOP(), "stackadj")); \
651 assert(STACK_LEVEL() <= f->f_stacksize); }
653 #define PUSH(v) BASIC_PUSH(v)
654 #define POP() BASIC_POP()
655 #define STACKADJ(n) BASIC_STACKADJ(n)
658 /* Local variable macros */
660 #define GETLOCAL(i) (fastlocals[i])
662 /* The SETLOCAL() macro must not DECREF the local variable in-place and
663 then store the new value; it must copy the old value to a temporary
664 value, then store the new value, and then DECREF the temporary value.
665 This is because it is possible that during the DECREF the frame is
666 accessed by other code (e.g. a __del__ method or gc.collect()) and the
667 variable would be pointing to already-freed memory. */
668 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
669 GETLOCAL(i) = value; \
670 Py_XDECREF(tmp); } while (0)
677 #ifdef USE_STACKCHECK
678 if (tstate
->recursion_depth
%10 == 0 && PyOS_CheckStack()) {
679 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
685 if (++tstate
->recursion_depth
> recursion_limit
) {
686 --tstate
->recursion_depth
;
687 PyErr_SetString(PyExc_RuntimeError
,
688 "maximum recursion depth exceeded");
689 tstate
->frame
= f
->f_back
;
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 --tstate
->recursion_depth
;
714 tstate
->frame
= f
->f_back
;
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 --tstate
->recursion_depth
;
726 tstate
->frame
= f
->f_back
;
733 names
= co
->co_names
;
734 consts
= co
->co_consts
;
735 fastlocals
= f
->f_localsplus
;
736 freevars
= f
->f_localsplus
+ f
->f_nlocals
;
737 _PyCode_GETCODEPTR(co
, &first_instr
);
738 /* An explanation is in order for the next line.
740 f->f_lasti now refers to the index of the last instruction
741 executed. You might think this was obvious from the name, but
742 this wasn't always true before 2.3! PyFrame_New now sets
743 f->f_lasti to -1 (i.e. the index *before* the first instruction)
744 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
745 does work. Promise. */
746 next_instr
= first_instr
+ f
->f_lasti
+ 1;
747 stack_pointer
= f
->f_stacktop
;
748 assert(stack_pointer
!= NULL
);
749 f
->f_stacktop
= NULL
; /* remains NULL unless yield suspends frame */
752 lltrace
= PyDict_GetItemString(f
->f_globals
,"__lltrace__") != NULL
;
754 #if defined(Py_DEBUG) || defined(LLTRACE)
755 filename
= PyString_AsString(co
->co_filename
);
760 x
= Py_None
; /* Not a reference, just anything non-NULL */
764 assert(stack_pointer
>= f
->f_valuestack
); /* else underflow */
765 assert(STACK_LEVEL() <= f
->f_stacksize
); /* else overflow */
767 /* Do periodic things. Doing this every time through
768 the loop would add too much overhead, so we do it
769 only every Nth instruction. We also do it if
770 ``things_to_do'' is set, i.e. when an asynchronous
771 event needs attention (e.g. a signal handler or
772 async I/O handler); see Py_AddPendingCall() and
773 Py_MakePendingCalls() above. */
775 if (--_Py_Ticker
< 0) {
776 if (*next_instr
== SETUP_FINALLY
) {
777 /* Make the last opcode before
778 a try: finally: block uninterruptable. */
779 goto fast_next_opcode
;
781 _Py_Ticker
= _Py_CheckInterval
;
782 tstate
->tick_counter
++;
784 if (Py_MakePendingCalls() < 0) {
789 #if !defined(HAVE_SIGNAL_H) || defined(macintosh)
790 /* If we have true signals, the signal handler
791 will call Py_AddPendingCall() so we don't
792 have to call PyErr_CheckSignals(). On the
793 Mac and DOS, alas, we have to call it. */
794 if (PyErr_CheckSignals()) {
801 if (interpreter_lock
) {
802 /* Give another thread a chance */
804 if (PyThreadState_Swap(NULL
) != tstate
)
805 Py_FatalError("ceval: tstate mix-up");
806 PyThread_release_lock(interpreter_lock
);
808 /* Other threads may run now */
810 PyThread_acquire_lock(interpreter_lock
, 1);
811 if (PyThreadState_Swap(tstate
) != NULL
)
812 Py_FatalError("ceval: orphan tstate");
814 /* Check for thread interrupts */
816 if (tstate
->async_exc
!= NULL
) {
817 x
= tstate
->async_exc
;
818 tstate
->async_exc
= NULL
;
829 f
->f_lasti
= INSTR_OFFSET();
831 /* line-by-line tracing support */
833 if (tstate
->c_tracefunc
!= NULL
&& !tstate
->tracing
) {
834 /* see maybe_call_line_trace
835 for expository comments */
836 f
->f_stacktop
= stack_pointer
;
838 err
= maybe_call_line_trace(tstate
->c_tracefunc
,
840 f
, &instr_lb
, &instr_ub
);
841 /* Reload possibly changed frame fields */
843 if (f
->f_stacktop
!= NULL
) {
844 stack_pointer
= f
->f_stacktop
;
845 f
->f_stacktop
= NULL
;
848 /* trace function raised an exception */
853 /* Extract opcode and argument */
859 #ifdef DYNAMIC_EXECUTION_PROFILE
861 dxpairs
[lastopcode
][opcode
]++;
868 /* Instruction tracing */
871 if (HAS_ARG(opcode
)) {
872 printf("%d: %d, %d\n",
873 f
->f_lasti
, opcode
, oparg
);
882 /* Main switch on opcode */
887 It is essential that any operation that fails sets either
888 x to NULL, err to nonzero, or why to anything but WHY_NOT,
889 and that no operation that succeeds does this! */
891 /* case STOP_CODE: this is an error! */
898 goto fast_next_opcode
;
900 format_exc_check_arg(PyExc_UnboundLocalError
,
901 UNBOUNDLOCAL_ERROR_MSG
,
902 PyTuple_GetItem(co
->co_varnames
, oparg
));
906 x
= GETITEM(consts
, oparg
);
909 goto fast_next_opcode
;
911 PREDICTED_WITH_ARG(STORE_FAST
);
915 goto fast_next_opcode
;
921 goto fast_next_opcode
;
928 goto fast_next_opcode
;
937 goto fast_next_opcode
;
948 goto fast_next_opcode
;
954 goto fast_next_opcode
;
965 goto fast_next_opcode
;
966 } else if (oparg
== 3) {
977 goto fast_next_opcode
;
979 Py_FatalError("invalid argument to DUP_TOPX"
980 " (bytecode corruption?)");
985 x
= PyNumber_Positive(v
);
988 if (x
!= NULL
) continue;
993 x
= PyNumber_Negative(v
);
996 if (x
!= NULL
) continue;
1001 err
= PyObject_IsTrue(v
);
1009 Py_INCREF(Py_False
);
1019 x
= PyObject_Repr(v
);
1022 if (x
!= NULL
) continue;
1027 x
= PyNumber_Invert(v
);
1030 if (x
!= NULL
) continue;
1036 x
= PyNumber_Power(v
, w
, Py_None
);
1040 if (x
!= NULL
) continue;
1043 case BINARY_MULTIPLY
:
1046 x
= PyNumber_Multiply(v
, w
);
1050 if (x
!= NULL
) continue;
1054 if (!_Py_QnewFlag
) {
1057 x
= PyNumber_Divide(v
, w
);
1061 if (x
!= NULL
) continue;
1064 /* -Qnew is in effect: fall through to
1065 BINARY_TRUE_DIVIDE */
1066 case BINARY_TRUE_DIVIDE
:
1069 x
= PyNumber_TrueDivide(v
, w
);
1073 if (x
!= NULL
) continue;
1076 case BINARY_FLOOR_DIVIDE
:
1079 x
= PyNumber_FloorDivide(v
, w
);
1083 if (x
!= NULL
) continue;
1089 x
= PyNumber_Remainder(v
, w
);
1093 if (x
!= NULL
) continue;
1099 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1100 /* INLINE: int + int */
1101 register long a
, b
, i
;
1102 a
= PyInt_AS_LONG(v
);
1103 b
= PyInt_AS_LONG(w
);
1105 if ((i
^a
) < 0 && (i
^b
) < 0)
1107 x
= PyInt_FromLong(i
);
1111 x
= PyNumber_Add(v
, w
);
1116 if (x
!= NULL
) continue;
1119 case BINARY_SUBTRACT
:
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
);
1134 x
= PyNumber_Subtract(v
, w
);
1139 if (x
!= NULL
) continue;
1145 if (PyList_CheckExact(v
) && PyInt_CheckExact(w
)) {
1146 /* INLINE: list[int] */
1147 long i
= PyInt_AsLong(w
);
1149 i
+= PyList_GET_SIZE(v
);
1151 i
>= PyList_GET_SIZE(v
)) {
1152 PyErr_SetString(PyExc_IndexError
,
1153 "list index out of range");
1157 x
= PyList_GET_ITEM(v
, i
);
1162 x
= PyObject_GetItem(v
, w
);
1166 if (x
!= NULL
) continue;
1172 x
= PyNumber_Lshift(v
, w
);
1176 if (x
!= NULL
) continue;
1182 x
= PyNumber_Rshift(v
, w
);
1186 if (x
!= NULL
) continue;
1192 x
= PyNumber_And(v
, w
);
1196 if (x
!= NULL
) continue;
1202 x
= PyNumber_Xor(v
, w
);
1206 if (x
!= NULL
) continue;
1212 x
= PyNumber_Or(v
, w
);
1216 if (x
!= NULL
) continue;
1222 x
= PyNumber_InPlacePower(v
, w
, Py_None
);
1226 if (x
!= NULL
) continue;
1229 case INPLACE_MULTIPLY
:
1232 x
= PyNumber_InPlaceMultiply(v
, w
);
1236 if (x
!= NULL
) continue;
1239 case INPLACE_DIVIDE
:
1240 if (!_Py_QnewFlag
) {
1243 x
= PyNumber_InPlaceDivide(v
, w
);
1247 if (x
!= NULL
) continue;
1250 /* -Qnew is in effect: fall through to
1251 INPLACE_TRUE_DIVIDE */
1252 case INPLACE_TRUE_DIVIDE
:
1255 x
= PyNumber_InPlaceTrueDivide(v
, w
);
1259 if (x
!= NULL
) continue;
1262 case INPLACE_FLOOR_DIVIDE
:
1265 x
= PyNumber_InPlaceFloorDivide(v
, w
);
1269 if (x
!= NULL
) continue;
1272 case INPLACE_MODULO
:
1275 x
= PyNumber_InPlaceRemainder(v
, w
);
1279 if (x
!= NULL
) continue;
1285 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1286 /* INLINE: int + int */
1287 register long a
, b
, i
;
1288 a
= PyInt_AS_LONG(v
);
1289 b
= PyInt_AS_LONG(w
);
1291 if ((i
^a
) < 0 && (i
^b
) < 0)
1293 x
= PyInt_FromLong(i
);
1297 x
= PyNumber_InPlaceAdd(v
, w
);
1302 if (x
!= NULL
) continue;
1305 case INPLACE_SUBTRACT
:
1308 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1309 /* INLINE: int - int */
1310 register long a
, b
, i
;
1311 a
= PyInt_AS_LONG(v
);
1312 b
= PyInt_AS_LONG(w
);
1314 if ((i
^a
) < 0 && (i
^~b
) < 0)
1316 x
= PyInt_FromLong(i
);
1320 x
= PyNumber_InPlaceSubtract(v
, w
);
1325 if (x
!= NULL
) continue;
1328 case INPLACE_LSHIFT
:
1331 x
= PyNumber_InPlaceLshift(v
, w
);
1335 if (x
!= NULL
) continue;
1338 case INPLACE_RSHIFT
:
1341 x
= PyNumber_InPlaceRshift(v
, w
);
1345 if (x
!= NULL
) continue;
1351 x
= PyNumber_InPlaceAnd(v
, w
);
1355 if (x
!= NULL
) continue;
1361 x
= PyNumber_InPlaceXor(v
, w
);
1365 if (x
!= NULL
) continue;
1371 x
= PyNumber_InPlaceOr(v
, w
);
1375 if (x
!= NULL
) continue;
1382 if ((opcode
-SLICE
) & 2)
1386 if ((opcode
-SLICE
) & 1)
1391 x
= apply_slice(u
, v
, w
);
1396 if (x
!= NULL
) continue;
1403 if ((opcode
-STORE_SLICE
) & 2)
1407 if ((opcode
-STORE_SLICE
) & 1)
1413 err
= assign_slice(u
, v
, w
, t
); /* u[v:w] = t */
1418 if (err
== 0) continue;
1421 case DELETE_SLICE
+0:
1422 case DELETE_SLICE
+1:
1423 case DELETE_SLICE
+2:
1424 case DELETE_SLICE
+3:
1425 if ((opcode
-DELETE_SLICE
) & 2)
1429 if ((opcode
-DELETE_SLICE
) & 1)
1434 err
= assign_slice(u
, v
, w
, (PyObject
*)NULL
);
1439 if (err
== 0) continue;
1448 err
= PyObject_SetItem(v
, w
, u
);
1452 if (err
== 0) continue;
1460 err
= PyObject_DelItem(v
, w
);
1463 if (err
== 0) continue;
1468 w
= PySys_GetObject("displayhook");
1470 PyErr_SetString(PyExc_RuntimeError
,
1471 "lost sys.displayhook");
1476 x
= Py_BuildValue("(O)", v
);
1481 w
= PyEval_CallObject(w
, x
);
1492 /* fall through to PRINT_ITEM */
1496 if (stream
== NULL
|| stream
== Py_None
) {
1497 w
= PySys_GetObject("stdout");
1499 PyErr_SetString(PyExc_RuntimeError
,
1504 /* PyFile_SoftSpace() can exececute arbitrary code
1505 if sys.stdout is an instance with a __getattr__.
1506 If __getattr__ raises an exception, w will
1507 be freed, so we need to prevent that temporarily. */
1509 if (w
!= NULL
&& PyFile_SoftSpace(w
, 0))
1510 err
= PyFile_WriteString(" ", w
);
1512 err
= PyFile_WriteObject(v
, w
, Py_PRINT_RAW
);
1514 /* XXX move into writeobject() ? */
1515 if (PyString_Check(v
)) {
1516 char *s
= PyString_AS_STRING(v
);
1517 int len
= PyString_GET_SIZE(v
);
1519 !isspace(Py_CHARMASK(s
[len
-1])) ||
1521 PyFile_SoftSpace(w
, 1);
1523 #ifdef Py_USING_UNICODE
1524 else if (PyUnicode_Check(v
)) {
1525 Py_UNICODE
*s
= PyUnicode_AS_UNICODE(v
);
1526 int len
= PyUnicode_GET_SIZE(v
);
1528 !Py_UNICODE_ISSPACE(s
[len
-1]) ||
1530 PyFile_SoftSpace(w
, 1);
1534 PyFile_SoftSpace(w
, 1);
1544 case PRINT_NEWLINE_TO
:
1546 /* fall through to PRINT_NEWLINE */
1549 if (stream
== NULL
|| stream
== Py_None
) {
1550 w
= PySys_GetObject("stdout");
1552 PyErr_SetString(PyExc_RuntimeError
,
1556 err
= PyFile_WriteString("\n", w
);
1558 PyFile_SoftSpace(w
, 0);
1566 default: switch (opcode
) {
1573 retval
= PyInt_FromLong(oparg
);
1581 u
= POP(); /* traceback */
1584 v
= POP(); /* value */
1587 w
= POP(); /* exc */
1588 case 0: /* Fallthrough */
1589 why
= do_raise(w
, v
, u
);
1592 PyErr_SetString(PyExc_SystemError
,
1593 "bad RAISE_VARARGS oparg");
1594 why
= WHY_EXCEPTION
;
1600 if ((x
= f
->f_locals
) == NULL
) {
1601 PyErr_SetString(PyExc_SystemError
,
1616 f
->f_stacktop
= stack_pointer
;
1626 err
= exec_statement(f
, u
, v
, w
);
1634 PyTryBlock
*b
= PyFrame_BlockPop(f
);
1635 while (STACK_LEVEL() > b
->b_level
) {
1644 if (PyInt_Check(v
)) {
1645 why
= (enum why_code
) PyInt_AS_LONG(v
);
1646 if (why
== WHY_RETURN
||
1648 why
== WHY_CONTINUE
)
1651 else if (PyString_Check(v
) || PyClass_Check(v
)) {
1654 PyErr_Restore(v
, w
, u
);
1658 else if (v
!= Py_None
) {
1659 PyErr_SetString(PyExc_SystemError
,
1660 "'finally' pops bad exception");
1661 why
= WHY_EXCEPTION
;
1671 x
= build_class(u
, v
, w
);
1679 w
= GETITEM(names
, oparg
);
1681 if ((x
= f
->f_locals
) == NULL
) {
1682 PyErr_Format(PyExc_SystemError
,
1683 "no locals found when storing %s",
1687 err
= PyDict_SetItem(x
, w
, v
);
1692 w
= GETITEM(names
, oparg
);
1693 if ((x
= f
->f_locals
) == NULL
) {
1694 PyErr_Format(PyExc_SystemError
,
1695 "no locals when deleting %s",
1699 if ((err
= PyDict_DelItem(x
, w
)) != 0)
1700 format_exc_check_arg(PyExc_NameError
,
1704 PREDICTED_WITH_ARG(UNPACK_SEQUENCE
);
1705 case UNPACK_SEQUENCE
:
1707 if (PyTuple_CheckExact(v
)) {
1708 if (PyTuple_Size(v
) != oparg
) {
1709 PyErr_SetString(PyExc_ValueError
,
1710 "unpack tuple of wrong size");
1711 why
= WHY_EXCEPTION
;
1714 for (; --oparg
>= 0; ) {
1715 w
= PyTuple_GET_ITEM(v
, oparg
);
1721 else if (PyList_CheckExact(v
)) {
1722 if (PyList_Size(v
) != oparg
) {
1723 PyErr_SetString(PyExc_ValueError
,
1724 "unpack list of wrong size");
1725 why
= WHY_EXCEPTION
;
1728 for (; --oparg
>= 0; ) {
1729 w
= PyList_GET_ITEM(v
, oparg
);
1735 else if (unpack_iterable(v
, oparg
,
1736 stack_pointer
+ oparg
))
1737 stack_pointer
+= oparg
;
1739 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1740 PyErr_SetString(PyExc_TypeError
,
1741 "unpack non-sequence");
1742 why
= WHY_EXCEPTION
;
1748 w
= GETITEM(names
, oparg
);
1752 err
= PyObject_SetAttr(v
, w
, u
); /* v.w = u */
1758 w
= GETITEM(names
, oparg
);
1760 err
= PyObject_SetAttr(v
, w
, (PyObject
*)NULL
);
1766 w
= GETITEM(names
, oparg
);
1768 err
= PyDict_SetItem(f
->f_globals
, w
, v
);
1773 w
= GETITEM(names
, oparg
);
1774 if ((err
= PyDict_DelItem(f
->f_globals
, w
)) != 0)
1775 format_exc_check_arg(
1776 PyExc_NameError
, GLOBAL_NAME_ERROR_MSG
, w
);
1780 w
= GETITEM(names
, oparg
);
1781 if ((x
= f
->f_locals
) == NULL
) {
1782 PyErr_Format(PyExc_SystemError
,
1783 "no locals when loading %s",
1787 x
= PyDict_GetItem(x
, w
);
1789 x
= PyDict_GetItem(f
->f_globals
, w
);
1791 x
= PyDict_GetItem(f
->f_builtins
, w
);
1793 format_exc_check_arg(
1805 w
= GETITEM(names
, oparg
);
1806 if (PyString_CheckExact(w
)) {
1807 /* Inline the PyDict_GetItem() calls.
1808 WARNING: this is an extreme speed hack.
1809 Do not try this at home. */
1810 long hash
= ((PyStringObject
*)w
)->ob_shash
;
1813 d
= (PyDictObject
*)(f
->f_globals
);
1814 x
= d
->ma_lookup(d
, w
, hash
)->me_value
;
1820 d
= (PyDictObject
*)(f
->f_builtins
);
1821 x
= d
->ma_lookup(d
, w
, hash
)->me_value
;
1827 goto load_global_error
;
1830 /* This is the un-inlined version of the code above */
1831 x
= PyDict_GetItem(f
->f_globals
, w
);
1833 x
= PyDict_GetItem(f
->f_builtins
, w
);
1836 format_exc_check_arg(
1838 GLOBAL_NAME_ERROR_MSG
, w
);
1847 x
= GETLOCAL(oparg
);
1849 format_exc_check_arg(
1850 PyExc_UnboundLocalError
,
1851 UNBOUNDLOCAL_ERROR_MSG
,
1852 PyTuple_GetItem(co
->co_varnames
, oparg
)
1856 SETLOCAL(oparg
, NULL
);
1860 x
= freevars
[oparg
];
1866 x
= freevars
[oparg
];
1870 /* Don't stomp existing exception */
1871 if (PyErr_Occurred())
1873 if (oparg
< f
->f_ncells
) {
1874 v
= PyTuple_GetItem(co
->co_cellvars
,
1876 format_exc_check_arg(
1877 PyExc_UnboundLocalError
,
1878 UNBOUNDLOCAL_ERROR_MSG
,
1881 v
= PyTuple_GetItem(
1883 oparg
- f
->f_ncells
);
1884 format_exc_check_arg(
1886 UNBOUNDFREE_ERROR_MSG
,
1896 x
= freevars
[oparg
];
1902 x
= PyTuple_New(oparg
);
1904 for (; --oparg
>= 0;) {
1906 PyTuple_SET_ITEM(x
, oparg
, w
);
1914 x
= PyList_New(oparg
);
1916 for (; --oparg
>= 0;) {
1918 PyList_SET_ITEM(x
, oparg
, w
);
1928 if (x
!= NULL
) continue;
1932 w
= GETITEM(names
, oparg
);
1934 x
= PyObject_GetAttr(v
, w
);
1937 if (x
!= NULL
) continue;
1943 if (PyInt_CheckExact(w
) && PyInt_CheckExact(v
)) {
1944 /* INLINE: cmp(int, int) */
1947 a
= PyInt_AS_LONG(v
);
1948 b
= PyInt_AS_LONG(w
);
1950 case PyCmp_LT
: res
= a
< b
; break;
1951 case PyCmp_LE
: res
= a
<= b
; break;
1952 case PyCmp_EQ
: res
= a
== b
; break;
1953 case PyCmp_NE
: res
= a
!= b
; break;
1954 case PyCmp_GT
: res
= a
> b
; break;
1955 case PyCmp_GE
: res
= a
>= b
; break;
1956 case PyCmp_IS
: res
= v
== w
; break;
1957 case PyCmp_IS_NOT
: res
= v
!= w
; break;
1958 default: goto slow_compare
;
1960 x
= res
? Py_True
: Py_False
;
1965 x
= cmp_outcome(oparg
, v
, w
);
1970 if (x
== NULL
) break;
1971 PREDICT(JUMP_IF_FALSE
);
1972 PREDICT(JUMP_IF_TRUE
);
1976 w
= GETITEM(names
, oparg
);
1977 x
= PyDict_GetItemString(f
->f_builtins
, "__import__");
1979 PyErr_SetString(PyExc_ImportError
,
1980 "__import__ not found");
1984 w
= Py_BuildValue("(OOOO)",
1987 f
->f_locals
== NULL
?
1988 Py_None
: f
->f_locals
,
1996 x
= PyEval_CallObject(x
, w
);
1999 if (x
!= NULL
) continue;
2004 PyFrame_FastToLocals(f
);
2005 if ((x
= f
->f_locals
) == NULL
) {
2006 PyErr_SetString(PyExc_SystemError
,
2007 "no locals found during 'import *'");
2010 err
= import_all_from(x
, v
);
2011 PyFrame_LocalsToFast(f
, 0);
2013 if (err
== 0) continue;
2017 w
= GETITEM(names
, oparg
);
2019 x
= import_from(v
, w
);
2021 if (x
!= NULL
) continue;
2026 goto fast_next_opcode
;
2028 PREDICTED_WITH_ARG(JUMP_IF_FALSE
);
2033 goto fast_next_opcode
;
2035 if (w
== Py_False
) {
2037 goto fast_next_opcode
;
2039 err
= PyObject_IsTrue(w
);
2048 PREDICTED_WITH_ARG(JUMP_IF_TRUE
);
2051 if (w
== Py_False
) {
2053 goto fast_next_opcode
;
2057 goto fast_next_opcode
;
2059 err
= PyObject_IsTrue(w
);
2075 /* before: [obj]; after [getiter(obj)] */
2077 x
= PyObject_GetIter(v
);
2087 PREDICTED_WITH_ARG(FOR_ITER
);
2089 /* before: [iter]; after: [iter, iter()] *or* [] */
2094 PREDICT(STORE_FAST
);
2095 PREDICT(UNPACK_SEQUENCE
);
2098 if (!PyErr_Occurred()) {
2099 /* iterator ended normally */
2110 PyFrame_BlockSetup(f
, opcode
, INSTR_OFFSET() + oparg
,
2116 x
= call_function(&stack_pointer
, oparg
);
2122 case CALL_FUNCTION_VAR
:
2123 case CALL_FUNCTION_KW
:
2124 case CALL_FUNCTION_VAR_KW
:
2126 int na
= oparg
& 0xff;
2127 int nk
= (oparg
>>8) & 0xff;
2128 int flags
= (opcode
- CALL_FUNCTION
) & 3;
2129 int n
= na
+ 2 * nk
;
2130 PyObject
**pfunc
, *func
;
2132 if (flags
& CALL_FLAG_VAR
)
2134 if (flags
& CALL_FLAG_KW
)
2136 pfunc
= stack_pointer
- n
- 1;
2139 if (PyMethod_Check(func
)
2140 && PyMethod_GET_SELF(func
) != NULL
) {
2141 PyObject
*self
= PyMethod_GET_SELF(func
);
2143 func
= PyMethod_GET_FUNCTION(func
);
2151 x
= ext_do_call(func
, &stack_pointer
, flags
, na
, nk
);
2154 while (stack_pointer
> pfunc
) {
2165 v
= POP(); /* code object */
2166 x
= PyFunction_New(v
, f
->f_globals
);
2168 /* XXX Maybe this should be a separate opcode? */
2169 if (x
!= NULL
&& oparg
> 0) {
2170 v
= PyTuple_New(oparg
);
2176 while (--oparg
>= 0) {
2178 PyTuple_SET_ITEM(v
, oparg
, w
);
2180 err
= PyFunction_SetDefaults(x
, v
);
2189 v
= POP(); /* code object */
2190 x
= PyFunction_New(v
, f
->f_globals
);
2191 nfree
= PyCode_GetNumFree((PyCodeObject
*)v
);
2193 /* XXX Maybe this should be a separate opcode? */
2194 if (x
!= NULL
&& nfree
> 0) {
2195 v
= PyTuple_New(nfree
);
2201 while (--nfree
>= 0) {
2203 PyTuple_SET_ITEM(v
, nfree
, w
);
2205 err
= PyFunction_SetClosure(x
, v
);
2208 if (x
!= NULL
&& oparg
> 0) {
2209 v
= PyTuple_New(oparg
);
2215 while (--oparg
>= 0) {
2217 PyTuple_SET_ITEM(v
, oparg
, w
);
2219 err
= PyFunction_SetDefaults(x
, v
);
2233 x
= PySlice_New(u
, v
, w
);
2238 if (x
!= NULL
) continue;
2243 oparg
= oparg
<<16 | NEXTARG();
2244 goto dispatch_opcode
;
2248 "XXX lineno: %d, opcode: %d\n",
2249 PyCode_Addr2Line(f
->f_code
, f
->f_lasti
),
2251 PyErr_SetString(PyExc_SystemError
, "unknown opcode");
2252 why
= WHY_EXCEPTION
;
2263 /* Quickly continue if no error occurred */
2265 if (why
== WHY_NOT
) {
2266 if (err
== 0 && x
!= NULL
) {
2268 /* This check is expensive! */
2269 if (PyErr_Occurred())
2271 "XXX undetected error\n");
2274 continue; /* Normal, fast path */
2276 why
= WHY_EXCEPTION
;
2281 /* Double-check exception status */
2283 if (why
== WHY_EXCEPTION
|| why
== WHY_RERAISE
) {
2284 if (!PyErr_Occurred()) {
2285 PyErr_SetString(PyExc_SystemError
,
2286 "error return without exception set");
2287 why
= WHY_EXCEPTION
;
2292 /* This check is expensive! */
2293 if (PyErr_Occurred()) {
2295 "XXX undetected error (why=%d)\n",
2297 why
= WHY_EXCEPTION
;
2302 /* Log traceback info if this is a real exception */
2304 if (why
== WHY_EXCEPTION
) {
2305 PyTraceBack_Here(f
);
2307 if (tstate
->c_tracefunc
!= NULL
)
2308 call_exc_trace(tstate
->c_tracefunc
,
2309 tstate
->c_traceobj
, f
);
2312 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2314 if (why
== WHY_RERAISE
)
2315 why
= WHY_EXCEPTION
;
2317 /* Unwind stacks if a (pseudo) exception occurred */
2319 while (why
!= WHY_NOT
&& why
!= WHY_YIELD
&& f
->f_iblock
> 0) {
2320 PyTryBlock
*b
= PyFrame_BlockPop(f
);
2322 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_CONTINUE
) {
2323 /* For a continue inside a try block,
2324 don't pop the block for the loop. */
2325 PyFrame_BlockSetup(f
, b
->b_type
, b
->b_handler
,
2328 JUMPTO(PyInt_AS_LONG(retval
));
2333 while (STACK_LEVEL() > b
->b_level
) {
2337 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_BREAK
) {
2339 JUMPTO(b
->b_handler
);
2342 if (b
->b_type
== SETUP_FINALLY
||
2343 (b
->b_type
== SETUP_EXCEPT
&&
2344 why
== WHY_EXCEPTION
)) {
2345 if (why
== WHY_EXCEPTION
) {
2346 PyObject
*exc
, *val
, *tb
;
2347 PyErr_Fetch(&exc
, &val
, &tb
);
2352 /* Make the raw exception data
2353 available to the handler,
2354 so a program can emulate the
2355 Python main loop. Don't do
2356 this for 'finally'. */
2357 if (b
->b_type
== SETUP_EXCEPT
) {
2358 PyErr_NormalizeException(
2360 set_exc_info(tstate
,
2372 if (why
== WHY_RETURN
||
2373 why
== WHY_CONTINUE
)
2375 v
= PyInt_FromLong((long)why
);
2379 JUMPTO(b
->b_handler
);
2382 } /* unwind stack */
2384 /* End the loop if we still have an error (or return) */
2391 if (why
!= WHY_YIELD
) {
2392 /* Pop remaining stack entries -- but when yielding */
2399 if (why
!= WHY_RETURN
&& why
!= WHY_YIELD
)
2402 if (tstate
->use_tracing
) {
2403 if (tstate
->c_tracefunc
2404 && (why
== WHY_RETURN
|| why
== WHY_YIELD
)) {
2405 if (call_trace(tstate
->c_tracefunc
,
2406 tstate
->c_traceobj
, f
,
2407 PyTrace_RETURN
, retval
)) {
2410 why
= WHY_EXCEPTION
;
2413 if (tstate
->c_profilefunc
) {
2414 if (why
== WHY_EXCEPTION
)
2415 call_trace_protected(tstate
->c_profilefunc
,
2416 tstate
->c_profileobj
, f
,
2418 else if (call_trace(tstate
->c_profilefunc
,
2419 tstate
->c_profileobj
, f
,
2420 PyTrace_RETURN
, retval
)) {
2423 why
= WHY_EXCEPTION
;
2428 reset_exc_info(tstate
);
2431 --tstate
->recursion_depth
;
2432 tstate
->frame
= f
->f_back
;
2438 PyEval_EvalCodeEx(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
,
2439 PyObject
**args
, int argcount
, PyObject
**kws
, int kwcount
,
2440 PyObject
**defs
, int defcount
, PyObject
*closure
)
2442 register PyFrameObject
*f
;
2443 register PyObject
*retval
= NULL
;
2444 register PyObject
**fastlocals
, **freevars
;
2445 PyThreadState
*tstate
= PyThreadState_GET();
2448 if (globals
== NULL
) {
2449 PyErr_SetString(PyExc_SystemError
,
2450 "PyEval_EvalCodeEx: NULL globals");
2454 assert(globals
!= NULL
);
2455 f
= PyFrame_New(tstate
, co
, globals
, locals
);
2459 fastlocals
= f
->f_localsplus
;
2460 freevars
= f
->f_localsplus
+ f
->f_nlocals
;
2462 if (co
->co_argcount
> 0 ||
2463 co
->co_flags
& (CO_VARARGS
| CO_VARKEYWORDS
)) {
2466 PyObject
*kwdict
= NULL
;
2467 if (co
->co_flags
& CO_VARKEYWORDS
) {
2468 kwdict
= PyDict_New();
2471 i
= co
->co_argcount
;
2472 if (co
->co_flags
& CO_VARARGS
)
2474 SETLOCAL(i
, kwdict
);
2476 if (argcount
> co
->co_argcount
) {
2477 if (!(co
->co_flags
& CO_VARARGS
)) {
2478 PyErr_Format(PyExc_TypeError
,
2479 "%.200s() takes %s %d "
2480 "%sargument%s (%d given)",
2481 PyString_AsString(co
->co_name
),
2482 defcount
? "at most" : "exactly",
2484 kwcount
? "non-keyword " : "",
2485 co
->co_argcount
== 1 ? "" : "s",
2489 n
= co
->co_argcount
;
2491 for (i
= 0; i
< n
; i
++) {
2496 if (co
->co_flags
& CO_VARARGS
) {
2497 u
= PyTuple_New(argcount
- n
);
2500 SETLOCAL(co
->co_argcount
, u
);
2501 for (i
= n
; i
< argcount
; i
++) {
2504 PyTuple_SET_ITEM(u
, i
-n
, x
);
2507 for (i
= 0; i
< kwcount
; i
++) {
2508 PyObject
*keyword
= kws
[2*i
];
2509 PyObject
*value
= kws
[2*i
+ 1];
2511 if (keyword
== NULL
|| !PyString_Check(keyword
)) {
2512 PyErr_Format(PyExc_TypeError
,
2513 "%.200s() keywords must be strings",
2514 PyString_AsString(co
->co_name
));
2517 /* XXX slow -- speed up using dictionary? */
2518 for (j
= 0; j
< co
->co_argcount
; j
++) {
2519 PyObject
*nm
= PyTuple_GET_ITEM(
2520 co
->co_varnames
, j
);
2521 int cmp
= PyObject_RichCompareBool(
2522 keyword
, nm
, Py_EQ
);
2528 /* Check errors from Compare */
2529 if (PyErr_Occurred())
2531 if (j
>= co
->co_argcount
) {
2532 if (kwdict
== NULL
) {
2533 PyErr_Format(PyExc_TypeError
,
2534 "%.200s() got an unexpected "
2535 "keyword argument '%.400s'",
2536 PyString_AsString(co
->co_name
),
2537 PyString_AsString(keyword
));
2540 PyDict_SetItem(kwdict
, keyword
, value
);
2543 if (GETLOCAL(j
) != NULL
) {
2544 PyErr_Format(PyExc_TypeError
,
2545 "%.200s() got multiple "
2546 "values for keyword "
2547 "argument '%.400s'",
2548 PyString_AsString(co
->co_name
),
2549 PyString_AsString(keyword
));
2556 if (argcount
< co
->co_argcount
) {
2557 int m
= co
->co_argcount
- defcount
;
2558 for (i
= argcount
; i
< m
; i
++) {
2559 if (GETLOCAL(i
) == NULL
) {
2560 PyErr_Format(PyExc_TypeError
,
2561 "%.200s() takes %s %d "
2562 "%sargument%s (%d given)",
2563 PyString_AsString(co
->co_name
),
2564 ((co
->co_flags
& CO_VARARGS
) ||
2565 defcount
) ? "at least"
2567 m
, kwcount
? "non-keyword " : "",
2568 m
== 1 ? "" : "s", i
);
2576 for (; i
< defcount
; i
++) {
2577 if (GETLOCAL(m
+i
) == NULL
) {
2578 PyObject
*def
= defs
[i
];
2586 if (argcount
> 0 || kwcount
> 0) {
2587 PyErr_Format(PyExc_TypeError
,
2588 "%.200s() takes no arguments (%d given)",
2589 PyString_AsString(co
->co_name
),
2590 argcount
+ kwcount
);
2594 /* Allocate and initialize storage for cell vars, and copy free
2595 vars into frame. This isn't too efficient right now. */
2597 int i
= 0, j
= 0, nargs
, found
;
2598 char *cellname
, *argname
;
2601 nargs
= co
->co_argcount
;
2602 if (co
->co_flags
& CO_VARARGS
)
2604 if (co
->co_flags
& CO_VARKEYWORDS
)
2607 /* Check for cells that shadow args */
2608 for (i
= 0; i
< f
->f_ncells
&& j
< nargs
; ++i
) {
2609 cellname
= PyString_AS_STRING(
2610 PyTuple_GET_ITEM(co
->co_cellvars
, i
));
2613 argname
= PyString_AS_STRING(
2614 PyTuple_GET_ITEM(co
->co_varnames
, j
));
2615 if (strcmp(cellname
, argname
) == 0) {
2616 c
= PyCell_New(GETLOCAL(j
));
2619 GETLOCAL(f
->f_nlocals
+ i
) = c
;
2626 c
= PyCell_New(NULL
);
2629 SETLOCAL(f
->f_nlocals
+ i
, c
);
2632 /* Initialize any that are left */
2633 while (i
< f
->f_ncells
) {
2634 c
= PyCell_New(NULL
);
2637 SETLOCAL(f
->f_nlocals
+ i
, c
);
2641 if (f
->f_nfreevars
) {
2643 for (i
= 0; i
< f
->f_nfreevars
; ++i
) {
2644 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
2646 freevars
[f
->f_ncells
+ i
] = o
;
2650 if (co
->co_flags
& CO_GENERATOR
) {
2651 /* Don't need to keep the reference to f_back, it will be set
2652 * when the generator is resumed. */
2653 Py_XDECREF(f
->f_back
);
2656 PCALL(PCALL_GENERATOR
);
2658 /* Create a new generator that owns the ready to run frame
2659 * and return that as the value. */
2663 retval
= eval_frame(f
);
2665 fail
: /* Jump here from prelude on failure */
2667 /* decref'ing the frame can cause __del__ methods to get invoked,
2668 which can call back into Python. While we're done with the
2669 current Python frame (f), the associated C stack is still in use,
2670 so recursion_depth must be boosted for the duration.
2672 assert(tstate
!= NULL
);
2673 ++tstate
->recursion_depth
;
2675 --tstate
->recursion_depth
;
2680 /* Implementation notes for set_exc_info() and reset_exc_info():
2682 - Below, 'exc_ZZZ' stands for 'exc_type', 'exc_value' and
2683 'exc_traceback'. These always travel together.
2685 - tstate->curexc_ZZZ is the "hot" exception that is set by
2686 PyErr_SetString(), cleared by PyErr_Clear(), and so on.
2688 - Once an exception is caught by an except clause, it is transferred
2689 from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info()
2690 can pick it up. This is the primary task of set_exc_info().
2692 - Now let me explain the complicated dance with frame->f_exc_ZZZ.
2694 Long ago, when none of this existed, there were just a few globals:
2695 one set corresponding to the "hot" exception, and one set
2696 corresponding to sys.exc_ZZZ. (Actually, the latter weren't C
2697 globals; they were simply stored as sys.exc_ZZZ. For backwards
2698 compatibility, they still are!) The problem was that in code like
2702 "something that may fail"
2703 except "some exception":
2704 "do something else first"
2705 "print the exception from sys.exc_ZZZ."
2707 if "do something else first" invoked something that raised and caught
2708 an exception, sys.exc_ZZZ were overwritten. That was a frequent
2709 cause of subtle bugs. I fixed this by changing the semantics as
2712 - Within one frame, sys.exc_ZZZ will hold the last exception caught
2715 - But initially, and as long as no exception is caught in a given
2716 frame, sys.exc_ZZZ will hold the last exception caught in the
2717 previous frame (or the frame before that, etc.).
2719 The first bullet fixed the bug in the above example. The second
2720 bullet was for backwards compatibility: it was (and is) common to
2721 have a function that is called when an exception is caught, and to
2722 have that function access the caught exception via sys.exc_ZZZ.
2723 (Example: traceback.print_exc()).
2725 At the same time I fixed the problem that sys.exc_ZZZ weren't
2726 thread-safe, by introducing sys.exc_info() which gets it from tstate;
2727 but that's really a separate improvement.
2729 The reset_exc_info() function in ceval.c restores the tstate->exc_ZZZ
2730 variables to what they were before the current frame was called. The
2731 set_exc_info() function saves them on the frame so that
2732 reset_exc_info() can restore them. The invariant is that
2733 frame->f_exc_ZZZ is NULL iff the current frame never caught an
2734 exception (where "catching" an exception applies only to successful
2735 except clauses); and if the current frame ever caught an exception,
2736 frame->f_exc_ZZZ is the exception that was stored in tstate->exc_ZZZ
2737 at the start of the current frame.
2742 set_exc_info(PyThreadState
*tstate
,
2743 PyObject
*type
, PyObject
*value
, PyObject
*tb
)
2745 PyFrameObject
*frame
;
2746 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
2748 frame
= tstate
->frame
;
2749 if (frame
->f_exc_type
== NULL
) {
2750 /* This frame didn't catch an exception before */
2751 /* Save previous exception of this thread in this frame */
2752 if (tstate
->exc_type
== NULL
) {
2754 tstate
->exc_type
= Py_None
;
2756 tmp_type
= frame
->f_exc_type
;
2757 tmp_value
= frame
->f_exc_value
;
2758 tmp_tb
= frame
->f_exc_traceback
;
2759 Py_XINCREF(tstate
->exc_type
);
2760 Py_XINCREF(tstate
->exc_value
);
2761 Py_XINCREF(tstate
->exc_traceback
);
2762 frame
->f_exc_type
= tstate
->exc_type
;
2763 frame
->f_exc_value
= tstate
->exc_value
;
2764 frame
->f_exc_traceback
= tstate
->exc_traceback
;
2765 Py_XDECREF(tmp_type
);
2766 Py_XDECREF(tmp_value
);
2769 /* Set new exception for this thread */
2770 tmp_type
= tstate
->exc_type
;
2771 tmp_value
= tstate
->exc_value
;
2772 tmp_tb
= tstate
->exc_traceback
;
2776 tstate
->exc_type
= type
;
2777 tstate
->exc_value
= value
;
2778 tstate
->exc_traceback
= tb
;
2779 Py_XDECREF(tmp_type
);
2780 Py_XDECREF(tmp_value
);
2782 /* For b/w compatibility */
2783 PySys_SetObject("exc_type", type
);
2784 PySys_SetObject("exc_value", value
);
2785 PySys_SetObject("exc_traceback", tb
);
2789 reset_exc_info(PyThreadState
*tstate
)
2791 PyFrameObject
*frame
;
2792 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
2793 frame
= tstate
->frame
;
2794 if (frame
->f_exc_type
!= NULL
) {
2795 /* This frame caught an exception */
2796 tmp_type
= tstate
->exc_type
;
2797 tmp_value
= tstate
->exc_value
;
2798 tmp_tb
= tstate
->exc_traceback
;
2799 Py_XINCREF(frame
->f_exc_type
);
2800 Py_XINCREF(frame
->f_exc_value
);
2801 Py_XINCREF(frame
->f_exc_traceback
);
2802 tstate
->exc_type
= frame
->f_exc_type
;
2803 tstate
->exc_value
= frame
->f_exc_value
;
2804 tstate
->exc_traceback
= frame
->f_exc_traceback
;
2805 Py_XDECREF(tmp_type
);
2806 Py_XDECREF(tmp_value
);
2808 /* For b/w compatibility */
2809 PySys_SetObject("exc_type", frame
->f_exc_type
);
2810 PySys_SetObject("exc_value", frame
->f_exc_value
);
2811 PySys_SetObject("exc_traceback", frame
->f_exc_traceback
);
2813 tmp_type
= frame
->f_exc_type
;
2814 tmp_value
= frame
->f_exc_value
;
2815 tmp_tb
= frame
->f_exc_traceback
;
2816 frame
->f_exc_type
= NULL
;
2817 frame
->f_exc_value
= NULL
;
2818 frame
->f_exc_traceback
= NULL
;
2819 Py_XDECREF(tmp_type
);
2820 Py_XDECREF(tmp_value
);
2824 /* Logic for the raise statement (too complicated for inlining).
2825 This *consumes* a reference count to each of its arguments. */
2826 static enum why_code
2827 do_raise(PyObject
*type
, PyObject
*value
, PyObject
*tb
)
2831 PyThreadState
*tstate
= PyThreadState_Get();
2832 type
= tstate
->exc_type
== NULL
? Py_None
: tstate
->exc_type
;
2833 value
= tstate
->exc_value
;
2834 tb
= tstate
->exc_traceback
;
2840 /* We support the following forms of raise:
2841 raise <class>, <classinstance>
2842 raise <class>, <argument tuple>
2844 raise <class>, <argument>
2845 raise <classinstance>, None
2846 raise <string>, <object>
2847 raise <string>, None
2849 An omitted second argument is the same as None.
2851 In addition, raise <tuple>, <anything> is the same as
2852 raising the tuple's first item (and it better have one!);
2853 this rule is applied recursively.
2855 Finally, an optional third argument can be supplied, which
2856 gives the traceback to be substituted (useful when
2857 re-raising an exception after examining it). */
2859 /* First, check the traceback argument, replacing None with
2861 if (tb
== Py_None
) {
2865 else if (tb
!= NULL
&& !PyTraceBack_Check(tb
)) {
2866 PyErr_SetString(PyExc_TypeError
,
2867 "raise: arg 3 must be a traceback or None");
2871 /* Next, replace a missing value with None */
2872 if (value
== NULL
) {
2877 /* Next, repeatedly, replace a tuple exception with its first item */
2878 while (PyTuple_Check(type
) && PyTuple_Size(type
) > 0) {
2879 PyObject
*tmp
= type
;
2880 type
= PyTuple_GET_ITEM(type
, 0);
2885 if (PyString_CheckExact(type
))
2886 /* Raising builtin string is deprecated but still allowed --
2887 * do nothing. Raising an instance of a new-style str
2888 * subclass is right out. */
2889 PyErr_Warn(PyExc_PendingDeprecationWarning
,
2890 "raising a string exception is deprecated");
2892 else if (PyClass_Check(type
))
2893 PyErr_NormalizeException(&type
, &value
, &tb
);
2895 else if (PyInstance_Check(type
)) {
2896 /* Raising an instance. The value should be a dummy. */
2897 if (value
!= Py_None
) {
2898 PyErr_SetString(PyExc_TypeError
,
2899 "instance exception may not have a separate value");
2903 /* Normalize to raise <class>, <instance> */
2906 type
= (PyObject
*) ((PyInstanceObject
*)type
)->in_class
;
2911 /* Not something you can raise. You get an exception
2912 anyway, just not what you specified :-) */
2913 PyErr_Format(PyExc_TypeError
,
2914 "exceptions must be classes, instances, or "
2915 "strings (deprecated), not %s",
2916 type
->ob_type
->tp_name
);
2919 PyErr_Restore(type
, value
, tb
);
2921 return WHY_EXCEPTION
;
2928 return WHY_EXCEPTION
;
2931 /* Iterate v argcnt times and store the results on the stack (via decreasing
2932 sp). Return 1 for success, 0 if error. */
2935 unpack_iterable(PyObject
*v
, int argcnt
, PyObject
**sp
)
2938 PyObject
*it
; /* iter(v) */
2943 it
= PyObject_GetIter(v
);
2947 for (; i
< argcnt
; i
++) {
2948 w
= PyIter_Next(it
);
2950 /* Iterator done, via error or exhaustion. */
2951 if (!PyErr_Occurred()) {
2952 PyErr_Format(PyExc_ValueError
,
2953 "need more than %d value%s to unpack",
2954 i
, i
== 1 ? "" : "s");
2961 /* We better have exhausted the iterator now. */
2962 w
= PyIter_Next(it
);
2964 if (PyErr_Occurred())
2970 PyErr_SetString(PyExc_ValueError
, "too many values to unpack");
2973 for (; i
> 0; i
--, sp
++)
2982 prtrace(PyObject
*v
, char *str
)
2985 if (PyObject_Print(v
, stdout
, 0) != 0)
2986 PyErr_Clear(); /* Don't know what else to do */
2993 call_exc_trace(Py_tracefunc func
, PyObject
*self
, PyFrameObject
*f
)
2995 PyObject
*type
, *value
, *traceback
, *arg
;
2997 PyErr_Fetch(&type
, &value
, &traceback
);
2998 if (value
== NULL
) {
3002 arg
= Py_BuildValue("(OOO)", type
, value
, traceback
);
3004 PyErr_Restore(type
, value
, traceback
);
3007 err
= call_trace(func
, self
, f
, PyTrace_EXCEPTION
, arg
);
3010 PyErr_Restore(type
, value
, traceback
);
3014 Py_XDECREF(traceback
);
3019 call_trace_protected(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3022 PyObject
*type
, *value
, *traceback
;
3024 PyErr_Fetch(&type
, &value
, &traceback
);
3025 err
= call_trace(func
, obj
, frame
, what
, NULL
);
3027 PyErr_Restore(type
, value
, traceback
);
3031 Py_XDECREF(traceback
);
3036 call_trace(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3037 int what
, PyObject
*arg
)
3039 register PyThreadState
*tstate
= frame
->f_tstate
;
3041 if (tstate
->tracing
)
3044 tstate
->use_tracing
= 0;
3045 result
= func(obj
, frame
, what
, arg
);
3046 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3047 || (tstate
->c_profilefunc
!= NULL
));
3053 _PyEval_CallTracing(PyObject
*func
, PyObject
*args
)
3055 PyFrameObject
*frame
= PyEval_GetFrame();
3056 PyThreadState
*tstate
= frame
->f_tstate
;
3057 int save_tracing
= tstate
->tracing
;
3058 int save_use_tracing
= tstate
->use_tracing
;
3061 tstate
->tracing
= 0;
3062 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3063 || (tstate
->c_profilefunc
!= NULL
));
3064 result
= PyObject_Call(func
, args
, NULL
);
3065 tstate
->tracing
= save_tracing
;
3066 tstate
->use_tracing
= save_use_tracing
;
3071 maybe_call_line_trace(Py_tracefunc func
, PyObject
*obj
,
3072 PyFrameObject
*frame
, int *instr_lb
, int *instr_ub
)
3074 /* The theory of SET_LINENO-less tracing.
3076 In a nutshell, we use the co_lnotab field of the code object
3077 to tell when execution has moved onto a different line.
3079 As mentioned above, the basic idea is so set things up so
3082 *instr_lb <= frame->f_lasti < *instr_ub
3084 is true so long as execution does not change lines.
3086 This is all fairly simple. Digging the information out of
3087 co_lnotab takes some work, but is conceptually clear.
3089 Somewhat harder to explain is why we don't *always* call the
3090 line trace function when the above test fails.
3100 which compiles to this:
3103 3 JUMP_IF_FALSE 9 (to 15)
3106 3 7 LOAD_CONST 1 (1)
3109 12 JUMP_FORWARD 6 (to 21)
3112 5 16 LOAD_CONST 2 (2)
3115 >> 21 LOAD_CONST 0 (None)
3118 If 'a' is false, execution will jump to instruction at offset
3119 15 and the co_lnotab will claim that execution has moved to
3120 line 3. This is at best misleading. In this case we could
3121 associate the POP_TOP with line 4, but that doesn't make
3122 sense in all cases (I think).
3124 What we do is only call the line trace function if the co_lnotab
3125 indicates we have jumped to the *start* of a line, i.e. if the
3126 current instruction offset matches the offset given for the
3127 start of a line by the co_lnotab.
3129 This also takes care of the situation where 'a' is true.
3130 Execution will jump from instruction offset 12 to offset 21.
3131 Then the co_lnotab would imply that execution has moved to line
3132 5, which is again misleading.
3134 Why do we set f_lineno when tracing? Well, consider the code
3135 above when 'a' is true. If stepping through this with 'n' in
3136 pdb, you would stop at line 1 with a "call" type event, then
3137 line events on lines 2 and 3, then a "return" type event -- but
3138 you would be shown line 5 during this event. This is a change
3139 from the behaviour in 2.2 and before, and I've found it
3140 confusing in practice. By setting and using f_lineno when
3141 tracing, one can report a line number different from that
3142 suggested by f_lasti on this one occasion where it's desirable.
3147 if ((frame
->f_lasti
< *instr_lb
|| frame
->f_lasti
>= *instr_ub
)) {
3148 PyCodeObject
* co
= frame
->f_code
;
3149 int size
, addr
, line
;
3152 size
= PyString_GET_SIZE(co
->co_lnotab
) / 2;
3153 p
= (unsigned char*)PyString_AS_STRING(co
->co_lnotab
);
3156 line
= co
->co_firstlineno
;
3158 /* possible optimization: if f->f_lasti == instr_ub
3159 (likely to be a common case) then we already know
3160 instr_lb -- if we stored the matching value of p
3161 somwhere we could skip the first while loop. */
3163 /* see comments in compile.c for the description of
3164 co_lnotab. A point to remember: increments to p
3165 should come in pairs -- although we don't care about
3166 the line increments here, treating them as byte
3167 increments gets confusing, to say the least. */
3170 if (addr
+ *p
> frame
->f_lasti
)
3173 if (*p
) *instr_lb
= addr
;
3178 if (addr
== frame
->f_lasti
) {
3179 frame
->f_lineno
= line
;
3180 result
= call_trace(func
, obj
, frame
,
3181 PyTrace_LINE
, Py_None
);
3185 while (--size
>= 0) {
3193 *instr_ub
= INT_MAX
;
3201 PyEval_SetProfile(Py_tracefunc func
, PyObject
*arg
)
3203 PyThreadState
*tstate
= PyThreadState_Get();
3204 PyObject
*temp
= tstate
->c_profileobj
;
3206 tstate
->c_profilefunc
= NULL
;
3207 tstate
->c_profileobj
= NULL
;
3208 tstate
->use_tracing
= tstate
->c_tracefunc
!= NULL
;
3210 tstate
->c_profilefunc
= func
;
3211 tstate
->c_profileobj
= arg
;
3212 tstate
->use_tracing
= (func
!= NULL
) || (tstate
->c_tracefunc
!= NULL
);
3216 PyEval_SetTrace(Py_tracefunc func
, PyObject
*arg
)
3218 PyThreadState
*tstate
= PyThreadState_Get();
3219 PyObject
*temp
= tstate
->c_traceobj
;
3221 tstate
->c_tracefunc
= NULL
;
3222 tstate
->c_traceobj
= NULL
;
3223 tstate
->use_tracing
= tstate
->c_profilefunc
!= NULL
;
3225 tstate
->c_tracefunc
= func
;
3226 tstate
->c_traceobj
= arg
;
3227 tstate
->use_tracing
= ((func
!= NULL
)
3228 || (tstate
->c_profilefunc
!= NULL
));
3232 PyEval_GetBuiltins(void)
3234 PyFrameObject
*current_frame
= PyEval_GetFrame();
3235 if (current_frame
== NULL
)
3236 return PyThreadState_Get()->interp
->builtins
;
3238 return current_frame
->f_builtins
;
3242 PyEval_GetLocals(void)
3244 PyFrameObject
*current_frame
= PyEval_GetFrame();
3245 if (current_frame
== NULL
)
3247 PyFrame_FastToLocals(current_frame
);
3248 return current_frame
->f_locals
;
3252 PyEval_GetGlobals(void)
3254 PyFrameObject
*current_frame
= PyEval_GetFrame();
3255 if (current_frame
== NULL
)
3258 return current_frame
->f_globals
;
3262 PyEval_GetFrame(void)
3264 PyThreadState
*tstate
= PyThreadState_Get();
3265 return _PyThreadState_GetFrame(tstate
);
3269 PyEval_GetRestricted(void)
3271 PyFrameObject
*current_frame
= PyEval_GetFrame();
3272 return current_frame
== NULL
? 0 : current_frame
->f_restricted
;
3276 PyEval_MergeCompilerFlags(PyCompilerFlags
*cf
)
3278 PyFrameObject
*current_frame
= PyEval_GetFrame();
3279 int result
= cf
->cf_flags
!= 0;
3281 if (current_frame
!= NULL
) {
3282 const int codeflags
= current_frame
->f_code
->co_flags
;
3283 const int compilerflags
= codeflags
& PyCF_MASK
;
3284 if (compilerflags
) {
3286 cf
->cf_flags
|= compilerflags
;
3288 #if 0 /* future keyword */
3289 if (codeflags
& CO_GENERATOR_ALLOWED
) {
3291 cf
->cf_flags
|= CO_GENERATOR_ALLOWED
;
3301 PyObject
*f
= PySys_GetObject("stdout");
3304 if (!PyFile_SoftSpace(f
, 0))
3306 return PyFile_WriteString("\n", f
);
3310 /* External interface to call any callable object.
3311 The arg must be a tuple or NULL. */
3313 #undef PyEval_CallObject
3314 /* for backward compatibility: export this interface */
3317 PyEval_CallObject(PyObject
*func
, PyObject
*arg
)
3319 return PyEval_CallObjectWithKeywords(func
, arg
, (PyObject
*)NULL
);
3321 #define PyEval_CallObject(func,arg) \
3322 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
3325 PyEval_CallObjectWithKeywords(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
3330 arg
= PyTuple_New(0);
3331 else if (!PyTuple_Check(arg
)) {
3332 PyErr_SetString(PyExc_TypeError
,
3333 "argument list must be a tuple");
3339 if (kw
!= NULL
&& !PyDict_Check(kw
)) {
3340 PyErr_SetString(PyExc_TypeError
,
3341 "keyword list must be a dictionary");
3346 result
= PyObject_Call(func
, arg
, kw
);
3352 PyEval_GetFuncName(PyObject
*func
)
3354 if (PyMethod_Check(func
))
3355 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func
));
3356 else if (PyFunction_Check(func
))
3357 return PyString_AsString(((PyFunctionObject
*)func
)->func_name
);
3358 else if (PyCFunction_Check(func
))
3359 return ((PyCFunctionObject
*)func
)->m_ml
->ml_name
;
3360 else if (PyClass_Check(func
))
3361 return PyString_AsString(((PyClassObject
*)func
)->cl_name
);
3362 else if (PyInstance_Check(func
)) {
3363 return PyString_AsString(
3364 ((PyInstanceObject
*)func
)->in_class
->cl_name
);
3366 return func
->ob_type
->tp_name
;
3371 PyEval_GetFuncDesc(PyObject
*func
)
3373 if (PyMethod_Check(func
))
3375 else if (PyFunction_Check(func
))
3377 else if (PyCFunction_Check(func
))
3379 else if (PyClass_Check(func
))
3380 return " constructor";
3381 else if (PyInstance_Check(func
)) {
3388 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
3391 err_args(PyObject
*func
, int flags
, int nargs
)
3393 if (flags
& METH_NOARGS
)
3394 PyErr_Format(PyExc_TypeError
,
3395 "%.200s() takes no arguments (%d given)",
3396 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3399 PyErr_Format(PyExc_TypeError
,
3400 "%.200s() takes exactly one argument (%d given)",
3401 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3406 call_function(PyObject
***pp_stack
, int oparg
)
3408 int na
= oparg
& 0xff;
3409 int nk
= (oparg
>>8) & 0xff;
3410 int n
= na
+ 2 * nk
;
3411 PyObject
**pfunc
= (*pp_stack
) - n
- 1;
3412 PyObject
*func
= *pfunc
;
3415 /* Always dispatch PyCFunction first, because these are
3416 presumed to be the most frequent callable object.
3418 if (PyCFunction_Check(func
) && nk
== 0) {
3419 int flags
= PyCFunction_GET_FLAGS(func
);
3420 PCALL(PCALL_CFUNCTION
);
3421 if (flags
& (METH_NOARGS
| METH_O
)) {
3422 PyCFunction meth
= PyCFunction_GET_FUNCTION(func
);
3423 PyObject
*self
= PyCFunction_GET_SELF(func
);
3424 if (flags
& METH_NOARGS
&& na
== 0)
3425 x
= (*meth
)(self
, NULL
);
3426 else if (flags
& METH_O
&& na
== 1) {
3427 PyObject
*arg
= EXT_POP(*pp_stack
);
3428 x
= (*meth
)(self
, arg
);
3432 err_args(func
, flags
, na
);
3438 callargs
= load_args(pp_stack
, na
);
3439 x
= PyCFunction_Call(func
, callargs
, NULL
);
3440 Py_XDECREF(callargs
);
3443 if (PyMethod_Check(func
) && PyMethod_GET_SELF(func
) != NULL
) {
3444 /* optimize access to bound methods */
3445 PyObject
*self
= PyMethod_GET_SELF(func
);
3446 PCALL(PCALL_METHOD
);
3447 PCALL(PCALL_BOUND_METHOD
);
3449 func
= PyMethod_GET_FUNCTION(func
);
3457 if (PyFunction_Check(func
))
3458 x
= fast_function(func
, pp_stack
, n
, na
, nk
);
3460 x
= do_call(func
, pp_stack
, na
, nk
);
3464 /* What does this do? */
3465 while ((*pp_stack
) > pfunc
) {
3466 w
= EXT_POP(*pp_stack
);
3473 /* The fast_function() function optimize calls for which no argument
3474 tuple is necessary; the objects are passed directly from the stack.
3475 For the simplest case -- a function that takes only positional
3476 arguments and is called with only positional arguments -- it
3477 inlines the most primitive frame setup code from
3478 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
3479 done before evaluating the frame.
3483 fast_function(PyObject
*func
, PyObject
***pp_stack
, int n
, int na
, int nk
)
3485 PyCodeObject
*co
= (PyCodeObject
*)PyFunction_GET_CODE(func
);
3486 PyObject
*globals
= PyFunction_GET_GLOBALS(func
);
3487 PyObject
*argdefs
= PyFunction_GET_DEFAULTS(func
);
3488 PyObject
**d
= NULL
;
3491 PCALL(PCALL_FUNCTION
);
3492 PCALL(PCALL_FAST_FUNCTION
);
3493 if (argdefs
== NULL
&& co
->co_argcount
== n
&& nk
==0 &&
3494 co
->co_flags
== (CO_OPTIMIZED
| CO_NEWLOCALS
| CO_NOFREE
)) {
3496 PyObject
*retval
= NULL
;
3497 PyThreadState
*tstate
= PyThreadState_GET();
3498 PyObject
**fastlocals
, **stack
;
3501 PCALL(PCALL_FASTER_FUNCTION
);
3502 assert(globals
!= NULL
);
3503 /* XXX Perhaps we should create a specialized
3504 PyFrame_New() that doesn't take locals, but does
3505 take builtins without sanity checking them.
3507 f
= PyFrame_New(tstate
, co
, globals
, NULL
);
3511 fastlocals
= f
->f_localsplus
;
3512 stack
= (*pp_stack
) - n
;
3514 for (i
= 0; i
< n
; i
++) {
3516 fastlocals
[i
] = *stack
++;
3518 retval
= eval_frame(f
);
3519 assert(tstate
!= NULL
);
3520 ++tstate
->recursion_depth
;
3522 --tstate
->recursion_depth
;
3525 if (argdefs
!= NULL
) {
3526 d
= &PyTuple_GET_ITEM(argdefs
, 0);
3527 nd
= ((PyTupleObject
*)argdefs
)->ob_size
;
3529 return PyEval_EvalCodeEx(co
, globals
,
3530 (PyObject
*)NULL
, (*pp_stack
)-n
, na
,
3531 (*pp_stack
)-2*nk
, nk
, d
, nd
,
3532 PyFunction_GET_CLOSURE(func
));
3536 update_keyword_args(PyObject
*orig_kwdict
, int nk
, PyObject
***pp_stack
,
3539 PyObject
*kwdict
= NULL
;
3540 if (orig_kwdict
== NULL
)
3541 kwdict
= PyDict_New();
3543 kwdict
= PyDict_Copy(orig_kwdict
);
3544 Py_DECREF(orig_kwdict
);
3550 PyObject
*value
= EXT_POP(*pp_stack
);
3551 PyObject
*key
= EXT_POP(*pp_stack
);
3552 if (PyDict_GetItem(kwdict
, key
) != NULL
) {
3553 PyErr_Format(PyExc_TypeError
,
3554 "%.200s%s got multiple values "
3555 "for keyword argument '%.200s'",
3556 PyEval_GetFuncName(func
),
3557 PyEval_GetFuncDesc(func
),
3558 PyString_AsString(key
));
3564 err
= PyDict_SetItem(kwdict
, key
, value
);
3576 update_star_args(int nstack
, int nstar
, PyObject
*stararg
,
3577 PyObject
***pp_stack
)
3579 PyObject
*callargs
, *w
;
3581 callargs
= PyTuple_New(nstack
+ nstar
);
3582 if (callargs
== NULL
) {
3587 for (i
= 0; i
< nstar
; i
++) {
3588 PyObject
*a
= PyTuple_GET_ITEM(stararg
, i
);
3590 PyTuple_SET_ITEM(callargs
, nstack
+ i
, a
);
3593 while (--nstack
>= 0) {
3594 w
= EXT_POP(*pp_stack
);
3595 PyTuple_SET_ITEM(callargs
, nstack
, w
);
3601 load_args(PyObject
***pp_stack
, int na
)
3603 PyObject
*args
= PyTuple_New(na
);
3609 w
= EXT_POP(*pp_stack
);
3610 PyTuple_SET_ITEM(args
, na
, w
);
3616 do_call(PyObject
*func
, PyObject
***pp_stack
, int na
, int nk
)
3618 PyObject
*callargs
= NULL
;
3619 PyObject
*kwdict
= NULL
;
3620 PyObject
*result
= NULL
;
3623 kwdict
= update_keyword_args(NULL
, nk
, pp_stack
, func
);
3627 callargs
= load_args(pp_stack
, na
);
3628 if (callargs
== NULL
)
3631 /* At this point, we have to look at the type of func to
3632 update the call stats properly. Do it here so as to avoid
3633 exposing the call stats machinery outside ceval.c
3635 if (PyFunction_Check(func
))
3636 PCALL(PCALL_FUNCTION
);
3637 else if (PyMethod_Check(func
))
3638 PCALL(PCALL_METHOD
);
3639 else if (PyType_Check(func
))
3644 result
= PyObject_Call(func
, callargs
, kwdict
);
3646 Py_XDECREF(callargs
);
3652 ext_do_call(PyObject
*func
, PyObject
***pp_stack
, int flags
, int na
, int nk
)
3655 PyObject
*callargs
= NULL
;
3656 PyObject
*stararg
= NULL
;
3657 PyObject
*kwdict
= NULL
;
3658 PyObject
*result
= NULL
;
3660 if (flags
& CALL_FLAG_KW
) {
3661 kwdict
= EXT_POP(*pp_stack
);
3662 if (!(kwdict
&& PyDict_Check(kwdict
))) {
3663 PyErr_Format(PyExc_TypeError
,
3664 "%s%s argument after ** "
3665 "must be a dictionary",
3666 PyEval_GetFuncName(func
),
3667 PyEval_GetFuncDesc(func
));
3671 if (flags
& CALL_FLAG_VAR
) {
3672 stararg
= EXT_POP(*pp_stack
);
3673 if (!PyTuple_Check(stararg
)) {
3675 t
= PySequence_Tuple(stararg
);
3677 if (PyErr_ExceptionMatches(PyExc_TypeError
)) {
3678 PyErr_Format(PyExc_TypeError
,
3679 "%s%s argument after * "
3680 "must be a sequence",
3681 PyEval_GetFuncName(func
),
3682 PyEval_GetFuncDesc(func
));
3689 nstar
= PyTuple_GET_SIZE(stararg
);
3692 kwdict
= update_keyword_args(kwdict
, nk
, pp_stack
, func
);
3696 callargs
= update_star_args(na
, nstar
, stararg
, pp_stack
);
3697 if (callargs
== NULL
)
3700 /* At this point, we have to look at the type of func to
3701 update the call stats properly. Do it here so as to avoid
3702 exposing the call stats machinery outside ceval.c
3704 if (PyFunction_Check(func
))
3705 PCALL(PCALL_FUNCTION
);
3706 else if (PyMethod_Check(func
))
3707 PCALL(PCALL_METHOD
);
3708 else if (PyType_Check(func
))
3713 result
= PyObject_Call(func
, callargs
, kwdict
);
3715 Py_XDECREF(callargs
);
3717 Py_XDECREF(stararg
);
3721 #define SLICE_ERROR_MSG \
3722 "standard sequence type does not support step size other than one"
3724 /* Extract a slice index from a PyInt or PyLong, and store in *pi.
3725 Silently reduce values larger than INT_MAX to INT_MAX, and silently
3726 boost values less than -INT_MAX to 0. Return 0 on error, 1 on success.
3728 /* Note: If v is NULL, return success without storing into *pi. This
3729 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
3730 called by the SLICE opcode with v and/or w equal to NULL.
3733 _PyEval_SliceIndex(PyObject
*v
, int *pi
)
3737 if (PyInt_Check(v
)) {
3738 x
= PyInt_AsLong(v
);
3739 } else if (PyLong_Check(v
)) {
3740 x
= PyLong_AsLong(v
);
3741 if (x
==-1 && PyErr_Occurred()) {
3742 PyObject
*long_zero
;
3745 if (!PyErr_ExceptionMatches(
3746 PyExc_OverflowError
)) {
3747 /* It's not an overflow error, so just
3752 /* Clear the OverflowError */
3755 /* It's an overflow error, so we need to
3756 check the sign of the long integer,
3757 set the value to INT_MAX or -INT_MAX,
3758 and clear the error. */
3760 /* Create a long integer with a value of 0 */
3761 long_zero
= PyLong_FromLong(0L);
3762 if (long_zero
== NULL
)
3766 cmp
= PyObject_RichCompareBool(v
, long_zero
,
3768 Py_DECREF(long_zero
);
3777 PyErr_SetString(PyExc_TypeError
,
3778 "slice indices must be integers");
3781 /* Truncate -- very long indices are truncated anyway */
3784 else if (x
< -INT_MAX
)
3792 #define ISINT(x) ((x) == NULL || PyInt_Check(x) || PyLong_Check(x))
3795 apply_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
) /* return u[v:w] */
3797 PyTypeObject
*tp
= u
->ob_type
;
3798 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
3800 if (sq
&& sq
->sq_slice
&& ISINT(v
) && ISINT(w
)) {
3801 int ilow
= 0, ihigh
= INT_MAX
;
3802 if (!_PyEval_SliceIndex(v
, &ilow
))
3804 if (!_PyEval_SliceIndex(w
, &ihigh
))
3806 return PySequence_GetSlice(u
, ilow
, ihigh
);
3809 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
3810 if (slice
!= NULL
) {
3811 PyObject
*res
= PyObject_GetItem(u
, slice
);
3821 assign_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
, PyObject
*x
)
3824 PyTypeObject
*tp
= u
->ob_type
;
3825 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
3827 if (sq
&& sq
->sq_slice
&& ISINT(v
) && ISINT(w
)) {
3828 int ilow
= 0, ihigh
= INT_MAX
;
3829 if (!_PyEval_SliceIndex(v
, &ilow
))
3831 if (!_PyEval_SliceIndex(w
, &ihigh
))
3834 return PySequence_DelSlice(u
, ilow
, ihigh
);
3836 return PySequence_SetSlice(u
, ilow
, ihigh
, x
);
3839 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
3840 if (slice
!= NULL
) {
3843 res
= PyObject_SetItem(u
, slice
, x
);
3845 res
= PyObject_DelItem(u
, slice
);
3855 cmp_outcome(int op
, register PyObject
*v
, register PyObject
*w
)
3866 res
= PySequence_Contains(w
, v
);
3871 res
= PySequence_Contains(w
, v
);
3876 case PyCmp_EXC_MATCH
:
3877 res
= PyErr_GivenExceptionMatches(v
, w
);
3880 return PyObject_RichCompare(v
, w
, op
);
3882 v
= res
? Py_True
: Py_False
;
3888 import_from(PyObject
*v
, PyObject
*name
)
3892 x
= PyObject_GetAttr(v
, name
);
3893 if (x
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
3894 PyErr_Format(PyExc_ImportError
,
3895 "cannot import name %.230s",
3896 PyString_AsString(name
));
3902 import_all_from(PyObject
*locals
, PyObject
*v
)
3904 PyObject
*all
= PyObject_GetAttrString(v
, "__all__");
3905 PyObject
*dict
, *name
, *value
;
3906 int skip_leading_underscores
= 0;
3910 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
3911 return -1; /* Unexpected error */
3913 dict
= PyObject_GetAttrString(v
, "__dict__");
3915 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
3917 PyErr_SetString(PyExc_ImportError
,
3918 "from-import-* object has no __dict__ and no __all__");
3921 all
= PyMapping_Keys(dict
);
3925 skip_leading_underscores
= 1;
3928 for (pos
= 0, err
= 0; ; pos
++) {
3929 name
= PySequence_GetItem(all
, pos
);
3931 if (!PyErr_ExceptionMatches(PyExc_IndexError
))
3937 if (skip_leading_underscores
&&
3938 PyString_Check(name
) &&
3939 PyString_AS_STRING(name
)[0] == '_')
3944 value
= PyObject_GetAttr(v
, name
);
3948 err
= PyDict_SetItem(locals
, name
, value
);
3959 build_class(PyObject
*methods
, PyObject
*bases
, PyObject
*name
)
3961 PyObject
*metaclass
= NULL
, *result
, *base
;
3963 if (PyDict_Check(methods
))
3964 metaclass
= PyDict_GetItemString(methods
, "__metaclass__");
3965 if (metaclass
!= NULL
)
3966 Py_INCREF(metaclass
);
3967 else if (PyTuple_Check(bases
) && PyTuple_GET_SIZE(bases
) > 0) {
3968 base
= PyTuple_GET_ITEM(bases
, 0);
3969 metaclass
= PyObject_GetAttrString(base
, "__class__");
3970 if (metaclass
== NULL
) {
3972 metaclass
= (PyObject
*)base
->ob_type
;
3973 Py_INCREF(metaclass
);
3977 PyObject
*g
= PyEval_GetGlobals();
3978 if (g
!= NULL
&& PyDict_Check(g
))
3979 metaclass
= PyDict_GetItemString(g
, "__metaclass__");
3980 if (metaclass
== NULL
)
3981 metaclass
= (PyObject
*) &PyClass_Type
;
3982 Py_INCREF(metaclass
);
3984 result
= PyObject_CallFunction(metaclass
, "OOO", name
, bases
, methods
);
3985 Py_DECREF(metaclass
);
3990 exec_statement(PyFrameObject
*f
, PyObject
*prog
, PyObject
*globals
,
3997 if (PyTuple_Check(prog
) && globals
== Py_None
&& locals
== Py_None
&&
3998 ((n
= PyTuple_Size(prog
)) == 2 || n
== 3)) {
3999 /* Backward compatibility hack */
4000 globals
= PyTuple_GetItem(prog
, 1);
4002 locals
= PyTuple_GetItem(prog
, 2);
4003 prog
= PyTuple_GetItem(prog
, 0);
4005 if (globals
== Py_None
) {
4006 globals
= PyEval_GetGlobals();
4007 if (locals
== Py_None
) {
4008 locals
= PyEval_GetLocals();
4012 else if (locals
== Py_None
)
4014 if (!PyString_Check(prog
) &&
4015 !PyUnicode_Check(prog
) &&
4016 !PyCode_Check(prog
) &&
4017 !PyFile_Check(prog
)) {
4018 PyErr_SetString(PyExc_TypeError
,
4019 "exec: arg 1 must be a string, file, or code object");
4022 if (!PyDict_Check(globals
)) {
4023 PyErr_SetString(PyExc_TypeError
,
4024 "exec: arg 2 must be a dictionary or None");
4027 if (!PyDict_Check(locals
)) {
4028 PyErr_SetString(PyExc_TypeError
,
4029 "exec: arg 3 must be a dictionary or None");
4032 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
)
4033 PyDict_SetItemString(globals
, "__builtins__", f
->f_builtins
);
4034 if (PyCode_Check(prog
)) {
4035 if (PyCode_GetNumFree((PyCodeObject
*)prog
) > 0) {
4036 PyErr_SetString(PyExc_TypeError
,
4037 "code object passed to exec may not contain free variables");
4040 v
= PyEval_EvalCode((PyCodeObject
*) prog
, globals
, locals
);
4042 else if (PyFile_Check(prog
)) {
4043 FILE *fp
= PyFile_AsFile(prog
);
4044 char *name
= PyString_AsString(PyFile_Name(prog
));
4047 if (PyEval_MergeCompilerFlags(&cf
))
4048 v
= PyRun_FileFlags(fp
, name
, Py_file_input
, globals
,
4051 v
= PyRun_File(fp
, name
, Py_file_input
, globals
,
4055 PyObject
*tmp
= NULL
;
4059 #ifdef Py_USING_UNICODE
4060 if (PyUnicode_Check(prog
)) {
4061 tmp
= PyUnicode_AsUTF8String(prog
);
4065 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
4068 if (PyString_AsStringAndSize(prog
, &str
, NULL
))
4070 if (PyEval_MergeCompilerFlags(&cf
))
4071 v
= PyRun_StringFlags(str
, Py_file_input
, globals
,
4074 v
= PyRun_String(str
, Py_file_input
, globals
, locals
);
4078 PyFrame_LocalsToFast(f
, 0);
4086 format_exc_check_arg(PyObject
*exc
, char *format_str
, PyObject
*obj
)
4093 obj_str
= PyString_AsString(obj
);
4097 PyErr_Format(exc
, format_str
, obj_str
);
4100 #ifdef DYNAMIC_EXECUTION_PROFILE
4103 getarray(long a
[256])
4106 PyObject
*l
= PyList_New(256);
4107 if (l
== NULL
) return NULL
;
4108 for (i
= 0; i
< 256; i
++) {
4109 PyObject
*x
= PyInt_FromLong(a
[i
]);
4114 PyList_SetItem(l
, i
, x
);
4116 for (i
= 0; i
< 256; i
++)
4122 _Py_GetDXProfile(PyObject
*self
, PyObject
*args
)
4125 return getarray(dxp
);
4128 PyObject
*l
= PyList_New(257);
4129 if (l
== NULL
) return NULL
;
4130 for (i
= 0; i
< 257; i
++) {
4131 PyObject
*x
= getarray(dxpairs
[i
]);
4136 PyList_SetItem(l
, i
, x
);