PageRenderTime 71ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/Python/eval.cc

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