You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4903 lines
148 KiB

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