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
;
31 "__ppc__" appears to be the preprocessor definition to detect on OS X, whereas
32 "__powerpc__" appears to be the correct one for Linux with GCC
34 #if defined(__ppc__) || defined (__powerpc__)
36 #define READ_TIMESTAMP(var) ppc_getcounter(&var)
39 ppc_getcounter(uint64
*v
)
41 register unsigned long tbu
, tb
, tbu2
;
44 asm volatile ("mftbu %0" : "=r" (tbu
) );
45 asm volatile ("mftb %0" : "=r" (tb
) );
46 asm volatile ("mftbu %0" : "=r" (tbu2
));
47 if (__builtin_expect(tbu
!= tbu2
, 0)) goto loop
;
49 /* The slightly peculiar way of writing the next lines is
50 compiled better by GCC than any other way I tried. */
51 ((long*)(v
))[0] = tbu
;
55 #elif defined(__i386__)
57 /* this is for linux/x86 (and probably any other GCC/x86 combo) */
59 #define READ_TIMESTAMP(val) \
60 __asm__ __volatile__("rdtsc" : "=A" (val))
62 #elif defined(__x86_64__)
64 /* for gcc/x86_64, the "A" constraint in DI mode means *either* rax *or* rdx;
65 not edx:eax as it does for i386. Since rdtsc puts its result in edx:eax
66 even in 64-bit mode, we need to use "a" and "d" for the lower and upper
67 32-bit pieces of the result. */
69 #define READ_TIMESTAMP(val) do { \
71 __asm__ __volatile__("rdtsc" : "=a" (l), "=d" (h)); \
72 (val) = ((uint64)l) | (((uint64)h) << 32); \
78 #error "Don't know how to implement timestamp counter for this architecture"
82 void dump_tsc(int opcode
, int ticked
, uint64 inst0
, uint64 inst1
,
83 uint64 loop0
, uint64 loop1
, uint64 intr0
, uint64 intr1
)
85 uint64 intr
, inst
, loop
;
86 PyThreadState
*tstate
= PyThreadState_Get();
87 if (!tstate
->interp
->tscdump
)
90 inst
= inst1
- inst0
- intr
;
91 loop
= loop1
- loop0
- intr
;
92 fprintf(stderr
, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
93 opcode
, ticked
, inst
, loop
);
98 /* Turn this on if your compiler chokes on the big switch: */
99 /* #define CASE_TOO_BIG 1 */
102 /* For debugging the interpreter: */
103 #define LLTRACE 1 /* Low-level trace feature */
104 #define CHECKEXC 1 /* Double-check exception checking */
107 typedef PyObject
*(*callproc
)(PyObject
*, PyObject
*, PyObject
*);
109 /* Forward declarations */
111 static PyObject
* call_function(PyObject
***, int, uint64
*, uint64
*);
113 static PyObject
* call_function(PyObject
***, int);
115 static PyObject
* fast_function(PyObject
*, PyObject
***, int, int, int);
116 static PyObject
* do_call(PyObject
*, PyObject
***, int, int);
117 static PyObject
* ext_do_call(PyObject
*, PyObject
***, int, int, int);
118 static PyObject
* update_keyword_args(PyObject
*, int, PyObject
***,
120 static PyObject
* update_star_args(int, int, PyObject
*, PyObject
***);
121 static PyObject
* load_args(PyObject
***, int);
122 #define CALL_FLAG_VAR 1
123 #define CALL_FLAG_KW 2
127 static int prtrace(PyObject
*, char *);
129 static int call_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*,
131 static int call_trace_protected(Py_tracefunc
, PyObject
*,
132 PyFrameObject
*, int, PyObject
*);
133 static void call_exc_trace(Py_tracefunc
, PyObject
*, PyFrameObject
*);
134 static int maybe_call_line_trace(Py_tracefunc
, PyObject
*,
135 PyFrameObject
*, int *, int *, int *);
137 static PyObject
* apply_slice(PyObject
*, PyObject
*, PyObject
*);
138 static int assign_slice(PyObject
*, PyObject
*,
139 PyObject
*, PyObject
*);
140 static PyObject
* cmp_outcome(int, PyObject
*, PyObject
*);
141 static PyObject
* import_from(PyObject
*, PyObject
*);
142 static int import_all_from(PyObject
*, PyObject
*);
143 static PyObject
* build_class(PyObject
*, PyObject
*, PyObject
*);
144 static int exec_statement(PyFrameObject
*,
145 PyObject
*, PyObject
*, PyObject
*);
146 static void set_exc_info(PyThreadState
*, PyObject
*, PyObject
*, PyObject
*);
147 static void reset_exc_info(PyThreadState
*);
148 static void format_exc_check_arg(PyObject
*, char *, PyObject
*);
149 static PyObject
* string_concatenate(PyObject
*, PyObject
*,
150 PyFrameObject
*, unsigned char *);
151 static PyObject
* kwd_as_string(PyObject
*);
152 static PyObject
* special_lookup(PyObject
*, char *, PyObject
**);
154 #define NAME_ERROR_MSG \
155 "name '%.200s' is not defined"
156 #define GLOBAL_NAME_ERROR_MSG \
157 "global name '%.200s' is not defined"
158 #define UNBOUNDLOCAL_ERROR_MSG \
159 "local variable '%.200s' referenced before assignment"
160 #define UNBOUNDFREE_ERROR_MSG \
161 "free variable '%.200s' referenced before assignment" \
162 " in enclosing scope"
164 /* Dynamic execution profile */
165 #ifdef DYNAMIC_EXECUTION_PROFILE
167 static long dxpairs
[257][256];
168 #define dxp dxpairs[256]
170 static long dxp
[256];
174 /* Function call profile */
177 static int pcall
[PCALL_NUM
];
180 #define PCALL_FUNCTION 1
181 #define PCALL_FAST_FUNCTION 2
182 #define PCALL_FASTER_FUNCTION 3
183 #define PCALL_METHOD 4
184 #define PCALL_BOUND_METHOD 5
185 #define PCALL_CFUNCTION 6
187 #define PCALL_GENERATOR 8
188 #define PCALL_OTHER 9
191 /* Notes about the statistics
195 FAST_FUNCTION means no argument tuple needs to be created.
196 FASTER_FUNCTION means that the fast-path frame setup code is used.
198 If there is a method call where the call can be optimized by changing
199 the argument tuple and calling the function directly, it gets recorded
202 As a result, the relationship among the statistics appears to be
203 PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
204 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
205 PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
206 PCALL_METHOD > PCALL_BOUND_METHOD
209 #define PCALL(POS) pcall[POS]++
212 PyEval_GetCallStats(PyObject
*self
)
214 return Py_BuildValue("iiiiiiiiiii",
215 pcall
[0], pcall
[1], pcall
[2], pcall
[3],
216 pcall
[4], pcall
[5], pcall
[6], pcall
[7],
217 pcall
[8], pcall
[9], pcall
[10]);
223 PyEval_GetCallStats(PyObject
*self
)
236 #include "pythread.h"
238 static PyThread_type_lock interpreter_lock
= 0; /* This is the GIL */
239 static PyThread_type_lock pending_lock
= 0; /* for pending calls */
240 static long main_thread
= 0;
243 PyEval_ThreadsInitialized(void)
245 return interpreter_lock
!= 0;
249 PyEval_InitThreads(void)
251 if (interpreter_lock
)
253 interpreter_lock
= PyThread_allocate_lock();
254 PyThread_acquire_lock(interpreter_lock
, 1);
255 main_thread
= PyThread_get_thread_ident();
259 PyEval_AcquireLock(void)
261 PyThread_acquire_lock(interpreter_lock
, 1);
265 PyEval_ReleaseLock(void)
267 PyThread_release_lock(interpreter_lock
);
271 PyEval_AcquireThread(PyThreadState
*tstate
)
274 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
275 /* Check someone has called PyEval_InitThreads() to create the lock */
276 assert(interpreter_lock
);
277 PyThread_acquire_lock(interpreter_lock
, 1);
278 if (PyThreadState_Swap(tstate
) != NULL
)
280 "PyEval_AcquireThread: non-NULL old thread state");
284 PyEval_ReleaseThread(PyThreadState
*tstate
)
287 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
288 if (PyThreadState_Swap(NULL
) != tstate
)
289 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
290 PyThread_release_lock(interpreter_lock
);
293 /* This function is called from PyOS_AfterFork to ensure that newly
294 created child processes don't hold locks referring to threads which
295 are not running in the child process. (This could also be done using
296 pthread_atfork mechanism, at least for the pthreads implementation.) */
299 PyEval_ReInitThreads(void)
301 PyObject
*threading
, *result
;
302 PyThreadState
*tstate
;
304 if (!interpreter_lock
)
306 /*XXX Can't use PyThread_free_lock here because it does too
307 much error-checking. Doing this cleanly would require
308 adding a new function to each thread_*.h. Instead, just
309 create a new lock and waste a little bit of memory */
310 interpreter_lock
= PyThread_allocate_lock();
311 pending_lock
= PyThread_allocate_lock();
312 PyThread_acquire_lock(interpreter_lock
, 1);
313 main_thread
= PyThread_get_thread_ident();
315 /* Update the threading module with the new state.
317 tstate
= PyThreadState_GET();
318 threading
= PyMapping_GetItemString(tstate
->interp
->modules
,
320 if (threading
== NULL
) {
321 /* threading not imported */
325 result
= PyObject_CallMethod(threading
, "_after_fork", NULL
);
327 PyErr_WriteUnraisable(threading
);
330 Py_DECREF(threading
);
334 /* Functions save_thread and restore_thread are always defined so
335 dynamically loaded modules needn't be compiled separately for use
336 with and without threads: */
339 PyEval_SaveThread(void)
341 PyThreadState
*tstate
= PyThreadState_Swap(NULL
);
343 Py_FatalError("PyEval_SaveThread: NULL tstate");
345 if (interpreter_lock
)
346 PyThread_release_lock(interpreter_lock
);
352 PyEval_RestoreThread(PyThreadState
*tstate
)
355 Py_FatalError("PyEval_RestoreThread: NULL tstate");
357 if (interpreter_lock
) {
359 PyThread_acquire_lock(interpreter_lock
, 1);
363 PyThreadState_Swap(tstate
);
367 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
368 signal handlers or Mac I/O completion routines) can schedule calls
369 to a function to be called synchronously.
370 The synchronous function is called with one void* argument.
371 It should return 0 for success or -1 for failure -- failure should
372 be accompanied by an exception.
374 If registry succeeds, the registry function returns 0; if it fails
375 (e.g. due to too many pending calls) it returns -1 (without setting
376 an exception condition).
378 Note that because registry may occur from within signal handlers,
379 or other asynchronous events, calling malloc() is unsafe!
382 Any thread can schedule pending calls, but only the main thread
384 There is no facility to schedule calls to a particular thread, but
385 that should be easy to change, should that ever be required. In
386 that case, the static variables here should go into the python
393 /* The WITH_THREAD implementation is thread-safe. It allows
394 scheduling to be made from any thread, and even from an executing
398 #define NPENDINGCALLS 32
402 } pendingcalls
[NPENDINGCALLS
];
403 static int pendingfirst
= 0;
404 static int pendinglast
= 0;
405 static volatile int pendingcalls_to_do
= 1; /* trigger initialization of lock */
406 static char pendingbusy
= 0;
409 Py_AddPendingCall(int (*func
)(void *), void *arg
)
412 PyThread_type_lock lock
= pending_lock
;
414 /* try a few times for the lock. Since this mechanism is used
415 * for signal handling (on the main thread), there is a (slim)
416 * chance that a signal is delivered on the same thread while we
417 * hold the lock during the Py_MakePendingCalls() function.
418 * This avoids a deadlock in that case.
419 * Note that signals can be delivered on any thread. In particular,
420 * on Windows, a SIGINT is delivered on a system-created worker
422 * We also check for lock being NULL, in the unlikely case that
423 * this function is called before any bytecode evaluation takes place.
426 for (i
= 0; i
<100; i
++) {
427 if (PyThread_acquire_lock(lock
, NOWAIT_LOCK
))
435 j
= (i
+ 1) % NPENDINGCALLS
;
436 if (j
== pendingfirst
) {
437 result
= -1; /* Queue full */
439 pendingcalls
[i
].func
= func
;
440 pendingcalls
[i
].arg
= arg
;
443 /* signal main loop */
445 pendingcalls_to_do
= 1;
447 PyThread_release_lock(lock
);
452 Py_MakePendingCalls(void)
458 /* initial allocation of the lock */
459 pending_lock
= PyThread_allocate_lock();
460 if (pending_lock
== NULL
)
464 /* only service pending calls on main thread */
465 if (main_thread
&& PyThread_get_thread_ident() != main_thread
)
467 /* don't perform recursive pending calls */
471 /* perform a bounded number of calls, in case of recursion */
472 for (i
=0; i
<NPENDINGCALLS
; i
++) {
477 /* pop one item off the queue while holding the lock */
478 PyThread_acquire_lock(pending_lock
, WAIT_LOCK
);
480 if (j
== pendinglast
) {
481 func
= NULL
; /* Queue empty */
483 func
= pendingcalls
[j
].func
;
484 arg
= pendingcalls
[j
].arg
;
485 pendingfirst
= (j
+ 1) % NPENDINGCALLS
;
487 pendingcalls_to_do
= pendingfirst
!= pendinglast
;
488 PyThread_release_lock(pending_lock
);
489 /* having released the lock, perform the callback */
500 #else /* if ! defined WITH_THREAD */
503 WARNING! ASYNCHRONOUSLY EXECUTING CODE!
504 This code is used for signal handling in python that isn't built
506 Don't use this implementation when Py_AddPendingCalls() can happen
507 on a different thread!
509 There are two possible race conditions:
510 (1) nested asynchronous calls to Py_AddPendingCall()
511 (2) AddPendingCall() calls made while pending calls are being processed.
513 (1) is very unlikely because typically signal delivery
514 is blocked during signal handling. So it should be impossible.
515 (2) is a real possibility.
516 The current code is safe against (2), but not against (1).
517 The safety against (2) is derived from the fact that only one
518 thread is present, interrupted by signals, and that the critical
519 section is protected with the "busy" variable. On Windows, which
520 delivers SIGINT on a system thread, this does not hold and therefore
521 Windows really shouldn't use this version.
522 The two threads could theoretically wiggle around the "busy" variable.
525 #define NPENDINGCALLS 32
529 } pendingcalls
[NPENDINGCALLS
];
530 static volatile int pendingfirst
= 0;
531 static volatile int pendinglast
= 0;
532 static volatile int pendingcalls_to_do
= 0;
535 Py_AddPendingCall(int (*func
)(void *), void *arg
)
537 static volatile int busy
= 0;
539 /* XXX Begin critical section */
544 j
= (i
+ 1) % NPENDINGCALLS
;
545 if (j
== pendingfirst
) {
547 return -1; /* Queue full */
549 pendingcalls
[i
].func
= func
;
550 pendingcalls
[i
].arg
= arg
;
554 pendingcalls_to_do
= 1; /* Signal main loop */
556 /* XXX End critical section */
561 Py_MakePendingCalls(void)
567 pendingcalls_to_do
= 0;
573 if (i
== pendinglast
)
574 break; /* Queue empty */
575 func
= pendingcalls
[i
].func
;
576 arg
= pendingcalls
[i
].arg
;
577 pendingfirst
= (i
+ 1) % NPENDINGCALLS
;
580 pendingcalls_to_do
= 1; /* We're not done yet */
588 #endif /* WITH_THREAD */
591 /* The interpreter's recursion limit */
593 #ifndef Py_DEFAULT_RECURSION_LIMIT
594 #define Py_DEFAULT_RECURSION_LIMIT 1000
596 static int recursion_limit
= Py_DEFAULT_RECURSION_LIMIT
;
597 int _Py_CheckRecursionLimit
= Py_DEFAULT_RECURSION_LIMIT
;
600 Py_GetRecursionLimit(void)
602 return recursion_limit
;
606 Py_SetRecursionLimit(int new_limit
)
608 recursion_limit
= new_limit
;
609 _Py_CheckRecursionLimit
= recursion_limit
;
612 /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
613 if the recursion_depth reaches _Py_CheckRecursionLimit.
614 If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
615 to guarantee that _Py_CheckRecursiveCall() is regularly called.
616 Without USE_STACKCHECK, there is no need for this. */
618 _Py_CheckRecursiveCall(char *where
)
620 PyThreadState
*tstate
= PyThreadState_GET();
622 #ifdef USE_STACKCHECK
623 if (PyOS_CheckStack()) {
624 --tstate
->recursion_depth
;
625 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
629 if (tstate
->recursion_depth
> recursion_limit
) {
630 --tstate
->recursion_depth
;
631 PyErr_Format(PyExc_RuntimeError
,
632 "maximum recursion depth exceeded%s",
636 _Py_CheckRecursionLimit
= recursion_limit
;
640 /* Status code for main loop (reason for stack unwind) */
642 WHY_NOT
= 0x0001, /* No error */
643 WHY_EXCEPTION
= 0x0002, /* Exception occurred */
644 WHY_RERAISE
= 0x0004, /* Exception re-raised by 'finally' */
645 WHY_RETURN
= 0x0008, /* 'return' statement */
646 WHY_BREAK
= 0x0010, /* 'break' statement */
647 WHY_CONTINUE
= 0x0020, /* 'continue' statement */
648 WHY_YIELD
= 0x0040 /* 'yield' operator */
651 static enum why_code
do_raise(PyObject
*, PyObject
*, PyObject
*);
652 static int unpack_iterable(PyObject
*, int, PyObject
**);
654 /* Records whether tracing is on for any thread. Counts the number of
655 threads for which tstate->c_tracefunc is non-NULL, so if the value
656 is 0, we know we don't have to check this thread's c_tracefunc.
657 This speeds up the if statement in PyEval_EvalFrameEx() after
659 static int _Py_TracingPossible
= 0;
661 /* for manipulating the thread switch and periodic "stuff" - used to be
662 per thread, now just a pair o' globals */
663 int _Py_CheckInterval
= 100;
664 volatile int _Py_Ticker
= 0; /* so that we hit a "tick" first thing */
667 PyEval_EvalCode(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
)
669 return PyEval_EvalCodeEx(co
,
671 (PyObject
**)NULL
, 0,
672 (PyObject
**)NULL
, 0,
673 (PyObject
**)NULL
, 0,
678 /* Interpreter main loop */
681 PyEval_EvalFrame(PyFrameObject
*f
) {
682 /* This is for backward compatibility with extension modules that
683 used this API; core interpreter code should call
684 PyEval_EvalFrameEx() */
685 return PyEval_EvalFrameEx(f
, 0);
689 PyEval_EvalFrameEx(PyFrameObject
*f
, int throwflag
)
694 register PyObject
**stack_pointer
; /* Next free slot in value stack */
695 register unsigned char *next_instr
;
696 register int opcode
; /* Current opcode */
697 register int oparg
; /* Current opcode argument, if any */
698 register enum why_code why
; /* Reason for block stack unwind */
699 register int err
; /* Error status -- nonzero if error */
700 register PyObject
*x
; /* Result object -- NULL if error */
701 register PyObject
*v
; /* Temporary objects popped off stack */
702 register PyObject
*w
;
703 register PyObject
*u
;
704 register PyObject
*t
;
705 register PyObject
*stream
= NULL
; /* for PRINT opcodes */
706 register PyObject
**fastlocals
, **freevars
;
707 PyObject
*retval
= NULL
; /* Return value */
708 PyThreadState
*tstate
= PyThreadState_GET();
711 /* when tracing we set things up so that
713 not (instr_lb <= current_bytecode_offset < instr_ub)
715 is true when the line being executed has changed. The
716 initial values are such as to make this false the first
717 time it is tested. */
718 int instr_ub
= -1, instr_lb
= 0, instr_prev
= -1;
720 unsigned char *first_instr
;
723 #if defined(Py_DEBUG) || defined(LLTRACE)
724 /* Make it easier to find out where we are with a debugger */
728 /* Tuple access macros */
731 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
733 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
737 /* Use Pentium timestamp counter to mark certain events:
738 inst0 -- beginning of switch statement for opcode dispatch
739 inst1 -- end of switch statement (may be skipped)
740 loop0 -- the top of the mainloop
741 loop1 -- place where control returns again to top of mainloop
743 intr1 -- beginning of long interruption
744 intr2 -- end of long interruption
746 Many opcodes call out to helper C functions. In some cases, the
747 time in those functions should be counted towards the time for the
748 opcode, but not in all cases. For example, a CALL_FUNCTION opcode
749 calls another Python function; there's no point in charge all the
750 bytecode executed by the called function to the caller.
752 It's hard to make a useful judgement statically. In the presence
753 of operator overloading, it's impossible to tell if a call will
754 execute new Python code or not.
756 It's a case-by-case judgement. I'll use intr1 for the following
762 CALL_FUNCTION (and friends)
765 uint64 inst0
, inst1
, loop0
, loop1
, intr0
= 0, intr1
= 0;
768 READ_TIMESTAMP(inst0
);
769 READ_TIMESTAMP(inst1
);
770 READ_TIMESTAMP(loop0
);
771 READ_TIMESTAMP(loop1
);
773 /* shut up the compiler */
777 /* Code access macros */
779 #define INSTR_OFFSET() ((int)(next_instr - first_instr))
780 #define NEXTOP() (*next_instr++)
781 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
782 #define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
783 #define JUMPTO(x) (next_instr = first_instr + (x))
784 #define JUMPBY(x) (next_instr += (x))
786 /* OpCode prediction macros
787 Some opcodes tend to come in pairs thus making it possible to
788 predict the second code when the first is run. For example,
789 GET_ITER is often followed by FOR_ITER. And FOR_ITER is often
790 followed by STORE_FAST or UNPACK_SEQUENCE.
792 Verifying the prediction costs a single high-speed test of a register
793 variable against a constant. If the pairing was good, then the
794 processor's own internal branch predication has a high likelihood of
795 success, resulting in a nearly zero-overhead transition to the
796 next opcode. A successful prediction saves a trip through the eval-loop
797 including its two unpredictable branches, the HAS_ARG test and the
798 switch-case. Combined with the processor's internal branch prediction,
799 a successful PREDICT has the effect of making the two opcodes run as if
800 they were a single new opcode with the bodies combined.
802 If collecting opcode statistics, your choices are to either keep the
803 predictions turned-on and interpret the results as if some opcodes
804 had been combined or turn-off predictions so that the opcode frequency
805 counter updates for both opcodes.
808 #ifdef DYNAMIC_EXECUTION_PROFILE
809 #define PREDICT(op) if (0) goto PRED_##op
811 #define PREDICT(op) if (*next_instr == op) goto PRED_##op
814 #define PREDICTED(op) PRED_##op: next_instr++
815 #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
817 /* Stack manipulation macros */
819 /* The stack can grow at most MAXINT deep, as co_nlocals and
820 co_stacksize are ints. */
821 #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
822 #define EMPTY() (STACK_LEVEL() == 0)
823 #define TOP() (stack_pointer[-1])
824 #define SECOND() (stack_pointer[-2])
825 #define THIRD() (stack_pointer[-3])
826 #define FOURTH() (stack_pointer[-4])
827 #define PEEK(n) (stack_pointer[-(n)])
828 #define SET_TOP(v) (stack_pointer[-1] = (v))
829 #define SET_SECOND(v) (stack_pointer[-2] = (v))
830 #define SET_THIRD(v) (stack_pointer[-3] = (v))
831 #define SET_FOURTH(v) (stack_pointer[-4] = (v))
832 #define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
833 #define BASIC_STACKADJ(n) (stack_pointer += n)
834 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
835 #define BASIC_POP() (*--stack_pointer)
838 #define PUSH(v) { (void)(BASIC_PUSH(v), \
839 lltrace && prtrace(TOP(), "push")); \
840 assert(STACK_LEVEL() <= co->co_stacksize); }
841 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
843 #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
844 lltrace && prtrace(TOP(), "stackadj")); \
845 assert(STACK_LEVEL() <= co->co_stacksize); }
846 #define EXT_POP(STACK_POINTER) ((void)(lltrace && \
847 prtrace((STACK_POINTER)[-1], "ext_pop")), \
850 #define PUSH(v) BASIC_PUSH(v)
851 #define POP() BASIC_POP()
852 #define STACKADJ(n) BASIC_STACKADJ(n)
853 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
856 /* Local variable macros */
858 #define GETLOCAL(i) (fastlocals[i])
860 /* The SETLOCAL() macro must not DECREF the local variable in-place and
861 then store the new value; it must copy the old value to a temporary
862 value, then store the new value, and then DECREF the temporary value.
863 This is because it is possible that during the DECREF the frame is
864 accessed by other code (e.g. a __del__ method or gc.collect()) and the
865 variable would be pointing to already-freed memory. */
866 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
867 GETLOCAL(i) = value; \
868 Py_XDECREF(tmp); } while (0)
876 if (Py_EnterRecursiveCall(""))
881 if (tstate
->use_tracing
) {
882 if (tstate
->c_tracefunc
!= NULL
) {
883 /* tstate->c_tracefunc, if defined, is a
884 function that will be called on *every* entry
885 to a code block. Its return value, if not
886 None, is a function that will be called at
887 the start of each executed line of code.
888 (Actually, the function must return itself
889 in order to continue tracing.) The trace
890 functions are called with three arguments:
891 a pointer to the current frame, a string
892 indicating why the function is called, and
893 an argument which depends on the situation.
894 The global trace function is also called
895 whenever an exception is detected. */
896 if (call_trace_protected(tstate
->c_tracefunc
,
898 f
, PyTrace_CALL
, Py_None
)) {
899 /* Trace function raised an error */
900 goto exit_eval_frame
;
903 if (tstate
->c_profilefunc
!= NULL
) {
904 /* Similar for c_profilefunc, except it needn't
905 return itself and isn't called for "line" events */
906 if (call_trace_protected(tstate
->c_profilefunc
,
907 tstate
->c_profileobj
,
908 f
, PyTrace_CALL
, Py_None
)) {
909 /* Profile function raised an error */
910 goto exit_eval_frame
;
916 names
= co
->co_names
;
917 consts
= co
->co_consts
;
918 fastlocals
= f
->f_localsplus
;
919 freevars
= f
->f_localsplus
+ co
->co_nlocals
;
920 first_instr
= (unsigned char*) PyString_AS_STRING(co
->co_code
);
921 /* An explanation is in order for the next line.
923 f->f_lasti now refers to the index of the last instruction
924 executed. You might think this was obvious from the name, but
925 this wasn't always true before 2.3! PyFrame_New now sets
926 f->f_lasti to -1 (i.e. the index *before* the first instruction)
927 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
930 When the PREDICT() macros are enabled, some opcode pairs follow in
931 direct succession without updating f->f_lasti. A successful
932 prediction effectively links the two codes together as if they
933 were a single new opcode; accordingly,f->f_lasti will point to
934 the first code in the pair (for instance, GET_ITER followed by
935 FOR_ITER is effectively a single opcode and f->f_lasti will point
936 at to the beginning of the combined pair.)
938 next_instr
= first_instr
+ f
->f_lasti
+ 1;
939 stack_pointer
= f
->f_stacktop
;
940 assert(stack_pointer
!= NULL
);
941 f
->f_stacktop
= NULL
; /* remains NULL unless yield suspends frame */
944 lltrace
= PyDict_GetItemString(f
->f_globals
, "__lltrace__") != NULL
;
946 #if defined(Py_DEBUG) || defined(LLTRACE)
947 filename
= PyString_AsString(co
->co_filename
);
952 x
= Py_None
; /* Not a reference, just anything non-NULL */
955 if (throwflag
) { /* support for generator.throw() */
963 /* Almost surely, the opcode executed a break
964 or a continue, preventing inst1 from being set
965 on the way out of the loop.
967 READ_TIMESTAMP(inst1
);
970 dump_tsc(opcode
, ticked
, inst0
, inst1
, loop0
, loop1
,
976 READ_TIMESTAMP(loop0
);
978 assert(stack_pointer
>= f
->f_valuestack
); /* else underflow */
979 assert(STACK_LEVEL() <= co
->co_stacksize
); /* else overflow */
981 /* Do periodic things. Doing this every time through
982 the loop would add too much overhead, so we do it
983 only every Nth instruction. We also do it if
984 ``pendingcalls_to_do'' is set, i.e. when an asynchronous
985 event needs attention (e.g. a signal handler or
986 async I/O handler); see Py_AddPendingCall() and
987 Py_MakePendingCalls() above. */
989 if (--_Py_Ticker
< 0) {
990 if (*next_instr
== SETUP_FINALLY
) {
991 /* Make the last opcode before
992 a try: finally: block uninterruptible. */
993 goto fast_next_opcode
;
995 _Py_Ticker
= _Py_CheckInterval
;
996 tstate
->tick_counter
++;
1000 if (pendingcalls_to_do
) {
1001 if (Py_MakePendingCalls() < 0) {
1002 why
= WHY_EXCEPTION
;
1005 if (pendingcalls_to_do
)
1006 /* MakePendingCalls() didn't succeed.
1007 Force early re-execution of this
1008 "periodic" code, possibly after
1013 if (interpreter_lock
) {
1014 /* Give another thread a chance */
1016 if (PyThreadState_Swap(NULL
) != tstate
)
1017 Py_FatalError("ceval: tstate mix-up");
1018 PyThread_release_lock(interpreter_lock
);
1020 /* Other threads may run now */
1022 PyThread_acquire_lock(interpreter_lock
, 1);
1024 if (PyThreadState_Swap(tstate
) != NULL
)
1025 Py_FatalError("ceval: orphan tstate");
1027 /* Check for thread interrupts */
1029 if (tstate
->async_exc
!= NULL
) {
1030 x
= tstate
->async_exc
;
1031 tstate
->async_exc
= NULL
;
1034 why
= WHY_EXCEPTION
;
1042 f
->f_lasti
= INSTR_OFFSET();
1044 /* line-by-line tracing support */
1046 if (_Py_TracingPossible
&&
1047 tstate
->c_tracefunc
!= NULL
&& !tstate
->tracing
) {
1048 /* see maybe_call_line_trace
1049 for expository comments */
1050 f
->f_stacktop
= stack_pointer
;
1052 err
= maybe_call_line_trace(tstate
->c_tracefunc
,
1054 f
, &instr_lb
, &instr_ub
,
1056 /* Reload possibly changed frame fields */
1058 if (f
->f_stacktop
!= NULL
) {
1059 stack_pointer
= f
->f_stacktop
;
1060 f
->f_stacktop
= NULL
;
1063 /* trace function raised an exception */
1068 /* Extract opcode and argument */
1071 oparg
= 0; /* allows oparg to be stored in a register because
1072 it doesn't have to be remembered across a full loop */
1073 if (HAS_ARG(opcode
))
1076 #ifdef DYNAMIC_EXECUTION_PROFILE
1078 dxpairs
[lastopcode
][opcode
]++;
1079 lastopcode
= opcode
;
1085 /* Instruction tracing */
1088 if (HAS_ARG(opcode
)) {
1089 printf("%d: %d, %d\n",
1090 f
->f_lasti
, opcode
, oparg
);
1094 f
->f_lasti
, opcode
);
1099 /* Main switch on opcode */
1100 READ_TIMESTAMP(inst0
);
1105 It is essential that any operation that fails sets either
1106 x to NULL, err to nonzero, or why to anything but WHY_NOT,
1107 and that no operation that succeeds does this! */
1109 /* case STOP_CODE: this is an error! */
1112 goto fast_next_opcode
;
1115 x
= GETLOCAL(oparg
);
1119 goto fast_next_opcode
;
1121 format_exc_check_arg(PyExc_UnboundLocalError
,
1122 UNBOUNDLOCAL_ERROR_MSG
,
1123 PyTuple_GetItem(co
->co_varnames
, oparg
));
1127 x
= GETITEM(consts
, oparg
);
1130 goto fast_next_opcode
;
1132 PREDICTED_WITH_ARG(STORE_FAST
);
1136 goto fast_next_opcode
;
1141 goto fast_next_opcode
;
1148 goto fast_next_opcode
;
1157 goto fast_next_opcode
;
1168 goto fast_next_opcode
;
1174 goto fast_next_opcode
;
1185 goto fast_next_opcode
;
1186 } else if (oparg
== 3) {
1197 goto fast_next_opcode
;
1199 Py_FatalError("invalid argument to DUP_TOPX"
1200 " (bytecode corruption?)");
1201 /* Never returns, so don't bother to set why. */
1204 case UNARY_POSITIVE
:
1206 x
= PyNumber_Positive(v
);
1209 if (x
!= NULL
) continue;
1212 case UNARY_NEGATIVE
:
1214 x
= PyNumber_Negative(v
);
1217 if (x
!= NULL
) continue;
1222 err
= PyObject_IsTrue(v
);
1230 Py_INCREF(Py_False
);
1240 x
= PyObject_Repr(v
);
1243 if (x
!= NULL
) continue;
1248 x
= PyNumber_Invert(v
);
1251 if (x
!= NULL
) continue;
1257 x
= PyNumber_Power(v
, w
, Py_None
);
1261 if (x
!= NULL
) continue;
1264 case BINARY_MULTIPLY
:
1267 x
= PyNumber_Multiply(v
, w
);
1271 if (x
!= NULL
) continue;
1275 if (!_Py_QnewFlag
) {
1278 x
= PyNumber_Divide(v
, w
);
1282 if (x
!= NULL
) continue;
1285 /* -Qnew is in effect: fall through to
1286 BINARY_TRUE_DIVIDE */
1287 case BINARY_TRUE_DIVIDE
:
1290 x
= PyNumber_TrueDivide(v
, w
);
1294 if (x
!= NULL
) continue;
1297 case BINARY_FLOOR_DIVIDE
:
1300 x
= PyNumber_FloorDivide(v
, w
);
1304 if (x
!= NULL
) continue;
1310 if (PyString_CheckExact(v
))
1311 x
= PyString_Format(v
, w
);
1313 x
= PyNumber_Remainder(v
, w
);
1317 if (x
!= NULL
) continue;
1323 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1324 /* INLINE: int + int */
1325 register long a
, b
, i
;
1326 a
= PyInt_AS_LONG(v
);
1327 b
= PyInt_AS_LONG(w
);
1328 /* cast to avoid undefined behaviour
1330 i
= (long)((unsigned long)a
+ b
);
1331 if ((i
^a
) < 0 && (i
^b
) < 0)
1333 x
= PyInt_FromLong(i
);
1335 else if (PyString_CheckExact(v
) &&
1336 PyString_CheckExact(w
)) {
1337 x
= string_concatenate(v
, w
, f
, next_instr
);
1338 /* string_concatenate consumed the ref to v */
1339 goto skip_decref_vx
;
1343 x
= PyNumber_Add(v
, w
);
1349 if (x
!= NULL
) continue;
1352 case BINARY_SUBTRACT
:
1355 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1356 /* INLINE: int - int */
1357 register long a
, b
, i
;
1358 a
= PyInt_AS_LONG(v
);
1359 b
= PyInt_AS_LONG(w
);
1360 /* cast to avoid undefined behaviour
1362 i
= (long)((unsigned long)a
- b
);
1363 if ((i
^a
) < 0 && (i
^~b
) < 0)
1365 x
= PyInt_FromLong(i
);
1369 x
= PyNumber_Subtract(v
, w
);
1374 if (x
!= NULL
) continue;
1380 if (PyList_CheckExact(v
) && PyInt_CheckExact(w
)) {
1381 /* INLINE: list[int] */
1382 Py_ssize_t i
= PyInt_AsSsize_t(w
);
1384 i
+= PyList_GET_SIZE(v
);
1385 if (i
>= 0 && i
< PyList_GET_SIZE(v
)) {
1386 x
= PyList_GET_ITEM(v
, i
);
1394 x
= PyObject_GetItem(v
, w
);
1398 if (x
!= NULL
) continue;
1404 x
= PyNumber_Lshift(v
, w
);
1408 if (x
!= NULL
) continue;
1414 x
= PyNumber_Rshift(v
, w
);
1418 if (x
!= NULL
) continue;
1424 x
= PyNumber_And(v
, w
);
1428 if (x
!= NULL
) continue;
1434 x
= PyNumber_Xor(v
, w
);
1438 if (x
!= NULL
) continue;
1444 x
= PyNumber_Or(v
, w
);
1448 if (x
!= NULL
) continue;
1454 err
= PyList_Append(v
, w
);
1457 PREDICT(JUMP_ABSOLUTE
);
1464 v
= stack_pointer
[-oparg
];
1465 err
= PySet_Add(v
, w
);
1468 PREDICT(JUMP_ABSOLUTE
);
1476 x
= PyNumber_InPlacePower(v
, w
, Py_None
);
1480 if (x
!= NULL
) continue;
1483 case INPLACE_MULTIPLY
:
1486 x
= PyNumber_InPlaceMultiply(v
, w
);
1490 if (x
!= NULL
) continue;
1493 case INPLACE_DIVIDE
:
1494 if (!_Py_QnewFlag
) {
1497 x
= PyNumber_InPlaceDivide(v
, w
);
1501 if (x
!= NULL
) continue;
1504 /* -Qnew is in effect: fall through to
1505 INPLACE_TRUE_DIVIDE */
1506 case INPLACE_TRUE_DIVIDE
:
1509 x
= PyNumber_InPlaceTrueDivide(v
, w
);
1513 if (x
!= NULL
) continue;
1516 case INPLACE_FLOOR_DIVIDE
:
1519 x
= PyNumber_InPlaceFloorDivide(v
, w
);
1523 if (x
!= NULL
) continue;
1526 case INPLACE_MODULO
:
1529 x
= PyNumber_InPlaceRemainder(v
, w
);
1533 if (x
!= NULL
) continue;
1539 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1540 /* INLINE: int + int */
1541 register long a
, b
, i
;
1542 a
= PyInt_AS_LONG(v
);
1543 b
= PyInt_AS_LONG(w
);
1545 if ((i
^a
) < 0 && (i
^b
) < 0)
1547 x
= PyInt_FromLong(i
);
1549 else if (PyString_CheckExact(v
) &&
1550 PyString_CheckExact(w
)) {
1551 x
= string_concatenate(v
, w
, f
, next_instr
);
1552 /* string_concatenate consumed the ref to v */
1557 x
= PyNumber_InPlaceAdd(v
, w
);
1563 if (x
!= NULL
) continue;
1566 case INPLACE_SUBTRACT
:
1569 if (PyInt_CheckExact(v
) && PyInt_CheckExact(w
)) {
1570 /* INLINE: int - int */
1571 register long a
, b
, i
;
1572 a
= PyInt_AS_LONG(v
);
1573 b
= PyInt_AS_LONG(w
);
1575 if ((i
^a
) < 0 && (i
^~b
) < 0)
1577 x
= PyInt_FromLong(i
);
1581 x
= PyNumber_InPlaceSubtract(v
, w
);
1586 if (x
!= NULL
) continue;
1589 case INPLACE_LSHIFT
:
1592 x
= PyNumber_InPlaceLshift(v
, w
);
1596 if (x
!= NULL
) continue;
1599 case INPLACE_RSHIFT
:
1602 x
= PyNumber_InPlaceRshift(v
, w
);
1606 if (x
!= NULL
) continue;
1612 x
= PyNumber_InPlaceAnd(v
, w
);
1616 if (x
!= NULL
) continue;
1622 x
= PyNumber_InPlaceXor(v
, w
);
1626 if (x
!= NULL
) continue;
1632 x
= PyNumber_InPlaceOr(v
, w
);
1636 if (x
!= NULL
) continue;
1643 if ((opcode
-SLICE
) & 2)
1647 if ((opcode
-SLICE
) & 1)
1652 x
= apply_slice(u
, v
, w
);
1657 if (x
!= NULL
) continue;
1664 if ((opcode
-STORE_SLICE
) & 2)
1668 if ((opcode
-STORE_SLICE
) & 1)
1674 err
= assign_slice(u
, v
, w
, t
); /* u[v:w] = t */
1679 if (err
== 0) continue;
1682 case DELETE_SLICE
+0:
1683 case DELETE_SLICE
+1:
1684 case DELETE_SLICE
+2:
1685 case DELETE_SLICE
+3:
1686 if ((opcode
-DELETE_SLICE
) & 2)
1690 if ((opcode
-DELETE_SLICE
) & 1)
1695 err
= assign_slice(u
, v
, w
, (PyObject
*)NULL
);
1700 if (err
== 0) continue;
1709 err
= PyObject_SetItem(v
, w
, u
);
1713 if (err
== 0) continue;
1721 err
= PyObject_DelItem(v
, w
);
1724 if (err
== 0) continue;
1729 w
= PySys_GetObject("displayhook");
1731 PyErr_SetString(PyExc_RuntimeError
,
1732 "lost sys.displayhook");
1737 x
= PyTuple_Pack(1, v
);
1742 w
= PyEval_CallObject(w
, x
);
1753 /* fall through to PRINT_ITEM */
1757 if (stream
== NULL
|| stream
== Py_None
) {
1758 w
= PySys_GetObject("stdout");
1760 PyErr_SetString(PyExc_RuntimeError
,
1765 /* PyFile_SoftSpace() can exececute arbitrary code
1766 if sys.stdout is an instance with a __getattr__.
1767 If __getattr__ raises an exception, w will
1768 be freed, so we need to prevent that temporarily. */
1770 if (w
!= NULL
&& PyFile_SoftSpace(w
, 0))
1771 err
= PyFile_WriteString(" ", w
);
1773 err
= PyFile_WriteObject(v
, w
, Py_PRINT_RAW
);
1775 /* XXX move into writeobject() ? */
1776 if (PyString_Check(v
)) {
1777 char *s
= PyString_AS_STRING(v
);
1778 Py_ssize_t len
= PyString_GET_SIZE(v
);
1780 !isspace(Py_CHARMASK(s
[len
-1])) ||
1782 PyFile_SoftSpace(w
, 1);
1784 #ifdef Py_USING_UNICODE
1785 else if (PyUnicode_Check(v
)) {
1786 Py_UNICODE
*s
= PyUnicode_AS_UNICODE(v
);
1787 Py_ssize_t len
= PyUnicode_GET_SIZE(v
);
1789 !Py_UNICODE_ISSPACE(s
[len
-1]) ||
1791 PyFile_SoftSpace(w
, 1);
1795 PyFile_SoftSpace(w
, 1);
1805 case PRINT_NEWLINE_TO
:
1807 /* fall through to PRINT_NEWLINE */
1810 if (stream
== NULL
|| stream
== Py_None
) {
1811 w
= PySys_GetObject("stdout");
1813 PyErr_SetString(PyExc_RuntimeError
,
1815 why
= WHY_EXCEPTION
;
1819 /* w.write() may replace sys.stdout, so we
1820 * have to keep our reference to it */
1822 err
= PyFile_WriteString("\n", w
);
1824 PyFile_SoftSpace(w
, 0);
1833 default: switch (opcode
) {
1839 u
= POP(); /* traceback */
1842 v
= POP(); /* value */
1845 w
= POP(); /* exc */
1846 case 0: /* Fallthrough */
1847 why
= do_raise(w
, v
, u
);
1850 PyErr_SetString(PyExc_SystemError
,
1851 "bad RAISE_VARARGS oparg");
1852 why
= WHY_EXCEPTION
;
1858 if ((x
= f
->f_locals
) != NULL
) {
1863 PyErr_SetString(PyExc_SystemError
, "no locals");
1869 goto fast_block_end
;
1873 f
->f_stacktop
= stack_pointer
;
1882 READ_TIMESTAMP(intr0
);
1883 err
= exec_statement(f
, u
, v
, w
);
1884 READ_TIMESTAMP(intr1
);
1892 PyTryBlock
*b
= PyFrame_BlockPop(f
);
1893 while (STACK_LEVEL() > b
->b_level
) {
1900 PREDICTED(END_FINALLY
);
1903 if (PyInt_Check(v
)) {
1904 why
= (enum why_code
) PyInt_AS_LONG(v
);
1905 assert(why
!= WHY_YIELD
);
1906 if (why
== WHY_RETURN
||
1907 why
== WHY_CONTINUE
)
1910 else if (PyExceptionClass_Check(v
) ||
1911 PyString_Check(v
)) {
1914 PyErr_Restore(v
, w
, u
);
1918 else if (v
!= Py_None
) {
1919 PyErr_SetString(PyExc_SystemError
,
1920 "'finally' pops bad exception");
1921 why
= WHY_EXCEPTION
;
1931 x
= build_class(u
, v
, w
);
1939 w
= GETITEM(names
, oparg
);
1941 if ((x
= f
->f_locals
) != NULL
) {
1942 if (PyDict_CheckExact(x
))
1943 err
= PyDict_SetItem(x
, w
, v
);
1945 err
= PyObject_SetItem(x
, w
, v
);
1947 if (err
== 0) continue;
1950 t
= PyObject_Repr(w
);
1953 PyErr_Format(PyExc_SystemError
,
1954 "no locals found when storing %s",
1955 PyString_AS_STRING(t
));
1960 w
= GETITEM(names
, oparg
);
1961 if ((x
= f
->f_locals
) != NULL
) {
1962 if ((err
= PyObject_DelItem(x
, w
)) != 0)
1963 format_exc_check_arg(PyExc_NameError
,
1968 t
= PyObject_Repr(w
);
1971 PyErr_Format(PyExc_SystemError
,
1972 "no locals when deleting %s",
1973 PyString_AS_STRING(w
));
1977 PREDICTED_WITH_ARG(UNPACK_SEQUENCE
);
1978 case UNPACK_SEQUENCE
:
1980 if (PyTuple_CheckExact(v
) &&
1981 PyTuple_GET_SIZE(v
) == oparg
) {
1982 PyObject
**items
= \
1983 ((PyTupleObject
*)v
)->ob_item
;
1991 } else if (PyList_CheckExact(v
) &&
1992 PyList_GET_SIZE(v
) == oparg
) {
1993 PyObject
**items
= \
1994 ((PyListObject
*)v
)->ob_item
;
2000 } else if (unpack_iterable(v
, oparg
,
2001 stack_pointer
+ oparg
)) {
2004 /* unpack_iterable() raised an exception */
2005 why
= WHY_EXCEPTION
;
2011 w
= GETITEM(names
, oparg
);
2015 err
= PyObject_SetAttr(v
, w
, u
); /* v.w = u */
2018 if (err
== 0) continue;
2022 w
= GETITEM(names
, oparg
);
2024 err
= PyObject_SetAttr(v
, w
, (PyObject
*)NULL
);
2030 w
= GETITEM(names
, oparg
);
2032 err
= PyDict_SetItem(f
->f_globals
, w
, v
);
2034 if (err
== 0) continue;
2038 w
= GETITEM(names
, oparg
);
2039 if ((err
= PyDict_DelItem(f
->f_globals
, w
)) != 0)
2040 format_exc_check_arg(
2041 PyExc_NameError
, GLOBAL_NAME_ERROR_MSG
, w
);
2045 w
= GETITEM(names
, oparg
);
2046 if ((v
= f
->f_locals
) == NULL
) {
2047 why
= WHY_EXCEPTION
;
2048 t
= PyObject_Repr(w
);
2051 PyErr_Format(PyExc_SystemError
,
2052 "no locals when loading %s",
2053 PyString_AS_STRING(w
));
2057 if (PyDict_CheckExact(v
)) {
2058 x
= PyDict_GetItem(v
, w
);
2062 x
= PyObject_GetItem(v
, w
);
2063 if (x
== NULL
&& PyErr_Occurred()) {
2064 if (!PyErr_ExceptionMatches(
2071 x
= PyDict_GetItem(f
->f_globals
, w
);
2073 x
= PyDict_GetItem(f
->f_builtins
, w
);
2075 format_exc_check_arg(
2087 w
= GETITEM(names
, oparg
);
2088 if (PyString_CheckExact(w
)) {
2089 /* Inline the PyDict_GetItem() calls.
2090 WARNING: this is an extreme speed hack.
2091 Do not try this at home. */
2092 long hash
= ((PyStringObject
*)w
)->ob_shash
;
2096 d
= (PyDictObject
*)(f
->f_globals
);
2097 e
= d
->ma_lookup(d
, w
, hash
);
2108 d
= (PyDictObject
*)(f
->f_builtins
);
2109 e
= d
->ma_lookup(d
, w
, hash
);
2120 goto load_global_error
;
2123 /* This is the un-inlined version of the code above */
2124 x
= PyDict_GetItem(f
->f_globals
, w
);
2126 x
= PyDict_GetItem(f
->f_builtins
, w
);
2129 format_exc_check_arg(
2131 GLOBAL_NAME_ERROR_MSG
, w
);
2140 x
= GETLOCAL(oparg
);
2142 SETLOCAL(oparg
, NULL
);
2145 format_exc_check_arg(
2146 PyExc_UnboundLocalError
,
2147 UNBOUNDLOCAL_ERROR_MSG
,
2148 PyTuple_GetItem(co
->co_varnames
, oparg
)
2153 x
= freevars
[oparg
];
2156 if (x
!= NULL
) continue;
2160 x
= freevars
[oparg
];
2167 /* Don't stomp existing exception */
2168 if (PyErr_Occurred())
2170 if (oparg
< PyTuple_GET_SIZE(co
->co_cellvars
)) {
2171 v
= PyTuple_GET_ITEM(co
->co_cellvars
,
2173 format_exc_check_arg(
2174 PyExc_UnboundLocalError
,
2175 UNBOUNDLOCAL_ERROR_MSG
,
2178 v
= PyTuple_GET_ITEM(co
->co_freevars
, oparg
-
2179 PyTuple_GET_SIZE(co
->co_cellvars
));
2180 format_exc_check_arg(PyExc_NameError
,
2181 UNBOUNDFREE_ERROR_MSG
, v
);
2187 x
= freevars
[oparg
];
2193 x
= PyTuple_New(oparg
);
2195 for (; --oparg
>= 0;) {
2197 PyTuple_SET_ITEM(x
, oparg
, w
);
2205 x
= PyList_New(oparg
);
2207 for (; --oparg
>= 0;) {
2209 PyList_SET_ITEM(x
, oparg
, w
);
2217 x
= PySet_New(NULL
);
2219 for (; --oparg
>= 0;) {
2222 err
= PySet_Add(x
, w
);
2236 x
= _PyDict_NewPresized((Py_ssize_t
)oparg
);
2238 if (x
!= NULL
) continue;
2242 w
= TOP(); /* key */
2243 u
= SECOND(); /* value */
2244 v
= THIRD(); /* dict */
2246 assert (PyDict_CheckExact(v
));
2247 err
= PyDict_SetItem(v
, w
, u
); /* v[w] = u */
2250 if (err
== 0) continue;
2254 w
= TOP(); /* key */
2255 u
= SECOND(); /* value */
2257 v
= stack_pointer
[-oparg
]; /* dict */
2258 assert (PyDict_CheckExact(v
));
2259 err
= PyDict_SetItem(v
, w
, u
); /* v[w] = u */
2263 PREDICT(JUMP_ABSOLUTE
);
2269 w
= GETITEM(names
, oparg
);
2271 x
= PyObject_GetAttr(v
, w
);
2274 if (x
!= NULL
) continue;
2280 if (PyInt_CheckExact(w
) && PyInt_CheckExact(v
)) {
2281 /* INLINE: cmp(int, int) */
2284 a
= PyInt_AS_LONG(v
);
2285 b
= PyInt_AS_LONG(w
);
2287 case PyCmp_LT
: res
= a
< b
; break;
2288 case PyCmp_LE
: res
= a
<= b
; break;
2289 case PyCmp_EQ
: res
= a
== b
; break;
2290 case PyCmp_NE
: res
= a
!= b
; break;
2291 case PyCmp_GT
: res
= a
> b
; break;
2292 case PyCmp_GE
: res
= a
>= b
; break;
2293 case PyCmp_IS
: res
= v
== w
; break;
2294 case PyCmp_IS_NOT
: res
= v
!= w
; break;
2295 default: goto slow_compare
;
2297 x
= res
? Py_True
: Py_False
;
2302 x
= cmp_outcome(oparg
, v
, w
);
2307 if (x
== NULL
) break;
2308 PREDICT(POP_JUMP_IF_FALSE
);
2309 PREDICT(POP_JUMP_IF_TRUE
);
2313 w
= GETITEM(names
, oparg
);
2314 x
= PyDict_GetItemString(f
->f_builtins
, "__import__");
2316 PyErr_SetString(PyExc_ImportError
,
2317 "__import__ not found");
2323 if (PyInt_AsLong(u
) != -1 || PyErr_Occurred())
2327 f
->f_locals
== NULL
?
2328 Py_None
: f
->f_locals
,
2335 f
->f_locals
== NULL
?
2336 Py_None
: f
->f_locals
,
2346 READ_TIMESTAMP(intr0
);
2348 x
= PyEval_CallObject(v
, w
);
2350 READ_TIMESTAMP(intr1
);
2353 if (x
!= NULL
) continue;
2358 PyFrame_FastToLocals(f
);
2359 if ((x
= f
->f_locals
) == NULL
) {
2360 PyErr_SetString(PyExc_SystemError
,
2361 "no locals found during 'import *'");
2364 READ_TIMESTAMP(intr0
);
2365 err
= import_all_from(x
, v
);
2366 READ_TIMESTAMP(intr1
);
2367 PyFrame_LocalsToFast(f
, 0);
2369 if (err
== 0) continue;
2373 w
= GETITEM(names
, oparg
);
2375 READ_TIMESTAMP(intr0
);
2376 x
= import_from(v
, w
);
2377 READ_TIMESTAMP(intr1
);
2379 if (x
!= NULL
) continue;
2384 goto fast_next_opcode
;
2386 PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE
);
2387 case POP_JUMP_IF_FALSE
:
2391 goto fast_next_opcode
;
2393 if (w
== Py_False
) {
2396 goto fast_next_opcode
;
2398 err
= PyObject_IsTrue(w
);
2408 PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE
);
2409 case POP_JUMP_IF_TRUE
:
2411 if (w
== Py_False
) {
2413 goto fast_next_opcode
;
2418 goto fast_next_opcode
;
2420 err
= PyObject_IsTrue(w
);
2432 case JUMP_IF_FALSE_OR_POP
:
2437 goto fast_next_opcode
;
2439 if (w
== Py_False
) {
2441 goto fast_next_opcode
;
2443 err
= PyObject_IsTrue(w
);
2455 case JUMP_IF_TRUE_OR_POP
:
2457 if (w
== Py_False
) {
2460 goto fast_next_opcode
;
2464 goto fast_next_opcode
;
2466 err
= PyObject_IsTrue(w
);
2471 else if (err
== 0) {
2479 PREDICTED_WITH_ARG(JUMP_ABSOLUTE
);
2483 /* Enabling this path speeds-up all while and for-loops by bypassing
2484 the per-loop checks for signals. By default, this should be turned-off
2485 because it prevents detection of a control-break in tight loops like
2486 "while 1: pass". Compile with this option turned-on when you need
2487 the speed-up and do not need break checking inside tight loops (ones
2488 that contain only instructions ending with goto fast_next_opcode).
2490 goto fast_next_opcode
;
2496 /* before: [obj]; after [getiter(obj)] */
2498 x
= PyObject_GetIter(v
);
2508 PREDICTED_WITH_ARG(FOR_ITER
);
2510 /* before: [iter]; after: [iter, iter()] *or* [] */
2512 x
= (*v
->ob_type
->tp_iternext
)(v
);
2515 PREDICT(STORE_FAST
);
2516 PREDICT(UNPACK_SEQUENCE
);
2519 if (PyErr_Occurred()) {
2520 if (!PyErr_ExceptionMatches(
2521 PyExc_StopIteration
))
2525 /* iterator ended normally */
2533 goto fast_block_end
;
2536 retval
= PyInt_FromLong(oparg
);
2542 goto fast_block_end
;
2547 /* NOTE: If you add any new block-setup opcodes that
2548 are not try/except/finally handlers, you may need
2549 to update the PyGen_NeedsFinalizing() function.
2552 PyFrame_BlockSetup(f
, opcode
, INSTR_OFFSET() + oparg
,
2558 static PyObject
*exit
, *enter
;
2560 x
= special_lookup(w
, "__exit__", &exit
);
2564 u
= special_lookup(w
, "__enter__", &enter
);
2570 x
= PyObject_CallFunctionObjArgs(u
, NULL
);
2574 /* Setup a finally block (SETUP_WITH as a block is
2575 equivalent to SETUP_FINALLY except it normalizes
2576 the exception) before pushing the result of
2577 __enter__ on the stack. */
2578 PyFrame_BlockSetup(f
, SETUP_WITH
, INSTR_OFFSET() + oparg
,
2587 /* At the top of the stack are 1-3 values indicating
2588 how/why we entered the finally clause:
2590 - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
2591 - TOP = WHY_*; no retval below it
2592 - (TOP, SECOND, THIRD) = exc_info()
2593 Below them is EXIT, the context.__exit__ bound method.
2594 In the last case, we must call
2595 EXIT(TOP, SECOND, THIRD)
2596 otherwise we must call
2597 EXIT(None, None, None)
2599 In all cases, we remove EXIT from the stack, leaving
2600 the rest in the same order.
2602 In addition, if the stack represents an exception,
2603 *and* the function call returns a 'true' value, we
2604 "zap" this information, to prevent END_FINALLY from
2605 re-raising the exception. (But non-local gotos
2606 should still be resumed.)
2609 PyObject
*exit_func
;
2617 else if (PyInt_Check(u
)) {
2618 switch(PyInt_AS_LONG(u
)) {
2621 /* Retval in TOP. */
2622 exit_func
= SECOND();
2631 u
= v
= w
= Py_None
;
2636 exit_func
= THIRD();
2641 /* XXX Not the fastest way to call it... */
2642 x
= PyObject_CallFunctionObjArgs(exit_func
, u
, v
, w
,
2644 Py_DECREF(exit_func
);
2646 break; /* Go to error exit */
2649 err
= PyObject_IsTrue(x
);
2655 break; /* Go to error exit */
2658 /* There was an exception and a true return */
2666 /* The stack was rearranged to remove EXIT
2667 above. Let END_FINALLY do its thing */
2669 PREDICT(END_FINALLY
);
2679 x
= call_function(&sp
, oparg
, &intr0
, &intr1
);
2681 x
= call_function(&sp
, oparg
);
2690 case CALL_FUNCTION_VAR
:
2691 case CALL_FUNCTION_KW
:
2692 case CALL_FUNCTION_VAR_KW
:
2694 int na
= oparg
& 0xff;
2695 int nk
= (oparg
>>8) & 0xff;
2696 int flags
= (opcode
- CALL_FUNCTION
) & 3;
2697 int n
= na
+ 2 * nk
;
2698 PyObject
**pfunc
, *func
, **sp
;
2700 if (flags
& CALL_FLAG_VAR
)
2702 if (flags
& CALL_FLAG_KW
)
2704 pfunc
= stack_pointer
- n
- 1;
2707 if (PyMethod_Check(func
)
2708 && PyMethod_GET_SELF(func
) != NULL
) {
2709 PyObject
*self
= PyMethod_GET_SELF(func
);
2711 func
= PyMethod_GET_FUNCTION(func
);
2719 READ_TIMESTAMP(intr0
);
2720 x
= ext_do_call(func
, &sp
, flags
, na
, nk
);
2721 READ_TIMESTAMP(intr1
);
2725 while (stack_pointer
> pfunc
) {
2736 v
= POP(); /* code object */
2737 x
= PyFunction_New(v
, f
->f_globals
);
2739 /* XXX Maybe this should be a separate opcode? */
2740 if (x
!= NULL
&& oparg
> 0) {
2741 v
= PyTuple_New(oparg
);
2747 while (--oparg
>= 0) {
2749 PyTuple_SET_ITEM(v
, oparg
, w
);
2751 err
= PyFunction_SetDefaults(x
, v
);
2759 v
= POP(); /* code object */
2760 x
= PyFunction_New(v
, f
->f_globals
);
2764 if (PyFunction_SetClosure(x
, v
) != 0) {
2765 /* Can't happen unless bytecode is corrupt. */
2766 why
= WHY_EXCEPTION
;
2770 if (x
!= NULL
&& oparg
> 0) {
2771 v
= PyTuple_New(oparg
);
2777 while (--oparg
>= 0) {
2779 PyTuple_SET_ITEM(v
, oparg
, w
);
2781 if (PyFunction_SetDefaults(x
, v
) != 0) {
2782 /* Can't happen unless
2783 PyFunction_SetDefaults changes. */
2784 why
= WHY_EXCEPTION
;
2799 x
= PySlice_New(u
, v
, w
);
2804 if (x
!= NULL
) continue;
2809 oparg
= oparg
<<16 | NEXTARG();
2810 goto dispatch_opcode
;
2814 "XXX lineno: %d, opcode: %d\n",
2815 PyFrame_GetLineNumber(f
),
2817 PyErr_SetString(PyExc_SystemError
, "unknown opcode");
2818 why
= WHY_EXCEPTION
;
2829 READ_TIMESTAMP(inst1
);
2831 /* Quickly continue if no error occurred */
2833 if (why
== WHY_NOT
) {
2834 if (err
== 0 && x
!= NULL
) {
2836 /* This check is expensive! */
2837 if (PyErr_Occurred())
2839 "XXX undetected error\n");
2842 READ_TIMESTAMP(loop1
);
2843 continue; /* Normal, fast path */
2848 why
= WHY_EXCEPTION
;
2853 /* Double-check exception status */
2855 if (why
== WHY_EXCEPTION
|| why
== WHY_RERAISE
) {
2856 if (!PyErr_Occurred()) {
2857 PyErr_SetString(PyExc_SystemError
,
2858 "error return without exception set");
2859 why
= WHY_EXCEPTION
;
2864 /* This check is expensive! */
2865 if (PyErr_Occurred()) {
2867 sprintf(buf
, "Stack unwind with exception "
2868 "set and why=%d", why
);
2874 /* Log traceback info if this is a real exception */
2876 if (why
== WHY_EXCEPTION
) {
2877 PyTraceBack_Here(f
);
2879 if (tstate
->c_tracefunc
!= NULL
)
2880 call_exc_trace(tstate
->c_tracefunc
,
2881 tstate
->c_traceobj
, f
);
2884 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2886 if (why
== WHY_RERAISE
)
2887 why
= WHY_EXCEPTION
;
2889 /* Unwind stacks if a (pseudo) exception occurred */
2892 while (why
!= WHY_NOT
&& f
->f_iblock
> 0) {
2893 /* Peek at the current block. */
2894 PyTryBlock
*b
= &f
->f_blockstack
[f
->f_iblock
- 1];
2896 assert(why
!= WHY_YIELD
);
2897 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_CONTINUE
) {
2899 JUMPTO(PyInt_AS_LONG(retval
));
2904 /* Now we have to pop the block. */
2907 while (STACK_LEVEL() > b
->b_level
) {
2911 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_BREAK
) {
2913 JUMPTO(b
->b_handler
);
2916 if (b
->b_type
== SETUP_FINALLY
||
2917 (b
->b_type
== SETUP_EXCEPT
&&
2918 why
== WHY_EXCEPTION
) ||
2919 b
->b_type
== SETUP_WITH
) {
2920 if (why
== WHY_EXCEPTION
) {
2921 PyObject
*exc
, *val
, *tb
;
2922 PyErr_Fetch(&exc
, &val
, &tb
);
2927 /* Make the raw exception data
2928 available to the handler,
2929 so a program can emulate the
2930 Python main loop. Don't do
2931 this for 'finally'. */
2932 if (b
->b_type
== SETUP_EXCEPT
||
2933 b
->b_type
== SETUP_WITH
) {
2934 PyErr_NormalizeException(
2936 set_exc_info(tstate
,
2948 if (why
& (WHY_RETURN
| WHY_CONTINUE
))
2950 v
= PyInt_FromLong((long)why
);
2954 JUMPTO(b
->b_handler
);
2957 } /* unwind stack */
2959 /* End the loop if we still have an error (or return) */
2963 READ_TIMESTAMP(loop1
);
2967 assert(why
!= WHY_YIELD
);
2968 /* Pop remaining stack entries. */
2974 if (why
!= WHY_RETURN
)
2978 if (tstate
->use_tracing
) {
2979 if (tstate
->c_tracefunc
) {
2980 if (why
== WHY_RETURN
|| why
== WHY_YIELD
) {
2981 if (call_trace(tstate
->c_tracefunc
,
2982 tstate
->c_traceobj
, f
,
2983 PyTrace_RETURN
, retval
)) {
2986 why
= WHY_EXCEPTION
;
2989 else if (why
== WHY_EXCEPTION
) {
2990 call_trace_protected(tstate
->c_tracefunc
,
2991 tstate
->c_traceobj
, f
,
2992 PyTrace_RETURN
, NULL
);
2995 if (tstate
->c_profilefunc
) {
2996 if (why
== WHY_EXCEPTION
)
2997 call_trace_protected(tstate
->c_profilefunc
,
2998 tstate
->c_profileobj
, f
,
2999 PyTrace_RETURN
, NULL
);
3000 else if (call_trace(tstate
->c_profilefunc
,
3001 tstate
->c_profileobj
, f
,
3002 PyTrace_RETURN
, retval
)) {
3005 why
= WHY_EXCEPTION
;
3010 if (tstate
->frame
->f_exc_type
!= NULL
)
3011 reset_exc_info(tstate
);
3013 assert(tstate
->frame
->f_exc_value
== NULL
);
3014 assert(tstate
->frame
->f_exc_traceback
== NULL
);
3019 Py_LeaveRecursiveCall();
3020 tstate
->frame
= f
->f_back
;
3025 /* This is gonna seem *real weird*, but if you put some other code between
3026 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
3027 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
3030 PyEval_EvalCodeEx(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
,
3031 PyObject
**args
, int argcount
, PyObject
**kws
, int kwcount
,
3032 PyObject
**defs
, int defcount
, PyObject
*closure
)
3034 register PyFrameObject
*f
;
3035 register PyObject
*retval
= NULL
;
3036 register PyObject
**fastlocals
, **freevars
;
3037 PyThreadState
*tstate
= PyThreadState_GET();
3040 if (globals
== NULL
) {
3041 PyErr_SetString(PyExc_SystemError
,
3042 "PyEval_EvalCodeEx: NULL globals");
3046 assert(tstate
!= NULL
);
3047 assert(globals
!= NULL
);
3048 f
= PyFrame_New(tstate
, co
, globals
, locals
);
3052 fastlocals
= f
->f_localsplus
;
3053 freevars
= f
->f_localsplus
+ co
->co_nlocals
;
3055 if (co
->co_argcount
> 0 ||
3056 co
->co_flags
& (CO_VARARGS
| CO_VARKEYWORDS
)) {
3059 PyObject
*kwdict
= NULL
;
3060 if (co
->co_flags
& CO_VARKEYWORDS
) {
3061 kwdict
= PyDict_New();
3064 i
= co
->co_argcount
;
3065 if (co
->co_flags
& CO_VARARGS
)
3067 SETLOCAL(i
, kwdict
);
3069 if (argcount
> co
->co_argcount
) {
3070 if (!(co
->co_flags
& CO_VARARGS
)) {
3071 PyErr_Format(PyExc_TypeError
,
3072 "%.200s() takes %s %d "
3073 "argument%s (%d given)",
3074 PyString_AsString(co
->co_name
),
3075 defcount
? "at most" : "exactly",
3077 co
->co_argcount
== 1 ? "" : "s",
3078 argcount
+ kwcount
);
3081 n
= co
->co_argcount
;
3083 for (i
= 0; i
< n
; i
++) {
3088 if (co
->co_flags
& CO_VARARGS
) {
3089 u
= PyTuple_New(argcount
- n
);
3092 SETLOCAL(co
->co_argcount
, u
);
3093 for (i
= n
; i
< argcount
; i
++) {
3096 PyTuple_SET_ITEM(u
, i
-n
, x
);
3099 for (i
= 0; i
< kwcount
; i
++) {
3100 PyObject
**co_varnames
;
3101 PyObject
*keyword
= kws
[2*i
];
3102 PyObject
*value
= kws
[2*i
+ 1];
3104 if (keyword
== NULL
|| !(PyString_Check(keyword
)
3105 #ifdef Py_USING_UNICODE
3106 || PyUnicode_Check(keyword
)
3109 PyErr_Format(PyExc_TypeError
,
3110 "%.200s() keywords must be strings",
3111 PyString_AsString(co
->co_name
));
3114 /* Speed hack: do raw pointer compares. As names are
3115 normally interned this should almost always hit. */
3116 co_varnames
= ((PyTupleObject
*)(co
->co_varnames
))->ob_item
;
3117 for (j
= 0; j
< co
->co_argcount
; j
++) {
3118 PyObject
*nm
= co_varnames
[j
];
3122 /* Slow fallback, just in case */
3123 for (j
= 0; j
< co
->co_argcount
; j
++) {
3124 PyObject
*nm
= co_varnames
[j
];
3125 int cmp
= PyObject_RichCompareBool(
3126 keyword
, nm
, Py_EQ
);
3132 if (kwdict
== NULL
) {
3133 PyObject
*kwd_str
= kwd_as_string(keyword
);
3135 PyErr_Format(PyExc_TypeError
,
3136 "%.200s() got an unexpected "
3137 "keyword argument '%.400s'",
3138 PyString_AsString(co
->co_name
),
3139 PyString_AsString(kwd_str
));
3144 PyDict_SetItem(kwdict
, keyword
, value
);
3147 if (GETLOCAL(j
) != NULL
) {
3148 PyObject
*kwd_str
= kwd_as_string(keyword
);
3150 PyErr_Format(PyExc_TypeError
,
3151 "%.200s() got multiple "
3152 "values for keyword "
3153 "argument '%.400s'",
3154 PyString_AsString(co
->co_name
),
3155 PyString_AsString(kwd_str
));
3163 if (argcount
< co
->co_argcount
) {
3164 int m
= co
->co_argcount
- defcount
;
3165 for (i
= argcount
; i
< m
; i
++) {
3166 if (GETLOCAL(i
) == NULL
) {
3168 for (j
= 0; j
< co
->co_argcount
; j
++)
3171 PyErr_Format(PyExc_TypeError
,
3172 "%.200s() takes %s %d "
3173 "argument%s (%d given)",
3174 PyString_AsString(co
->co_name
),
3175 ((co
->co_flags
& CO_VARARGS
) ||
3176 defcount
) ? "at least"
3178 m
, m
== 1 ? "" : "s", given
);
3186 for (; i
< defcount
; i
++) {
3187 if (GETLOCAL(m
+i
) == NULL
) {
3188 PyObject
*def
= defs
[i
];
3195 else if (argcount
> 0 || kwcount
> 0) {
3196 PyErr_Format(PyExc_TypeError
,
3197 "%.200s() takes no arguments (%d given)",
3198 PyString_AsString(co
->co_name
),
3199 argcount
+ kwcount
);
3202 /* Allocate and initialize storage for cell vars, and copy free
3203 vars into frame. This isn't too efficient right now. */
3204 if (PyTuple_GET_SIZE(co
->co_cellvars
)) {
3205 int i
, j
, nargs
, found
;
3206 char *cellname
, *argname
;
3209 nargs
= co
->co_argcount
;
3210 if (co
->co_flags
& CO_VARARGS
)
3212 if (co
->co_flags
& CO_VARKEYWORDS
)
3215 /* Initialize each cell var, taking into account
3216 cell vars that are initialized from arguments.
3218 Should arrange for the compiler to put cellvars
3219 that are arguments at the beginning of the cellvars
3220 list so that we can march over it more efficiently?
3222 for (i
= 0; i
< PyTuple_GET_SIZE(co
->co_cellvars
); ++i
) {
3223 cellname
= PyString_AS_STRING(
3224 PyTuple_GET_ITEM(co
->co_cellvars
, i
));
3226 for (j
= 0; j
< nargs
; j
++) {
3227 argname
= PyString_AS_STRING(
3228 PyTuple_GET_ITEM(co
->co_varnames
, j
));
3229 if (strcmp(cellname
, argname
) == 0) {
3230 c
= PyCell_New(GETLOCAL(j
));
3233 GETLOCAL(co
->co_nlocals
+ i
) = c
;
3239 c
= PyCell_New(NULL
);
3242 SETLOCAL(co
->co_nlocals
+ i
, c
);
3246 if (PyTuple_GET_SIZE(co
->co_freevars
)) {
3248 for (i
= 0; i
< PyTuple_GET_SIZE(co
->co_freevars
); ++i
) {
3249 PyObject
*o
= PyTuple_GET_ITEM(closure
, i
);
3251 freevars
[PyTuple_GET_SIZE(co
->co_cellvars
) + i
] = o
;
3255 if (co
->co_flags
& CO_GENERATOR
) {
3256 /* Don't need to keep the reference to f_back, it will be set
3257 * when the generator is resumed. */
3258 Py_CLEAR(f
->f_back
);
3260 PCALL(PCALL_GENERATOR
);
3262 /* Create a new generator that owns the ready to run frame
3263 * and return that as the value. */
3264 return PyGen_New(f
);
3267 retval
= PyEval_EvalFrameEx(f
,0);
3269 fail
: /* Jump here from prelude on failure */
3271 /* decref'ing the frame can cause __del__ methods to get invoked,
3272 which can call back into Python. While we're done with the
3273 current Python frame (f), the associated C stack is still in use,
3274 so recursion_depth must be boosted for the duration.
3276 assert(tstate
!= NULL
);
3277 ++tstate
->recursion_depth
;
3279 --tstate
->recursion_depth
;
3285 special_lookup(PyObject
*o
, char *meth
, PyObject
**cache
)
3288 if (PyInstance_Check(o
)) {
3290 return PyObject_GetAttrString(o
, meth
);
3292 return PyObject_GetAttr(o
, *cache
);
3294 res
= _PyObject_LookupSpecial(o
, meth
, cache
);
3295 if (res
== NULL
&& !PyErr_Occurred()) {
3296 PyErr_SetObject(PyExc_AttributeError
, *cache
);
3304 kwd_as_string(PyObject
*kwd
) {
3305 #ifdef Py_USING_UNICODE
3306 if (PyString_Check(kwd
)) {
3308 assert(PyString_Check(kwd
));
3312 #ifdef Py_USING_UNICODE
3314 return _PyUnicode_AsDefaultEncodedString(kwd
, "replace");
3319 /* Implementation notes for set_exc_info() and reset_exc_info():
3321 - Below, 'exc_ZZZ' stands for 'exc_type', 'exc_value' and
3322 'exc_traceback'. These always travel together.
3324 - tstate->curexc_ZZZ is the "hot" exception that is set by
3325 PyErr_SetString(), cleared by PyErr_Clear(), and so on.
3327 - Once an exception is caught by an except clause, it is transferred
3328 from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info()
3329 can pick it up. This is the primary task of set_exc_info().
3330 XXX That can't be right: set_exc_info() doesn't look at tstate->curexc_ZZZ.
3332 - Now let me explain the complicated dance with frame->f_exc_ZZZ.
3334 Long ago, when none of this existed, there were just a few globals:
3335 one set corresponding to the "hot" exception, and one set
3336 corresponding to sys.exc_ZZZ. (Actually, the latter weren't C
3337 globals; they were simply stored as sys.exc_ZZZ. For backwards
3338 compatibility, they still are!) The problem was that in code like
3342 "something that may fail"
3343 except "some exception":
3344 "do something else first"
3345 "print the exception from sys.exc_ZZZ."
3347 if "do something else first" invoked something that raised and caught
3348 an exception, sys.exc_ZZZ were overwritten. That was a frequent
3349 cause of subtle bugs. I fixed this by changing the semantics as
3352 - Within one frame, sys.exc_ZZZ will hold the last exception caught
3355 - But initially, and as long as no exception is caught in a given
3356 frame, sys.exc_ZZZ will hold the last exception caught in the
3357 previous frame (or the frame before that, etc.).
3359 The first bullet fixed the bug in the above example. The second
3360 bullet was for backwards compatibility: it was (and is) common to
3361 have a function that is called when an exception is caught, and to
3362 have that function access the caught exception via sys.exc_ZZZ.
3363 (Example: traceback.print_exc()).
3365 At the same time I fixed the problem that sys.exc_ZZZ weren't
3366 thread-safe, by introducing sys.exc_info() which gets it from tstate;
3367 but that's really a separate improvement.
3369 The reset_exc_info() function in ceval.c restores the tstate->exc_ZZZ
3370 variables to what they were before the current frame was called. The
3371 set_exc_info() function saves them on the frame so that
3372 reset_exc_info() can restore them. The invariant is that
3373 frame->f_exc_ZZZ is NULL iff the current frame never caught an
3374 exception (where "catching" an exception applies only to successful
3375 except clauses); and if the current frame ever caught an exception,
3376 frame->f_exc_ZZZ is the exception that was stored in tstate->exc_ZZZ
3377 at the start of the current frame.
3382 set_exc_info(PyThreadState
*tstate
,
3383 PyObject
*type
, PyObject
*value
, PyObject
*tb
)
3385 PyFrameObject
*frame
= tstate
->frame
;
3386 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
3388 assert(type
!= NULL
);
3389 assert(frame
!= NULL
);
3390 if (frame
->f_exc_type
== NULL
) {
3391 assert(frame
->f_exc_value
== NULL
);
3392 assert(frame
->f_exc_traceback
== NULL
);
3393 /* This frame didn't catch an exception before. */
3394 /* Save previous exception of this thread in this frame. */
3395 if (tstate
->exc_type
== NULL
) {
3396 /* XXX Why is this set to Py_None? */
3398 tstate
->exc_type
= Py_None
;
3400 Py_INCREF(tstate
->exc_type
);
3401 Py_XINCREF(tstate
->exc_value
);
3402 Py_XINCREF(tstate
->exc_traceback
);
3403 frame
->f_exc_type
= tstate
->exc_type
;
3404 frame
->f_exc_value
= tstate
->exc_value
;
3405 frame
->f_exc_traceback
= tstate
->exc_traceback
;
3407 /* Set new exception for this thread. */
3408 tmp_type
= tstate
->exc_type
;
3409 tmp_value
= tstate
->exc_value
;
3410 tmp_tb
= tstate
->exc_traceback
;
3414 tstate
->exc_type
= type
;
3415 tstate
->exc_value
= value
;
3416 tstate
->exc_traceback
= tb
;
3417 Py_XDECREF(tmp_type
);
3418 Py_XDECREF(tmp_value
);
3420 /* For b/w compatibility */
3421 PySys_SetObject("exc_type", type
);
3422 PySys_SetObject("exc_value", value
);
3423 PySys_SetObject("exc_traceback", tb
);
3427 reset_exc_info(PyThreadState
*tstate
)
3429 PyFrameObject
*frame
;
3430 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
3432 /* It's a precondition that the thread state's frame caught an
3433 * exception -- verify in a debug build.
3435 assert(tstate
!= NULL
);
3436 frame
= tstate
->frame
;
3437 assert(frame
!= NULL
);
3438 assert(frame
->f_exc_type
!= NULL
);
3440 /* Copy the frame's exception info back to the thread state. */
3441 tmp_type
= tstate
->exc_type
;
3442 tmp_value
= tstate
->exc_value
;
3443 tmp_tb
= tstate
->exc_traceback
;
3444 Py_INCREF(frame
->f_exc_type
);
3445 Py_XINCREF(frame
->f_exc_value
);
3446 Py_XINCREF(frame
->f_exc_traceback
);
3447 tstate
->exc_type
= frame
->f_exc_type
;
3448 tstate
->exc_value
= frame
->f_exc_value
;
3449 tstate
->exc_traceback
= frame
->f_exc_traceback
;
3450 Py_XDECREF(tmp_type
);
3451 Py_XDECREF(tmp_value
);
3454 /* For b/w compatibility */
3455 PySys_SetObject("exc_type", frame
->f_exc_type
);
3456 PySys_SetObject("exc_value", frame
->f_exc_value
);
3457 PySys_SetObject("exc_traceback", frame
->f_exc_traceback
);
3459 /* Clear the frame's exception info. */
3460 tmp_type
= frame
->f_exc_type
;
3461 tmp_value
= frame
->f_exc_value
;
3462 tmp_tb
= frame
->f_exc_traceback
;
3463 frame
->f_exc_type
= NULL
;
3464 frame
->f_exc_value
= NULL
;
3465 frame
->f_exc_traceback
= NULL
;
3466 Py_DECREF(tmp_type
);
3467 Py_XDECREF(tmp_value
);
3471 /* Logic for the raise statement (too complicated for inlining).
3472 This *consumes* a reference count to each of its arguments. */
3473 static enum why_code
3474 do_raise(PyObject
*type
, PyObject
*value
, PyObject
*tb
)
3478 PyThreadState
*tstate
= PyThreadState_GET();
3479 type
= tstate
->exc_type
== NULL
? Py_None
: tstate
->exc_type
;
3480 value
= tstate
->exc_value
;
3481 tb
= tstate
->exc_traceback
;
3487 /* We support the following forms of raise:
3488 raise <class>, <classinstance>
3489 raise <class>, <argument tuple>
3491 raise <class>, <argument>
3492 raise <classinstance>, None
3493 raise <string>, <object>
3494 raise <string>, None
3496 An omitted second argument is the same as None.
3498 In addition, raise <tuple>, <anything> is the same as
3499 raising the tuple's first item (and it better have one!);
3500 this rule is applied recursively.
3502 Finally, an optional third argument can be supplied, which
3503 gives the traceback to be substituted (useful when
3504 re-raising an exception after examining it). */
3506 /* First, check the traceback argument, replacing None with
3508 if (tb
== Py_None
) {
3512 else if (tb
!= NULL
&& !PyTraceBack_Check(tb
)) {
3513 PyErr_SetString(PyExc_TypeError
,
3514 "raise: arg 3 must be a traceback or None");
3518 /* Next, replace a missing value with None */
3519 if (value
== NULL
) {
3524 /* Next, repeatedly, replace a tuple exception with its first item */
3525 while (PyTuple_Check(type
) && PyTuple_Size(type
) > 0) {
3526 PyObject
*tmp
= type
;
3527 type
= PyTuple_GET_ITEM(type
, 0);
3532 if (PyExceptionClass_Check(type
)) {
3533 PyErr_NormalizeException(&type
, &value
, &tb
);
3534 if (!PyExceptionInstance_Check(value
)) {
3535 PyErr_Format(PyExc_TypeError
,
3536 "calling %s() should have returned an instance of "
3537 "BaseException, not '%s'",
3538 ((PyTypeObject
*)type
)->tp_name
,
3539 Py_TYPE(value
)->tp_name
);
3543 else if (PyExceptionInstance_Check(type
)) {
3544 /* Raising an instance. The value should be a dummy. */
3545 if (value
!= Py_None
) {
3546 PyErr_SetString(PyExc_TypeError
,
3547 "instance exception may not have a separate value");
3551 /* Normalize to raise <class>, <instance> */
3554 type
= PyExceptionInstance_Class(type
);
3559 /* Not something you can raise. You get an exception
3560 anyway, just not what you specified :-) */
3561 PyErr_Format(PyExc_TypeError
,
3562 "exceptions must be old-style classes or "
3563 "derived from BaseException, not %s",
3564 type
->ob_type
->tp_name
);
3568 assert(PyExceptionClass_Check(type
));
3569 if (Py_Py3kWarningFlag
&& PyClass_Check(type
)) {
3570 if (PyErr_WarnEx(PyExc_DeprecationWarning
,
3571 "exceptions must derive from BaseException "
3576 PyErr_Restore(type
, value
, tb
);
3578 return WHY_EXCEPTION
;
3585 return WHY_EXCEPTION
;
3588 /* Iterate v argcnt times and store the results on the stack (via decreasing
3589 sp). Return 1 for success, 0 if error. */
3592 unpack_iterable(PyObject
*v
, int argcnt
, PyObject
**sp
)
3595 PyObject
*it
; /* iter(v) */
3600 it
= PyObject_GetIter(v
);
3604 for (; i
< argcnt
; i
++) {
3605 w
= PyIter_Next(it
);
3607 /* Iterator done, via error or exhaustion. */
3608 if (!PyErr_Occurred()) {
3609 PyErr_Format(PyExc_ValueError
,
3610 "need more than %d value%s to unpack",
3611 i
, i
== 1 ? "" : "s");
3618 /* We better have exhausted the iterator now. */
3619 w
= PyIter_Next(it
);
3621 if (PyErr_Occurred())
3627 PyErr_SetString(PyExc_ValueError
, "too many values to unpack");
3630 for (; i
> 0; i
--, sp
++)
3639 prtrace(PyObject
*v
, char *str
)
3642 if (PyObject_Print(v
, stdout
, 0) != 0)
3643 PyErr_Clear(); /* Don't know what else to do */
3650 call_exc_trace(Py_tracefunc func
, PyObject
*self
, PyFrameObject
*f
)
3652 PyObject
*type
, *value
, *traceback
, *arg
;
3654 PyErr_Fetch(&type
, &value
, &traceback
);
3655 if (value
== NULL
) {
3659 arg
= PyTuple_Pack(3, type
, value
, traceback
);
3661 PyErr_Restore(type
, value
, traceback
);
3664 err
= call_trace(func
, self
, f
, PyTrace_EXCEPTION
, arg
);
3667 PyErr_Restore(type
, value
, traceback
);
3671 Py_XDECREF(traceback
);
3676 call_trace_protected(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3677 int what
, PyObject
*arg
)
3679 PyObject
*type
, *value
, *traceback
;
3681 PyErr_Fetch(&type
, &value
, &traceback
);
3682 err
= call_trace(func
, obj
, frame
, what
, arg
);
3685 PyErr_Restore(type
, value
, traceback
);
3691 Py_XDECREF(traceback
);
3697 call_trace(Py_tracefunc func
, PyObject
*obj
, PyFrameObject
*frame
,
3698 int what
, PyObject
*arg
)
3700 register PyThreadState
*tstate
= frame
->f_tstate
;
3702 if (tstate
->tracing
)
3705 tstate
->use_tracing
= 0;
3706 result
= func(obj
, frame
, what
, arg
);
3707 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3708 || (tstate
->c_profilefunc
!= NULL
));
3714 _PyEval_CallTracing(PyObject
*func
, PyObject
*args
)
3716 PyFrameObject
*frame
= PyEval_GetFrame();
3717 PyThreadState
*tstate
= frame
->f_tstate
;
3718 int save_tracing
= tstate
->tracing
;
3719 int save_use_tracing
= tstate
->use_tracing
;
3722 tstate
->tracing
= 0;
3723 tstate
->use_tracing
= ((tstate
->c_tracefunc
!= NULL
)
3724 || (tstate
->c_profilefunc
!= NULL
));
3725 result
= PyObject_Call(func
, args
, NULL
);
3726 tstate
->tracing
= save_tracing
;
3727 tstate
->use_tracing
= save_use_tracing
;
3731 /* See Objects/lnotab_notes.txt for a description of how tracing works. */
3733 maybe_call_line_trace(Py_tracefunc func
, PyObject
*obj
,
3734 PyFrameObject
*frame
, int *instr_lb
, int *instr_ub
,
3738 int line
= frame
->f_lineno
;
3740 /* If the last instruction executed isn't in the current
3741 instruction window, reset the window.
3743 if (frame
->f_lasti
< *instr_lb
|| frame
->f_lasti
>= *instr_ub
) {
3745 line
= _PyCode_CheckLineNumber(frame
->f_code
, frame
->f_lasti
,
3747 *instr_lb
= bounds
.ap_lower
;
3748 *instr_ub
= bounds
.ap_upper
;
3750 /* If the last instruction falls at the start of a line or if
3751 it represents a jump backwards, update the frame's line
3752 number and call the trace function. */
3753 if (frame
->f_lasti
== *instr_lb
|| frame
->f_lasti
< *instr_prev
) {
3754 frame
->f_lineno
= line
;
3755 result
= call_trace(func
, obj
, frame
, PyTrace_LINE
, Py_None
);
3757 *instr_prev
= frame
->f_lasti
;
3762 PyEval_SetProfile(Py_tracefunc func
, PyObject
*arg
)
3764 PyThreadState
*tstate
= PyThreadState_GET();
3765 PyObject
*temp
= tstate
->c_profileobj
;
3767 tstate
->c_profilefunc
= NULL
;
3768 tstate
->c_profileobj
= NULL
;
3769 /* Must make sure that tracing is not ignored if 'temp' is freed */
3770 tstate
->use_tracing
= tstate
->c_tracefunc
!= NULL
;
3772 tstate
->c_profilefunc
= func
;
3773 tstate
->c_profileobj
= arg
;
3774 /* Flag that tracing or profiling is turned on */
3775 tstate
->use_tracing
= (func
!= NULL
) || (tstate
->c_tracefunc
!= NULL
);
3779 PyEval_SetTrace(Py_tracefunc func
, PyObject
*arg
)
3781 PyThreadState
*tstate
= PyThreadState_GET();
3782 PyObject
*temp
= tstate
->c_traceobj
;
3783 _Py_TracingPossible
+= (func
!= NULL
) - (tstate
->c_tracefunc
!= NULL
);
3785 tstate
->c_tracefunc
= NULL
;
3786 tstate
->c_traceobj
= NULL
;
3787 /* Must make sure that profiling is not ignored if 'temp' is freed */
3788 tstate
->use_tracing
= tstate
->c_profilefunc
!= NULL
;
3790 tstate
->c_tracefunc
= func
;
3791 tstate
->c_traceobj
= arg
;
3792 /* Flag that tracing or profiling is turned on */
3793 tstate
->use_tracing
= ((func
!= NULL
)
3794 || (tstate
->c_profilefunc
!= NULL
));
3798 PyEval_GetBuiltins(void)
3800 PyFrameObject
*current_frame
= PyEval_GetFrame();
3801 if (current_frame
== NULL
)
3802 return PyThreadState_GET()->interp
->builtins
;
3804 return current_frame
->f_builtins
;
3808 PyEval_GetLocals(void)
3810 PyFrameObject
*current_frame
= PyEval_GetFrame();
3811 if (current_frame
== NULL
)
3813 PyFrame_FastToLocals(current_frame
);
3814 return current_frame
->f_locals
;
3818 PyEval_GetGlobals(void)
3820 PyFrameObject
*current_frame
= PyEval_GetFrame();
3821 if (current_frame
== NULL
)
3824 return current_frame
->f_globals
;
3828 PyEval_GetFrame(void)
3830 PyThreadState
*tstate
= PyThreadState_GET();
3831 return _PyThreadState_GetFrame(tstate
);
3835 PyEval_GetRestricted(void)
3837 PyFrameObject
*current_frame
= PyEval_GetFrame();
3838 return current_frame
== NULL
? 0 : PyFrame_IsRestricted(current_frame
);
3842 PyEval_MergeCompilerFlags(PyCompilerFlags
*cf
)
3844 PyFrameObject
*current_frame
= PyEval_GetFrame();
3845 int result
= cf
->cf_flags
!= 0;
3847 if (current_frame
!= NULL
) {
3848 const int codeflags
= current_frame
->f_code
->co_flags
;
3849 const int compilerflags
= codeflags
& PyCF_MASK
;
3850 if (compilerflags
) {
3852 cf
->cf_flags
|= compilerflags
;
3854 #if 0 /* future keyword */
3855 if (codeflags
& CO_GENERATOR_ALLOWED
) {
3857 cf
->cf_flags
|= CO_GENERATOR_ALLOWED
;
3867 PyObject
*f
= PySys_GetObject("stdout");
3870 if (!PyFile_SoftSpace(f
, 0))
3872 return PyFile_WriteString("\n", f
);
3876 /* External interface to call any callable object.
3877 The arg must be a tuple or NULL. The kw must be a dict or NULL. */
3880 PyEval_CallObjectWithKeywords(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
3885 arg
= PyTuple_New(0);
3889 else if (!PyTuple_Check(arg
)) {
3890 PyErr_SetString(PyExc_TypeError
,
3891 "argument list must be a tuple");
3897 if (kw
!= NULL
&& !PyDict_Check(kw
)) {
3898 PyErr_SetString(PyExc_TypeError
,
3899 "keyword list must be a dictionary");
3904 result
= PyObject_Call(func
, arg
, kw
);
3910 PyEval_GetFuncName(PyObject
*func
)
3912 if (PyMethod_Check(func
))
3913 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func
));
3914 else if (PyFunction_Check(func
))
3915 return PyString_AsString(((PyFunctionObject
*)func
)->func_name
);
3916 else if (PyCFunction_Check(func
))
3917 return ((PyCFunctionObject
*)func
)->m_ml
->ml_name
;
3918 else if (PyClass_Check(func
))
3919 return PyString_AsString(((PyClassObject
*)func
)->cl_name
);
3920 else if (PyInstance_Check(func
)) {
3921 return PyString_AsString(
3922 ((PyInstanceObject
*)func
)->in_class
->cl_name
);
3924 return func
->ob_type
->tp_name
;
3929 PyEval_GetFuncDesc(PyObject
*func
)
3931 if (PyMethod_Check(func
))
3933 else if (PyFunction_Check(func
))
3935 else if (PyCFunction_Check(func
))
3937 else if (PyClass_Check(func
))
3938 return " constructor";
3939 else if (PyInstance_Check(func
)) {
3947 err_args(PyObject
*func
, int flags
, int nargs
)
3949 if (flags
& METH_NOARGS
)
3950 PyErr_Format(PyExc_TypeError
,
3951 "%.200s() takes no arguments (%d given)",
3952 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3955 PyErr_Format(PyExc_TypeError
,
3956 "%.200s() takes exactly one argument (%d given)",
3957 ((PyCFunctionObject
*)func
)->m_ml
->ml_name
,
3961 #define C_TRACE(x, call) \
3962 if (tstate->use_tracing && tstate->c_profilefunc) { \
3963 if (call_trace(tstate->c_profilefunc, \
3964 tstate->c_profileobj, \
3965 tstate->frame, PyTrace_C_CALL, \
3971 if (tstate->c_profilefunc != NULL) { \
3973 call_trace_protected(tstate->c_profilefunc, \
3974 tstate->c_profileobj, \
3975 tstate->frame, PyTrace_C_EXCEPTION, \
3977 /* XXX should pass (type, value, tb) */ \
3979 if (call_trace(tstate->c_profilefunc, \
3980 tstate->c_profileobj, \
3981 tstate->frame, PyTrace_C_RETURN, \
3994 call_function(PyObject
***pp_stack
, int oparg
3996 , uint64
* pintr0
, uint64
* pintr1
4000 int na
= oparg
& 0xff;
4001 int nk
= (oparg
>>8) & 0xff;
4002 int n
= na
+ 2 * nk
;
4003 PyObject
**pfunc
= (*pp_stack
) - n
- 1;
4004 PyObject
*func
= *pfunc
;
4007 /* Always dispatch PyCFunction first, because these are
4008 presumed to be the most frequent callable object.
4010 if (PyCFunction_Check(func
) && nk
== 0) {
4011 int flags
= PyCFunction_GET_FLAGS(func
);
4012 PyThreadState
*tstate
= PyThreadState_GET();
4014 PCALL(PCALL_CFUNCTION
);
4015 if (flags
& (METH_NOARGS
| METH_O
)) {
4016 PyCFunction meth
= PyCFunction_GET_FUNCTION(func
);
4017 PyObject
*self
= PyCFunction_GET_SELF(func
);
4018 if (flags
& METH_NOARGS
&& na
== 0) {
4019 C_TRACE(x
, (*meth
)(self
,NULL
));
4021 else if (flags
& METH_O
&& na
== 1) {
4022 PyObject
*arg
= EXT_POP(*pp_stack
);
4023 C_TRACE(x
, (*meth
)(self
,arg
));
4027 err_args(func
, flags
, na
);
4033 callargs
= load_args(pp_stack
, na
);
4034 READ_TIMESTAMP(*pintr0
);
4035 C_TRACE(x
, PyCFunction_Call(func
,callargs
,NULL
));
4036 READ_TIMESTAMP(*pintr1
);
4037 Py_XDECREF(callargs
);
4040 if (PyMethod_Check(func
) && PyMethod_GET_SELF(func
) != NULL
) {
4041 /* optimize access to bound methods */
4042 PyObject
*self
= PyMethod_GET_SELF(func
);
4043 PCALL(PCALL_METHOD
);
4044 PCALL(PCALL_BOUND_METHOD
);
4046 func
= PyMethod_GET_FUNCTION(func
);
4054 READ_TIMESTAMP(*pintr0
);
4055 if (PyFunction_Check(func
))
4056 x
= fast_function(func
, pp_stack
, n
, na
, nk
);
4058 x
= do_call(func
, pp_stack
, na
, nk
);
4059 READ_TIMESTAMP(*pintr1
);
4063 /* Clear the stack of the function object. Also removes
4064 the arguments in case they weren't consumed already
4065 (fast_function() and err_args() leave them on the stack).
4067 while ((*pp_stack
) > pfunc
) {
4068 w
= EXT_POP(*pp_stack
);
4075 /* The fast_function() function optimize calls for which no argument
4076 tuple is necessary; the objects are passed directly from the stack.
4077 For the simplest case -- a function that takes only positional
4078 arguments and is called with only positional arguments -- it
4079 inlines the most primitive frame setup code from
4080 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
4081 done before evaluating the frame.
4085 fast_function(PyObject
*func
, PyObject
***pp_stack
, int n
, int na
, int nk
)
4087 PyCodeObject
*co
= (PyCodeObject
*)PyFunction_GET_CODE(func
);
4088 PyObject
*globals
= PyFunction_GET_GLOBALS(func
);
4089 PyObject
*argdefs
= PyFunction_GET_DEFAULTS(func
);
4090 PyObject
**d
= NULL
;
4093 PCALL(PCALL_FUNCTION
);
4094 PCALL(PCALL_FAST_FUNCTION
);
4095 if (argdefs
== NULL
&& co
->co_argcount
== n
&& nk
==0 &&
4096 co
->co_flags
== (CO_OPTIMIZED
| CO_NEWLOCALS
| CO_NOFREE
)) {
4098 PyObject
*retval
= NULL
;
4099 PyThreadState
*tstate
= PyThreadState_GET();
4100 PyObject
**fastlocals
, **stack
;
4103 PCALL(PCALL_FASTER_FUNCTION
);
4104 assert(globals
!= NULL
);
4105 /* XXX Perhaps we should create a specialized
4106 PyFrame_New() that doesn't take locals, but does
4107 take builtins without sanity checking them.
4109 assert(tstate
!= NULL
);
4110 f
= PyFrame_New(tstate
, co
, globals
, NULL
);
4114 fastlocals
= f
->f_localsplus
;
4115 stack
= (*pp_stack
) - n
;
4117 for (i
= 0; i
< n
; i
++) {
4119 fastlocals
[i
] = *stack
++;
4121 retval
= PyEval_EvalFrameEx(f
,0);
4122 ++tstate
->recursion_depth
;
4124 --tstate
->recursion_depth
;
4127 if (argdefs
!= NULL
) {
4128 d
= &PyTuple_GET_ITEM(argdefs
, 0);
4129 nd
= Py_SIZE(argdefs
);
4131 return PyEval_EvalCodeEx(co
, globals
,
4132 (PyObject
*)NULL
, (*pp_stack
)-n
, na
,
4133 (*pp_stack
)-2*nk
, nk
, d
, nd
,
4134 PyFunction_GET_CLOSURE(func
));
4138 update_keyword_args(PyObject
*orig_kwdict
, int nk
, PyObject
***pp_stack
,
4141 PyObject
*kwdict
= NULL
;
4142 if (orig_kwdict
== NULL
)
4143 kwdict
= PyDict_New();
4145 kwdict
= PyDict_Copy(orig_kwdict
);
4146 Py_DECREF(orig_kwdict
);
4152 PyObject
*value
= EXT_POP(*pp_stack
);
4153 PyObject
*key
= EXT_POP(*pp_stack
);
4154 if (PyDict_GetItem(kwdict
, key
) != NULL
) {
4155 PyErr_Format(PyExc_TypeError
,
4156 "%.200s%s got multiple values "
4157 "for keyword argument '%.200s'",
4158 PyEval_GetFuncName(func
),
4159 PyEval_GetFuncDesc(func
),
4160 PyString_AsString(key
));
4166 err
= PyDict_SetItem(kwdict
, key
, value
);
4178 update_star_args(int nstack
, int nstar
, PyObject
*stararg
,
4179 PyObject
***pp_stack
)
4181 PyObject
*callargs
, *w
;
4183 callargs
= PyTuple_New(nstack
+ nstar
);
4184 if (callargs
== NULL
) {
4189 for (i
= 0; i
< nstar
; i
++) {
4190 PyObject
*a
= PyTuple_GET_ITEM(stararg
, i
);
4192 PyTuple_SET_ITEM(callargs
, nstack
+ i
, a
);
4195 while (--nstack
>= 0) {
4196 w
= EXT_POP(*pp_stack
);
4197 PyTuple_SET_ITEM(callargs
, nstack
, w
);
4203 load_args(PyObject
***pp_stack
, int na
)
4205 PyObject
*args
= PyTuple_New(na
);
4211 w
= EXT_POP(*pp_stack
);
4212 PyTuple_SET_ITEM(args
, na
, w
);
4218 do_call(PyObject
*func
, PyObject
***pp_stack
, int na
, int nk
)
4220 PyObject
*callargs
= NULL
;
4221 PyObject
*kwdict
= NULL
;
4222 PyObject
*result
= NULL
;
4225 kwdict
= update_keyword_args(NULL
, nk
, pp_stack
, func
);
4229 callargs
= load_args(pp_stack
, na
);
4230 if (callargs
== NULL
)
4233 /* At this point, we have to look at the type of func to
4234 update the call stats properly. Do it here so as to avoid
4235 exposing the call stats machinery outside ceval.c
4237 if (PyFunction_Check(func
))
4238 PCALL(PCALL_FUNCTION
);
4239 else if (PyMethod_Check(func
))
4240 PCALL(PCALL_METHOD
);
4241 else if (PyType_Check(func
))
4243 else if (PyCFunction_Check(func
))
4244 PCALL(PCALL_CFUNCTION
);
4248 if (PyCFunction_Check(func
)) {
4249 PyThreadState
*tstate
= PyThreadState_GET();
4250 C_TRACE(result
, PyCFunction_Call(func
, callargs
, kwdict
));
4253 result
= PyObject_Call(func
, callargs
, kwdict
);
4255 Py_XDECREF(callargs
);
4261 ext_do_call(PyObject
*func
, PyObject
***pp_stack
, int flags
, int na
, int nk
)
4264 PyObject
*callargs
= NULL
;
4265 PyObject
*stararg
= NULL
;
4266 PyObject
*kwdict
= NULL
;
4267 PyObject
*result
= NULL
;
4269 if (flags
& CALL_FLAG_KW
) {
4270 kwdict
= EXT_POP(*pp_stack
);
4271 if (!PyDict_Check(kwdict
)) {
4276 if (PyDict_Update(d
, kwdict
) != 0) {
4278 /* PyDict_Update raises attribute
4279 * error (percolated from an attempt
4280 * to get 'keys' attribute) instead of
4281 * a type error if its second argument
4284 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
4285 PyErr_Format(PyExc_TypeError
,
4286 "%.200s%.200s argument after ** "
4287 "must be a mapping, not %.200s",
4288 PyEval_GetFuncName(func
),
4289 PyEval_GetFuncDesc(func
),
4290 kwdict
->ob_type
->tp_name
);
4298 if (flags
& CALL_FLAG_VAR
) {
4299 stararg
= EXT_POP(*pp_stack
);
4300 if (!PyTuple_Check(stararg
)) {
4302 t
= PySequence_Tuple(stararg
);
4304 if (PyErr_ExceptionMatches(PyExc_TypeError
)) {
4305 PyErr_Format(PyExc_TypeError
,
4306 "%.200s%.200s argument after * "
4307 "must be a sequence, not %200s",
4308 PyEval_GetFuncName(func
),
4309 PyEval_GetFuncDesc(func
),
4310 stararg
->ob_type
->tp_name
);
4317 nstar
= PyTuple_GET_SIZE(stararg
);
4320 kwdict
= update_keyword_args(kwdict
, nk
, pp_stack
, func
);
4324 callargs
= update_star_args(na
, nstar
, stararg
, pp_stack
);
4325 if (callargs
== NULL
)
4328 /* At this point, we have to look at the type of func to
4329 update the call stats properly. Do it here so as to avoid
4330 exposing the call stats machinery outside ceval.c
4332 if (PyFunction_Check(func
))
4333 PCALL(PCALL_FUNCTION
);
4334 else if (PyMethod_Check(func
))
4335 PCALL(PCALL_METHOD
);
4336 else if (PyType_Check(func
))
4338 else if (PyCFunction_Check(func
))
4339 PCALL(PCALL_CFUNCTION
);
4343 if (PyCFunction_Check(func
)) {
4344 PyThreadState
*tstate
= PyThreadState_GET();
4345 C_TRACE(result
, PyCFunction_Call(func
, callargs
, kwdict
));
4348 result
= PyObject_Call(func
, callargs
, kwdict
);
4350 Py_XDECREF(callargs
);
4352 Py_XDECREF(stararg
);
4356 /* Extract a slice index from a PyInt or PyLong or an object with the
4357 nb_index slot defined, and store in *pi.
4358 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
4359 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
4360 Return 0 on error, 1 on success.
4362 /* Note: If v is NULL, return success without storing into *pi. This
4363 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
4364 called by the SLICE opcode with v and/or w equal to NULL.
4367 _PyEval_SliceIndex(PyObject
*v
, Py_ssize_t
*pi
)
4371 if (PyInt_Check(v
)) {
4372 /* XXX(nnorwitz): I think PyInt_AS_LONG is correct,
4373 however, it looks like it should be AsSsize_t.
4374 There should be a comment here explaining why.
4376 x
= PyInt_AS_LONG(v
);
4378 else if (PyIndex_Check(v
)) {
4379 x
= PyNumber_AsSsize_t(v
, NULL
);
4380 if (x
== -1 && PyErr_Occurred())
4384 PyErr_SetString(PyExc_TypeError
,
4385 "slice indices must be integers or "
4386 "None or have an __index__ method");
4395 #define ISINDEX(x) ((x) == NULL || \
4396 PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
4399 apply_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
) /* return u[v:w] */
4401 PyTypeObject
*tp
= u
->ob_type
;
4402 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
4404 if (sq
&& sq
->sq_slice
&& ISINDEX(v
) && ISINDEX(w
)) {
4405 Py_ssize_t ilow
= 0, ihigh
= PY_SSIZE_T_MAX
;
4406 if (!_PyEval_SliceIndex(v
, &ilow
))
4408 if (!_PyEval_SliceIndex(w
, &ihigh
))
4410 return PySequence_GetSlice(u
, ilow
, ihigh
);
4413 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
4414 if (slice
!= NULL
) {
4415 PyObject
*res
= PyObject_GetItem(u
, slice
);
4425 assign_slice(PyObject
*u
, PyObject
*v
, PyObject
*w
, PyObject
*x
)
4428 PyTypeObject
*tp
= u
->ob_type
;
4429 PySequenceMethods
*sq
= tp
->tp_as_sequence
;
4431 if (sq
&& sq
->sq_ass_slice
&& ISINDEX(v
) && ISINDEX(w
)) {
4432 Py_ssize_t ilow
= 0, ihigh
= PY_SSIZE_T_MAX
;
4433 if (!_PyEval_SliceIndex(v
, &ilow
))
4435 if (!_PyEval_SliceIndex(w
, &ihigh
))
4438 return PySequence_DelSlice(u
, ilow
, ihigh
);
4440 return PySequence_SetSlice(u
, ilow
, ihigh
, x
);
4443 PyObject
*slice
= PySlice_New(v
, w
, NULL
);
4444 if (slice
!= NULL
) {
4447 res
= PyObject_SetItem(u
, slice
, x
);
4449 res
= PyObject_DelItem(u
, slice
);
4458 #define Py3kExceptionClass_Check(x) \
4459 (PyType_Check((x)) && \
4460 PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
4462 #define CANNOT_CATCH_MSG "catching classes that don't inherit from " \
4463 "BaseException is not allowed in 3.x"
4466 cmp_outcome(int op
, register PyObject
*v
, register PyObject
*w
)
4477 res
= PySequence_Contains(w
, v
);
4482 res
= PySequence_Contains(w
, v
);
4487 case PyCmp_EXC_MATCH
:
4488 if (PyTuple_Check(w
)) {
4489 Py_ssize_t i
, length
;
4490 length
= PyTuple_Size(w
);
4491 for (i
= 0; i
< length
; i
+= 1) {
4492 PyObject
*exc
= PyTuple_GET_ITEM(w
, i
);
4493 if (PyString_Check(exc
)) {
4495 ret_val
= PyErr_WarnEx(
4496 PyExc_DeprecationWarning
,
4497 "catching of string "
4498 "exceptions is deprecated", 1);
4502 else if (Py_Py3kWarningFlag
&&
4503 !PyTuple_Check(exc
) &&
4504 !Py3kExceptionClass_Check(exc
))
4507 ret_val
= PyErr_WarnEx(
4508 PyExc_DeprecationWarning
,
4509 CANNOT_CATCH_MSG
, 1);
4516 if (PyString_Check(w
)) {
4518 ret_val
= PyErr_WarnEx(
4519 PyExc_DeprecationWarning
,
4520 "catching of string "
4521 "exceptions is deprecated", 1);
4525 else if (Py_Py3kWarningFlag
&&
4526 !PyTuple_Check(w
) &&
4527 !Py3kExceptionClass_Check(w
))
4530 ret_val
= PyErr_WarnEx(
4531 PyExc_DeprecationWarning
,
4532 CANNOT_CATCH_MSG
, 1);
4537 res
= PyErr_GivenExceptionMatches(v
, w
);
4540 return PyObject_RichCompare(v
, w
, op
);
4542 v
= res
? Py_True
: Py_False
;
4548 import_from(PyObject
*v
, PyObject
*name
)
4552 x
= PyObject_GetAttr(v
, name
);
4553 if (x
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
4554 PyErr_Format(PyExc_ImportError
,
4555 "cannot import name %.230s",
4556 PyString_AsString(name
));
4562 import_all_from(PyObject
*locals
, PyObject
*v
)
4564 PyObject
*all
= PyObject_GetAttrString(v
, "__all__");
4565 PyObject
*dict
, *name
, *value
;
4566 int skip_leading_underscores
= 0;
4570 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4571 return -1; /* Unexpected error */
4573 dict
= PyObject_GetAttrString(v
, "__dict__");
4575 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4577 PyErr_SetString(PyExc_ImportError
,
4578 "from-import-* object has no __dict__ and no __all__");
4581 all
= PyMapping_Keys(dict
);
4585 skip_leading_underscores
= 1;
4588 for (pos
= 0, err
= 0; ; pos
++) {
4589 name
= PySequence_GetItem(all
, pos
);
4591 if (!PyErr_ExceptionMatches(PyExc_IndexError
))
4597 if (skip_leading_underscores
&&
4598 PyString_Check(name
) &&
4599 PyString_AS_STRING(name
)[0] == '_')
4604 value
= PyObject_GetAttr(v
, name
);
4607 else if (PyDict_CheckExact(locals
))
4608 err
= PyDict_SetItem(locals
, name
, value
);
4610 err
= PyObject_SetItem(locals
, name
, value
);
4621 build_class(PyObject
*methods
, PyObject
*bases
, PyObject
*name
)
4623 PyObject
*metaclass
= NULL
, *result
, *base
;
4625 if (PyDict_Check(methods
))
4626 metaclass
= PyDict_GetItemString(methods
, "__metaclass__");
4627 if (metaclass
!= NULL
)
4628 Py_INCREF(metaclass
);
4629 else if (PyTuple_Check(bases
) && PyTuple_GET_SIZE(bases
) > 0) {
4630 base
= PyTuple_GET_ITEM(bases
, 0);
4631 metaclass
= PyObject_GetAttrString(base
, "__class__");
4632 if (metaclass
== NULL
) {
4634 metaclass
= (PyObject
*)base
->ob_type
;
4635 Py_INCREF(metaclass
);
4639 PyObject
*g
= PyEval_GetGlobals();
4640 if (g
!= NULL
&& PyDict_Check(g
))
4641 metaclass
= PyDict_GetItemString(g
, "__metaclass__");
4642 if (metaclass
== NULL
)
4643 metaclass
= (PyObject
*) &PyClass_Type
;
4644 Py_INCREF(metaclass
);
4646 result
= PyObject_CallFunctionObjArgs(metaclass
, name
, bases
, methods
,
4648 Py_DECREF(metaclass
);
4649 if (result
== NULL
&& PyErr_ExceptionMatches(PyExc_TypeError
)) {
4650 /* A type error here likely means that the user passed
4651 in a base that was not a class (such the random module
4652 instead of the random.random type). Help them out with
4653 by augmenting the error message with more information.*/
4655 PyObject
*ptype
, *pvalue
, *ptraceback
;
4657 PyErr_Fetch(&ptype
, &pvalue
, &ptraceback
);
4658 if (PyString_Check(pvalue
)) {
4660 newmsg
= PyString_FromFormat(
4661 "Error when calling the metaclass bases\n"
4663 PyString_AS_STRING(pvalue
));
4664 if (newmsg
!= NULL
) {
4669 PyErr_Restore(ptype
, pvalue
, ptraceback
);
4675 exec_statement(PyFrameObject
*f
, PyObject
*prog
, PyObject
*globals
,
4682 if (PyTuple_Check(prog
) && globals
== Py_None
&& locals
== Py_None
&&
4683 ((n
= PyTuple_Size(prog
)) == 2 || n
== 3)) {
4684 /* Backward compatibility hack */
4685 globals
= PyTuple_GetItem(prog
, 1);
4687 locals
= PyTuple_GetItem(prog
, 2);
4688 prog
= PyTuple_GetItem(prog
, 0);
4690 if (globals
== Py_None
) {
4691 globals
= PyEval_GetGlobals();
4692 if (locals
== Py_None
) {
4693 locals
= PyEval_GetLocals();
4696 if (!globals
|| !locals
) {
4697 PyErr_SetString(PyExc_SystemError
,
4698 "globals and locals cannot be NULL");
4702 else if (locals
== Py_None
)
4704 if (!PyString_Check(prog
) &&
4705 #ifdef Py_USING_UNICODE
4706 !PyUnicode_Check(prog
) &&
4708 !PyCode_Check(prog
) &&
4709 !PyFile_Check(prog
)) {
4710 PyErr_SetString(PyExc_TypeError
,
4711 "exec: arg 1 must be a string, file, or code object");
4714 if (!PyDict_Check(globals
)) {
4715 PyErr_SetString(PyExc_TypeError
,
4716 "exec: arg 2 must be a dictionary or None");
4719 if (!PyMapping_Check(locals
)) {
4720 PyErr_SetString(PyExc_TypeError
,
4721 "exec: arg 3 must be a mapping or None");
4724 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
)
4725 PyDict_SetItemString(globals
, "__builtins__", f
->f_builtins
);
4726 if (PyCode_Check(prog
)) {
4727 if (PyCode_GetNumFree((PyCodeObject
*)prog
) > 0) {
4728 PyErr_SetString(PyExc_TypeError
,
4729 "code object passed to exec may not contain free variables");
4732 v
= PyEval_EvalCode((PyCodeObject
*) prog
, globals
, locals
);
4734 else if (PyFile_Check(prog
)) {
4735 FILE *fp
= PyFile_AsFile(prog
);
4736 char *name
= PyString_AsString(PyFile_Name(prog
));
4741 if (PyEval_MergeCompilerFlags(&cf
))
4742 v
= PyRun_FileFlags(fp
, name
, Py_file_input
, globals
,
4745 v
= PyRun_File(fp
, name
, Py_file_input
, globals
,
4749 PyObject
*tmp
= NULL
;
4753 #ifdef Py_USING_UNICODE
4754 if (PyUnicode_Check(prog
)) {
4755 tmp
= PyUnicode_AsUTF8String(prog
);
4759 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
4762 if (PyString_AsStringAndSize(prog
, &str
, NULL
))
4764 if (PyEval_MergeCompilerFlags(&cf
))
4765 v
= PyRun_StringFlags(str
, Py_file_input
, globals
,
4768 v
= PyRun_String(str
, Py_file_input
, globals
, locals
);
4772 PyFrame_LocalsToFast(f
, 0);
4780 format_exc_check_arg(PyObject
*exc
, char *format_str
, PyObject
*obj
)
4787 obj_str
= PyString_AsString(obj
);
4791 PyErr_Format(exc
, format_str
, obj_str
);
4795 string_concatenate(PyObject
*v
, PyObject
*w
,
4796 PyFrameObject
*f
, unsigned char *next_instr
)
4798 /* This function implements 'variable += expr' when both arguments
4800 Py_ssize_t v_len
= PyString_GET_SIZE(v
);
4801 Py_ssize_t w_len
= PyString_GET_SIZE(w
);
4802 Py_ssize_t new_len
= v_len
+ w_len
;
4804 PyErr_SetString(PyExc_OverflowError
,
4805 "strings are too large to concat");
4809 if (v
->ob_refcnt
== 2) {
4810 /* In the common case, there are 2 references to the value
4811 * stored in 'variable' when the += is performed: one on the
4812 * value stack (in 'v') and one still stored in the
4813 * 'variable'. We try to delete the variable now to reduce
4816 switch (*next_instr
) {
4819 int oparg
= PEEKARG();
4820 PyObject
**fastlocals
= f
->f_localsplus
;
4821 if (GETLOCAL(oparg
) == v
)
4822 SETLOCAL(oparg
, NULL
);
4827 PyObject
**freevars
= (f
->f_localsplus
+
4828 f
->f_code
->co_nlocals
);
4829 PyObject
*c
= freevars
[PEEKARG()];
4830 if (PyCell_GET(c
) == v
)
4831 PyCell_Set(c
, NULL
);
4836 PyObject
*names
= f
->f_code
->co_names
;
4837 PyObject
*name
= GETITEM(names
, PEEKARG());
4838 PyObject
*locals
= f
->f_locals
;
4839 if (PyDict_CheckExact(locals
) &&
4840 PyDict_GetItem(locals
, name
) == v
) {
4841 if (PyDict_DelItem(locals
, name
) != 0) {
4850 if (v
->ob_refcnt
== 1 && !PyString_CHECK_INTERNED(v
)) {
4851 /* Now we own the last reference to 'v', so we can resize it
4854 if (_PyString_Resize(&v
, new_len
) != 0) {
4855 /* XXX if _PyString_Resize() fails, 'v' has been
4856 * deallocated so it cannot be put back into
4857 * 'variable'. The MemoryError is raised when there
4858 * is no value in 'variable', which might (very
4859 * remotely) be a cause of incompatibilities.
4863 /* copy 'w' into the newly allocated area of 'v' */
4864 memcpy(PyString_AS_STRING(v
) + v_len
,
4865 PyString_AS_STRING(w
), w_len
);
4869 /* When in-place resizing is not an option. */
4870 PyString_Concat(&v
, w
);
4875 #ifdef DYNAMIC_EXECUTION_PROFILE
4878 getarray(long a
[256])
4881 PyObject
*l
= PyList_New(256);
4882 if (l
== NULL
) return NULL
;
4883 for (i
= 0; i
< 256; i
++) {
4884 PyObject
*x
= PyInt_FromLong(a
[i
]);
4889 PyList_SetItem(l
, i
, x
);
4891 for (i
= 0; i
< 256; i
++)
4897 _Py_GetDXProfile(PyObject
*self
, PyObject
*args
)
4900 return getarray(dxp
);
4903 PyObject
*l
= PyList_New(257);
4904 if (l
== NULL
) return NULL
;
4905 for (i
= 0; i
< 257; i
++) {
4906 PyObject
*x
= getarray(dxpairs
[i
]);
4911 PyList_SetItem(l
, i
, x
);