1
2 /* Execute compiled code */
3
4 /* XXX TO DO:
5 XXX speed up searching for keywords by using a dictionary
6 XXX document it!
7 */
8
9 /* enable more aggressive intra-module optimizations, where available */
10 #define PY_LOCAL_AGGRESSIVE
11
12 #include "Python.h"
13 #include "pycore_abstract.h" // _PyIndex_Check()
14 #include "pycore_call.h"
15 #include "pycore_ceval.h"
16 #include "pycore_code.h"
17 #include "pycore_initconfig.h"
18 #include "pycore_object.h"
19 #include "pycore_pyerrors.h"
20 #include "pycore_pylifecycle.h"
21 #include "pycore_pymem.h" // _PyMem_IsPtrFreed()
22 #include "pycore_pystate.h" // _PyInterpreterState_GET()
23 #include "pycore_sysmodule.h"
24 #include "pycore_tupleobject.h"
25
26 #include "code.h"
27 #include "dictobject.h"
28 #include "frameobject.h"
29 #include "opcode.h"
30 #include "pydtrace.h"
31 #include "setobject.h"
32
33 #include <ctype.h>
34
35 #ifdef Py_DEBUG
36 /* For debugging the interpreter: */
37 #define LLTRACE 1 /* Low-level trace feature */
38 #define CHECKEXC 1 /* Double-check exception checking */
39 #endif
40
41 #if !defined(Py_BUILD_CORE)
42 # error "ceval.c must be build with Py_BUILD_CORE define for best performance"
43 #endif
44
45 _Py_IDENTIFIER(__name__);
46
47 /* Forward declarations */
48 Py_LOCAL_INLINE(PyObject *) call_function(
49 PyThreadState *tstate, PyObject ***pp_stack,
50 Py_ssize_t oparg, PyObject *kwnames);
51 static PyObject * do_call_core(
52 PyThreadState *tstate, PyObject *func,
53 PyObject *callargs, PyObject *kwdict);
54
55 #ifdef LLTRACE
56 static int lltrace;
57 static int prtrace(PyThreadState *, PyObject *, const char *);
58 #endif
59 static int call_trace(Py_tracefunc, PyObject *,
60 PyThreadState *, PyFrameObject *,
61 int, PyObject *);
62 static int call_trace_protected(Py_tracefunc, PyObject *,
63 PyThreadState *, PyFrameObject *,
64 int, PyObject *);
65 static void call_exc_trace(Py_tracefunc, PyObject *,
66 PyThreadState *, PyFrameObject *);
67 static int maybe_call_line_trace(Py_tracefunc, PyObject *,
68 PyThreadState *, PyFrameObject *,
69 int *, int *, int *);
70 static void maybe_dtrace_line(PyFrameObject *, int *, int *, int *);
71 static void dtrace_function_entry(PyFrameObject *);
72 static void dtrace_function_return(PyFrameObject *);
73
74 static PyObject * import_name(PyThreadState *, PyFrameObject *,
75 PyObject *, PyObject *, PyObject *);
76 static PyObject * import_from(PyThreadState *, PyObject *, PyObject *);
77 static int import_all_from(PyThreadState *, PyObject *, PyObject *);
78 static void format_exc_check_arg(PyThreadState *, PyObject *, const char *, PyObject *);
79 static void format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
80 static PyObject * unicode_concatenate(PyThreadState *, PyObject *, PyObject *,
81 PyFrameObject *, const _Py_CODEUNIT *);
82 static PyObject * special_lookup(PyThreadState *, PyObject *, _Py_Identifier *);
83 static int check_args_iterable(PyThreadState *, PyObject *func, PyObject *vararg);
84 static void format_kwargs_error(PyThreadState *, PyObject *func, PyObject *kwargs);
85 static void format_awaitable_error(PyThreadState *, PyTypeObject *, int, int);
86
87 #define NAME_ERROR_MSG \
88 "name '%.200s' is not defined"
89 #define UNBOUNDLOCAL_ERROR_MSG \
90 "local variable '%.200s' referenced before assignment"
91 #define UNBOUNDFREE_ERROR_MSG \
92 "free variable '%.200s' referenced before assignment" \
93 " in enclosing scope"
94
95 /* Dynamic execution profile */
96 #ifdef DYNAMIC_EXECUTION_PROFILE
97 #ifdef DXPAIRS
98 static long dxpairs[257][256];
99 #define dxp dxpairs[256]
100 #else
101 static long dxp[256];
102 #endif
103 #endif
104
105 /* per opcode cache */
106 #ifdef Py_DEBUG
107 // --with-pydebug is used to find memory leak. opcache makes it harder.
108 // So we disable opcache when Py_DEBUG is defined.
109 // See bpo-37146
110 #define OPCACHE_MIN_RUNS 0 /* disable opcache */
111 #else
112 #define OPCACHE_MIN_RUNS 1024 /* create opcache when code executed this time */
113 #endif
114 #define OPCACHE_STATS 0 /* Enable stats */
115
116 #if OPCACHE_STATS
117 static size_t opcache_code_objects = 0;
118 static size_t opcache_code_objects_extra_mem = 0;
119
120 static size_t opcache_global_opts = 0;
121 static size_t opcache_global_hits = 0;
122 static size_t opcache_global_misses = 0;
123 #endif
124
125
126 #ifndef NDEBUG
127 /* Ensure that tstate is valid: sanity check for PyEval_AcquireThread() and
128 PyEval_RestoreThread(). Detect if tstate memory was freed. It can happen
129 when a thread continues to run after Python finalization, especially
130 daemon threads. */
131 static int
is_tstate_valid(PyThreadState * tstate)132 is_tstate_valid(PyThreadState *tstate)
133 {
134 assert(!_PyMem_IsPtrFreed(tstate));
135 assert(!_PyMem_IsPtrFreed(tstate->interp));
136 return 1;
137 }
138 #endif
139
140
141 /* This can set eval_breaker to 0 even though gil_drop_request became
142 1. We believe this is all right because the eval loop will release
143 the GIL eventually anyway. */
144 static inline void
COMPUTE_EVAL_BREAKER(PyInterpreterState * interp,struct _ceval_runtime_state * ceval,struct _ceval_state * ceval2)145 COMPUTE_EVAL_BREAKER(PyInterpreterState *interp,
146 struct _ceval_runtime_state *ceval,
147 struct _ceval_state *ceval2)
148 {
149 _Py_atomic_store_relaxed(&ceval2->eval_breaker,
150 _Py_atomic_load_relaxed(&ceval2->gil_drop_request)
151 | (_Py_atomic_load_relaxed(&ceval->signals_pending)
152 && _Py_ThreadCanHandleSignals(interp))
153 | (_Py_atomic_load_relaxed(&ceval2->pending.calls_to_do)
154 && _Py_ThreadCanHandlePendingCalls())
155 | ceval2->pending.async_exc);
156 }
157
158
159 static inline void
SET_GIL_DROP_REQUEST(PyInterpreterState * interp)160 SET_GIL_DROP_REQUEST(PyInterpreterState *interp)
161 {
162 struct _ceval_state *ceval2 = &interp->ceval;
163 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 1);
164 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
165 }
166
167
168 static inline void
RESET_GIL_DROP_REQUEST(PyInterpreterState * interp)169 RESET_GIL_DROP_REQUEST(PyInterpreterState *interp)
170 {
171 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
172 struct _ceval_state *ceval2 = &interp->ceval;
173 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 0);
174 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
175 }
176
177
178 static inline void
SIGNAL_PENDING_CALLS(PyInterpreterState * interp)179 SIGNAL_PENDING_CALLS(PyInterpreterState *interp)
180 {
181 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
182 struct _ceval_state *ceval2 = &interp->ceval;
183 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 1);
184 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
185 }
186
187
188 static inline void
UNSIGNAL_PENDING_CALLS(PyInterpreterState * interp)189 UNSIGNAL_PENDING_CALLS(PyInterpreterState *interp)
190 {
191 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
192 struct _ceval_state *ceval2 = &interp->ceval;
193 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 0);
194 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
195 }
196
197
198 static inline void
SIGNAL_PENDING_SIGNALS(PyInterpreterState * interp,int force)199 SIGNAL_PENDING_SIGNALS(PyInterpreterState *interp, int force)
200 {
201 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
202 struct _ceval_state *ceval2 = &interp->ceval;
203 _Py_atomic_store_relaxed(&ceval->signals_pending, 1);
204 if (force) {
205 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
206 }
207 else {
208 /* eval_breaker is not set to 1 if thread_can_handle_signals() is false */
209 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
210 }
211 }
212
213
214 static inline void
UNSIGNAL_PENDING_SIGNALS(PyInterpreterState * interp)215 UNSIGNAL_PENDING_SIGNALS(PyInterpreterState *interp)
216 {
217 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
218 struct _ceval_state *ceval2 = &interp->ceval;
219 _Py_atomic_store_relaxed(&ceval->signals_pending, 0);
220 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
221 }
222
223
224 static inline void
SIGNAL_ASYNC_EXC(PyInterpreterState * interp)225 SIGNAL_ASYNC_EXC(PyInterpreterState *interp)
226 {
227 struct _ceval_state *ceval2 = &interp->ceval;
228 ceval2->pending.async_exc = 1;
229 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
230 }
231
232
233 static inline void
UNSIGNAL_ASYNC_EXC(PyInterpreterState * interp)234 UNSIGNAL_ASYNC_EXC(PyInterpreterState *interp)
235 {
236 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
237 struct _ceval_state *ceval2 = &interp->ceval;
238 ceval2->pending.async_exc = 0;
239 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
240 }
241
242
243 #ifdef HAVE_ERRNO_H
244 #include <errno.h>
245 #endif
246 #include "ceval_gil.h"
247
248 void _Py_NO_RETURN
_Py_FatalError_TstateNULL(const char * func)249 _Py_FatalError_TstateNULL(const char *func)
250 {
251 _Py_FatalErrorFunc(func,
252 "the function must be called with the GIL held, "
253 "but the GIL is released "
254 "(the current Python thread state is NULL)");
255 }
256
257
258 int
_PyEval_ThreadsInitialized(_PyRuntimeState * runtime)259 _PyEval_ThreadsInitialized(_PyRuntimeState *runtime)
260 {
261 return gil_created(&runtime->ceval.gil);
262 }
263
264 int
PyEval_ThreadsInitialized(void)265 PyEval_ThreadsInitialized(void)
266 {
267 _PyRuntimeState *runtime = &_PyRuntime;
268 return _PyEval_ThreadsInitialized(runtime);
269 }
270
271 PyStatus
_PyEval_InitGIL(PyThreadState * tstate)272 _PyEval_InitGIL(PyThreadState *tstate)
273 {
274 if (!_Py_IsMainInterpreter(tstate)) {
275 /* Currently, the GIL is shared by all interpreters,
276 and only the main interpreter is responsible to create
277 and destroy it. */
278 return _PyStatus_OK();
279 }
280
281 struct _gil_runtime_state *gil = &tstate->interp->runtime->ceval.gil;
282 assert(!gil_created(gil));
283
284 PyThread_init_thread();
285 create_gil(gil);
286
287 take_gil(tstate);
288
289 assert(gil_created(gil));
290 return _PyStatus_OK();
291 }
292
293 void
_PyEval_FiniGIL(PyThreadState * tstate)294 _PyEval_FiniGIL(PyThreadState *tstate)
295 {
296 if (!_Py_IsMainInterpreter(tstate)) {
297 /* Currently, the GIL is shared by all interpreters,
298 and only the main interpreter is responsible to create
299 and destroy it. */
300 return;
301 }
302
303 struct _gil_runtime_state *gil = &tstate->interp->runtime->ceval.gil;
304 if (!gil_created(gil)) {
305 /* First Py_InitializeFromConfig() call: the GIL doesn't exist
306 yet: do nothing. */
307 return;
308 }
309
310 destroy_gil(gil);
311 assert(!gil_created(gil));
312 }
313
314 void
PyEval_InitThreads(void)315 PyEval_InitThreads(void)
316 {
317 /* Do nothing: kept for backward compatibility */
318 }
319
320 void
_PyEval_Fini(void)321 _PyEval_Fini(void)
322 {
323 #if OPCACHE_STATS
324 fprintf(stderr, "-- Opcode cache number of objects = %zd\n",
325 opcache_code_objects);
326
327 fprintf(stderr, "-- Opcode cache total extra mem = %zd\n",
328 opcache_code_objects_extra_mem);
329
330 fprintf(stderr, "\n");
331
332 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL hits = %zd (%d%%)\n",
333 opcache_global_hits,
334 (int) (100.0 * opcache_global_hits /
335 (opcache_global_hits + opcache_global_misses)));
336
337 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL misses = %zd (%d%%)\n",
338 opcache_global_misses,
339 (int) (100.0 * opcache_global_misses /
340 (opcache_global_hits + opcache_global_misses)));
341
342 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL opts = %zd\n",
343 opcache_global_opts);
344
345 fprintf(stderr, "\n");
346 #endif
347 }
348
349 void
PyEval_AcquireLock(void)350 PyEval_AcquireLock(void)
351 {
352 _PyRuntimeState *runtime = &_PyRuntime;
353 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
354 _Py_EnsureTstateNotNULL(tstate);
355
356 take_gil(tstate);
357 }
358
359 void
PyEval_ReleaseLock(void)360 PyEval_ReleaseLock(void)
361 {
362 _PyRuntimeState *runtime = &_PyRuntime;
363 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
364 /* This function must succeed when the current thread state is NULL.
365 We therefore avoid PyThreadState_Get() which dumps a fatal error
366 in debug mode. */
367 struct _ceval_runtime_state *ceval = &runtime->ceval;
368 struct _ceval_state *ceval2 = &tstate->interp->ceval;
369 drop_gil(ceval, ceval2, tstate);
370 }
371
372 void
_PyEval_ReleaseLock(PyThreadState * tstate)373 _PyEval_ReleaseLock(PyThreadState *tstate)
374 {
375 struct _ceval_runtime_state *ceval = &tstate->interp->runtime->ceval;
376 struct _ceval_state *ceval2 = &tstate->interp->ceval;
377 drop_gil(ceval, ceval2, tstate);
378 }
379
380 void
PyEval_AcquireThread(PyThreadState * tstate)381 PyEval_AcquireThread(PyThreadState *tstate)
382 {
383 _Py_EnsureTstateNotNULL(tstate);
384
385 take_gil(tstate);
386
387 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
388 if (_PyThreadState_Swap(gilstate, tstate) != NULL) {
389 Py_FatalError("non-NULL old thread state");
390 }
391 }
392
393 void
PyEval_ReleaseThread(PyThreadState * tstate)394 PyEval_ReleaseThread(PyThreadState *tstate)
395 {
396 assert(is_tstate_valid(tstate));
397
398 _PyRuntimeState *runtime = tstate->interp->runtime;
399 PyThreadState *new_tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
400 if (new_tstate != tstate) {
401 Py_FatalError("wrong thread state");
402 }
403 struct _ceval_runtime_state *ceval = &runtime->ceval;
404 struct _ceval_state *ceval2 = &tstate->interp->ceval;
405 drop_gil(ceval, ceval2, tstate);
406 }
407
408 #ifdef HAVE_FORK
409 /* This function is called from PyOS_AfterFork_Child to destroy all threads
410 * which are not running in the child process, and clear internal locks
411 * which might be held by those threads.
412 */
413
414 void
_PyEval_ReInitThreads(_PyRuntimeState * runtime)415 _PyEval_ReInitThreads(_PyRuntimeState *runtime)
416 {
417 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
418 _Py_EnsureTstateNotNULL(tstate);
419
420 struct _gil_runtime_state *gil = &runtime->ceval.gil;
421 if (!gil_created(gil)) {
422 return;
423 }
424 recreate_gil(gil);
425
426 take_gil(tstate);
427
428 struct _pending_calls *pending = &tstate->interp->ceval.pending;
429 if (_PyThread_at_fork_reinit(&pending->lock) < 0) {
430 Py_FatalError("Can't initialize threads for pending calls");
431 }
432
433 /* Destroy all threads except the current one */
434 _PyThreadState_DeleteExcept(runtime, tstate);
435 }
436 #endif
437
438 /* This function is used to signal that async exceptions are waiting to be
439 raised. */
440
441 void
_PyEval_SignalAsyncExc(PyThreadState * tstate)442 _PyEval_SignalAsyncExc(PyThreadState *tstate)
443 {
444 assert(is_tstate_valid(tstate));
445 SIGNAL_ASYNC_EXC(tstate->interp);
446 }
447
448 PyThreadState *
PyEval_SaveThread(void)449 PyEval_SaveThread(void)
450 {
451 _PyRuntimeState *runtime = &_PyRuntime;
452 PyThreadState *tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
453 _Py_EnsureTstateNotNULL(tstate);
454
455 struct _ceval_runtime_state *ceval = &runtime->ceval;
456 struct _ceval_state *ceval2 = &tstate->interp->ceval;
457 assert(gil_created(&ceval->gil));
458 drop_gil(ceval, ceval2, tstate);
459 return tstate;
460 }
461
462 void
PyEval_RestoreThread(PyThreadState * tstate)463 PyEval_RestoreThread(PyThreadState *tstate)
464 {
465 _Py_EnsureTstateNotNULL(tstate);
466
467 take_gil(tstate);
468
469 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
470 _PyThreadState_Swap(gilstate, tstate);
471 }
472
473
474 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
475 signal handlers or Mac I/O completion routines) can schedule calls
476 to a function to be called synchronously.
477 The synchronous function is called with one void* argument.
478 It should return 0 for success or -1 for failure -- failure should
479 be accompanied by an exception.
480
481 If registry succeeds, the registry function returns 0; if it fails
482 (e.g. due to too many pending calls) it returns -1 (without setting
483 an exception condition).
484
485 Note that because registry may occur from within signal handlers,
486 or other asynchronous events, calling malloc() is unsafe!
487
488 Any thread can schedule pending calls, but only the main thread
489 will execute them.
490 There is no facility to schedule calls to a particular thread, but
491 that should be easy to change, should that ever be required. In
492 that case, the static variables here should go into the python
493 threadstate.
494 */
495
496 void
_PyEval_SignalReceived(PyInterpreterState * interp)497 _PyEval_SignalReceived(PyInterpreterState *interp)
498 {
499 #ifdef MS_WINDOWS
500 // bpo-42296: On Windows, _PyEval_SignalReceived() is called from a signal
501 // handler which can run in a thread different than the Python thread, in
502 // which case _Py_ThreadCanHandleSignals() is wrong. Ignore
503 // _Py_ThreadCanHandleSignals() and always set eval_breaker to 1.
504 //
505 // The next eval_frame_handle_pending() call will call
506 // _Py_ThreadCanHandleSignals() to recompute eval_breaker.
507 int force = 1;
508 #else
509 int force = 0;
510 #endif
511 /* bpo-30703: Function called when the C signal handler of Python gets a
512 signal. We cannot queue a callback using _PyEval_AddPendingCall() since
513 that function is not async-signal-safe. */
514 SIGNAL_PENDING_SIGNALS(interp, force);
515 }
516
517 /* Push one item onto the queue while holding the lock. */
518 static int
_push_pending_call(struct _pending_calls * pending,int (* func)(void *),void * arg)519 _push_pending_call(struct _pending_calls *pending,
520 int (*func)(void *), void *arg)
521 {
522 int i = pending->last;
523 int j = (i + 1) % NPENDINGCALLS;
524 if (j == pending->first) {
525 return -1; /* Queue full */
526 }
527 pending->calls[i].func = func;
528 pending->calls[i].arg = arg;
529 pending->last = j;
530 return 0;
531 }
532
533 /* Pop one item off the queue while holding the lock. */
534 static void
_pop_pending_call(struct _pending_calls * pending,int (** func)(void *),void ** arg)535 _pop_pending_call(struct _pending_calls *pending,
536 int (**func)(void *), void **arg)
537 {
538 int i = pending->first;
539 if (i == pending->last) {
540 return; /* Queue empty */
541 }
542
543 *func = pending->calls[i].func;
544 *arg = pending->calls[i].arg;
545 pending->first = (i + 1) % NPENDINGCALLS;
546 }
547
548 /* This implementation is thread-safe. It allows
549 scheduling to be made from any thread, and even from an executing
550 callback.
551 */
552
553 int
_PyEval_AddPendingCall(PyInterpreterState * interp,int (* func)(void *),void * arg)554 _PyEval_AddPendingCall(PyInterpreterState *interp,
555 int (*func)(void *), void *arg)
556 {
557 struct _pending_calls *pending = &interp->ceval.pending;
558
559 /* Ensure that _PyEval_InitPendingCalls() was called
560 and that _PyEval_FiniPendingCalls() is not called yet. */
561 assert(pending->lock != NULL);
562
563 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
564 int result = _push_pending_call(pending, func, arg);
565 PyThread_release_lock(pending->lock);
566
567 /* signal main loop */
568 SIGNAL_PENDING_CALLS(interp);
569 return result;
570 }
571
572 int
Py_AddPendingCall(int (* func)(void *),void * arg)573 Py_AddPendingCall(int (*func)(void *), void *arg)
574 {
575 /* Best-effort to support subinterpreters and calls with the GIL released.
576
577 First attempt _PyThreadState_GET() since it supports subinterpreters.
578
579 If the GIL is released, _PyThreadState_GET() returns NULL . In this
580 case, use PyGILState_GetThisThreadState() which works even if the GIL
581 is released.
582
583 Sadly, PyGILState_GetThisThreadState() doesn't support subinterpreters:
584 see bpo-10915 and bpo-15751.
585
586 Py_AddPendingCall() doesn't require the caller to hold the GIL. */
587 PyThreadState *tstate = _PyThreadState_GET();
588 if (tstate == NULL) {
589 tstate = PyGILState_GetThisThreadState();
590 }
591
592 PyInterpreterState *interp;
593 if (tstate != NULL) {
594 interp = tstate->interp;
595 }
596 else {
597 /* Last resort: use the main interpreter */
598 interp = _PyRuntime.interpreters.main;
599 }
600 return _PyEval_AddPendingCall(interp, func, arg);
601 }
602
603 static int
handle_signals(PyThreadState * tstate)604 handle_signals(PyThreadState *tstate)
605 {
606 assert(is_tstate_valid(tstate));
607 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
608 return 0;
609 }
610
611 UNSIGNAL_PENDING_SIGNALS(tstate->interp);
612 if (_PyErr_CheckSignalsTstate(tstate) < 0) {
613 /* On failure, re-schedule a call to handle_signals(). */
614 SIGNAL_PENDING_SIGNALS(tstate->interp, 0);
615 return -1;
616 }
617 return 0;
618 }
619
620 static int
make_pending_calls(PyThreadState * tstate)621 make_pending_calls(PyThreadState *tstate)
622 {
623 assert(is_tstate_valid(tstate));
624
625 /* only execute pending calls on main thread */
626 if (!_Py_ThreadCanHandlePendingCalls()) {
627 return 0;
628 }
629
630 /* don't perform recursive pending calls */
631 static int busy = 0;
632 if (busy) {
633 return 0;
634 }
635 busy = 1;
636
637 /* unsignal before starting to call callbacks, so that any callback
638 added in-between re-signals */
639 UNSIGNAL_PENDING_CALLS(tstate->interp);
640 int res = 0;
641
642 /* perform a bounded number of calls, in case of recursion */
643 struct _pending_calls *pending = &tstate->interp->ceval.pending;
644 for (int i=0; i<NPENDINGCALLS; i++) {
645 int (*func)(void *) = NULL;
646 void *arg = NULL;
647
648 /* pop one item off the queue while holding the lock */
649 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
650 _pop_pending_call(pending, &func, &arg);
651 PyThread_release_lock(pending->lock);
652
653 /* having released the lock, perform the callback */
654 if (func == NULL) {
655 break;
656 }
657 res = func(arg);
658 if (res) {
659 goto error;
660 }
661 }
662
663 busy = 0;
664 return res;
665
666 error:
667 busy = 0;
668 SIGNAL_PENDING_CALLS(tstate->interp);
669 return res;
670 }
671
672 void
_Py_FinishPendingCalls(PyThreadState * tstate)673 _Py_FinishPendingCalls(PyThreadState *tstate)
674 {
675 assert(PyGILState_Check());
676
677 struct _pending_calls *pending = &tstate->interp->ceval.pending;
678
679 if (!_Py_atomic_load_relaxed(&(pending->calls_to_do))) {
680 return;
681 }
682
683 if (make_pending_calls(tstate) < 0) {
684 PyObject *exc, *val, *tb;
685 _PyErr_Fetch(tstate, &exc, &val, &tb);
686 PyErr_BadInternalCall();
687 _PyErr_ChainExceptions(exc, val, tb);
688 _PyErr_Print(tstate);
689 }
690 }
691
692 /* Py_MakePendingCalls() is a simple wrapper for the sake
693 of backward-compatibility. */
694 int
Py_MakePendingCalls(void)695 Py_MakePendingCalls(void)
696 {
697 assert(PyGILState_Check());
698
699 PyThreadState *tstate = _PyThreadState_GET();
700
701 /* Python signal handler doesn't really queue a callback: it only signals
702 that a signal was received, see _PyEval_SignalReceived(). */
703 int res = handle_signals(tstate);
704 if (res != 0) {
705 return res;
706 }
707
708 res = make_pending_calls(tstate);
709 if (res != 0) {
710 return res;
711 }
712
713 return 0;
714 }
715
716 /* The interpreter's recursion limit */
717
718 #ifndef Py_DEFAULT_RECURSION_LIMIT
719 #define Py_DEFAULT_RECURSION_LIMIT 1000
720 #endif
721
722 int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT;
723
724 void
_PyEval_InitRuntimeState(struct _ceval_runtime_state * ceval)725 _PyEval_InitRuntimeState(struct _ceval_runtime_state *ceval)
726 {
727 _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT;
728 _gil_initialize(&ceval->gil);
729 }
730
731 int
_PyEval_InitState(struct _ceval_state * ceval)732 _PyEval_InitState(struct _ceval_state *ceval)
733 {
734 ceval->recursion_limit = Py_DEFAULT_RECURSION_LIMIT;
735
736 struct _pending_calls *pending = &ceval->pending;
737 assert(pending->lock == NULL);
738
739 pending->lock = PyThread_allocate_lock();
740 if (pending->lock == NULL) {
741 return -1;
742 }
743
744 return 0;
745 }
746
747 void
_PyEval_FiniState(struct _ceval_state * ceval)748 _PyEval_FiniState(struct _ceval_state *ceval)
749 {
750 struct _pending_calls *pending = &ceval->pending;
751 if (pending->lock != NULL) {
752 PyThread_free_lock(pending->lock);
753 pending->lock = NULL;
754 }
755 }
756
757 int
Py_GetRecursionLimit(void)758 Py_GetRecursionLimit(void)
759 {
760 PyThreadState *tstate = _PyThreadState_GET();
761 return tstate->interp->ceval.recursion_limit;
762 }
763
764 void
Py_SetRecursionLimit(int new_limit)765 Py_SetRecursionLimit(int new_limit)
766 {
767 PyThreadState *tstate = _PyThreadState_GET();
768 tstate->interp->ceval.recursion_limit = new_limit;
769 if (_Py_IsMainInterpreter(tstate)) {
770 _Py_CheckRecursionLimit = new_limit;
771 }
772 }
773
774 /* The function _Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
775 if the recursion_depth reaches _Py_CheckRecursionLimit.
776 If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
777 to guarantee that _Py_CheckRecursiveCall() is regularly called.
778 Without USE_STACKCHECK, there is no need for this. */
779 int
_Py_CheckRecursiveCall(PyThreadState * tstate,const char * where)780 _Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
781 {
782 int recursion_limit = tstate->interp->ceval.recursion_limit;
783
784 #ifdef USE_STACKCHECK
785 tstate->stackcheck_counter = 0;
786 if (PyOS_CheckStack()) {
787 --tstate->recursion_depth;
788 _PyErr_SetString(tstate, PyExc_MemoryError, "Stack overflow");
789 return -1;
790 }
791 if (_Py_IsMainInterpreter(tstate)) {
792 /* Needed for ABI backwards-compatibility (see bpo-31857) */
793 _Py_CheckRecursionLimit = recursion_limit;
794 }
795 #endif
796 if (tstate->recursion_critical)
797 /* Somebody asked that we don't check for recursion. */
798 return 0;
799 if (tstate->overflowed) {
800 if (tstate->recursion_depth > recursion_limit + 50) {
801 /* Overflowing while handling an overflow. Give up. */
802 Py_FatalError("Cannot recover from stack overflow.");
803 }
804 return 0;
805 }
806 if (tstate->recursion_depth > recursion_limit) {
807 --tstate->recursion_depth;
808 tstate->overflowed = 1;
809 _PyErr_Format(tstate, PyExc_RecursionError,
810 "maximum recursion depth exceeded%s",
811 where);
812 return -1;
813 }
814 return 0;
815 }
816
817 static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
818 static int unpack_iterable(PyThreadState *, PyObject *, int, int, PyObject **);
819
820 #define _Py_TracingPossible(ceval) ((ceval)->tracing_possible)
821
822
823 PyObject *
PyEval_EvalCode(PyObject * co,PyObject * globals,PyObject * locals)824 PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
825 {
826 return PyEval_EvalCodeEx(co,
827 globals, locals,
828 (PyObject **)NULL, 0,
829 (PyObject **)NULL, 0,
830 (PyObject **)NULL, 0,
831 NULL, NULL);
832 }
833
834
835 /* Interpreter main loop */
836
837 PyObject *
PyEval_EvalFrame(PyFrameObject * f)838 PyEval_EvalFrame(PyFrameObject *f)
839 {
840 /* Function kept for backward compatibility */
841 PyThreadState *tstate = _PyThreadState_GET();
842 return _PyEval_EvalFrame(tstate, f, 0);
843 }
844
845 PyObject *
PyEval_EvalFrameEx(PyFrameObject * f,int throwflag)846 PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
847 {
848 PyThreadState *tstate = _PyThreadState_GET();
849 return _PyEval_EvalFrame(tstate, f, throwflag);
850 }
851
852
853 /* Handle signals, pending calls, GIL drop request
854 and asynchronous exception */
855 static int
eval_frame_handle_pending(PyThreadState * tstate)856 eval_frame_handle_pending(PyThreadState *tstate)
857 {
858 _PyRuntimeState * const runtime = &_PyRuntime;
859 struct _ceval_runtime_state *ceval = &runtime->ceval;
860
861 /* Pending signals */
862 if (_Py_atomic_load_relaxed(&ceval->signals_pending)) {
863 if (handle_signals(tstate) != 0) {
864 return -1;
865 }
866 }
867
868 /* Pending calls */
869 struct _ceval_state *ceval2 = &tstate->interp->ceval;
870 if (_Py_atomic_load_relaxed(&ceval2->pending.calls_to_do)) {
871 if (make_pending_calls(tstate) != 0) {
872 return -1;
873 }
874 }
875
876 /* GIL drop request */
877 if (_Py_atomic_load_relaxed(&ceval2->gil_drop_request)) {
878 /* Give another thread a chance */
879 if (_PyThreadState_Swap(&runtime->gilstate, NULL) != tstate) {
880 Py_FatalError("tstate mix-up");
881 }
882 drop_gil(ceval, ceval2, tstate);
883
884 /* Other threads may run now */
885
886 take_gil(tstate);
887
888 if (_PyThreadState_Swap(&runtime->gilstate, tstate) != NULL) {
889 Py_FatalError("orphan tstate");
890 }
891 }
892
893 /* Check for asynchronous exception. */
894 if (tstate->async_exc != NULL) {
895 PyObject *exc = tstate->async_exc;
896 tstate->async_exc = NULL;
897 UNSIGNAL_ASYNC_EXC(tstate->interp);
898 _PyErr_SetNone(tstate, exc);
899 Py_DECREF(exc);
900 return -1;
901 }
902
903 #ifdef MS_WINDOWS
904 // bpo-42296: On Windows, _PyEval_SignalReceived() can be called in a
905 // different thread than the Python thread, in which case
906 // _Py_ThreadCanHandleSignals() is wrong. Recompute eval_breaker in the
907 // current Python thread with the correct _Py_ThreadCanHandleSignals()
908 // value. It prevents to interrupt the eval loop at every instruction if
909 // the current Python thread cannot handle signals (if
910 // _Py_ThreadCanHandleSignals() is false).
911 COMPUTE_EVAL_BREAKER(tstate->interp, ceval, ceval2);
912 #endif
913
914 return 0;
915 }
916
917 PyObject* _Py_HOT_FUNCTION
_PyEval_EvalFrameDefault(PyThreadState * tstate,PyFrameObject * f,int throwflag)918 _PyEval_EvalFrameDefault(PyThreadState *tstate, PyFrameObject *f, int throwflag)
919 {
920 _Py_EnsureTstateNotNULL(tstate);
921
922 #ifdef DXPAIRS
923 int lastopcode = 0;
924 #endif
925 PyObject **stack_pointer; /* Next free slot in value stack */
926 const _Py_CODEUNIT *next_instr;
927 int opcode; /* Current opcode */
928 int oparg; /* Current opcode argument, if any */
929 PyObject **fastlocals, **freevars;
930 PyObject *retval = NULL; /* Return value */
931 struct _ceval_state * const ceval2 = &tstate->interp->ceval;
932 _Py_atomic_int * const eval_breaker = &ceval2->eval_breaker;
933 PyCodeObject *co;
934
935 /* when tracing we set things up so that
936
937 not (instr_lb <= current_bytecode_offset < instr_ub)
938
939 is true when the line being executed has changed. The
940 initial values are such as to make this false the first
941 time it is tested. */
942 int instr_ub = -1, instr_lb = 0, instr_prev = -1;
943
944 const _Py_CODEUNIT *first_instr;
945 PyObject *names;
946 PyObject *consts;
947 _PyOpcache *co_opcache;
948
949 #ifdef LLTRACE
950 _Py_IDENTIFIER(__ltrace__);
951 #endif
952
953 /* Computed GOTOs, or
954 the-optimization-commonly-but-improperly-known-as-"threaded code"
955 using gcc's labels-as-values extension
956 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
957
958 The traditional bytecode evaluation loop uses a "switch" statement, which
959 decent compilers will optimize as a single indirect branch instruction
960 combined with a lookup table of jump addresses. However, since the
961 indirect jump instruction is shared by all opcodes, the CPU will have a
962 hard time making the right prediction for where to jump next (actually,
963 it will be always wrong except in the uncommon case of a sequence of
964 several identical opcodes).
965
966 "Threaded code" in contrast, uses an explicit jump table and an explicit
967 indirect jump instruction at the end of each opcode. Since the jump
968 instruction is at a different address for each opcode, the CPU will make a
969 separate prediction for each of these instructions, which is equivalent to
970 predicting the second opcode of each opcode pair. These predictions have
971 a much better chance to turn out valid, especially in small bytecode loops.
972
973 A mispredicted branch on a modern CPU flushes the whole pipeline and
974 can cost several CPU cycles (depending on the pipeline depth),
975 and potentially many more instructions (depending on the pipeline width).
976 A correctly predicted branch, however, is nearly free.
977
978 At the time of this writing, the "threaded code" version is up to 15-20%
979 faster than the normal "switch" version, depending on the compiler and the
980 CPU architecture.
981
982 We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined,
983 because it would render the measurements invalid.
984
985
986 NOTE: care must be taken that the compiler doesn't try to "optimize" the
987 indirect jumps by sharing them between all opcodes. Such optimizations
988 can be disabled on gcc by using the -fno-gcse flag (or possibly
989 -fno-crossjumping).
990 */
991
992 #ifdef DYNAMIC_EXECUTION_PROFILE
993 #undef USE_COMPUTED_GOTOS
994 #define USE_COMPUTED_GOTOS 0
995 #endif
996
997 #ifdef HAVE_COMPUTED_GOTOS
998 #ifndef USE_COMPUTED_GOTOS
999 #define USE_COMPUTED_GOTOS 1
1000 #endif
1001 #else
1002 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
1003 #error "Computed gotos are not supported on this compiler."
1004 #endif
1005 #undef USE_COMPUTED_GOTOS
1006 #define USE_COMPUTED_GOTOS 0
1007 #endif
1008
1009 #if USE_COMPUTED_GOTOS
1010 /* Import the static jump table */
1011 #include "opcode_targets.h"
1012
1013 #define TARGET(op) \
1014 op: \
1015 TARGET_##op
1016
1017 #ifdef LLTRACE
1018 #define FAST_DISPATCH() \
1019 { \
1020 if (!lltrace && !_Py_TracingPossible(ceval2) && !PyDTrace_LINE_ENABLED()) { \
1021 f->f_lasti = INSTR_OFFSET(); \
1022 NEXTOPARG(); \
1023 goto *opcode_targets[opcode]; \
1024 } \
1025 goto fast_next_opcode; \
1026 }
1027 #else
1028 #define FAST_DISPATCH() \
1029 { \
1030 if (!_Py_TracingPossible(ceval2) && !PyDTrace_LINE_ENABLED()) { \
1031 f->f_lasti = INSTR_OFFSET(); \
1032 NEXTOPARG(); \
1033 goto *opcode_targets[opcode]; \
1034 } \
1035 goto fast_next_opcode; \
1036 }
1037 #endif
1038
1039 #define DISPATCH() \
1040 { \
1041 if (!_Py_atomic_load_relaxed(eval_breaker)) { \
1042 FAST_DISPATCH(); \
1043 } \
1044 continue; \
1045 }
1046
1047 #else
1048 #define TARGET(op) op
1049 #define FAST_DISPATCH() goto fast_next_opcode
1050 #define DISPATCH() continue
1051 #endif
1052
1053
1054 /* Tuple access macros */
1055
1056 #ifndef Py_DEBUG
1057 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
1058 #else
1059 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
1060 #endif
1061
1062 /* Code access macros */
1063
1064 /* The integer overflow is checked by an assertion below. */
1065 #define INSTR_OFFSET() \
1066 (sizeof(_Py_CODEUNIT) * (int)(next_instr - first_instr))
1067 #define NEXTOPARG() do { \
1068 _Py_CODEUNIT word = *next_instr; \
1069 opcode = _Py_OPCODE(word); \
1070 oparg = _Py_OPARG(word); \
1071 next_instr++; \
1072 } while (0)
1073 #define JUMPTO(x) (next_instr = first_instr + (x) / sizeof(_Py_CODEUNIT))
1074 #define JUMPBY(x) (next_instr += (x) / sizeof(_Py_CODEUNIT))
1075
1076 /* OpCode prediction macros
1077 Some opcodes tend to come in pairs thus making it possible to
1078 predict the second code when the first is run. For example,
1079 COMPARE_OP is often followed by POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE.
1080
1081 Verifying the prediction costs a single high-speed test of a register
1082 variable against a constant. If the pairing was good, then the
1083 processor's own internal branch predication has a high likelihood of
1084 success, resulting in a nearly zero-overhead transition to the
1085 next opcode. A successful prediction saves a trip through the eval-loop
1086 including its unpredictable switch-case branch. Combined with the
1087 processor's internal branch prediction, a successful PREDICT has the
1088 effect of making the two opcodes run as if they were a single new opcode
1089 with the bodies combined.
1090
1091 If collecting opcode statistics, your choices are to either keep the
1092 predictions turned-on and interpret the results as if some opcodes
1093 had been combined or turn-off predictions so that the opcode frequency
1094 counter updates for both opcodes.
1095
1096 Opcode prediction is disabled with threaded code, since the latter allows
1097 the CPU to record separate branch prediction information for each
1098 opcode.
1099
1100 */
1101
1102 #define PREDICT_ID(op) PRED_##op
1103
1104 #if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
1105 #define PREDICT(op) if (0) goto PREDICT_ID(op)
1106 #else
1107 #define PREDICT(op) \
1108 do { \
1109 _Py_CODEUNIT word = *next_instr; \
1110 opcode = _Py_OPCODE(word); \
1111 if (opcode == op) { \
1112 oparg = _Py_OPARG(word); \
1113 next_instr++; \
1114 goto PREDICT_ID(op); \
1115 } \
1116 } while(0)
1117 #endif
1118 #define PREDICTED(op) PREDICT_ID(op):
1119
1120
1121 /* Stack manipulation macros */
1122
1123 /* The stack can grow at most MAXINT deep, as co_nlocals and
1124 co_stacksize are ints. */
1125 #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
1126 #define EMPTY() (STACK_LEVEL() == 0)
1127 #define TOP() (stack_pointer[-1])
1128 #define SECOND() (stack_pointer[-2])
1129 #define THIRD() (stack_pointer[-3])
1130 #define FOURTH() (stack_pointer[-4])
1131 #define PEEK(n) (stack_pointer[-(n)])
1132 #define SET_TOP(v) (stack_pointer[-1] = (v))
1133 #define SET_SECOND(v) (stack_pointer[-2] = (v))
1134 #define SET_THIRD(v) (stack_pointer[-3] = (v))
1135 #define SET_FOURTH(v) (stack_pointer[-4] = (v))
1136 #define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
1137 #define BASIC_STACKADJ(n) (stack_pointer += n)
1138 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
1139 #define BASIC_POP() (*--stack_pointer)
1140
1141 #ifdef LLTRACE
1142 #define PUSH(v) { (void)(BASIC_PUSH(v), \
1143 lltrace && prtrace(tstate, TOP(), "push")); \
1144 assert(STACK_LEVEL() <= co->co_stacksize); }
1145 #define POP() ((void)(lltrace && prtrace(tstate, TOP(), "pop")), \
1146 BASIC_POP())
1147 #define STACK_GROW(n) do { \
1148 assert(n >= 0); \
1149 (void)(BASIC_STACKADJ(n), \
1150 lltrace && prtrace(tstate, TOP(), "stackadj")); \
1151 assert(STACK_LEVEL() <= co->co_stacksize); \
1152 } while (0)
1153 #define STACK_SHRINK(n) do { \
1154 assert(n >= 0); \
1155 (void)(lltrace && prtrace(tstate, TOP(), "stackadj")); \
1156 (void)(BASIC_STACKADJ(-n)); \
1157 assert(STACK_LEVEL() <= co->co_stacksize); \
1158 } while (0)
1159 #define EXT_POP(STACK_POINTER) ((void)(lltrace && \
1160 prtrace(tstate, (STACK_POINTER)[-1], "ext_pop")), \
1161 *--(STACK_POINTER))
1162 #else
1163 #define PUSH(v) BASIC_PUSH(v)
1164 #define POP() BASIC_POP()
1165 #define STACK_GROW(n) BASIC_STACKADJ(n)
1166 #define STACK_SHRINK(n) BASIC_STACKADJ(-n)
1167 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
1168 #endif
1169
1170 /* Local variable macros */
1171
1172 #define GETLOCAL(i) (fastlocals[i])
1173
1174 /* The SETLOCAL() macro must not DECREF the local variable in-place and
1175 then store the new value; it must copy the old value to a temporary
1176 value, then store the new value, and then DECREF the temporary value.
1177 This is because it is possible that during the DECREF the frame is
1178 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1179 variable would be pointing to already-freed memory. */
1180 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
1181 GETLOCAL(i) = value; \
1182 Py_XDECREF(tmp); } while (0)
1183
1184
1185 #define UNWIND_BLOCK(b) \
1186 while (STACK_LEVEL() > (b)->b_level) { \
1187 PyObject *v = POP(); \
1188 Py_XDECREF(v); \
1189 }
1190
1191 #define UNWIND_EXCEPT_HANDLER(b) \
1192 do { \
1193 PyObject *type, *value, *traceback; \
1194 _PyErr_StackItem *exc_info; \
1195 assert(STACK_LEVEL() >= (b)->b_level + 3); \
1196 while (STACK_LEVEL() > (b)->b_level + 3) { \
1197 value = POP(); \
1198 Py_XDECREF(value); \
1199 } \
1200 exc_info = tstate->exc_info; \
1201 type = exc_info->exc_type; \
1202 value = exc_info->exc_value; \
1203 traceback = exc_info->exc_traceback; \
1204 exc_info->exc_type = POP(); \
1205 exc_info->exc_value = POP(); \
1206 exc_info->exc_traceback = POP(); \
1207 Py_XDECREF(type); \
1208 Py_XDECREF(value); \
1209 Py_XDECREF(traceback); \
1210 } while(0)
1211
1212 /* macros for opcode cache */
1213 #define OPCACHE_CHECK() \
1214 do { \
1215 co_opcache = NULL; \
1216 if (co->co_opcache != NULL) { \
1217 unsigned char co_opt_offset = \
1218 co->co_opcache_map[next_instr - first_instr]; \
1219 if (co_opt_offset > 0) { \
1220 assert(co_opt_offset <= co->co_opcache_size); \
1221 co_opcache = &co->co_opcache[co_opt_offset - 1]; \
1222 assert(co_opcache != NULL); \
1223 } \
1224 } \
1225 } while (0)
1226
1227 #if OPCACHE_STATS
1228
1229 #define OPCACHE_STAT_GLOBAL_HIT() \
1230 do { \
1231 if (co->co_opcache != NULL) opcache_global_hits++; \
1232 } while (0)
1233
1234 #define OPCACHE_STAT_GLOBAL_MISS() \
1235 do { \
1236 if (co->co_opcache != NULL) opcache_global_misses++; \
1237 } while (0)
1238
1239 #define OPCACHE_STAT_GLOBAL_OPT() \
1240 do { \
1241 if (co->co_opcache != NULL) opcache_global_opts++; \
1242 } while (0)
1243
1244 #else /* OPCACHE_STATS */
1245
1246 #define OPCACHE_STAT_GLOBAL_HIT()
1247 #define OPCACHE_STAT_GLOBAL_MISS()
1248 #define OPCACHE_STAT_GLOBAL_OPT()
1249
1250 #endif
1251
1252 /* Start of code */
1253
1254 /* push frame */
1255 if (_Py_EnterRecursiveCall(tstate, "")) {
1256 return NULL;
1257 }
1258
1259 tstate->frame = f;
1260
1261 if (tstate->use_tracing) {
1262 if (tstate->c_tracefunc != NULL) {
1263 /* tstate->c_tracefunc, if defined, is a
1264 function that will be called on *every* entry
1265 to a code block. Its return value, if not
1266 None, is a function that will be called at
1267 the start of each executed line of code.
1268 (Actually, the function must return itself
1269 in order to continue tracing.) The trace
1270 functions are called with three arguments:
1271 a pointer to the current frame, a string
1272 indicating why the function is called, and
1273 an argument which depends on the situation.
1274 The global trace function is also called
1275 whenever an exception is detected. */
1276 if (call_trace_protected(tstate->c_tracefunc,
1277 tstate->c_traceobj,
1278 tstate, f, PyTrace_CALL, Py_None)) {
1279 /* Trace function raised an error */
1280 goto exit_eval_frame;
1281 }
1282 }
1283 if (tstate->c_profilefunc != NULL) {
1284 /* Similar for c_profilefunc, except it needn't
1285 return itself and isn't called for "line" events */
1286 if (call_trace_protected(tstate->c_profilefunc,
1287 tstate->c_profileobj,
1288 tstate, f, PyTrace_CALL, Py_None)) {
1289 /* Profile function raised an error */
1290 goto exit_eval_frame;
1291 }
1292 }
1293 }
1294
1295 if (PyDTrace_FUNCTION_ENTRY_ENABLED())
1296 dtrace_function_entry(f);
1297
1298 co = f->f_code;
1299 names = co->co_names;
1300 consts = co->co_consts;
1301 fastlocals = f->f_localsplus;
1302 freevars = f->f_localsplus + co->co_nlocals;
1303 assert(PyBytes_Check(co->co_code));
1304 assert(PyBytes_GET_SIZE(co->co_code) <= INT_MAX);
1305 assert(PyBytes_GET_SIZE(co->co_code) % sizeof(_Py_CODEUNIT) == 0);
1306 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(co->co_code), sizeof(_Py_CODEUNIT)));
1307 first_instr = (_Py_CODEUNIT *) PyBytes_AS_STRING(co->co_code);
1308 /*
1309 f->f_lasti refers to the index of the last instruction,
1310 unless it's -1 in which case next_instr should be first_instr.
1311
1312 YIELD_FROM sets f_lasti to itself, in order to repeatedly yield
1313 multiple values.
1314
1315 When the PREDICT() macros are enabled, some opcode pairs follow in
1316 direct succession without updating f->f_lasti. A successful
1317 prediction effectively links the two codes together as if they
1318 were a single new opcode; accordingly,f->f_lasti will point to
1319 the first code in the pair (for instance, GET_ITER followed by
1320 FOR_ITER is effectively a single opcode and f->f_lasti will point
1321 to the beginning of the combined pair.)
1322 */
1323 assert(f->f_lasti >= -1);
1324 next_instr = first_instr;
1325 if (f->f_lasti >= 0) {
1326 assert(f->f_lasti % sizeof(_Py_CODEUNIT) == 0);
1327 next_instr += f->f_lasti / sizeof(_Py_CODEUNIT) + 1;
1328 }
1329 stack_pointer = f->f_stacktop;
1330 assert(stack_pointer != NULL);
1331 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
1332 f->f_executing = 1;
1333
1334 if (co->co_opcache_flag < OPCACHE_MIN_RUNS) {
1335 co->co_opcache_flag++;
1336 if (co->co_opcache_flag == OPCACHE_MIN_RUNS) {
1337 if (_PyCode_InitOpcache(co) < 0) {
1338 goto exit_eval_frame;
1339 }
1340 #if OPCACHE_STATS
1341 opcache_code_objects_extra_mem +=
1342 PyBytes_Size(co->co_code) / sizeof(_Py_CODEUNIT) +
1343 sizeof(_PyOpcache) * co->co_opcache_size;
1344 opcache_code_objects++;
1345 #endif
1346 }
1347 }
1348
1349 #ifdef LLTRACE
1350 lltrace = _PyDict_GetItemId(f->f_globals, &PyId___ltrace__) != NULL;
1351 #endif
1352
1353 if (throwflag) /* support for generator.throw() */
1354 goto error;
1355
1356 #ifdef Py_DEBUG
1357 /* _PyEval_EvalFrameDefault() must not be called with an exception set,
1358 because it can clear it (directly or indirectly) and so the
1359 caller loses its exception */
1360 assert(!_PyErr_Occurred(tstate));
1361 #endif
1362
1363 main_loop:
1364 for (;;) {
1365 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1366 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
1367 assert(!_PyErr_Occurred(tstate));
1368
1369 /* Do periodic things. Doing this every time through
1370 the loop would add too much overhead, so we do it
1371 only every Nth instruction. We also do it if
1372 ``pending.calls_to_do'' is set, i.e. when an asynchronous
1373 event needs attention (e.g. a signal handler or
1374 async I/O handler); see Py_AddPendingCall() and
1375 Py_MakePendingCalls() above. */
1376
1377 if (_Py_atomic_load_relaxed(eval_breaker)) {
1378 opcode = _Py_OPCODE(*next_instr);
1379 if (opcode == SETUP_FINALLY ||
1380 opcode == SETUP_WITH ||
1381 opcode == BEFORE_ASYNC_WITH ||
1382 opcode == YIELD_FROM) {
1383 /* Few cases where we skip running signal handlers and other
1384 pending calls:
1385 - If we're about to enter the 'with:'. It will prevent
1386 emitting a resource warning in the common idiom
1387 'with open(path) as file:'.
1388 - If we're about to enter the 'async with:'.
1389 - If we're about to enter the 'try:' of a try/finally (not
1390 *very* useful, but might help in some cases and it's
1391 traditional)
1392 - If we're resuming a chain of nested 'yield from' or
1393 'await' calls, then each frame is parked with YIELD_FROM
1394 as its next opcode. If the user hit control-C we want to
1395 wait until we've reached the innermost frame before
1396 running the signal handler and raising KeyboardInterrupt
1397 (see bpo-30039).
1398 */
1399 goto fast_next_opcode;
1400 }
1401
1402 if (eval_frame_handle_pending(tstate) != 0) {
1403 goto error;
1404 }
1405 }
1406
1407 fast_next_opcode:
1408 f->f_lasti = INSTR_OFFSET();
1409
1410 if (PyDTrace_LINE_ENABLED())
1411 maybe_dtrace_line(f, &instr_lb, &instr_ub, &instr_prev);
1412
1413 /* line-by-line tracing support */
1414
1415 if (_Py_TracingPossible(ceval2) &&
1416 tstate->c_tracefunc != NULL && !tstate->tracing) {
1417 int err;
1418 /* see maybe_call_line_trace
1419 for expository comments */
1420 f->f_stacktop = stack_pointer;
1421
1422 err = maybe_call_line_trace(tstate->c_tracefunc,
1423 tstate->c_traceobj,
1424 tstate, f,
1425 &instr_lb, &instr_ub, &instr_prev);
1426 /* Reload possibly changed frame fields */
1427 JUMPTO(f->f_lasti);
1428 if (f->f_stacktop != NULL) {
1429 stack_pointer = f->f_stacktop;
1430 f->f_stacktop = NULL;
1431 }
1432 if (err)
1433 /* trace function raised an exception */
1434 goto error;
1435 }
1436
1437 /* Extract opcode and argument */
1438
1439 NEXTOPARG();
1440 dispatch_opcode:
1441 #ifdef DYNAMIC_EXECUTION_PROFILE
1442 #ifdef DXPAIRS
1443 dxpairs[lastopcode][opcode]++;
1444 lastopcode = opcode;
1445 #endif
1446 dxp[opcode]++;
1447 #endif
1448
1449 #ifdef LLTRACE
1450 /* Instruction tracing */
1451
1452 if (lltrace) {
1453 if (HAS_ARG(opcode)) {
1454 printf("%d: %d, %d\n",
1455 f->f_lasti, opcode, oparg);
1456 }
1457 else {
1458 printf("%d: %d\n",
1459 f->f_lasti, opcode);
1460 }
1461 }
1462 #endif
1463
1464 switch (opcode) {
1465
1466 /* BEWARE!
1467 It is essential that any operation that fails must goto error
1468 and that all operation that succeed call [FAST_]DISPATCH() ! */
1469
1470 case TARGET(NOP): {
1471 FAST_DISPATCH();
1472 }
1473
1474 case TARGET(LOAD_FAST): {
1475 PyObject *value = GETLOCAL(oparg);
1476 if (value == NULL) {
1477 format_exc_check_arg(tstate, PyExc_UnboundLocalError,
1478 UNBOUNDLOCAL_ERROR_MSG,
1479 PyTuple_GetItem(co->co_varnames, oparg));
1480 goto error;
1481 }
1482 Py_INCREF(value);
1483 PUSH(value);
1484 FAST_DISPATCH();
1485 }
1486
1487 case TARGET(LOAD_CONST): {
1488 PREDICTED(LOAD_CONST);
1489 PyObject *value = GETITEM(consts, oparg);
1490 Py_INCREF(value);
1491 PUSH(value);
1492 FAST_DISPATCH();
1493 }
1494
1495 case TARGET(STORE_FAST): {
1496 PREDICTED(STORE_FAST);
1497 PyObject *value = POP();
1498 SETLOCAL(oparg, value);
1499 FAST_DISPATCH();
1500 }
1501
1502 case TARGET(POP_TOP): {
1503 PyObject *value = POP();
1504 Py_DECREF(value);
1505 FAST_DISPATCH();
1506 }
1507
1508 case TARGET(ROT_TWO): {
1509 PyObject *top = TOP();
1510 PyObject *second = SECOND();
1511 SET_TOP(second);
1512 SET_SECOND(top);
1513 FAST_DISPATCH();
1514 }
1515
1516 case TARGET(ROT_THREE): {
1517 PyObject *top = TOP();
1518 PyObject *second = SECOND();
1519 PyObject *third = THIRD();
1520 SET_TOP(second);
1521 SET_SECOND(third);
1522 SET_THIRD(top);
1523 FAST_DISPATCH();
1524 }
1525
1526 case TARGET(ROT_FOUR): {
1527 PyObject *top = TOP();
1528 PyObject *second = SECOND();
1529 PyObject *third = THIRD();
1530 PyObject *fourth = FOURTH();
1531 SET_TOP(second);
1532 SET_SECOND(third);
1533 SET_THIRD(fourth);
1534 SET_FOURTH(top);
1535 FAST_DISPATCH();
1536 }
1537
1538 case TARGET(DUP_TOP): {
1539 PyObject *top = TOP();
1540 Py_INCREF(top);
1541 PUSH(top);
1542 FAST_DISPATCH();
1543 }
1544
1545 case TARGET(DUP_TOP_TWO): {
1546 PyObject *top = TOP();
1547 PyObject *second = SECOND();
1548 Py_INCREF(top);
1549 Py_INCREF(second);
1550 STACK_GROW(2);
1551 SET_TOP(top);
1552 SET_SECOND(second);
1553 FAST_DISPATCH();
1554 }
1555
1556 case TARGET(UNARY_POSITIVE): {
1557 PyObject *value = TOP();
1558 PyObject *res = PyNumber_Positive(value);
1559 Py_DECREF(value);
1560 SET_TOP(res);
1561 if (res == NULL)
1562 goto error;
1563 DISPATCH();
1564 }
1565
1566 case TARGET(UNARY_NEGATIVE): {
1567 PyObject *value = TOP();
1568 PyObject *res = PyNumber_Negative(value);
1569 Py_DECREF(value);
1570 SET_TOP(res);
1571 if (res == NULL)
1572 goto error;
1573 DISPATCH();
1574 }
1575
1576 case TARGET(UNARY_NOT): {
1577 PyObject *value = TOP();
1578 int err = PyObject_IsTrue(value);
1579 Py_DECREF(value);
1580 if (err == 0) {
1581 Py_INCREF(Py_True);
1582 SET_TOP(Py_True);
1583 DISPATCH();
1584 }
1585 else if (err > 0) {
1586 Py_INCREF(Py_False);
1587 SET_TOP(Py_False);
1588 DISPATCH();
1589 }
1590 STACK_SHRINK(1);
1591 goto error;
1592 }
1593
1594 case TARGET(UNARY_INVERT): {
1595 PyObject *value = TOP();
1596 PyObject *res = PyNumber_Invert(value);
1597 Py_DECREF(value);
1598 SET_TOP(res);
1599 if (res == NULL)
1600 goto error;
1601 DISPATCH();
1602 }
1603
1604 case TARGET(BINARY_POWER): {
1605 PyObject *exp = POP();
1606 PyObject *base = TOP();
1607 PyObject *res = PyNumber_Power(base, exp, Py_None);
1608 Py_DECREF(base);
1609 Py_DECREF(exp);
1610 SET_TOP(res);
1611 if (res == NULL)
1612 goto error;
1613 DISPATCH();
1614 }
1615
1616 case TARGET(BINARY_MULTIPLY): {
1617 PyObject *right = POP();
1618 PyObject *left = TOP();
1619 PyObject *res = PyNumber_Multiply(left, right);
1620 Py_DECREF(left);
1621 Py_DECREF(right);
1622 SET_TOP(res);
1623 if (res == NULL)
1624 goto error;
1625 DISPATCH();
1626 }
1627
1628 case TARGET(BINARY_MATRIX_MULTIPLY): {
1629 PyObject *right = POP();
1630 PyObject *left = TOP();
1631 PyObject *res = PyNumber_MatrixMultiply(left, right);
1632 Py_DECREF(left);
1633 Py_DECREF(right);
1634 SET_TOP(res);
1635 if (res == NULL)
1636 goto error;
1637 DISPATCH();
1638 }
1639
1640 case TARGET(BINARY_TRUE_DIVIDE): {
1641 PyObject *divisor = POP();
1642 PyObject *dividend = TOP();
1643 PyObject *quotient = PyNumber_TrueDivide(dividend, divisor);
1644 Py_DECREF(dividend);
1645 Py_DECREF(divisor);
1646 SET_TOP(quotient);
1647 if (quotient == NULL)
1648 goto error;
1649 DISPATCH();
1650 }
1651
1652 case TARGET(BINARY_FLOOR_DIVIDE): {
1653 PyObject *divisor = POP();
1654 PyObject *dividend = TOP();
1655 PyObject *quotient = PyNumber_FloorDivide(dividend, divisor);
1656 Py_DECREF(dividend);
1657 Py_DECREF(divisor);
1658 SET_TOP(quotient);
1659 if (quotient == NULL)
1660 goto error;
1661 DISPATCH();
1662 }
1663
1664 case TARGET(BINARY_MODULO): {
1665 PyObject *divisor = POP();
1666 PyObject *dividend = TOP();
1667 PyObject *res;
1668 if (PyUnicode_CheckExact(dividend) && (
1669 !PyUnicode_Check(divisor) || PyUnicode_CheckExact(divisor))) {
1670 // fast path; string formatting, but not if the RHS is a str subclass
1671 // (see issue28598)
1672 res = PyUnicode_Format(dividend, divisor);
1673 } else {
1674 res = PyNumber_Remainder(dividend, divisor);
1675 }
1676 Py_DECREF(divisor);
1677 Py_DECREF(dividend);
1678 SET_TOP(res);
1679 if (res == NULL)
1680 goto error;
1681 DISPATCH();
1682 }
1683
1684 case TARGET(BINARY_ADD): {
1685 PyObject *right = POP();
1686 PyObject *left = TOP();
1687 PyObject *sum;
1688 /* NOTE(haypo): Please don't try to micro-optimize int+int on
1689 CPython using bytecode, it is simply worthless.
1690 See http://bugs.python.org/issue21955 and
1691 http://bugs.python.org/issue10044 for the discussion. In short,
1692 no patch shown any impact on a realistic benchmark, only a minor
1693 speedup on microbenchmarks. */
1694 if (PyUnicode_CheckExact(left) &&
1695 PyUnicode_CheckExact(right)) {
1696 sum = unicode_concatenate(tstate, left, right, f, next_instr);
1697 /* unicode_concatenate consumed the ref to left */
1698 }
1699 else {
1700 sum = PyNumber_Add(left, right);
1701 Py_DECREF(left);
1702 }
1703 Py_DECREF(right);
1704 SET_TOP(sum);
1705 if (sum == NULL)
1706 goto error;
1707 DISPATCH();
1708 }
1709
1710 case TARGET(BINARY_SUBTRACT): {
1711 PyObject *right = POP();
1712 PyObject *left = TOP();
1713 PyObject *diff = PyNumber_Subtract(left, right);
1714 Py_DECREF(right);
1715 Py_DECREF(left);
1716 SET_TOP(diff);
1717 if (diff == NULL)
1718 goto error;
1719 DISPATCH();
1720 }
1721
1722 case TARGET(BINARY_SUBSCR): {
1723 PyObject *sub = POP();
1724 PyObject *container = TOP();
1725 PyObject *res = PyObject_GetItem(container, sub);
1726 Py_DECREF(container);
1727 Py_DECREF(sub);
1728 SET_TOP(res);
1729 if (res == NULL)
1730 goto error;
1731 DISPATCH();
1732 }
1733
1734 case TARGET(BINARY_LSHIFT): {
1735 PyObject *right = POP();
1736 PyObject *left = TOP();
1737 PyObject *res = PyNumber_Lshift(left, right);
1738 Py_DECREF(left);
1739 Py_DECREF(right);
1740 SET_TOP(res);
1741 if (res == NULL)
1742 goto error;
1743 DISPATCH();
1744 }
1745
1746 case TARGET(BINARY_RSHIFT): {
1747 PyObject *right = POP();
1748 PyObject *left = TOP();
1749 PyObject *res = PyNumber_Rshift(left, right);
1750 Py_DECREF(left);
1751 Py_DECREF(right);
1752 SET_TOP(res);
1753 if (res == NULL)
1754 goto error;
1755 DISPATCH();
1756 }
1757
1758 case TARGET(BINARY_AND): {
1759 PyObject *right = POP();
1760 PyObject *left = TOP();
1761 PyObject *res = PyNumber_And(left, right);
1762 Py_DECREF(left);
1763 Py_DECREF(right);
1764 SET_TOP(res);
1765 if (res == NULL)
1766 goto error;
1767 DISPATCH();
1768 }
1769
1770 case TARGET(BINARY_XOR): {
1771 PyObject *right = POP();
1772 PyObject *left = TOP();
1773 PyObject *res = PyNumber_Xor(left, right);
1774 Py_DECREF(left);
1775 Py_DECREF(right);
1776 SET_TOP(res);
1777 if (res == NULL)
1778 goto error;
1779 DISPATCH();
1780 }
1781
1782 case TARGET(BINARY_OR): {
1783 PyObject *right = POP();
1784 PyObject *left = TOP();
1785 PyObject *res = PyNumber_Or(left, right);
1786 Py_DECREF(left);
1787 Py_DECREF(right);
1788 SET_TOP(res);
1789 if (res == NULL)
1790 goto error;
1791 DISPATCH();
1792 }
1793
1794 case TARGET(LIST_APPEND): {
1795 PyObject *v = POP();
1796 PyObject *list = PEEK(oparg);
1797 int err;
1798 err = PyList_Append(list, v);
1799 Py_DECREF(v);
1800 if (err != 0)
1801 goto error;
1802 PREDICT(JUMP_ABSOLUTE);
1803 DISPATCH();
1804 }
1805
1806 case TARGET(SET_ADD): {
1807 PyObject *v = POP();
1808 PyObject *set = PEEK(oparg);
1809 int err;
1810 err = PySet_Add(set, v);
1811 Py_DECREF(v);
1812 if (err != 0)
1813 goto error;
1814 PREDICT(JUMP_ABSOLUTE);
1815 DISPATCH();
1816 }
1817
1818 case TARGET(INPLACE_POWER): {
1819 PyObject *exp = POP();
1820 PyObject *base = TOP();
1821 PyObject *res = PyNumber_InPlacePower(base, exp, Py_None);
1822 Py_DECREF(base);
1823 Py_DECREF(exp);
1824 SET_TOP(res);
1825 if (res == NULL)
1826 goto error;
1827 DISPATCH();
1828 }
1829
1830 case TARGET(INPLACE_MULTIPLY): {
1831 PyObject *right = POP();
1832 PyObject *left = TOP();
1833 PyObject *res = PyNumber_InPlaceMultiply(left, right);
1834 Py_DECREF(left);
1835 Py_DECREF(right);
1836 SET_TOP(res);
1837 if (res == NULL)
1838 goto error;
1839 DISPATCH();
1840 }
1841
1842 case TARGET(INPLACE_MATRIX_MULTIPLY): {
1843 PyObject *right = POP();
1844 PyObject *left = TOP();
1845 PyObject *res = PyNumber_InPlaceMatrixMultiply(left, right);
1846 Py_DECREF(left);
1847 Py_DECREF(right);
1848 SET_TOP(res);
1849 if (res == NULL)
1850 goto error;
1851 DISPATCH();
1852 }
1853
1854 case TARGET(INPLACE_TRUE_DIVIDE): {
1855 PyObject *divisor = POP();
1856 PyObject *dividend = TOP();
1857 PyObject *quotient = PyNumber_InPlaceTrueDivide(dividend, divisor);
1858 Py_DECREF(dividend);
1859 Py_DECREF(divisor);
1860 SET_TOP(quotient);
1861 if (quotient == NULL)
1862 goto error;
1863 DISPATCH();
1864 }
1865
1866 case TARGET(INPLACE_FLOOR_DIVIDE): {
1867 PyObject *divisor = POP();
1868 PyObject *dividend = TOP();
1869 PyObject *quotient = PyNumber_InPlaceFloorDivide(dividend, divisor);
1870 Py_DECREF(dividend);
1871 Py_DECREF(divisor);
1872 SET_TOP(quotient);
1873 if (quotient == NULL)
1874 goto error;
1875 DISPATCH();
1876 }
1877
1878 case TARGET(INPLACE_MODULO): {
1879 PyObject *right = POP();
1880 PyObject *left = TOP();
1881 PyObject *mod = PyNumber_InPlaceRemainder(left, right);
1882 Py_DECREF(left);
1883 Py_DECREF(right);
1884 SET_TOP(mod);
1885 if (mod == NULL)
1886 goto error;
1887 DISPATCH();
1888 }
1889
1890 case TARGET(INPLACE_ADD): {
1891 PyObject *right = POP();
1892 PyObject *left = TOP();
1893 PyObject *sum;
1894 if (PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)) {
1895 sum = unicode_concatenate(tstate, left, right, f, next_instr);
1896 /* unicode_concatenate consumed the ref to left */
1897 }
1898 else {
1899 sum = PyNumber_InPlaceAdd(left, right);
1900 Py_DECREF(left);
1901 }
1902 Py_DECREF(right);
1903 SET_TOP(sum);
1904 if (sum == NULL)
1905 goto error;
1906 DISPATCH();
1907 }
1908
1909 case TARGET(INPLACE_SUBTRACT): {
1910 PyObject *right = POP();
1911 PyObject *left = TOP();
1912 PyObject *diff = PyNumber_InPlaceSubtract(left, right);
1913 Py_DECREF(left);
1914 Py_DECREF(right);
1915 SET_TOP(diff);
1916 if (diff == NULL)
1917 goto error;
1918 DISPATCH();
1919 }
1920
1921 case TARGET(INPLACE_LSHIFT): {
1922 PyObject *right = POP();
1923 PyObject *left = TOP();
1924 PyObject *res = PyNumber_InPlaceLshift(left, right);
1925 Py_DECREF(left);
1926 Py_DECREF(right);
1927 SET_TOP(res);
1928 if (res == NULL)
1929 goto error;
1930 DISPATCH();
1931 }
1932
1933 case TARGET(INPLACE_RSHIFT): {
1934 PyObject *right = POP();
1935 PyObject *left = TOP();
1936 PyObject *res = PyNumber_InPlaceRshift(left, right);
1937 Py_DECREF(left);
1938 Py_DECREF(right);
1939 SET_TOP(res);
1940 if (res == NULL)
1941 goto error;
1942 DISPATCH();
1943 }
1944
1945 case TARGET(INPLACE_AND): {
1946 PyObject *right = POP();
1947 PyObject *left = TOP();
1948 PyObject *res = PyNumber_InPlaceAnd(left, right);
1949 Py_DECREF(left);
1950 Py_DECREF(right);
1951 SET_TOP(res);
1952 if (res == NULL)
1953 goto error;
1954 DISPATCH();
1955 }
1956
1957 case TARGET(INPLACE_XOR): {
1958 PyObject *right = POP();
1959 PyObject *left = TOP();
1960 PyObject *res = PyNumber_InPlaceXor(left, right);
1961 Py_DECREF(left);
1962 Py_DECREF(right);
1963 SET_TOP(res);
1964 if (res == NULL)
1965 goto error;
1966 DISPATCH();
1967 }
1968
1969 case TARGET(INPLACE_OR): {
1970 PyObject *right = POP();
1971 PyObject *left = TOP();
1972 PyObject *res = PyNumber_InPlaceOr(left, right);
1973 Py_DECREF(left);
1974 Py_DECREF(right);
1975 SET_TOP(res);
1976 if (res == NULL)
1977 goto error;
1978 DISPATCH();
1979 }
1980
1981 case TARGET(STORE_SUBSCR): {
1982 PyObject *sub = TOP();
1983 PyObject *container = SECOND();
1984 PyObject *v = THIRD();
1985 int err;
1986 STACK_SHRINK(3);
1987 /* container[sub] = v */
1988 err = PyObject_SetItem(container, sub, v);
1989 Py_DECREF(v);
1990 Py_DECREF(container);
1991 Py_DECREF(sub);
1992 if (err != 0)
1993 goto error;
1994 DISPATCH();
1995 }
1996
1997 case TARGET(DELETE_SUBSCR): {
1998 PyObject *sub = TOP();
1999 PyObject *container = SECOND();
2000 int err;
2001 STACK_SHRINK(2);
2002 /* del container[sub] */
2003 err = PyObject_DelItem(container, sub);
2004 Py_DECREF(container);
2005 Py_DECREF(sub);
2006 if (err != 0)
2007 goto error;
2008 DISPATCH();
2009 }
2010
2011 case TARGET(PRINT_EXPR): {
2012 _Py_IDENTIFIER(displayhook);
2013 PyObject *value = POP();
2014 PyObject *hook = _PySys_GetObjectId(&PyId_displayhook);
2015 PyObject *res;
2016 if (hook == NULL) {
2017 _PyErr_SetString(tstate, PyExc_RuntimeError,
2018 "lost sys.displayhook");
2019 Py_DECREF(value);
2020 goto error;
2021 }
2022 res = PyObject_CallOneArg(hook, value);
2023 Py_DECREF(value);
2024 if (res == NULL)
2025 goto error;
2026 Py_DECREF(res);
2027 DISPATCH();
2028 }
2029
2030 case TARGET(RAISE_VARARGS): {
2031 PyObject *cause = NULL, *exc = NULL;
2032 switch (oparg) {
2033 case 2:
2034 cause = POP(); /* cause */
2035 /* fall through */
2036 case 1:
2037 exc = POP(); /* exc */
2038 /* fall through */
2039 case 0:
2040 if (do_raise(tstate, exc, cause)) {
2041 goto exception_unwind;
2042 }
2043 break;
2044 default:
2045 _PyErr_SetString(tstate, PyExc_SystemError,
2046 "bad RAISE_VARARGS oparg");
2047 break;
2048 }
2049 goto error;
2050 }
2051
2052 case TARGET(RETURN_VALUE): {
2053 retval = POP();
2054 assert(f->f_iblock == 0);
2055 assert(EMPTY());
2056 goto exiting;
2057 }
2058
2059 case TARGET(GET_AITER): {
2060 unaryfunc getter = NULL;
2061 PyObject *iter = NULL;
2062 PyObject *obj = TOP();
2063 PyTypeObject *type = Py_TYPE(obj);
2064
2065 if (type->tp_as_async != NULL) {
2066 getter = type->tp_as_async->am_aiter;
2067 }
2068
2069 if (getter != NULL) {
2070 iter = (*getter)(obj);
2071 Py_DECREF(obj);
2072 if (iter == NULL) {
2073 SET_TOP(NULL);
2074 goto error;
2075 }
2076 }
2077 else {
2078 SET_TOP(NULL);
2079 _PyErr_Format(tstate, PyExc_TypeError,
2080 "'async for' requires an object with "
2081 "__aiter__ method, got %.100s",
2082 type->tp_name);
2083 Py_DECREF(obj);
2084 goto error;
2085 }
2086
2087 if (Py_TYPE(iter)->tp_as_async == NULL ||
2088 Py_TYPE(iter)->tp_as_async->am_anext == NULL) {
2089
2090 SET_TOP(NULL);
2091 _PyErr_Format(tstate, PyExc_TypeError,
2092 "'async for' received an object from __aiter__ "
2093 "that does not implement __anext__: %.100s",
2094 Py_TYPE(iter)->tp_name);
2095 Py_DECREF(iter);
2096 goto error;
2097 }
2098
2099 SET_TOP(iter);
2100 DISPATCH();
2101 }
2102
2103 case TARGET(GET_ANEXT): {
2104 unaryfunc getter = NULL;
2105 PyObject *next_iter = NULL;
2106 PyObject *awaitable = NULL;
2107 PyObject *aiter = TOP();
2108 PyTypeObject *type = Py_TYPE(aiter);
2109
2110 if (PyAsyncGen_CheckExact(aiter)) {
2111 awaitable = type->tp_as_async->am_anext(aiter);
2112 if (awaitable == NULL) {
2113 goto error;
2114 }
2115 } else {
2116 if (type->tp_as_async != NULL){
2117 getter = type->tp_as_async->am_anext;
2118 }
2119
2120 if (getter != NULL) {
2121 next_iter = (*getter)(aiter);
2122 if (next_iter == NULL) {
2123 goto error;
2124 }
2125 }
2126 else {
2127 _PyErr_Format(tstate, PyExc_TypeError,
2128 "'async for' requires an iterator with "
2129 "__anext__ method, got %.100s",
2130 type->tp_name);
2131 goto error;
2132 }
2133
2134 awaitable = _PyCoro_GetAwaitableIter(next_iter);
2135 if (awaitable == NULL) {
2136 _PyErr_FormatFromCause(
2137 PyExc_TypeError,
2138 "'async for' received an invalid object "
2139 "from __anext__: %.100s",
2140 Py_TYPE(next_iter)->tp_name);
2141
2142 Py_DECREF(next_iter);
2143 goto error;
2144 } else {
2145 Py_DECREF(next_iter);
2146 }
2147 }
2148
2149 PUSH(awaitable);
2150 PREDICT(LOAD_CONST);
2151 DISPATCH();
2152 }
2153
2154 case TARGET(GET_AWAITABLE): {
2155 PREDICTED(GET_AWAITABLE);
2156 PyObject *iterable = TOP();
2157 PyObject *iter = _PyCoro_GetAwaitableIter(iterable);
2158
2159 if (iter == NULL) {
2160 int opcode_at_minus_3 = 0;
2161 if ((next_instr - first_instr) > 2) {
2162 opcode_at_minus_3 = _Py_OPCODE(next_instr[-3]);
2163 }
2164 format_awaitable_error(tstate, Py_TYPE(iterable),
2165 opcode_at_minus_3,
2166 _Py_OPCODE(next_instr[-2]));
2167 }
2168
2169 Py_DECREF(iterable);
2170
2171 if (iter != NULL && PyCoro_CheckExact(iter)) {
2172 PyObject *yf = _PyGen_yf((PyGenObject*)iter);
2173 if (yf != NULL) {
2174 /* `iter` is a coroutine object that is being
2175 awaited, `yf` is a pointer to the current awaitable
2176 being awaited on. */
2177 Py_DECREF(yf);
2178 Py_CLEAR(iter);
2179 _PyErr_SetString(tstate, PyExc_RuntimeError,
2180 "coroutine is being awaited already");
2181 /* The code below jumps to `error` if `iter` is NULL. */
2182 }
2183 }
2184
2185 SET_TOP(iter); /* Even if it's NULL */
2186
2187 if (iter == NULL) {
2188 goto error;
2189 }
2190
2191 PREDICT(LOAD_CONST);
2192 DISPATCH();
2193 }
2194
2195 case TARGET(YIELD_FROM): {
2196 PyObject *v = POP();
2197 PyObject *receiver = TOP();
2198 int err;
2199 if (PyGen_CheckExact(receiver) || PyCoro_CheckExact(receiver)) {
2200 retval = _PyGen_Send((PyGenObject *)receiver, v);
2201 } else {
2202 _Py_IDENTIFIER(send);
2203 if (v == Py_None)
2204 retval = Py_TYPE(receiver)->tp_iternext(receiver);
2205 else
2206 retval = _PyObject_CallMethodIdOneArg(receiver, &PyId_send, v);
2207 }
2208 Py_DECREF(v);
2209 if (retval == NULL) {
2210 PyObject *val;
2211 if (tstate->c_tracefunc != NULL
2212 && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
2213 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f);
2214 err = _PyGen_FetchStopIterationValue(&val);
2215 if (err < 0)
2216 goto error;
2217 Py_DECREF(receiver);
2218 SET_TOP(val);
2219 DISPATCH();
2220 }
2221 /* receiver remains on stack, retval is value to be yielded */
2222 f->f_stacktop = stack_pointer;
2223 /* and repeat... */
2224 assert(f->f_lasti >= (int)sizeof(_Py_CODEUNIT));
2225 f->f_lasti -= sizeof(_Py_CODEUNIT);
2226 goto exiting;
2227 }
2228
2229 case TARGET(YIELD_VALUE): {
2230 retval = POP();
2231
2232 if (co->co_flags & CO_ASYNC_GENERATOR) {
2233 PyObject *w = _PyAsyncGenValueWrapperNew(retval);
2234 Py_DECREF(retval);
2235 if (w == NULL) {
2236 retval = NULL;
2237 goto error;
2238 }
2239 retval = w;
2240 }
2241
2242 f->f_stacktop = stack_pointer;
2243 goto exiting;
2244 }
2245
2246 case TARGET(POP_EXCEPT): {
2247 PyObject *type, *value, *traceback;
2248 _PyErr_StackItem *exc_info;
2249 PyTryBlock *b = PyFrame_BlockPop(f);
2250 if (b->b_type != EXCEPT_HANDLER) {
2251 _PyErr_SetString(tstate, PyExc_SystemError,
2252 "popped block is not an except handler");
2253 goto error;
2254 }
2255 assert(STACK_LEVEL() >= (b)->b_level + 3 &&
2256 STACK_LEVEL() <= (b)->b_level + 4);
2257 exc_info = tstate->exc_info;
2258 type = exc_info->exc_type;
2259 value = exc_info->exc_value;
2260 traceback = exc_info->exc_traceback;
2261 exc_info->exc_type = POP();
2262 exc_info->exc_value = POP();
2263 exc_info->exc_traceback = POP();
2264 Py_XDECREF(type);
2265 Py_XDECREF(value);
2266 Py_XDECREF(traceback);
2267 DISPATCH();
2268 }
2269
2270 case TARGET(POP_BLOCK): {
2271 PREDICTED(POP_BLOCK);
2272 PyFrame_BlockPop(f);
2273 DISPATCH();
2274 }
2275
2276 case TARGET(RERAISE): {
2277 PyObject *exc = POP();
2278 PyObject *val = POP();
2279 PyObject *tb = POP();
2280 assert(PyExceptionClass_Check(exc));
2281 _PyErr_Restore(tstate, exc, val, tb);
2282 goto exception_unwind;
2283 }
2284
2285 case TARGET(END_ASYNC_FOR): {
2286 PyObject *exc = POP();
2287 assert(PyExceptionClass_Check(exc));
2288 if (PyErr_GivenExceptionMatches(exc, PyExc_StopAsyncIteration)) {
2289 PyTryBlock *b = PyFrame_BlockPop(f);
2290 assert(b->b_type == EXCEPT_HANDLER);
2291 Py_DECREF(exc);
2292 UNWIND_EXCEPT_HANDLER(b);
2293 Py_DECREF(POP());
2294 JUMPBY(oparg);
2295 FAST_DISPATCH();
2296 }
2297 else {
2298 PyObject *val = POP();
2299 PyObject *tb = POP();
2300 _PyErr_Restore(tstate, exc, val, tb);
2301 goto exception_unwind;
2302 }
2303 }
2304
2305 case TARGET(LOAD_ASSERTION_ERROR): {
2306 PyObject *value = PyExc_AssertionError;
2307 Py_INCREF(value);
2308 PUSH(value);
2309 FAST_DISPATCH();
2310 }
2311
2312 case TARGET(LOAD_BUILD_CLASS): {
2313 _Py_IDENTIFIER(__build_class__);
2314
2315 PyObject *bc;
2316 if (PyDict_CheckExact(f->f_builtins)) {
2317 bc = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___build_class__);
2318 if (bc == NULL) {
2319 if (!_PyErr_Occurred(tstate)) {
2320 _PyErr_SetString(tstate, PyExc_NameError,
2321 "__build_class__ not found");
2322 }
2323 goto error;
2324 }
2325 Py_INCREF(bc);
2326 }
2327 else {
2328 PyObject *build_class_str = _PyUnicode_FromId(&PyId___build_class__);
2329 if (build_class_str == NULL)
2330 goto error;
2331 bc = PyObject_GetItem(f->f_builtins, build_class_str);
2332 if (bc == NULL) {
2333 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
2334 _PyErr_SetString(tstate, PyExc_NameError,
2335 "__build_class__ not found");
2336 goto error;
2337 }
2338 }
2339 PUSH(bc);
2340 DISPATCH();
2341 }
2342
2343 case TARGET(STORE_NAME): {
2344 PyObject *name = GETITEM(names, oparg);
2345 PyObject *v = POP();
2346 PyObject *ns = f->f_locals;
2347 int err;
2348 if (ns == NULL) {
2349 _PyErr_Format(tstate, PyExc_SystemError,
2350 "no locals found when storing %R", name);
2351 Py_DECREF(v);
2352 goto error;
2353 }
2354 if (PyDict_CheckExact(ns))
2355 err = PyDict_SetItem(ns, name, v);
2356 else
2357 err = PyObject_SetItem(ns, name, v);
2358 Py_DECREF(v);
2359 if (err != 0)
2360 goto error;
2361 DISPATCH();
2362 }
2363
2364 case TARGET(DELETE_NAME): {
2365 PyObject *name = GETITEM(names, oparg);
2366 PyObject *ns = f->f_locals;
2367 int err;
2368 if (ns == NULL) {
2369 _PyErr_Format(tstate, PyExc_SystemError,
2370 "no locals when deleting %R", name);
2371 goto error;
2372 }
2373 err = PyObject_DelItem(ns, name);
2374 if (err != 0) {
2375 format_exc_check_arg(tstate, PyExc_NameError,
2376 NAME_ERROR_MSG,
2377 name);
2378 goto error;
2379 }
2380 DISPATCH();
2381 }
2382
2383 case TARGET(UNPACK_SEQUENCE): {
2384 PREDICTED(UNPACK_SEQUENCE);
2385 PyObject *seq = POP(), *item, **items;
2386 if (PyTuple_CheckExact(seq) &&
2387 PyTuple_GET_SIZE(seq) == oparg) {
2388 items = ((PyTupleObject *)seq)->ob_item;
2389 while (oparg--) {
2390 item = items[oparg];
2391 Py_INCREF(item);
2392 PUSH(item);
2393 }
2394 } else if (PyList_CheckExact(seq) &&
2395 PyList_GET_SIZE(seq) == oparg) {
2396 items = ((PyListObject *)seq)->ob_item;
2397 while (oparg--) {
2398 item = items[oparg];
2399 Py_INCREF(item);
2400 PUSH(item);
2401 }
2402 } else if (unpack_iterable(tstate, seq, oparg, -1,
2403 stack_pointer + oparg)) {
2404 STACK_GROW(oparg);
2405 } else {
2406 /* unpack_iterable() raised an exception */
2407 Py_DECREF(seq);
2408 goto error;
2409 }
2410 Py_DECREF(seq);
2411 DISPATCH();
2412 }
2413
2414 case TARGET(UNPACK_EX): {
2415 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
2416 PyObject *seq = POP();
2417
2418 if (unpack_iterable(tstate, seq, oparg & 0xFF, oparg >> 8,
2419 stack_pointer + totalargs)) {
2420 stack_pointer += totalargs;
2421 } else {
2422 Py_DECREF(seq);
2423 goto error;
2424 }
2425 Py_DECREF(seq);
2426 DISPATCH();
2427 }
2428
2429 case TARGET(STORE_ATTR): {
2430 PyObject *name = GETITEM(names, oparg);
2431 PyObject *owner = TOP();
2432 PyObject *v = SECOND();
2433 int err;
2434 STACK_SHRINK(2);
2435 err = PyObject_SetAttr(owner, name, v);
2436 Py_DECREF(v);
2437 Py_DECREF(owner);
2438 if (err != 0)
2439 goto error;
2440 DISPATCH();
2441 }
2442
2443 case TARGET(DELETE_ATTR): {
2444 PyObject *name = GETITEM(names, oparg);
2445 PyObject *owner = POP();
2446 int err;
2447 err = PyObject_SetAttr(owner, name, (PyObject *)NULL);
2448 Py_DECREF(owner);
2449 if (err != 0)
2450 goto error;
2451 DISPATCH();
2452 }
2453
2454 case TARGET(STORE_GLOBAL): {
2455 PyObject *name = GETITEM(names, oparg);
2456 PyObject *v = POP();
2457 int err;
2458 err = PyDict_SetItem(f->f_globals, name, v);
2459 Py_DECREF(v);
2460 if (err != 0)
2461 goto error;
2462 DISPATCH();
2463 }
2464
2465 case TARGET(DELETE_GLOBAL): {
2466 PyObject *name = GETITEM(names, oparg);
2467 int err;
2468 err = PyDict_DelItem(f->f_globals, name);
2469 if (err != 0) {
2470 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2471 format_exc_check_arg(tstate, PyExc_NameError,
2472 NAME_ERROR_MSG, name);
2473 }
2474 goto error;
2475 }
2476 DISPATCH();
2477 }
2478
2479 case TARGET(LOAD_NAME): {
2480 PyObject *name = GETITEM(names, oparg);
2481 PyObject *locals = f->f_locals;
2482 PyObject *v;
2483 if (locals == NULL) {
2484 _PyErr_Format(tstate, PyExc_SystemError,
2485 "no locals when loading %R", name);
2486 goto error;
2487 }
2488 if (PyDict_CheckExact(locals)) {
2489 v = PyDict_GetItemWithError(locals, name);
2490 if (v != NULL) {
2491 Py_INCREF(v);
2492 }
2493 else if (_PyErr_Occurred(tstate)) {
2494 goto error;
2495 }
2496 }
2497 else {
2498 v = PyObject_GetItem(locals, name);
2499 if (v == NULL) {
2500 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
2501 goto error;
2502 _PyErr_Clear(tstate);
2503 }
2504 }
2505 if (v == NULL) {
2506 v = PyDict_GetItemWithError(f->f_globals, name);
2507 if (v != NULL) {
2508 Py_INCREF(v);
2509 }
2510 else if (_PyErr_Occurred(tstate)) {
2511 goto error;
2512 }
2513 else {
2514 if (PyDict_CheckExact(f->f_builtins)) {
2515 v = PyDict_GetItemWithError(f->f_builtins, name);
2516 if (v == NULL) {
2517 if (!_PyErr_Occurred(tstate)) {
2518 format_exc_check_arg(
2519 tstate, PyExc_NameError,
2520 NAME_ERROR_MSG, name);
2521 }
2522 goto error;
2523 }
2524 Py_INCREF(v);
2525 }
2526 else {
2527 v = PyObject_GetItem(f->f_builtins, name);
2528 if (v == NULL) {
2529 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2530 format_exc_check_arg(
2531 tstate, PyExc_NameError,
2532 NAME_ERROR_MSG, name);
2533 }
2534 goto error;
2535 }
2536 }
2537 }
2538 }
2539 PUSH(v);
2540 DISPATCH();
2541 }
2542
2543 case TARGET(LOAD_GLOBAL): {
2544 PyObject *name;
2545 PyObject *v;
2546 if (PyDict_CheckExact(f->f_globals)
2547 && PyDict_CheckExact(f->f_builtins))
2548 {
2549 OPCACHE_CHECK();
2550 if (co_opcache != NULL && co_opcache->optimized > 0) {
2551 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2552
2553 if (lg->globals_ver ==
2554 ((PyDictObject *)f->f_globals)->ma_version_tag
2555 && lg->builtins_ver ==
2556 ((PyDictObject *)f->f_builtins)->ma_version_tag)
2557 {
2558 PyObject *ptr = lg->ptr;
2559 OPCACHE_STAT_GLOBAL_HIT();
2560 assert(ptr != NULL);
2561 Py_INCREF(ptr);
2562 PUSH(ptr);
2563 DISPATCH();
2564 }
2565 }
2566
2567 name = GETITEM(names, oparg);
2568 v = _PyDict_LoadGlobal((PyDictObject *)f->f_globals,
2569 (PyDictObject *)f->f_builtins,
2570 name);
2571 if (v == NULL) {
2572 if (!_PyErr_OCCURRED()) {
2573 /* _PyDict_LoadGlobal() returns NULL without raising
2574 * an exception if the key doesn't exist */
2575 format_exc_check_arg(tstate, PyExc_NameError,
2576 NAME_ERROR_MSG, name);
2577 }
2578 goto error;
2579 }
2580
2581 if (co_opcache != NULL) {
2582 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2583
2584 if (co_opcache->optimized == 0) {
2585 /* Wasn't optimized before. */
2586 OPCACHE_STAT_GLOBAL_OPT();
2587 } else {
2588 OPCACHE_STAT_GLOBAL_MISS();
2589 }
2590
2591 co_opcache->optimized = 1;
2592 lg->globals_ver =
2593 ((PyDictObject *)f->f_globals)->ma_version_tag;
2594 lg->builtins_ver =
2595 ((PyDictObject *)f->f_builtins)->ma_version_tag;
2596 lg->ptr = v; /* borrowed */
2597 }
2598
2599 Py_INCREF(v);
2600 }
2601 else {
2602 /* Slow-path if globals or builtins is not a dict */
2603
2604 /* namespace 1: globals */
2605 name = GETITEM(names, oparg);
2606 v = PyObject_GetItem(f->f_globals, name);
2607 if (v == NULL) {
2608 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2609 goto error;
2610 }
2611 _PyErr_Clear(tstate);
2612
2613 /* namespace 2: builtins */
2614 v = PyObject_GetItem(f->f_builtins, name);
2615 if (v == NULL) {
2616 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2617 format_exc_check_arg(
2618 tstate, PyExc_NameError,
2619 NAME_ERROR_MSG, name);
2620 }
2621 goto error;
2622 }
2623 }
2624 }
2625 PUSH(v);
2626 DISPATCH();
2627 }
2628
2629 case TARGET(DELETE_FAST): {
2630 PyObject *v = GETLOCAL(oparg);
2631 if (v != NULL) {
2632 SETLOCAL(oparg, NULL);
2633 DISPATCH();
2634 }
2635 format_exc_check_arg(
2636 tstate, PyExc_UnboundLocalError,
2637 UNBOUNDLOCAL_ERROR_MSG,
2638 PyTuple_GetItem(co->co_varnames, oparg)
2639 );
2640 goto error;
2641 }
2642
2643 case TARGET(DELETE_DEREF): {
2644 PyObject *cell = freevars[oparg];
2645 PyObject *oldobj = PyCell_GET(cell);
2646 if (oldobj != NULL) {
2647 PyCell_SET(cell, NULL);
2648 Py_DECREF(oldobj);
2649 DISPATCH();
2650 }
2651 format_exc_unbound(tstate, co, oparg);
2652 goto error;
2653 }
2654
2655 case TARGET(LOAD_CLOSURE): {
2656 PyObject *cell = freevars[oparg];
2657 Py_INCREF(cell);
2658 PUSH(cell);
2659 DISPATCH();
2660 }
2661
2662 case TARGET(LOAD_CLASSDEREF): {
2663 PyObject *name, *value, *locals = f->f_locals;
2664 Py_ssize_t idx;
2665 assert(locals);
2666 assert(oparg >= PyTuple_GET_SIZE(co->co_cellvars));
2667 idx = oparg - PyTuple_GET_SIZE(co->co_cellvars);
2668 assert(idx >= 0 && idx < PyTuple_GET_SIZE(co->co_freevars));
2669 name = PyTuple_GET_ITEM(co->co_freevars, idx);
2670 if (PyDict_CheckExact(locals)) {
2671 value = PyDict_GetItemWithError(locals, name);
2672 if (value != NULL) {
2673 Py_INCREF(value);
2674 }
2675 else if (_PyErr_Occurred(tstate)) {
2676 goto error;
2677 }
2678 }
2679 else {
2680 value = PyObject_GetItem(locals, name);
2681 if (value == NULL) {
2682 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2683 goto error;
2684 }
2685 _PyErr_Clear(tstate);
2686 }
2687 }
2688 if (!value) {
2689 PyObject *cell = freevars[oparg];
2690 value = PyCell_GET(cell);
2691 if (value == NULL) {
2692 format_exc_unbound(tstate, co, oparg);
2693 goto error;
2694 }
2695 Py_INCREF(value);
2696 }
2697 PUSH(value);
2698 DISPATCH();
2699 }
2700
2701 case TARGET(LOAD_DEREF): {
2702 PyObject *cell = freevars[oparg];
2703 PyObject *value = PyCell_GET(cell);
2704 if (value == NULL) {
2705 format_exc_unbound(tstate, co, oparg);
2706 goto error;
2707 }
2708 Py_INCREF(value);
2709 PUSH(value);
2710 DISPATCH();
2711 }
2712
2713 case TARGET(STORE_DEREF): {
2714 PyObject *v = POP();
2715 PyObject *cell = freevars[oparg];
2716 PyObject *oldobj = PyCell_GET(cell);
2717 PyCell_SET(cell, v);
2718 Py_XDECREF(oldobj);
2719 DISPATCH();
2720 }
2721
2722 case TARGET(BUILD_STRING): {
2723 PyObject *str;
2724 PyObject *empty = PyUnicode_New(0, 0);
2725 if (empty == NULL) {
2726 goto error;
2727 }
2728 str = _PyUnicode_JoinArray(empty, stack_pointer - oparg, oparg);
2729 Py_DECREF(empty);
2730 if (str == NULL)
2731 goto error;
2732 while (--oparg >= 0) {
2733 PyObject *item = POP();
2734 Py_DECREF(item);
2735 }
2736 PUSH(str);
2737 DISPATCH();
2738 }
2739
2740 case TARGET(BUILD_TUPLE): {
2741 PyObject *tup = PyTuple_New(oparg);
2742 if (tup == NULL)
2743 goto error;
2744 while (--oparg >= 0) {
2745 PyObject *item = POP();
2746 PyTuple_SET_ITEM(tup, oparg, item);
2747 }
2748 PUSH(tup);
2749 DISPATCH();
2750 }
2751
2752 case TARGET(BUILD_LIST): {
2753 PyObject *list = PyList_New(oparg);
2754 if (list == NULL)
2755 goto error;
2756 while (--oparg >= 0) {
2757 PyObject *item = POP();
2758 PyList_SET_ITEM(list, oparg, item);
2759 }
2760 PUSH(list);
2761 DISPATCH();
2762 }
2763
2764 case TARGET(LIST_TO_TUPLE): {
2765 PyObject *list = POP();
2766 PyObject *tuple = PyList_AsTuple(list);
2767 Py_DECREF(list);
2768 if (tuple == NULL) {
2769 goto error;
2770 }
2771 PUSH(tuple);
2772 DISPATCH();
2773 }
2774
2775 case TARGET(LIST_EXTEND): {
2776 PyObject *iterable = POP();
2777 PyObject *list = PEEK(oparg);
2778 PyObject *none_val = _PyList_Extend((PyListObject *)list, iterable);
2779 if (none_val == NULL) {
2780 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
2781 (Py_TYPE(iterable)->tp_iter == NULL && !PySequence_Check(iterable)))
2782 {
2783 _PyErr_Clear(tstate);
2784 _PyErr_Format(tstate, PyExc_TypeError,
2785 "Value after * must be an iterable, not %.200s",
2786 Py_TYPE(iterable)->tp_name);
2787 }
2788 Py_DECREF(iterable);
2789 goto error;
2790 }
2791 Py_DECREF(none_val);
2792 Py_DECREF(iterable);
2793 DISPATCH();
2794 }
2795
2796 case TARGET(SET_UPDATE): {
2797 PyObject *iterable = POP();
2798 PyObject *set = PEEK(oparg);
2799 int err = _PySet_Update(set, iterable);
2800 Py_DECREF(iterable);
2801 if (err < 0) {
2802 goto error;
2803 }
2804 DISPATCH();
2805 }
2806
2807 case TARGET(BUILD_SET): {
2808 PyObject *set = PySet_New(NULL);
2809 int err = 0;
2810 int i;
2811 if (set == NULL)
2812 goto error;
2813 for (i = oparg; i > 0; i--) {
2814 PyObject *item = PEEK(i);
2815 if (err == 0)
2816 err = PySet_Add(set, item);
2817 Py_DECREF(item);
2818 }
2819 STACK_SHRINK(oparg);
2820 if (err != 0) {
2821 Py_DECREF(set);
2822 goto error;
2823 }
2824 PUSH(set);
2825 DISPATCH();
2826 }
2827
2828 case TARGET(BUILD_MAP): {
2829 Py_ssize_t i;
2830 PyObject *map = _PyDict_NewPresized((Py_ssize_t)oparg);
2831 if (map == NULL)
2832 goto error;
2833 for (i = oparg; i > 0; i--) {
2834 int err;
2835 PyObject *key = PEEK(2*i);
2836 PyObject *value = PEEK(2*i - 1);
2837 err = PyDict_SetItem(map, key, value);
2838 if (err != 0) {
2839 Py_DECREF(map);
2840 goto error;
2841 }
2842 }
2843
2844 while (oparg--) {
2845 Py_DECREF(POP());
2846 Py_DECREF(POP());
2847 }
2848 PUSH(map);
2849 DISPATCH();
2850 }
2851
2852 case TARGET(SETUP_ANNOTATIONS): {
2853 _Py_IDENTIFIER(__annotations__);
2854 int err;
2855 PyObject *ann_dict;
2856 if (f->f_locals == NULL) {
2857 _PyErr_Format(tstate, PyExc_SystemError,
2858 "no locals found when setting up annotations");
2859 goto error;
2860 }
2861 /* check if __annotations__ in locals()... */
2862 if (PyDict_CheckExact(f->f_locals)) {
2863 ann_dict = _PyDict_GetItemIdWithError(f->f_locals,
2864 &PyId___annotations__);
2865 if (ann_dict == NULL) {
2866 if (_PyErr_Occurred(tstate)) {
2867 goto error;
2868 }
2869 /* ...if not, create a new one */
2870 ann_dict = PyDict_New();
2871 if (ann_dict == NULL) {
2872 goto error;
2873 }
2874 err = _PyDict_SetItemId(f->f_locals,
2875 &PyId___annotations__, ann_dict);
2876 Py_DECREF(ann_dict);
2877 if (err != 0) {
2878 goto error;
2879 }
2880 }
2881 }
2882 else {
2883 /* do the same if locals() is not a dict */
2884 PyObject *ann_str = _PyUnicode_FromId(&PyId___annotations__);
2885 if (ann_str == NULL) {
2886 goto error;
2887 }
2888 ann_dict = PyObject_GetItem(f->f_locals, ann_str);
2889 if (ann_dict == NULL) {
2890 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2891 goto error;
2892 }
2893 _PyErr_Clear(tstate);
2894 ann_dict = PyDict_New();
2895 if (ann_dict == NULL) {
2896 goto error;
2897 }
2898 err = PyObject_SetItem(f->f_locals, ann_str, ann_dict);
2899 Py_DECREF(ann_dict);
2900 if (err != 0) {
2901 goto error;
2902 }
2903 }
2904 else {
2905 Py_DECREF(ann_dict);
2906 }
2907 }
2908 DISPATCH();
2909 }
2910
2911 case TARGET(BUILD_CONST_KEY_MAP): {
2912 Py_ssize_t i;
2913 PyObject *map;
2914 PyObject *keys = TOP();
2915 if (!PyTuple_CheckExact(keys) ||
2916 PyTuple_GET_SIZE(keys) != (Py_ssize_t)oparg) {
2917 _PyErr_SetString(tstate, PyExc_SystemError,
2918 "bad BUILD_CONST_KEY_MAP keys argument");
2919 goto error;
2920 }
2921 map = _PyDict_NewPresized((Py_ssize_t)oparg);
2922 if (map == NULL) {
2923 goto error;
2924 }
2925 for (i = oparg; i > 0; i--) {
2926 int err;
2927 PyObject *key = PyTuple_GET_ITEM(keys, oparg - i);
2928 PyObject *value = PEEK(i + 1);
2929 err = PyDict_SetItem(map, key, value);
2930 if (err != 0) {
2931 Py_DECREF(map);
2932 goto error;
2933 }
2934 }
2935
2936 Py_DECREF(POP());
2937 while (oparg--) {
2938 Py_DECREF(POP());
2939 }
2940 PUSH(map);
2941 DISPATCH();
2942 }
2943
2944 case TARGET(DICT_UPDATE): {
2945 PyObject *update = POP();
2946 PyObject *dict = PEEK(oparg);
2947 if (PyDict_Update(dict, update) < 0) {
2948 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
2949 _PyErr_Format(tstate, PyExc_TypeError,
2950 "'%.200s' object is not a mapping",
2951 Py_TYPE(update)->tp_name);
2952 }
2953 Py_DECREF(update);
2954 goto error;
2955 }
2956 Py_DECREF(update);
2957 DISPATCH();
2958 }
2959
2960 case TARGET(DICT_MERGE): {
2961 PyObject *update = POP();
2962 PyObject *dict = PEEK(oparg);
2963
2964 if (_PyDict_MergeEx(dict, update, 2) < 0) {
2965 format_kwargs_error(tstate, PEEK(2 + oparg), update);
2966 Py_DECREF(update);
2967 goto error;
2968 }
2969 Py_DECREF(update);
2970 PREDICT(CALL_FUNCTION_EX);
2971 DISPATCH();
2972 }
2973
2974 case TARGET(MAP_ADD): {
2975 PyObject *value = TOP();
2976 PyObject *key = SECOND();
2977 PyObject *map;
2978 int err;
2979 STACK_SHRINK(2);
2980 map = PEEK(oparg); /* dict */
2981 assert(PyDict_CheckExact(map));
2982 err = PyDict_SetItem(map, key, value); /* map[key] = value */
2983 Py_DECREF(value);
2984 Py_DECREF(key);
2985 if (err != 0)
2986 goto error;
2987 PREDICT(JUMP_ABSOLUTE);
2988 DISPATCH();
2989 }
2990
2991 case TARGET(LOAD_ATTR): {
2992 PyObject *name = GETITEM(names, oparg);
2993 PyObject *owner = TOP();
2994 PyObject *res = PyObject_GetAttr(owner, name);
2995 Py_DECREF(owner);
2996 SET_TOP(res);
2997 if (res == NULL)
2998 goto error;
2999 DISPATCH();
3000 }
3001
3002 case TARGET(COMPARE_OP): {
3003 assert(oparg <= Py_GE);
3004 PyObject *right = POP();
3005 PyObject *left = TOP();
3006 PyObject *res = PyObject_RichCompare(left, right, oparg);
3007 SET_TOP(res);
3008 Py_DECREF(left);
3009 Py_DECREF(right);
3010 if (res == NULL)
3011 goto error;
3012 PREDICT(POP_JUMP_IF_FALSE);
3013 PREDICT(POP_JUMP_IF_TRUE);
3014 DISPATCH();
3015 }
3016
3017 case TARGET(IS_OP): {
3018 PyObject *right = POP();
3019 PyObject *left = TOP();
3020 int res = (left == right)^oparg;
3021 PyObject *b = res ? Py_True : Py_False;
3022 Py_INCREF(b);
3023 SET_TOP(b);
3024 Py_DECREF(left);
3025 Py_DECREF(right);
3026 PREDICT(POP_JUMP_IF_FALSE);
3027 PREDICT(POP_JUMP_IF_TRUE);
3028 FAST_DISPATCH();
3029 }
3030
3031 case TARGET(CONTAINS_OP): {
3032 PyObject *right = POP();
3033 PyObject *left = POP();
3034 int res = PySequence_Contains(right, left);
3035 Py_DECREF(left);
3036 Py_DECREF(right);
3037 if (res < 0) {
3038 goto error;
3039 }
3040 PyObject *b = (res^oparg) ? Py_True : Py_False;
3041 Py_INCREF(b);
3042 PUSH(b);
3043 PREDICT(POP_JUMP_IF_FALSE);
3044 PREDICT(POP_JUMP_IF_TRUE);
3045 FAST_DISPATCH();
3046 }
3047
3048 #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
3049 "BaseException is not allowed"
3050
3051 case TARGET(JUMP_IF_NOT_EXC_MATCH): {
3052 PyObject *right = POP();
3053 PyObject *left = POP();
3054 if (PyTuple_Check(right)) {
3055 Py_ssize_t i, length;
3056 length = PyTuple_GET_SIZE(right);
3057 for (i = 0; i < length; i++) {
3058 PyObject *exc = PyTuple_GET_ITEM(right, i);
3059 if (!PyExceptionClass_Check(exc)) {
3060 _PyErr_SetString(tstate, PyExc_TypeError,
3061 CANNOT_CATCH_MSG);
3062 Py_DECREF(left);
3063 Py_DECREF(right);
3064 goto error;
3065 }
3066 }
3067 }
3068 else {
3069 if (!PyExceptionClass_Check(right)) {
3070 _PyErr_SetString(tstate, PyExc_TypeError,
3071 CANNOT_CATCH_MSG);
3072 Py_DECREF(left);
3073 Py_DECREF(right);
3074 goto error;
3075 }
3076 }
3077 int res = PyErr_GivenExceptionMatches(left, right);
3078 Py_DECREF(left);
3079 Py_DECREF(right);
3080 if (res > 0) {
3081 /* Exception matches -- Do nothing */;
3082 }
3083 else if (res == 0) {
3084 JUMPTO(oparg);
3085 }
3086 else {
3087 goto error;
3088 }
3089 DISPATCH();
3090 }
3091
3092 case TARGET(IMPORT_NAME): {
3093 PyObject *name = GETITEM(names, oparg);
3094 PyObject *fromlist = POP();
3095 PyObject *level = TOP();
3096 PyObject *res;
3097 res = import_name(tstate, f, name, fromlist, level);
3098 Py_DECREF(level);
3099 Py_DECREF(fromlist);
3100 SET_TOP(res);
3101 if (res == NULL)
3102 goto error;
3103 DISPATCH();
3104 }
3105
3106 case TARGET(IMPORT_STAR): {
3107 PyObject *from = POP(), *locals;
3108 int err;
3109 if (PyFrame_FastToLocalsWithError(f) < 0) {
3110 Py_DECREF(from);
3111 goto error;
3112 }
3113
3114 locals = f->f_locals;
3115 if (locals == NULL) {
3116 _PyErr_SetString(tstate, PyExc_SystemError,
3117 "no locals found during 'import *'");
3118 Py_DECREF(from);
3119 goto error;
3120 }
3121 err = import_all_from(tstate, locals, from);
3122 PyFrame_LocalsToFast(f, 0);
3123 Py_DECREF(from);
3124 if (err != 0)
3125 goto error;
3126 DISPATCH();
3127 }
3128
3129 case TARGET(IMPORT_FROM): {
3130 PyObject *name = GETITEM(names, oparg);
3131 PyObject *from = TOP();
3132 PyObject *res;
3133 res = import_from(tstate, from, name);
3134 PUSH(res);
3135 if (res == NULL)
3136 goto error;
3137 DISPATCH();
3138 }
3139
3140 case TARGET(JUMP_FORWARD): {
3141 JUMPBY(oparg);
3142 FAST_DISPATCH();
3143 }
3144
3145 case TARGET(POP_JUMP_IF_FALSE): {
3146 PREDICTED(POP_JUMP_IF_FALSE);
3147 PyObject *cond = POP();
3148 int err;
3149 if (cond == Py_True) {
3150 Py_DECREF(cond);
3151 FAST_DISPATCH();
3152 }
3153 if (cond == Py_False) {
3154 Py_DECREF(cond);
3155 JUMPTO(oparg);
3156 FAST_DISPATCH();
3157 }
3158 err = PyObject_IsTrue(cond);
3159 Py_DECREF(cond);
3160 if (err > 0)
3161 ;
3162 else if (err == 0)
3163 JUMPTO(oparg);
3164 else
3165 goto error;
3166 DISPATCH();
3167 }
3168
3169 case TARGET(POP_JUMP_IF_TRUE): {
3170 PREDICTED(POP_JUMP_IF_TRUE);
3171 PyObject *cond = POP();
3172 int err;
3173 if (cond == Py_False) {
3174 Py_DECREF(cond);
3175 FAST_DISPATCH();
3176 }
3177 if (cond == Py_True) {
3178 Py_DECREF(cond);
3179 JUMPTO(oparg);
3180 FAST_DISPATCH();
3181 }
3182 err = PyObject_IsTrue(cond);
3183 Py_DECREF(cond);
3184 if (err > 0) {
3185 JUMPTO(oparg);
3186 }
3187 else if (err == 0)
3188 ;
3189 else
3190 goto error;
3191 DISPATCH();
3192 }
3193
3194 case TARGET(JUMP_IF_FALSE_OR_POP): {
3195 PyObject *cond = TOP();
3196 int err;
3197 if (cond == Py_True) {
3198 STACK_SHRINK(1);
3199 Py_DECREF(cond);
3200 FAST_DISPATCH();
3201 }
3202 if (cond == Py_False) {
3203 JUMPTO(oparg);
3204 FAST_DISPATCH();
3205 }
3206 err = PyObject_IsTrue(cond);
3207 if (err > 0) {
3208 STACK_SHRINK(1);
3209 Py_DECREF(cond);
3210 }
3211 else if (err == 0)
3212 JUMPTO(oparg);
3213 else
3214 goto error;
3215 DISPATCH();
3216 }
3217
3218 case TARGET(JUMP_IF_TRUE_OR_POP): {
3219 PyObject *cond = TOP();
3220 int err;
3221 if (cond == Py_False) {
3222 STACK_SHRINK(1);
3223 Py_DECREF(cond);
3224 FAST_DISPATCH();
3225 }
3226 if (cond == Py_True) {
3227 JUMPTO(oparg);
3228 FAST_DISPATCH();
3229 }
3230 err = PyObject_IsTrue(cond);
3231 if (err > 0) {
3232 JUMPTO(oparg);
3233 }
3234 else if (err == 0) {
3235 STACK_SHRINK(1);
3236 Py_DECREF(cond);
3237 }
3238 else
3239 goto error;
3240 DISPATCH();
3241 }
3242
3243 case TARGET(JUMP_ABSOLUTE): {
3244 PREDICTED(JUMP_ABSOLUTE);
3245 JUMPTO(oparg);
3246 #if FAST_LOOPS
3247 /* Enabling this path speeds-up all while and for-loops by bypassing
3248 the per-loop checks for signals. By default, this should be turned-off
3249 because it prevents detection of a control-break in tight loops like
3250 "while 1: pass". Compile with this option turned-on when you need
3251 the speed-up and do not need break checking inside tight loops (ones
3252 that contain only instructions ending with FAST_DISPATCH).
3253 */
3254 FAST_DISPATCH();
3255 #else
3256 DISPATCH();
3257 #endif
3258 }
3259
3260 case TARGET(GET_ITER): {
3261 /* before: [obj]; after [getiter(obj)] */
3262 PyObject *iterable = TOP();
3263 PyObject *iter = PyObject_GetIter(iterable);
3264 Py_DECREF(iterable);
3265 SET_TOP(iter);
3266 if (iter == NULL)
3267 goto error;
3268 PREDICT(FOR_ITER);
3269 PREDICT(CALL_FUNCTION);
3270 DISPATCH();
3271 }
3272
3273 case TARGET(GET_YIELD_FROM_ITER): {
3274 /* before: [obj]; after [getiter(obj)] */
3275 PyObject *iterable = TOP();
3276 PyObject *iter;
3277 if (PyCoro_CheckExact(iterable)) {
3278 /* `iterable` is a coroutine */
3279 if (!(co->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))) {
3280 /* and it is used in a 'yield from' expression of a
3281 regular generator. */
3282 Py_DECREF(iterable);
3283 SET_TOP(NULL);
3284 _PyErr_SetString(tstate, PyExc_TypeError,
3285 "cannot 'yield from' a coroutine object "
3286 "in a non-coroutine generator");
3287 goto error;
3288 }
3289 }
3290 else if (!PyGen_CheckExact(iterable)) {
3291 /* `iterable` is not a generator. */
3292 iter = PyObject_GetIter(iterable);
3293 Py_DECREF(iterable);
3294 SET_TOP(iter);
3295 if (iter == NULL)
3296 goto error;
3297 }
3298 PREDICT(LOAD_CONST);
3299 DISPATCH();
3300 }
3301
3302 case TARGET(FOR_ITER): {
3303 PREDICTED(FOR_ITER);
3304 /* before: [iter]; after: [iter, iter()] *or* [] */
3305 PyObject *iter = TOP();
3306 PyObject *next = (*Py_TYPE(iter)->tp_iternext)(iter);
3307 if (next != NULL) {
3308 PUSH(next);
3309 PREDICT(STORE_FAST);
3310 PREDICT(UNPACK_SEQUENCE);
3311 DISPATCH();
3312 }
3313 if (_PyErr_Occurred(tstate)) {
3314 if (!_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
3315 goto error;
3316 }
3317 else if (tstate->c_tracefunc != NULL) {
3318 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f);
3319 }
3320 _PyErr_Clear(tstate);
3321 }
3322 /* iterator ended normally */
3323 STACK_SHRINK(1);
3324 Py_DECREF(iter);
3325 JUMPBY(oparg);
3326 PREDICT(POP_BLOCK);
3327 DISPATCH();
3328 }
3329
3330 case TARGET(SETUP_FINALLY): {
3331 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
3332 STACK_LEVEL());
3333 DISPATCH();
3334 }
3335
3336 case TARGET(BEFORE_ASYNC_WITH): {
3337 _Py_IDENTIFIER(__aenter__);
3338 _Py_IDENTIFIER(__aexit__);
3339 PyObject *mgr = TOP();
3340 PyObject *enter = special_lookup(tstate, mgr, &PyId___aenter__);
3341 PyObject *res;
3342 if (enter == NULL) {
3343 goto error;
3344 }
3345 PyObject *exit = special_lookup(tstate, mgr, &PyId___aexit__);
3346 if (exit == NULL) {
3347 Py_DECREF(enter);
3348 goto error;
3349 }
3350 SET_TOP(exit);
3351 Py_DECREF(mgr);
3352 res = _PyObject_CallNoArg(enter);
3353 Py_DECREF(enter);
3354 if (res == NULL)
3355 goto error;
3356 PUSH(res);
3357 PREDICT(GET_AWAITABLE);
3358 DISPATCH();
3359 }
3360
3361 case TARGET(SETUP_ASYNC_WITH): {
3362 PyObject *res = POP();
3363 /* Setup the finally block before pushing the result
3364 of __aenter__ on the stack. */
3365 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
3366 STACK_LEVEL());
3367 PUSH(res);
3368 DISPATCH();
3369 }
3370
3371 case TARGET(SETUP_WITH): {
3372 _Py_IDENTIFIER(__enter__);
3373 _Py_IDENTIFIER(__exit__);
3374 PyObject *mgr = TOP();
3375 PyObject *enter = special_lookup(tstate, mgr, &PyId___enter__);
3376 PyObject *res;
3377 if (enter == NULL) {
3378 goto error;
3379 }
3380 PyObject *exit = special_lookup(tstate, mgr, &PyId___exit__);
3381 if (exit == NULL) {
3382 Py_DECREF(enter);
3383 goto error;
3384 }
3385 SET_TOP(exit);
3386 Py_DECREF(mgr);
3387 res = _PyObject_CallNoArg(enter);
3388 Py_DECREF(enter);
3389 if (res == NULL)
3390 goto error;
3391 /* Setup the finally block before pushing the result
3392 of __enter__ on the stack. */
3393 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
3394 STACK_LEVEL());
3395
3396 PUSH(res);
3397 DISPATCH();
3398 }
3399
3400 case TARGET(WITH_EXCEPT_START): {
3401 /* At the top of the stack are 7 values:
3402 - (TOP, SECOND, THIRD) = exc_info()
3403 - (FOURTH, FIFTH, SIXTH) = previous exception for EXCEPT_HANDLER
3404 - SEVENTH: the context.__exit__ bound method
3405 We call SEVENTH(TOP, SECOND, THIRD).
3406 Then we push again the TOP exception and the __exit__
3407 return value.
3408 */
3409 PyObject *exit_func;
3410 PyObject *exc, *val, *tb, *res;
3411
3412 exc = TOP();
3413 val = SECOND();
3414 tb = THIRD();
3415 assert(exc != Py_None);
3416 assert(!PyLong_Check(exc));
3417 exit_func = PEEK(7);
3418 PyObject *stack[4] = {NULL, exc, val, tb};
3419 res = PyObject_Vectorcall(exit_func, stack + 1,
3420 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
3421 if (res == NULL)
3422 goto error;
3423
3424 PUSH(res);
3425 DISPATCH();
3426 }
3427
3428 case TARGET(LOAD_METHOD): {
3429 /* Designed to work in tandem with CALL_METHOD. */
3430 PyObject *name = GETITEM(names, oparg);
3431 PyObject *obj = TOP();
3432 PyObject *meth = NULL;
3433
3434 int meth_found = _PyObject_GetMethod(obj, name, &meth);
3435
3436 if (meth == NULL) {
3437 /* Most likely attribute wasn't found. */
3438 goto error;
3439 }
3440
3441 if (meth_found) {
3442 /* We can bypass temporary bound method object.
3443 meth is unbound method and obj is self.
3444
3445 meth | self | arg1 | ... | argN
3446 */
3447 SET_TOP(meth);
3448 PUSH(obj); // self
3449 }
3450 else {
3451 /* meth is not an unbound method (but a regular attr, or
3452 something was returned by a descriptor protocol). Set
3453 the second element of the stack to NULL, to signal
3454 CALL_METHOD that it's not a method call.
3455
3456 NULL | meth | arg1 | ... | argN
3457 */
3458 SET_TOP(NULL);
3459 Py_DECREF(obj);
3460 PUSH(meth);
3461 }
3462 DISPATCH();
3463 }
3464
3465 case TARGET(CALL_METHOD): {
3466 /* Designed to work in tamdem with LOAD_METHOD. */
3467 PyObject **sp, *res, *meth;
3468
3469 sp = stack_pointer;
3470
3471 meth = PEEK(oparg + 2);
3472 if (meth == NULL) {
3473 /* `meth` is NULL when LOAD_METHOD thinks that it's not
3474 a method call.
3475
3476 Stack layout:
3477
3478 ... | NULL | callable | arg1 | ... | argN
3479 ^- TOP()
3480 ^- (-oparg)
3481 ^- (-oparg-1)
3482 ^- (-oparg-2)
3483
3484 `callable` will be POPed by call_function.
3485 NULL will will be POPed manually later.
3486 */
3487 res = call_function(tstate, &sp, oparg, NULL);
3488 stack_pointer = sp;
3489 (void)POP(); /* POP the NULL. */
3490 }
3491 else {
3492 /* This is a method call. Stack layout:
3493
3494 ... | method | self | arg1 | ... | argN
3495 ^- TOP()
3496 ^- (-oparg)
3497 ^- (-oparg-1)
3498 ^- (-oparg-2)
3499
3500 `self` and `method` will be POPed by call_function.
3501 We'll be passing `oparg + 1` to call_function, to
3502 make it accept the `self` as a first argument.
3503 */
3504 res = call_function(tstate, &sp, oparg + 1, NULL);
3505 stack_pointer = sp;
3506 }
3507
3508 PUSH(res);
3509 if (res == NULL)
3510 goto error;
3511 DISPATCH();
3512 }
3513
3514 case TARGET(CALL_FUNCTION): {
3515 PREDICTED(CALL_FUNCTION);
3516 PyObject **sp, *res;
3517 sp = stack_pointer;
3518 res = call_function(tstate, &sp, oparg, NULL);
3519 stack_pointer = sp;
3520 PUSH(res);
3521 if (res == NULL) {
3522 goto error;
3523 }
3524 DISPATCH();
3525 }
3526
3527 case TARGET(CALL_FUNCTION_KW): {
3528 PyObject **sp, *res, *names;
3529
3530 names = POP();
3531 assert(PyTuple_Check(names));
3532 assert(PyTuple_GET_SIZE(names) <= oparg);
3533 /* We assume without checking that names contains only strings */
3534 sp = stack_pointer;
3535 res = call_function(tstate, &sp, oparg, names);
3536 stack_pointer = sp;
3537 PUSH(res);
3538 Py_DECREF(names);
3539
3540 if (res == NULL) {
3541 goto error;
3542 }
3543 DISPATCH();
3544 }
3545
3546 case TARGET(CALL_FUNCTION_EX): {
3547 PREDICTED(CALL_FUNCTION_EX);
3548 PyObject *func, *callargs, *kwargs = NULL, *result;
3549 if (oparg & 0x01) {
3550 kwargs = POP();
3551 if (!PyDict_CheckExact(kwargs)) {
3552 PyObject *d = PyDict_New();
3553 if (d == NULL)
3554 goto error;
3555 if (_PyDict_MergeEx(d, kwargs, 2) < 0) {
3556 Py_DECREF(d);
3557 format_kwargs_error(tstate, SECOND(), kwargs);
3558 Py_DECREF(kwargs);
3559 goto error;
3560 }
3561 Py_DECREF(kwargs);
3562 kwargs = d;
3563 }
3564 assert(PyDict_CheckExact(kwargs));
3565 }
3566 callargs = POP();
3567 func = TOP();
3568 if (!PyTuple_CheckExact(callargs)) {
3569 if (check_args_iterable(tstate, func, callargs) < 0) {
3570 Py_DECREF(callargs);
3571 goto error;
3572 }
3573 Py_SETREF(callargs, PySequence_Tuple(callargs));
3574 if (callargs == NULL) {
3575 goto error;
3576 }
3577 }
3578 assert(PyTuple_CheckExact(callargs));
3579
3580 result = do_call_core(tstate, func, callargs, kwargs);
3581 Py_DECREF(func);
3582 Py_DECREF(callargs);
3583 Py_XDECREF(kwargs);
3584
3585 SET_TOP(result);
3586 if (result == NULL) {
3587 goto error;
3588 }
3589 DISPATCH();
3590 }
3591
3592 case TARGET(MAKE_FUNCTION): {
3593 PyObject *qualname = POP();
3594 PyObject *codeobj = POP();
3595 PyFunctionObject *func = (PyFunctionObject *)
3596 PyFunction_NewWithQualName(codeobj, f->f_globals, qualname);
3597
3598 Py_DECREF(codeobj);
3599 Py_DECREF(qualname);
3600 if (func == NULL) {
3601 goto error;
3602 }
3603
3604 if (oparg & 0x08) {
3605 assert(PyTuple_CheckExact(TOP()));
3606 func ->func_closure = POP();
3607 }
3608 if (oparg & 0x04) {
3609 assert(PyDict_CheckExact(TOP()));
3610 func->func_annotations = POP();
3611 }
3612 if (oparg & 0x02) {
3613 assert(PyDict_CheckExact(TOP()));
3614 func->func_kwdefaults = POP();
3615 }
3616 if (oparg & 0x01) {
3617 assert(PyTuple_CheckExact(TOP()));
3618 func->func_defaults = POP();
3619 }
3620
3621 PUSH((PyObject *)func);
3622 DISPATCH();
3623 }
3624
3625 case TARGET(BUILD_SLICE): {
3626 PyObject *start, *stop, *step, *slice;
3627 if (oparg == 3)
3628 step = POP();
3629 else
3630 step = NULL;
3631 stop = POP();
3632 start = TOP();
3633 slice = PySlice_New(start, stop, step);
3634 Py_DECREF(start);
3635 Py_DECREF(stop);
3636 Py_XDECREF(step);
3637 SET_TOP(slice);
3638 if (slice == NULL)
3639 goto error;
3640 DISPATCH();
3641 }
3642
3643 case TARGET(FORMAT_VALUE): {
3644 /* Handles f-string value formatting. */
3645 PyObject *result;
3646 PyObject *fmt_spec;
3647 PyObject *value;
3648 PyObject *(*conv_fn)(PyObject *);
3649 int which_conversion = oparg & FVC_MASK;
3650 int have_fmt_spec = (oparg & FVS_MASK) == FVS_HAVE_SPEC;
3651
3652 fmt_spec = have_fmt_spec ? POP() : NULL;
3653 value = POP();
3654
3655 /* See if any conversion is specified. */
3656 switch (which_conversion) {
3657 case FVC_NONE: conv_fn = NULL; break;
3658 case FVC_STR: conv_fn = PyObject_Str; break;
3659 case FVC_REPR: conv_fn = PyObject_Repr; break;
3660 case FVC_ASCII: conv_fn = PyObject_ASCII; break;
3661 default:
3662 _PyErr_Format(tstate, PyExc_SystemError,
3663 "unexpected conversion flag %d",
3664 which_conversion);
3665 goto error;
3666 }
3667
3668 /* If there's a conversion function, call it and replace
3669 value with that result. Otherwise, just use value,
3670 without conversion. */
3671 if (conv_fn != NULL) {
3672 result = conv_fn(value);
3673 Py_DECREF(value);
3674 if (result == NULL) {
3675 Py_XDECREF(fmt_spec);
3676 goto error;
3677 }
3678 value = result;
3679 }
3680
3681 /* If value is a unicode object, and there's no fmt_spec,
3682 then we know the result of format(value) is value
3683 itself. In that case, skip calling format(). I plan to
3684 move this optimization in to PyObject_Format()
3685 itself. */
3686 if (PyUnicode_CheckExact(value) && fmt_spec == NULL) {
3687 /* Do nothing, just transfer ownership to result. */
3688 result = value;
3689 } else {
3690 /* Actually call format(). */
3691 result = PyObject_Format(value, fmt_spec);
3692 Py_DECREF(value);
3693 Py_XDECREF(fmt_spec);
3694 if (result == NULL) {
3695 goto error;
3696 }
3697 }
3698
3699 PUSH(result);
3700 DISPATCH();
3701 }
3702
3703 case TARGET(EXTENDED_ARG): {
3704 int oldoparg = oparg;
3705 NEXTOPARG();
3706 oparg |= oldoparg << 8;
3707 goto dispatch_opcode;
3708 }
3709
3710
3711 #if USE_COMPUTED_GOTOS
3712 _unknown_opcode:
3713 #endif
3714 default:
3715 fprintf(stderr,
3716 "XXX lineno: %d, opcode: %d\n",
3717 PyFrame_GetLineNumber(f),
3718 opcode);
3719 _PyErr_SetString(tstate, PyExc_SystemError, "unknown opcode");
3720 goto error;
3721
3722 } /* switch */
3723
3724 /* This should never be reached. Every opcode should end with DISPATCH()
3725 or goto error. */
3726 Py_UNREACHABLE();
3727
3728 error:
3729 /* Double-check exception status. */
3730 #ifdef NDEBUG
3731 if (!_PyErr_Occurred(tstate)) {
3732 _PyErr_SetString(tstate, PyExc_SystemError,
3733 "error return without exception set");
3734 }
3735 #else
3736 assert(_PyErr_Occurred(tstate));
3737 #endif
3738
3739 /* Log traceback info. */
3740 PyTraceBack_Here(f);
3741
3742 if (tstate->c_tracefunc != NULL)
3743 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj,
3744 tstate, f);
3745
3746 exception_unwind:
3747 /* Unwind stacks if an exception occurred */
3748 while (f->f_iblock > 0) {
3749 /* Pop the current block. */
3750 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
3751
3752 if (b->b_type == EXCEPT_HANDLER) {
3753 UNWIND_EXCEPT_HANDLER(b);
3754 continue;
3755 }
3756 UNWIND_BLOCK(b);
3757 if (b->b_type == SETUP_FINALLY) {
3758 PyObject *exc, *val, *tb;
3759 int handler = b->b_handler;
3760 _PyErr_StackItem *exc_info = tstate->exc_info;
3761 /* Beware, this invalidates all b->b_* fields */
3762 PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL());
3763 PUSH(exc_info->exc_traceback);
3764 PUSH(exc_info->exc_value);
3765 if (exc_info->exc_type != NULL) {
3766 PUSH(exc_info->exc_type);
3767 }
3768 else {
3769 Py_INCREF(Py_None);
3770 PUSH(Py_None);
3771 }
3772 _PyErr_Fetch(tstate, &exc, &val, &tb);
3773 /* Make the raw exception data
3774 available to the handler,
3775 so a program can emulate the
3776 Python main loop. */
3777 _PyErr_NormalizeException(tstate, &exc, &val, &tb);
3778 if (tb != NULL)
3779 PyException_SetTraceback(val, tb);
3780 else
3781 PyException_SetTraceback(val, Py_None);
3782 Py_INCREF(exc);
3783 exc_info->exc_type = exc;
3784 Py_INCREF(val);
3785 exc_info->exc_value = val;
3786 exc_info->exc_traceback = tb;
3787 if (tb == NULL)
3788 tb = Py_None;
3789 Py_INCREF(tb);
3790 PUSH(tb);
3791 PUSH(val);
3792 PUSH(exc);
3793 JUMPTO(handler);
3794 if (_Py_TracingPossible(ceval2)) {
3795 int needs_new_execution_window = (f->f_lasti < instr_lb || f->f_lasti >= instr_ub);
3796 int needs_line_update = (f->f_lasti == instr_lb || f->f_lasti < instr_prev);
3797 /* Make sure that we trace line after exception if we are in a new execution
3798 * window or we don't need a line update and we are not in the first instruction
3799 * of the line. */
3800 if (needs_new_execution_window || (!needs_line_update && instr_lb > 0)) {
3801 instr_prev = INT_MAX;
3802 }
3803 }
3804 /* Resume normal execution */
3805 goto main_loop;
3806 }
3807 } /* unwind stack */
3808
3809 /* End the loop as we still have an error */
3810 break;
3811 } /* main loop */
3812
3813 assert(retval == NULL);
3814 assert(_PyErr_Occurred(tstate));
3815
3816 /* Pop remaining stack entries. */
3817 while (!EMPTY()) {
3818 PyObject *o = POP();
3819 Py_XDECREF(o);
3820 }
3821
3822 exiting:
3823 if (tstate->use_tracing) {
3824 if (tstate->c_tracefunc) {
3825 if (call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj,
3826 tstate, f, PyTrace_RETURN, retval)) {
3827 Py_CLEAR(retval);
3828 }
3829 }
3830 if (tstate->c_profilefunc) {
3831 if (call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj,
3832 tstate, f, PyTrace_RETURN, retval)) {
3833 Py_CLEAR(retval);
3834 }
3835 }
3836 }
3837
3838 /* pop frame */
3839 exit_eval_frame:
3840 if (PyDTrace_FUNCTION_RETURN_ENABLED())
3841 dtrace_function_return(f);
3842 _Py_LeaveRecursiveCall(tstate);
3843 f->f_executing = 0;
3844 tstate->frame = f->f_back;
3845
3846 return _Py_CheckFunctionResult(tstate, NULL, retval, __func__);
3847 }
3848
3849 static void
format_missing(PyThreadState * tstate,const char * kind,PyCodeObject * co,PyObject * names)3850 format_missing(PyThreadState *tstate, const char *kind,
3851 PyCodeObject *co, PyObject *names)
3852 {
3853 int err;
3854 Py_ssize_t len = PyList_GET_SIZE(names);
3855 PyObject *name_str, *comma, *tail, *tmp;
3856
3857 assert(PyList_CheckExact(names));
3858 assert(len >= 1);
3859 /* Deal with the joys of natural language. */
3860 switch (len) {
3861 case 1:
3862 name_str = PyList_GET_ITEM(names, 0);
3863 Py_INCREF(name_str);
3864 break;
3865 case 2:
3866 name_str = PyUnicode_FromFormat("%U and %U",
3867 PyList_GET_ITEM(names, len - 2),
3868 PyList_GET_ITEM(names, len - 1));
3869 break;
3870 default:
3871 tail = PyUnicode_FromFormat(", %U, and %U",
3872 PyList_GET_ITEM(names, len - 2),
3873 PyList_GET_ITEM(names, len - 1));
3874 if (tail == NULL)
3875 return;
3876 /* Chop off the last two objects in the list. This shouldn't actually
3877 fail, but we can't be too careful. */
3878 err = PyList_SetSlice(names, len - 2, len, NULL);
3879 if (err == -1) {
3880 Py_DECREF(tail);
3881 return;
3882 }
3883 /* Stitch everything up into a nice comma-separated list. */
3884 comma = PyUnicode_FromString(", ");
3885 if (comma == NULL) {
3886 Py_DECREF(tail);
3887 return;
3888 }
3889 tmp = PyUnicode_Join(comma, names);
3890 Py_DECREF(comma);
3891 if (tmp == NULL) {
3892 Py_DECREF(tail);
3893 return;
3894 }
3895 name_str = PyUnicode_Concat(tmp, tail);
3896 Py_DECREF(tmp);
3897 Py_DECREF(tail);
3898 break;
3899 }
3900 if (name_str == NULL)
3901 return;
3902 _PyErr_Format(tstate, PyExc_TypeError,
3903 "%U() missing %i required %s argument%s: %U",
3904 co->co_name,
3905 len,
3906 kind,
3907 len == 1 ? "" : "s",
3908 name_str);
3909 Py_DECREF(name_str);
3910 }
3911
3912 static void
missing_arguments(PyThreadState * tstate,PyCodeObject * co,Py_ssize_t missing,Py_ssize_t defcount,PyObject ** fastlocals)3913 missing_arguments(PyThreadState *tstate, PyCodeObject *co,
3914 Py_ssize_t missing, Py_ssize_t defcount,
3915 PyObject **fastlocals)
3916 {
3917 Py_ssize_t i, j = 0;
3918 Py_ssize_t start, end;
3919 int positional = (defcount != -1);
3920 const char *kind = positional ? "positional" : "keyword-only";
3921 PyObject *missing_names;
3922
3923 /* Compute the names of the arguments that are missing. */
3924 missing_names = PyList_New(missing);
3925 if (missing_names == NULL)
3926 return;
3927 if (positional) {
3928 start = 0;
3929 end = co->co_argcount - defcount;
3930 }
3931 else {
3932 start = co->co_argcount;
3933 end = start + co->co_kwonlyargcount;
3934 }
3935 for (i = start; i < end; i++) {
3936 if (GETLOCAL(i) == NULL) {
3937 PyObject *raw = PyTuple_GET_ITEM(co->co_varnames, i);
3938 PyObject *name = PyObject_Repr(raw);
3939 if (name == NULL) {
3940 Py_DECREF(missing_names);
3941 return;
3942 }
3943 PyList_SET_ITEM(missing_names, j++, name);
3944 }
3945 }
3946 assert(j == missing);
3947 format_missing(tstate, kind, co, missing_names);
3948 Py_DECREF(missing_names);
3949 }
3950
3951 static void
too_many_positional(PyThreadState * tstate,PyCodeObject * co,Py_ssize_t given,Py_ssize_t defcount,PyObject ** fastlocals)3952 too_many_positional(PyThreadState *tstate, PyCodeObject *co,
3953 Py_ssize_t given, Py_ssize_t defcount,
3954 PyObject **fastlocals)
3955 {
3956 int plural;
3957 Py_ssize_t kwonly_given = 0;
3958 Py_ssize_t i;
3959 PyObject *sig, *kwonly_sig;
3960 Py_ssize_t co_argcount = co->co_argcount;
3961
3962 assert((co->co_flags & CO_VARARGS) == 0);
3963 /* Count missing keyword-only args. */
3964 for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
3965 if (GETLOCAL(i) != NULL) {
3966 kwonly_given++;
3967 }
3968 }
3969 if (defcount) {
3970 Py_ssize_t atleast = co_argcount - defcount;
3971 plural = 1;
3972 sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
3973 }
3974 else {
3975 plural = (co_argcount != 1);
3976 sig = PyUnicode_FromFormat("%zd", co_argcount);
3977 }
3978 if (sig == NULL)
3979 return;
3980 if (kwonly_given) {
3981 const char *format = " positional argument%s (and %zd keyword-only argument%s)";
3982 kwonly_sig = PyUnicode_FromFormat(format,
3983 given != 1 ? "s" : "",
3984 kwonly_given,
3985 kwonly_given != 1 ? "s" : "");
3986 if (kwonly_sig == NULL) {
3987 Py_DECREF(sig);
3988 return;
3989 }
3990 }
3991 else {
3992 /* This will not fail. */
3993 kwonly_sig = PyUnicode_FromString("");
3994 assert(kwonly_sig != NULL);
3995 }
3996 _PyErr_Format(tstate, PyExc_TypeError,
3997 "%U() takes %U positional argument%s but %zd%U %s given",
3998 co->co_name,
3999 sig,
4000 plural ? "s" : "",
4001 given,
4002 kwonly_sig,
4003 given == 1 && !kwonly_given ? "was" : "were");
4004 Py_DECREF(sig);
4005 Py_DECREF(kwonly_sig);
4006 }
4007
4008 static int
positional_only_passed_as_keyword(PyThreadState * tstate,PyCodeObject * co,Py_ssize_t kwcount,PyObject * const * kwnames)4009 positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
4010 Py_ssize_t kwcount, PyObject* const* kwnames)
4011 {
4012 int posonly_conflicts = 0;
4013 PyObject* posonly_names = PyList_New(0);
4014
4015 for(int k=0; k < co->co_posonlyargcount; k++){
4016 PyObject* posonly_name = PyTuple_GET_ITEM(co->co_varnames, k);
4017
4018 for (int k2=0; k2<kwcount; k2++){
4019 /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
4020 PyObject* kwname = kwnames[k2];
4021 if (kwname == posonly_name){
4022 if(PyList_Append(posonly_names, kwname) != 0) {
4023 goto fail;
4024 }
4025 posonly_conflicts++;
4026 continue;
4027 }
4028
4029 int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
4030
4031 if ( cmp > 0) {
4032 if(PyList_Append(posonly_names, kwname) != 0) {
4033 goto fail;
4034 }
4035 posonly_conflicts++;
4036 } else if (cmp < 0) {
4037 goto fail;
4038 }
4039
4040 }
4041 }
4042 if (posonly_conflicts) {
4043 PyObject* comma = PyUnicode_FromString(", ");
4044 if (comma == NULL) {
4045 goto fail;
4046 }
4047 PyObject* error_names = PyUnicode_Join(comma, posonly_names);
4048 Py_DECREF(comma);
4049 if (error_names == NULL) {
4050 goto fail;
4051 }
4052 _PyErr_Format(tstate, PyExc_TypeError,
4053 "%U() got some positional-only arguments passed"
4054 " as keyword arguments: '%U'",
4055 co->co_name, error_names);
4056 Py_DECREF(error_names);
4057 goto fail;
4058 }
4059
4060 Py_DECREF(posonly_names);
4061 return 0;
4062
4063 fail:
4064 Py_XDECREF(posonly_names);
4065 return 1;
4066
4067 }
4068
4069 /* This is gonna seem *real weird*, but if you put some other code between
4070 PyEval_EvalFrame() and _PyEval_EvalFrameDefault() you will need to adjust
4071 the test in the if statements in Misc/gdbinit (pystack and pystackv). */
4072
4073 PyObject *
_PyEval_EvalCode(PyThreadState * tstate,PyObject * _co,PyObject * globals,PyObject * locals,PyObject * const * args,Py_ssize_t argcount,PyObject * const * kwnames,PyObject * const * kwargs,Py_ssize_t kwcount,int kwstep,PyObject * const * defs,Py_ssize_t defcount,PyObject * kwdefs,PyObject * closure,PyObject * name,PyObject * qualname)4074 _PyEval_EvalCode(PyThreadState *tstate,
4075 PyObject *_co, PyObject *globals, PyObject *locals,
4076 PyObject *const *args, Py_ssize_t argcount,
4077 PyObject *const *kwnames, PyObject *const *kwargs,
4078 Py_ssize_t kwcount, int kwstep,
4079 PyObject *const *defs, Py_ssize_t defcount,
4080 PyObject *kwdefs, PyObject *closure,
4081 PyObject *name, PyObject *qualname)
4082 {
4083 assert(is_tstate_valid(tstate));
4084
4085 PyCodeObject* co = (PyCodeObject*)_co;
4086 PyFrameObject *f;
4087 PyObject *retval = NULL;
4088 PyObject **fastlocals, **freevars;
4089 PyObject *x, *u;
4090 const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
4091 Py_ssize_t i, j, n;
4092 PyObject *kwdict;
4093
4094 if (globals == NULL) {
4095 _PyErr_SetString(tstate, PyExc_SystemError,
4096 "PyEval_EvalCodeEx: NULL globals");
4097 return NULL;
4098 }
4099
4100 /* Create the frame */
4101 f = _PyFrame_New_NoTrack(tstate, co, globals, locals);
4102 if (f == NULL) {
4103 return NULL;
4104 }
4105 fastlocals = f->f_localsplus;
4106 freevars = f->f_localsplus + co->co_nlocals;
4107
4108 /* Create a dictionary for keyword parameters (**kwags) */
4109 if (co->co_flags & CO_VARKEYWORDS) {
4110 kwdict = PyDict_New();
4111 if (kwdict == NULL)
4112 goto fail;
4113 i = total_args;
4114 if (co->co_flags & CO_VARARGS) {
4115 i++;
4116 }
4117 SETLOCAL(i, kwdict);
4118 }
4119 else {
4120 kwdict = NULL;
4121 }
4122
4123 /* Copy all positional arguments into local variables */
4124 if (argcount > co->co_argcount) {
4125 n = co->co_argcount;
4126 }
4127 else {
4128 n = argcount;
4129 }
4130 for (j = 0; j < n; j++) {
4131 x = args[j];
4132 Py_INCREF(x);
4133 SETLOCAL(j, x);
4134 }
4135
4136 /* Pack other positional arguments into the *args argument */
4137 if (co->co_flags & CO_VARARGS) {
4138 u = _PyTuple_FromArray(args + n, argcount - n);
4139 if (u == NULL) {
4140 goto fail;
4141 }
4142 SETLOCAL(total_args, u);
4143 }
4144
4145 /* Handle keyword arguments passed as two strided arrays */
4146 kwcount *= kwstep;
4147 for (i = 0; i < kwcount; i += kwstep) {
4148 PyObject **co_varnames;
4149 PyObject *keyword = kwnames[i];
4150 PyObject *value = kwargs[i];
4151 Py_ssize_t j;
4152
4153 if (keyword == NULL || !PyUnicode_Check(keyword)) {
4154 _PyErr_Format(tstate, PyExc_TypeError,
4155 "%U() keywords must be strings",
4156 co->co_name);
4157 goto fail;
4158 }
4159
4160 /* Speed hack: do raw pointer compares. As names are
4161 normally interned this should almost always hit. */
4162 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
4163 for (j = co->co_posonlyargcount; j < total_args; j++) {
4164 PyObject *name = co_varnames[j];
4165 if (name == keyword) {
4166 goto kw_found;
4167 }
4168 }
4169
4170 /* Slow fallback, just in case */
4171 for (j = co->co_posonlyargcount; j < total_args; j++) {
4172 PyObject *name = co_varnames[j];
4173 int cmp = PyObject_RichCompareBool( keyword, name, Py_EQ);
4174 if (cmp > 0) {
4175 goto kw_found;
4176 }
4177 else if (cmp < 0) {
4178 goto fail;
4179 }
4180 }
4181
4182 assert(j >= total_args);
4183 if (kwdict == NULL) {
4184
4185 if (co->co_posonlyargcount
4186 && positional_only_passed_as_keyword(tstate, co,
4187 kwcount, kwnames))
4188 {
4189 goto fail;
4190 }
4191
4192 _PyErr_Format(tstate, PyExc_TypeError,
4193 "%U() got an unexpected keyword argument '%S'",
4194 co->co_name, keyword);
4195 goto fail;
4196 }
4197
4198 if (PyDict_SetItem(kwdict, keyword, value) == -1) {
4199 goto fail;
4200 }
4201 continue;
4202
4203 kw_found:
4204 if (GETLOCAL(j) != NULL) {
4205 _PyErr_Format(tstate, PyExc_TypeError,
4206 "%U() got multiple values for argument '%S'",
4207 co->co_name, keyword);
4208 goto fail;
4209 }
4210 Py_INCREF(value);
4211 SETLOCAL(j, value);
4212 }
4213
4214 /* Check the number of positional arguments */
4215 if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
4216 too_many_positional(tstate, co, argcount, defcount, fastlocals);
4217 goto fail;
4218 }
4219
4220 /* Add missing positional arguments (copy default values from defs) */
4221 if (argcount < co->co_argcount) {
4222 Py_ssize_t m = co->co_argcount - defcount;
4223 Py_ssize_t missing = 0;
4224 for (i = argcount; i < m; i++) {
4225 if (GETLOCAL(i) == NULL) {
4226 missing++;
4227 }
4228 }
4229 if (missing) {
4230 missing_arguments(tstate, co, missing, defcount, fastlocals);
4231 goto fail;
4232 }
4233 if (n > m)
4234 i = n - m;
4235 else
4236 i = 0;
4237 for (; i < defcount; i++) {
4238 if (GETLOCAL(m+i) == NULL) {
4239 PyObject *def = defs[i];
4240 Py_INCREF(def);
4241 SETLOCAL(m+i, def);
4242 }
4243 }
4244 }
4245
4246 /* Add missing keyword arguments (copy default values from kwdefs) */
4247 if (co->co_kwonlyargcount > 0) {
4248 Py_ssize_t missing = 0;
4249 for (i = co->co_argcount; i < total_args; i++) {
4250 PyObject *name;
4251 if (GETLOCAL(i) != NULL)
4252 continue;
4253 name = PyTuple_GET_ITEM(co->co_varnames, i);
4254 if (kwdefs != NULL) {
4255 PyObject *def = PyDict_GetItemWithError(kwdefs, name);
4256 if (def) {
4257 Py_INCREF(def);
4258 SETLOCAL(i, def);
4259 continue;
4260 }
4261 else if (_PyErr_Occurred(tstate)) {
4262 goto fail;
4263 }
4264 }
4265 missing++;
4266 }
4267 if (missing) {
4268 missing_arguments(tstate, co, missing, -1, fastlocals);
4269 goto fail;
4270 }
4271 }
4272
4273 /* Allocate and initialize storage for cell vars, and copy free
4274 vars into frame. */
4275 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
4276 PyObject *c;
4277 Py_ssize_t arg;
4278 /* Possibly account for the cell variable being an argument. */
4279 if (co->co_cell2arg != NULL &&
4280 (arg = co->co_cell2arg[i]) != CO_CELL_NOT_AN_ARG) {
4281 c = PyCell_New(GETLOCAL(arg));
4282 /* Clear the local copy. */
4283 SETLOCAL(arg, NULL);
4284 }
4285 else {
4286 c = PyCell_New(NULL);
4287 }
4288 if (c == NULL)
4289 goto fail;
4290 SETLOCAL(co->co_nlocals + i, c);
4291 }
4292
4293 /* Copy closure variables to free variables */
4294 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
4295 PyObject *o = PyTuple_GET_ITEM(closure, i);
4296 Py_INCREF(o);
4297 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
4298 }
4299
4300 /* Handle generator/coroutine/asynchronous generator */
4301 if (co->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
4302 PyObject *gen;
4303 int is_coro = co->co_flags & CO_COROUTINE;
4304
4305 /* Don't need to keep the reference to f_back, it will be set
4306 * when the generator is resumed. */
4307 Py_CLEAR(f->f_back);
4308
4309 /* Create a new generator that owns the ready to run frame
4310 * and return that as the value. */
4311 if (is_coro) {
4312 gen = PyCoro_New(f, name, qualname);
4313 } else if (co->co_flags & CO_ASYNC_GENERATOR) {
4314 gen = PyAsyncGen_New(f, name, qualname);
4315 } else {
4316 gen = PyGen_NewWithQualName(f, name, qualname);
4317 }
4318 if (gen == NULL) {
4319 return NULL;
4320 }
4321
4322 _PyObject_GC_TRACK(f);
4323
4324 return gen;
4325 }
4326
4327 retval = _PyEval_EvalFrame(tstate, f, 0);
4328
4329 fail: /* Jump here from prelude on failure */
4330
4331 /* decref'ing the frame can cause __del__ methods to get invoked,
4332 which can call back into Python. While we're done with the
4333 current Python frame (f), the associated C stack is still in use,
4334 so recursion_depth must be boosted for the duration.
4335 */
4336 if (Py_REFCNT(f) > 1) {
4337 Py_DECREF(f);
4338 _PyObject_GC_TRACK(f);
4339 }
4340 else {
4341 ++tstate->recursion_depth;
4342 Py_DECREF(f);
4343 --tstate->recursion_depth;
4344 }
4345 return retval;
4346 }
4347
4348
4349 PyObject *
_PyEval_EvalCodeWithName(PyObject * _co,PyObject * globals,PyObject * locals,PyObject * const * args,Py_ssize_t argcount,PyObject * const * kwnames,PyObject * const * kwargs,Py_ssize_t kwcount,int kwstep,PyObject * const * defs,Py_ssize_t defcount,PyObject * kwdefs,PyObject * closure,PyObject * name,PyObject * qualname)4350 _PyEval_EvalCodeWithName(PyObject *_co, PyObject *globals, PyObject *locals,
4351 PyObject *const *args, Py_ssize_t argcount,
4352 PyObject *const *kwnames, PyObject *const *kwargs,
4353 Py_ssize_t kwcount, int kwstep,
4354 PyObject *const *defs, Py_ssize_t defcount,
4355 PyObject *kwdefs, PyObject *closure,
4356 PyObject *name, PyObject *qualname)
4357 {
4358 PyThreadState *tstate = _PyThreadState_GET();
4359 return _PyEval_EvalCode(tstate, _co, globals, locals,
4360 args, argcount,
4361 kwnames, kwargs,
4362 kwcount, kwstep,
4363 defs, defcount,
4364 kwdefs, closure,
4365 name, qualname);
4366 }
4367
4368 PyObject *
PyEval_EvalCodeEx(PyObject * _co,PyObject * globals,PyObject * locals,PyObject * const * args,int argcount,PyObject * const * kws,int kwcount,PyObject * const * defs,int defcount,PyObject * kwdefs,PyObject * closure)4369 PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
4370 PyObject *const *args, int argcount,
4371 PyObject *const *kws, int kwcount,
4372 PyObject *const *defs, int defcount,
4373 PyObject *kwdefs, PyObject *closure)
4374 {
4375 return _PyEval_EvalCodeWithName(_co, globals, locals,
4376 args, argcount,
4377 kws, kws != NULL ? kws + 1 : NULL,
4378 kwcount, 2,
4379 defs, defcount,
4380 kwdefs, closure,
4381 NULL, NULL);
4382 }
4383
4384 static PyObject *
special_lookup(PyThreadState * tstate,PyObject * o,_Py_Identifier * id)4385 special_lookup(PyThreadState *tstate, PyObject *o, _Py_Identifier *id)
4386 {
4387 PyObject *res;
4388 res = _PyObject_LookupSpecial(o, id);
4389 if (res == NULL && !_PyErr_Occurred(tstate)) {
4390 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(id));
4391 return NULL;
4392 }
4393 return res;
4394 }
4395
4396
4397 /* Logic for the raise statement (too complicated for inlining).
4398 This *consumes* a reference count to each of its arguments. */
4399 static int
do_raise(PyThreadState * tstate,PyObject * exc,PyObject * cause)4400 do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
4401 {
4402 PyObject *type = NULL, *value = NULL;
4403
4404 if (exc == NULL) {
4405 /* Reraise */
4406 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
4407 PyObject *tb;
4408 type = exc_info->exc_type;
4409 value = exc_info->exc_value;
4410 tb = exc_info->exc_traceback;
4411 if (type == Py_None || type == NULL) {
4412 _PyErr_SetString(tstate, PyExc_RuntimeError,
4413 "No active exception to reraise");
4414 return 0;
4415 }
4416 Py_XINCREF(type);
4417 Py_XINCREF(value);
4418 Py_XINCREF(tb);
4419 _PyErr_Restore(tstate, type, value, tb);
4420 return 1;
4421 }
4422
4423 /* We support the following forms of raise:
4424 raise
4425 raise <instance>
4426 raise <type> */
4427
4428 if (PyExceptionClass_Check(exc)) {
4429 type = exc;
4430 value = _PyObject_CallNoArg(exc);
4431 if (value == NULL)
4432 goto raise_error;
4433 if (!PyExceptionInstance_Check(value)) {
4434 _PyErr_Format(tstate, PyExc_TypeError,
4435 "calling %R should have returned an instance of "
4436 "BaseException, not %R",
4437 type, Py_TYPE(value));
4438 goto raise_error;
4439 }
4440 }
4441 else if (PyExceptionInstance_Check(exc)) {
4442 value = exc;
4443 type = PyExceptionInstance_Class(exc);
4444 Py_INCREF(type);
4445 }
4446 else {
4447 /* Not something you can raise. You get an exception
4448 anyway, just not what you specified :-) */
4449 Py_DECREF(exc);
4450 _PyErr_SetString(tstate, PyExc_TypeError,
4451 "exceptions must derive from BaseException");
4452 goto raise_error;
4453 }
4454
4455 assert(type != NULL);
4456 assert(value != NULL);
4457
4458 if (cause) {
4459 PyObject *fixed_cause;
4460 if (PyExceptionClass_Check(cause)) {
4461 fixed_cause = _PyObject_CallNoArg(cause);
4462 if (fixed_cause == NULL)
4463 goto raise_error;
4464 Py_DECREF(cause);
4465 }
4466 else if (PyExceptionInstance_Check(cause)) {
4467 fixed_cause = cause;
4468 }
4469 else if (cause == Py_None) {
4470 Py_DECREF(cause);
4471 fixed_cause = NULL;
4472 }
4473 else {
4474 _PyErr_SetString(tstate, PyExc_TypeError,
4475 "exception causes must derive from "
4476 "BaseException");
4477 goto raise_error;
4478 }
4479 PyException_SetCause(value, fixed_cause);
4480 }
4481
4482 _PyErr_SetObject(tstate, type, value);
4483 /* _PyErr_SetObject incref's its arguments */
4484 Py_DECREF(value);
4485 Py_DECREF(type);
4486 return 0;
4487
4488 raise_error:
4489 Py_XDECREF(value);
4490 Py_XDECREF(type);
4491 Py_XDECREF(cause);
4492 return 0;
4493 }
4494
4495 /* Iterate v argcnt times and store the results on the stack (via decreasing
4496 sp). Return 1 for success, 0 if error.
4497
4498 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
4499 with a variable target.
4500 */
4501
4502 static int
unpack_iterable(PyThreadState * tstate,PyObject * v,int argcnt,int argcntafter,PyObject ** sp)4503 unpack_iterable(PyThreadState *tstate, PyObject *v,
4504 int argcnt, int argcntafter, PyObject **sp)
4505 {
4506 int i = 0, j = 0;
4507 Py_ssize_t ll = 0;
4508 PyObject *it; /* iter(v) */
4509 PyObject *w;
4510 PyObject *l = NULL; /* variable list */
4511
4512 assert(v != NULL);
4513
4514 it = PyObject_GetIter(v);
4515 if (it == NULL) {
4516 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
4517 Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
4518 {
4519 _PyErr_Format(tstate, PyExc_TypeError,
4520 "cannot unpack non-iterable %.200s object",
4521 Py_TYPE(v)->tp_name);
4522 }
4523 return 0;
4524 }
4525
4526 for (; i < argcnt; i++) {
4527 w = PyIter_Next(it);
4528 if (w == NULL) {
4529 /* Iterator done, via error or exhaustion. */
4530 if (!_PyErr_Occurred(tstate)) {
4531 if (argcntafter == -1) {
4532 _PyErr_Format(tstate, PyExc_ValueError,
4533 "not enough values to unpack "
4534 "(expected %d, got %d)",
4535 argcnt, i);
4536 }
4537 else {
4538 _PyErr_Format(tstate, PyExc_ValueError,
4539 "not enough values to unpack "
4540 "(expected at least %d, got %d)",
4541 argcnt + argcntafter, i);
4542 }
4543 }
4544 goto Error;
4545 }
4546 *--sp = w;
4547 }
4548
4549 if (argcntafter == -1) {
4550 /* We better have exhausted the iterator now. */
4551 w = PyIter_Next(it);
4552 if (w == NULL) {
4553 if (_PyErr_Occurred(tstate))
4554 goto Error;
4555 Py_DECREF(it);
4556 return 1;
4557 }
4558 Py_DECREF(w);
4559 _PyErr_Format(tstate, PyExc_ValueError,
4560 "too many values to unpack (expected %d)",
4561 argcnt);
4562 goto Error;
4563 }
4564
4565 l = PySequence_List(it);
4566 if (l == NULL)
4567 goto Error;
4568 *--sp = l;
4569 i++;
4570
4571 ll = PyList_GET_SIZE(l);
4572 if (ll < argcntafter) {
4573 _PyErr_Format(tstate, PyExc_ValueError,
4574 "not enough values to unpack (expected at least %d, got %zd)",
4575 argcnt + argcntafter, argcnt + ll);
4576 goto Error;
4577 }
4578
4579 /* Pop the "after-variable" args off the list. */
4580 for (j = argcntafter; j > 0; j--, i++) {
4581 *--sp = PyList_GET_ITEM(l, ll - j);
4582 }
4583 /* Resize the list. */
4584 Py_SET_SIZE(l, ll - argcntafter);
4585 Py_DECREF(it);
4586 return 1;
4587
4588 Error:
4589 for (; i > 0; i--, sp++)
4590 Py_DECREF(*sp);
4591 Py_XDECREF(it);
4592 return 0;
4593 }
4594
4595
4596 #ifdef LLTRACE
4597 static int
prtrace(PyThreadState * tstate,PyObject * v,const char * str)4598 prtrace(PyThreadState *tstate, PyObject *v, const char *str)
4599 {
4600 printf("%s ", str);
4601 if (PyObject_Print(v, stdout, 0) != 0) {
4602 /* Don't know what else to do */
4603 _PyErr_Clear(tstate);
4604 }
4605 printf("\n");
4606 return 1;
4607 }
4608 #endif
4609
4610 static void
call_exc_trace(Py_tracefunc func,PyObject * self,PyThreadState * tstate,PyFrameObject * f)4611 call_exc_trace(Py_tracefunc func, PyObject *self,
4612 PyThreadState *tstate, PyFrameObject *f)
4613 {
4614 PyObject *type, *value, *traceback, *orig_traceback, *arg;
4615 int err;
4616 _PyErr_Fetch(tstate, &type, &value, &orig_traceback);
4617 if (value == NULL) {
4618 value = Py_None;
4619 Py_INCREF(value);
4620 }
4621 _PyErr_NormalizeException(tstate, &type, &value, &orig_traceback);
4622 traceback = (orig_traceback != NULL) ? orig_traceback : Py_None;
4623 arg = PyTuple_Pack(3, type, value, traceback);
4624 if (arg == NULL) {
4625 _PyErr_Restore(tstate, type, value, orig_traceback);
4626 return;
4627 }
4628 err = call_trace(func, self, tstate, f, PyTrace_EXCEPTION, arg);
4629 Py_DECREF(arg);
4630 if (err == 0) {
4631 _PyErr_Restore(tstate, type, value, orig_traceback);
4632 }
4633 else {
4634 Py_XDECREF(type);
4635 Py_XDECREF(value);
4636 Py_XDECREF(orig_traceback);
4637 }
4638 }
4639
4640 static int
call_trace_protected(Py_tracefunc func,PyObject * obj,PyThreadState * tstate,PyFrameObject * frame,int what,PyObject * arg)4641 call_trace_protected(Py_tracefunc func, PyObject *obj,
4642 PyThreadState *tstate, PyFrameObject *frame,
4643 int what, PyObject *arg)
4644 {
4645 PyObject *type, *value, *traceback;
4646 int err;
4647 _PyErr_Fetch(tstate, &type, &value, &traceback);
4648 err = call_trace(func, obj, tstate, frame, what, arg);
4649 if (err == 0)
4650 {
4651 _PyErr_Restore(tstate, type, value, traceback);
4652 return 0;
4653 }
4654 else {
4655 Py_XDECREF(type);
4656 Py_XDECREF(value);
4657 Py_XDECREF(traceback);
4658 return -1;
4659 }
4660 }
4661
4662 static int
call_trace(Py_tracefunc func,PyObject * obj,PyThreadState * tstate,PyFrameObject * frame,int what,PyObject * arg)4663 call_trace(Py_tracefunc func, PyObject *obj,
4664 PyThreadState *tstate, PyFrameObject *frame,
4665 int what, PyObject *arg)
4666 {
4667 int result;
4668 if (tstate->tracing)
4669 return 0;
4670 tstate->tracing++;
4671 tstate->use_tracing = 0;
4672 result = func(obj, frame, what, arg);
4673 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
4674 || (tstate->c_profilefunc != NULL));
4675 tstate->tracing--;
4676 return result;
4677 }
4678
4679 PyObject *
_PyEval_CallTracing(PyObject * func,PyObject * args)4680 _PyEval_CallTracing(PyObject *func, PyObject *args)
4681 {
4682 PyThreadState *tstate = _PyThreadState_GET();
4683 int save_tracing = tstate->tracing;
4684 int save_use_tracing = tstate->use_tracing;
4685 PyObject *result;
4686
4687 tstate->tracing = 0;
4688 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
4689 || (tstate->c_profilefunc != NULL));
4690 result = PyObject_Call(func, args, NULL);
4691 tstate->tracing = save_tracing;
4692 tstate->use_tracing = save_use_tracing;
4693 return result;
4694 }
4695
4696 /* See Objects/lnotab_notes.txt for a description of how tracing works. */
4697 static int
maybe_call_line_trace(Py_tracefunc func,PyObject * obj,PyThreadState * tstate,PyFrameObject * frame,int * instr_lb,int * instr_ub,int * instr_prev)4698 maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
4699 PyThreadState *tstate, PyFrameObject *frame,
4700 int *instr_lb, int *instr_ub, int *instr_prev)
4701 {
4702 int result = 0;
4703 int line = frame->f_lineno;
4704
4705 /* If the last instruction executed isn't in the current
4706 instruction window, reset the window.
4707 */
4708 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
4709 PyAddrPair bounds;
4710 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
4711 &bounds);
4712 *instr_lb = bounds.ap_lower;
4713 *instr_ub = bounds.ap_upper;
4714 }
4715 /* If the last instruction falls at the start of a line or if it
4716 represents a jump backwards, update the frame's line number and
4717 then call the trace function if we're tracing source lines.
4718 */
4719 if ((frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev)) {
4720 frame->f_lineno = line;
4721 if (frame->f_trace_lines) {
4722 result = call_trace(func, obj, tstate, frame, PyTrace_LINE, Py_None);
4723 }
4724 }
4725 /* Always emit an opcode event if we're tracing all opcodes. */
4726 if (frame->f_trace_opcodes) {
4727 result = call_trace(func, obj, tstate, frame, PyTrace_OPCODE, Py_None);
4728 }
4729 *instr_prev = frame->f_lasti;
4730 return result;
4731 }
4732
4733 int
_PyEval_SetProfile(PyThreadState * tstate,Py_tracefunc func,PyObject * arg)4734 _PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
4735 {
4736 assert(is_tstate_valid(tstate));
4737 /* The caller must hold the GIL */
4738 assert(PyGILState_Check());
4739
4740 /* Call _PySys_Audit() in the context of the current thread state,
4741 even if tstate is not the current thread state. */
4742 PyThreadState *current_tstate = _PyThreadState_GET();
4743 if (_PySys_Audit(current_tstate, "sys.setprofile", NULL) < 0) {
4744 return -1;
4745 }
4746
4747 PyObject *profileobj = tstate->c_profileobj;
4748
4749 tstate->c_profilefunc = NULL;
4750 tstate->c_profileobj = NULL;
4751 /* Must make sure that tracing is not ignored if 'profileobj' is freed */
4752 tstate->use_tracing = tstate->c_tracefunc != NULL;
4753 Py_XDECREF(profileobj);
4754
4755 Py_XINCREF(arg);
4756 tstate->c_profileobj = arg;
4757 tstate->c_profilefunc = func;
4758
4759 /* Flag that tracing or profiling is turned on */
4760 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
4761 return 0;
4762 }
4763
4764 void
PyEval_SetProfile(Py_tracefunc func,PyObject * arg)4765 PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
4766 {
4767 PyThreadState *tstate = _PyThreadState_GET();
4768 if (_PyEval_SetProfile(tstate, func, arg) < 0) {
4769 /* Log _PySys_Audit() error */
4770 _PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL);
4771 }
4772 }
4773
4774 int
_PyEval_SetTrace(PyThreadState * tstate,Py_tracefunc func,PyObject * arg)4775 _PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
4776 {
4777 assert(is_tstate_valid(tstate));
4778 /* The caller must hold the GIL */
4779 assert(PyGILState_Check());
4780
4781 /* Call _PySys_Audit() in the context of the current thread state,
4782 even if tstate is not the current thread state. */
4783 PyThreadState *current_tstate = _PyThreadState_GET();
4784 if (_PySys_Audit(current_tstate, "sys.settrace", NULL) < 0) {
4785 return -1;
4786 }
4787
4788 struct _ceval_state *ceval2 = &tstate->interp->ceval;
4789 PyObject *traceobj = tstate->c_traceobj;
4790 ceval2->tracing_possible += (func != NULL) - (tstate->c_tracefunc != NULL);
4791
4792 tstate->c_tracefunc = NULL;
4793 tstate->c_traceobj = NULL;
4794 /* Must make sure that profiling is not ignored if 'traceobj' is freed */
4795 tstate->use_tracing = (tstate->c_profilefunc != NULL);
4796 Py_XDECREF(traceobj);
4797
4798 Py_XINCREF(arg);
4799 tstate->c_traceobj = arg;
4800 tstate->c_tracefunc = func;
4801
4802 /* Flag that tracing or profiling is turned on */
4803 tstate->use_tracing = ((func != NULL)
4804 || (tstate->c_profilefunc != NULL));
4805
4806 return 0;
4807 }
4808
4809 void
PyEval_SetTrace(Py_tracefunc func,PyObject * arg)4810 PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
4811 {
4812 PyThreadState *tstate = _PyThreadState_GET();
4813 if (_PyEval_SetTrace(tstate, func, arg) < 0) {
4814 /* Log _PySys_Audit() error */
4815 _PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL);
4816 }
4817 }
4818
4819
4820 void
_PyEval_SetCoroutineOriginTrackingDepth(PyThreadState * tstate,int new_depth)4821 _PyEval_SetCoroutineOriginTrackingDepth(PyThreadState *tstate, int new_depth)
4822 {
4823 assert(new_depth >= 0);
4824 tstate->coroutine_origin_tracking_depth = new_depth;
4825 }
4826
4827 int
_PyEval_GetCoroutineOriginTrackingDepth(void)4828 _PyEval_GetCoroutineOriginTrackingDepth(void)
4829 {
4830 PyThreadState *tstate = _PyThreadState_GET();
4831 return tstate->coroutine_origin_tracking_depth;
4832 }
4833
4834 int
_PyEval_SetAsyncGenFirstiter(PyObject * firstiter)4835 _PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
4836 {
4837 PyThreadState *tstate = _PyThreadState_GET();
4838
4839 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
4840 return -1;
4841 }
4842
4843 Py_XINCREF(firstiter);
4844 Py_XSETREF(tstate->async_gen_firstiter, firstiter);
4845 return 0;
4846 }
4847
4848 PyObject *
_PyEval_GetAsyncGenFirstiter(void)4849 _PyEval_GetAsyncGenFirstiter(void)
4850 {
4851 PyThreadState *tstate = _PyThreadState_GET();
4852 return tstate->async_gen_firstiter;
4853 }
4854
4855 int
_PyEval_SetAsyncGenFinalizer(PyObject * finalizer)4856 _PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
4857 {
4858 PyThreadState *tstate = _PyThreadState_GET();
4859
4860 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
4861 return -1;
4862 }
4863
4864 Py_XINCREF(finalizer);
4865 Py_XSETREF(tstate->async_gen_finalizer, finalizer);
4866 return 0;
4867 }
4868
4869 PyObject *
_PyEval_GetAsyncGenFinalizer(void)4870 _PyEval_GetAsyncGenFinalizer(void)
4871 {
4872 PyThreadState *tstate = _PyThreadState_GET();
4873 return tstate->async_gen_finalizer;
4874 }
4875
4876 PyFrameObject *
PyEval_GetFrame(void)4877 PyEval_GetFrame(void)
4878 {
4879 PyThreadState *tstate = _PyThreadState_GET();
4880 return tstate->frame;
4881 }
4882
4883 PyObject *
PyEval_GetBuiltins(void)4884 PyEval_GetBuiltins(void)
4885 {
4886 PyThreadState *tstate = _PyThreadState_GET();
4887 PyFrameObject *current_frame = tstate->frame;
4888 if (current_frame == NULL)
4889 return tstate->interp->builtins;
4890 else
4891 return current_frame->f_builtins;
4892 }
4893
4894 /* Convenience function to get a builtin from its name */
4895 PyObject *
_PyEval_GetBuiltinId(_Py_Identifier * name)4896 _PyEval_GetBuiltinId(_Py_Identifier *name)
4897 {
4898 PyThreadState *tstate = _PyThreadState_GET();
4899 PyObject *attr = _PyDict_GetItemIdWithError(PyEval_GetBuiltins(), name);
4900 if (attr) {
4901 Py_INCREF(attr);
4902 }
4903 else if (!_PyErr_Occurred(tstate)) {
4904 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(name));
4905 }
4906 return attr;
4907 }
4908
4909 PyObject *
PyEval_GetLocals(void)4910 PyEval_GetLocals(void)
4911 {
4912 PyThreadState *tstate = _PyThreadState_GET();
4913 PyFrameObject *current_frame = tstate->frame;
4914 if (current_frame == NULL) {
4915 _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
4916 return NULL;
4917 }
4918
4919 if (PyFrame_FastToLocalsWithError(current_frame) < 0) {
4920 return NULL;
4921 }
4922
4923 assert(current_frame->f_locals != NULL);
4924 return current_frame->f_locals;
4925 }
4926
4927 PyObject *
PyEval_GetGlobals(void)4928 PyEval_GetGlobals(void)
4929 {
4930 PyThreadState *tstate = _PyThreadState_GET();
4931 PyFrameObject *current_frame = tstate->frame;
4932 if (current_frame == NULL) {
4933 return NULL;
4934 }
4935
4936 assert(current_frame->f_globals != NULL);
4937 return current_frame->f_globals;
4938 }
4939
4940 int
PyEval_MergeCompilerFlags(PyCompilerFlags * cf)4941 PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
4942 {
4943 PyThreadState *tstate = _PyThreadState_GET();
4944 PyFrameObject *current_frame = tstate->frame;
4945 int result = cf->cf_flags != 0;
4946
4947 if (current_frame != NULL) {
4948 const int codeflags = current_frame->f_code->co_flags;
4949 const int compilerflags = codeflags & PyCF_MASK;
4950 if (compilerflags) {
4951 result = 1;
4952 cf->cf_flags |= compilerflags;
4953 }
4954 #if 0 /* future keyword */
4955 if (codeflags & CO_GENERATOR_ALLOWED) {
4956 result = 1;
4957 cf->cf_flags |= CO_GENERATOR_ALLOWED;
4958 }
4959 #endif
4960 }
4961 return result;
4962 }
4963
4964
4965 const char *
PyEval_GetFuncName(PyObject * func)4966 PyEval_GetFuncName(PyObject *func)
4967 {
4968 if (PyMethod_Check(func))
4969 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
4970 else if (PyFunction_Check(func))
4971 return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
4972 else if (PyCFunction_Check(func))
4973 return ((PyCFunctionObject*)func)->m_ml->ml_name;
4974 else
4975 return Py_TYPE(func)->tp_name;
4976 }
4977
4978 const char *
PyEval_GetFuncDesc(PyObject * func)4979 PyEval_GetFuncDesc(PyObject *func)
4980 {
4981 if (PyMethod_Check(func))
4982 return "()";
4983 else if (PyFunction_Check(func))
4984 return "()";
4985 else if (PyCFunction_Check(func))
4986 return "()";
4987 else
4988 return " object";
4989 }
4990
4991 #define C_TRACE(x, call) \
4992 if (tstate->use_tracing && tstate->c_profilefunc) { \
4993 if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
4994 tstate, tstate->frame, \
4995 PyTrace_C_CALL, func)) { \
4996 x = NULL; \
4997 } \
4998 else { \
4999 x = call; \
5000 if (tstate->c_profilefunc != NULL) { \
5001 if (x == NULL) { \
5002 call_trace_protected(tstate->c_profilefunc, \
5003 tstate->c_profileobj, \
5004 tstate, tstate->frame, \
5005 PyTrace_C_EXCEPTION, func); \
5006 /* XXX should pass (type, value, tb) */ \
5007 } else { \
5008 if (call_trace(tstate->c_profilefunc, \
5009 tstate->c_profileobj, \
5010 tstate, tstate->frame, \
5011 PyTrace_C_RETURN, func)) { \
5012 Py_DECREF(x); \
5013 x = NULL; \
5014 } \
5015 } \
5016 } \
5017 } \
5018 } else { \
5019 x = call; \
5020 }
5021
5022
5023 static PyObject *
trace_call_function(PyThreadState * tstate,PyObject * func,PyObject ** args,Py_ssize_t nargs,PyObject * kwnames)5024 trace_call_function(PyThreadState *tstate,
5025 PyObject *func,
5026 PyObject **args, Py_ssize_t nargs,
5027 PyObject *kwnames)
5028 {
5029 PyObject *x;
5030 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
5031 C_TRACE(x, PyObject_Vectorcall(func, args, nargs, kwnames));
5032 return x;
5033 }
5034 else if (Py_IS_TYPE(func, &PyMethodDescr_Type) && nargs > 0) {
5035 /* We need to create a temporary bound method as argument
5036 for profiling.
5037
5038 If nargs == 0, then this cannot work because we have no
5039 "self". In any case, the call itself would raise
5040 TypeError (foo needs an argument), so we just skip
5041 profiling. */
5042 PyObject *self = args[0];
5043 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5044 if (func == NULL) {
5045 return NULL;
5046 }
5047 C_TRACE(x, PyObject_Vectorcall(func,
5048 args+1, nargs-1,
5049 kwnames));
5050 Py_DECREF(func);
5051 return x;
5052 }
5053 return PyObject_Vectorcall(func, args, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
5054 }
5055
5056 /* Issue #29227: Inline call_function() into _PyEval_EvalFrameDefault()
5057 to reduce the stack consumption. */
Py_LOCAL_INLINE(PyObject *)5058 Py_LOCAL_INLINE(PyObject *) _Py_HOT_FUNCTION
5059 call_function(PyThreadState *tstate, PyObject ***pp_stack, Py_ssize_t oparg, PyObject *kwnames)
5060 {
5061 PyObject **pfunc = (*pp_stack) - oparg - 1;
5062 PyObject *func = *pfunc;
5063 PyObject *x, *w;
5064 Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
5065 Py_ssize_t nargs = oparg - nkwargs;
5066 PyObject **stack = (*pp_stack) - nargs - nkwargs;
5067
5068 if (tstate->use_tracing) {
5069 x = trace_call_function(tstate, func, stack, nargs, kwnames);
5070 }
5071 else {
5072 x = PyObject_Vectorcall(func, stack, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
5073 }
5074
5075 assert((x != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5076
5077 /* Clear the stack of the function object. */
5078 while ((*pp_stack) > pfunc) {
5079 w = EXT_POP(*pp_stack);
5080 Py_DECREF(w);
5081 }
5082
5083 return x;
5084 }
5085
5086 static PyObject *
do_call_core(PyThreadState * tstate,PyObject * func,PyObject * callargs,PyObject * kwdict)5087 do_call_core(PyThreadState *tstate, PyObject *func, PyObject *callargs, PyObject *kwdict)
5088 {
5089 PyObject *result;
5090
5091 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
5092 C_TRACE(result, PyObject_Call(func, callargs, kwdict));
5093 return result;
5094 }
5095 else if (Py_IS_TYPE(func, &PyMethodDescr_Type)) {
5096 Py_ssize_t nargs = PyTuple_GET_SIZE(callargs);
5097 if (nargs > 0 && tstate->use_tracing) {
5098 /* We need to create a temporary bound method as argument
5099 for profiling.
5100
5101 If nargs == 0, then this cannot work because we have no
5102 "self". In any case, the call itself would raise
5103 TypeError (foo needs an argument), so we just skip
5104 profiling. */
5105 PyObject *self = PyTuple_GET_ITEM(callargs, 0);
5106 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5107 if (func == NULL) {
5108 return NULL;
5109 }
5110
5111 C_TRACE(result, _PyObject_FastCallDictTstate(
5112 tstate, func,
5113 &_PyTuple_ITEMS(callargs)[1],
5114 nargs - 1,
5115 kwdict));
5116 Py_DECREF(func);
5117 return result;
5118 }
5119 }
5120 return PyObject_Call(func, callargs, kwdict);
5121 }
5122
5123 /* Extract a slice index from a PyLong or an object with the
5124 nb_index slot defined, and store in *pi.
5125 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
5126 and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
5127 Return 0 on error, 1 on success.
5128 */
5129 int
_PyEval_SliceIndex(PyObject * v,Py_ssize_t * pi)5130 _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
5131 {
5132 PyThreadState *tstate = _PyThreadState_GET();
5133 if (v != Py_None) {
5134 Py_ssize_t x;
5135 if (_PyIndex_Check(v)) {
5136 x = PyNumber_AsSsize_t(v, NULL);
5137 if (x == -1 && _PyErr_Occurred(tstate))
5138 return 0;
5139 }
5140 else {
5141 _PyErr_SetString(tstate, PyExc_TypeError,
5142 "slice indices must be integers or "
5143 "None or have an __index__ method");
5144 return 0;
5145 }
5146 *pi = x;
5147 }
5148 return 1;
5149 }
5150
5151 int
_PyEval_SliceIndexNotNone(PyObject * v,Py_ssize_t * pi)5152 _PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
5153 {
5154 PyThreadState *tstate = _PyThreadState_GET();
5155 Py_ssize_t x;
5156 if (_PyIndex_Check(v)) {
5157 x = PyNumber_AsSsize_t(v, NULL);
5158 if (x == -1 && _PyErr_Occurred(tstate))
5159 return 0;
5160 }
5161 else {
5162 _PyErr_SetString(tstate, PyExc_TypeError,
5163 "slice indices must be integers or "
5164 "have an __index__ method");
5165 return 0;
5166 }
5167 *pi = x;
5168 return 1;
5169 }
5170
5171 static PyObject *
import_name(PyThreadState * tstate,PyFrameObject * f,PyObject * name,PyObject * fromlist,PyObject * level)5172 import_name(PyThreadState *tstate, PyFrameObject *f,
5173 PyObject *name, PyObject *fromlist, PyObject *level)
5174 {
5175 _Py_IDENTIFIER(__import__);
5176 PyObject *import_func, *res;
5177 PyObject* stack[5];
5178
5179 import_func = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___import__);
5180 if (import_func == NULL) {
5181 if (!_PyErr_Occurred(tstate)) {
5182 _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
5183 }
5184 return NULL;
5185 }
5186
5187 /* Fast path for not overloaded __import__. */
5188 if (import_func == tstate->interp->import_func) {
5189 int ilevel = _PyLong_AsInt(level);
5190 if (ilevel == -1 && _PyErr_Occurred(tstate)) {
5191 return NULL;
5192 }
5193 res = PyImport_ImportModuleLevelObject(
5194 name,
5195 f->f_globals,
5196 f->f_locals == NULL ? Py_None : f->f_locals,
5197 fromlist,
5198 ilevel);
5199 return res;
5200 }
5201
5202 Py_INCREF(import_func);
5203
5204 stack[0] = name;
5205 stack[1] = f->f_globals;
5206 stack[2] = f->f_locals == NULL ? Py_None : f->f_locals;
5207 stack[3] = fromlist;
5208 stack[4] = level;
5209 res = _PyObject_FastCall(import_func, stack, 5);
5210 Py_DECREF(import_func);
5211 return res;
5212 }
5213
5214 static PyObject *
import_from(PyThreadState * tstate,PyObject * v,PyObject * name)5215 import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
5216 {
5217 PyObject *x;
5218 PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg;
5219
5220 if (_PyObject_LookupAttr(v, name, &x) != 0) {
5221 return x;
5222 }
5223 /* Issue #17636: in case this failed because of a circular relative
5224 import, try to fallback on reading the module directly from
5225 sys.modules. */
5226 pkgname = _PyObject_GetAttrId(v, &PyId___name__);
5227 if (pkgname == NULL) {
5228 goto error;
5229 }
5230 if (!PyUnicode_Check(pkgname)) {
5231 Py_CLEAR(pkgname);
5232 goto error;
5233 }
5234 fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
5235 if (fullmodname == NULL) {
5236 Py_DECREF(pkgname);
5237 return NULL;
5238 }
5239 x = PyImport_GetModule(fullmodname);
5240 Py_DECREF(fullmodname);
5241 if (x == NULL && !_PyErr_Occurred(tstate)) {
5242 goto error;
5243 }
5244 Py_DECREF(pkgname);
5245 return x;
5246 error:
5247 pkgpath = PyModule_GetFilenameObject(v);
5248 if (pkgname == NULL) {
5249 pkgname_or_unknown = PyUnicode_FromString("<unknown module name>");
5250 if (pkgname_or_unknown == NULL) {
5251 Py_XDECREF(pkgpath);
5252 return NULL;
5253 }
5254 } else {
5255 pkgname_or_unknown = pkgname;
5256 }
5257
5258 if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
5259 _PyErr_Clear(tstate);
5260 errmsg = PyUnicode_FromFormat(
5261 "cannot import name %R from %R (unknown location)",
5262 name, pkgname_or_unknown
5263 );
5264 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
5265 PyErr_SetImportError(errmsg, pkgname, NULL);
5266 }
5267 else {
5268 _Py_IDENTIFIER(__spec__);
5269 PyObject *spec = _PyObject_GetAttrId(v, &PyId___spec__);
5270 const char *fmt =
5271 _PyModuleSpec_IsInitializing(spec) ?
5272 "cannot import name %R from partially initialized module %R "
5273 "(most likely due to a circular import) (%S)" :
5274 "cannot import name %R from %R (%S)";
5275 Py_XDECREF(spec);
5276
5277 errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
5278 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
5279 PyErr_SetImportError(errmsg, pkgname, pkgpath);
5280 }
5281
5282 Py_XDECREF(errmsg);
5283 Py_XDECREF(pkgname_or_unknown);
5284 Py_XDECREF(pkgpath);
5285 return NULL;
5286 }
5287
5288 static int
import_all_from(PyThreadState * tstate,PyObject * locals,PyObject * v)5289 import_all_from(PyThreadState *tstate, PyObject *locals, PyObject *v)
5290 {
5291 _Py_IDENTIFIER(__all__);
5292 _Py_IDENTIFIER(__dict__);
5293 PyObject *all, *dict, *name, *value;
5294 int skip_leading_underscores = 0;
5295 int pos, err;
5296
5297 if (_PyObject_LookupAttrId(v, &PyId___all__, &all) < 0) {
5298 return -1; /* Unexpected error */
5299 }
5300 if (all == NULL) {
5301 if (_PyObject_LookupAttrId(v, &PyId___dict__, &dict) < 0) {
5302 return -1;
5303 }
5304 if (dict == NULL) {
5305 _PyErr_SetString(tstate, PyExc_ImportError,
5306 "from-import-* object has no __dict__ and no __all__");
5307 return -1;
5308 }
5309 all = PyMapping_Keys(dict);
5310 Py_DECREF(dict);
5311 if (all == NULL)
5312 return -1;
5313 skip_leading_underscores = 1;
5314 }
5315
5316 for (pos = 0, err = 0; ; pos++) {
5317 name = PySequence_GetItem(all, pos);
5318 if (name == NULL) {
5319 if (!_PyErr_ExceptionMatches(tstate, PyExc_IndexError)) {
5320 err = -1;
5321 }
5322 else {
5323 _PyErr_Clear(tstate);
5324 }
5325 break;
5326 }
5327 if (!PyUnicode_Check(name)) {
5328 PyObject *modname = _PyObject_GetAttrId(v, &PyId___name__);
5329 if (modname == NULL) {
5330 Py_DECREF(name);
5331 err = -1;
5332 break;
5333 }
5334 if (!PyUnicode_Check(modname)) {
5335 _PyErr_Format(tstate, PyExc_TypeError,
5336 "module __name__ must be a string, not %.100s",
5337 Py_TYPE(modname)->tp_name);
5338 }
5339 else {
5340 _PyErr_Format(tstate, PyExc_TypeError,
5341 "%s in %U.%s must be str, not %.100s",
5342 skip_leading_underscores ? "Key" : "Item",
5343 modname,
5344 skip_leading_underscores ? "__dict__" : "__all__",
5345 Py_TYPE(name)->tp_name);
5346 }
5347 Py_DECREF(modname);
5348 Py_DECREF(name);
5349 err = -1;
5350 break;
5351 }
5352 if (skip_leading_underscores) {
5353 if (PyUnicode_READY(name) == -1) {
5354 Py_DECREF(name);
5355 err = -1;
5356 break;
5357 }
5358 if (PyUnicode_READ_CHAR(name, 0) == '_') {
5359 Py_DECREF(name);
5360 continue;
5361 }
5362 }
5363 value = PyObject_GetAttr(v, name);
5364 if (value == NULL)
5365 err = -1;
5366 else if (PyDict_CheckExact(locals))
5367 err = PyDict_SetItem(locals, name, value);
5368 else
5369 err = PyObject_SetItem(locals, name, value);
5370 Py_DECREF(name);
5371 Py_XDECREF(value);
5372 if (err != 0)
5373 break;
5374 }
5375 Py_DECREF(all);
5376 return err;
5377 }
5378
5379 static int
check_args_iterable(PyThreadState * tstate,PyObject * func,PyObject * args)5380 check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
5381 {
5382 if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
5383 /* check_args_iterable() may be called with a live exception:
5384 * clear it to prevent calling _PyObject_FunctionStr() with an
5385 * exception set. */
5386 _PyErr_Clear(tstate);
5387 PyObject *funcstr = _PyObject_FunctionStr(func);
5388 if (funcstr != NULL) {
5389 _PyErr_Format(tstate, PyExc_TypeError,
5390 "%U argument after * must be an iterable, not %.200s",
5391 funcstr, Py_TYPE(args)->tp_name);
5392 Py_DECREF(funcstr);
5393 }
5394 return -1;
5395 }
5396 return 0;
5397 }
5398
5399 static void
format_kwargs_error(PyThreadState * tstate,PyObject * func,PyObject * kwargs)5400 format_kwargs_error(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
5401 {
5402 /* _PyDict_MergeEx raises attribute
5403 * error (percolated from an attempt
5404 * to get 'keys' attribute) instead of
5405 * a type error if its second argument
5406 * is not a mapping.
5407 */
5408 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
5409 _PyErr_Clear(tstate);
5410 PyObject *funcstr = _PyObject_FunctionStr(func);
5411 if (funcstr != NULL) {
5412 _PyErr_Format(
5413 tstate, PyExc_TypeError,
5414 "%U argument after ** must be a mapping, not %.200s",
5415 funcstr, Py_TYPE(kwargs)->tp_name);
5416 Py_DECREF(funcstr);
5417 }
5418 }
5419 else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
5420 PyObject *exc, *val, *tb;
5421 _PyErr_Fetch(tstate, &exc, &val, &tb);
5422 if (val && PyTuple_Check(val) && PyTuple_GET_SIZE(val) == 1) {
5423 _PyErr_Clear(tstate);
5424 PyObject *funcstr = _PyObject_FunctionStr(func);
5425 if (funcstr != NULL) {
5426 PyObject *key = PyTuple_GET_ITEM(val, 0);
5427 _PyErr_Format(
5428 tstate, PyExc_TypeError,
5429 "%U got multiple values for keyword argument '%S'",
5430 funcstr, key);
5431 Py_DECREF(funcstr);
5432 }
5433 Py_XDECREF(exc);
5434 Py_XDECREF(val);
5435 Py_XDECREF(tb);
5436 }
5437 else {
5438 _PyErr_Restore(tstate, exc, val, tb);
5439 }
5440 }
5441 }
5442
5443 static void
format_exc_check_arg(PyThreadState * tstate,PyObject * exc,const char * format_str,PyObject * obj)5444 format_exc_check_arg(PyThreadState *tstate, PyObject *exc,
5445 const char *format_str, PyObject *obj)
5446 {
5447 const char *obj_str;
5448
5449 if (!obj)
5450 return;
5451
5452 obj_str = PyUnicode_AsUTF8(obj);
5453 if (!obj_str)
5454 return;
5455
5456 _PyErr_Format(tstate, exc, format_str, obj_str);
5457 }
5458
5459 static void
format_exc_unbound(PyThreadState * tstate,PyCodeObject * co,int oparg)5460 format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
5461 {
5462 PyObject *name;
5463 /* Don't stomp existing exception */
5464 if (_PyErr_Occurred(tstate))
5465 return;
5466 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
5467 name = PyTuple_GET_ITEM(co->co_cellvars,
5468 oparg);
5469 format_exc_check_arg(tstate,
5470 PyExc_UnboundLocalError,
5471 UNBOUNDLOCAL_ERROR_MSG,
5472 name);
5473 } else {
5474 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
5475 PyTuple_GET_SIZE(co->co_cellvars));
5476 format_exc_check_arg(tstate, PyExc_NameError,
5477 UNBOUNDFREE_ERROR_MSG, name);
5478 }
5479 }
5480
5481 static void
format_awaitable_error(PyThreadState * tstate,PyTypeObject * type,int prevprevopcode,int prevopcode)5482 format_awaitable_error(PyThreadState *tstate, PyTypeObject *type, int prevprevopcode, int prevopcode)
5483 {
5484 if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
5485 if (prevopcode == BEFORE_ASYNC_WITH) {
5486 _PyErr_Format(tstate, PyExc_TypeError,
5487 "'async with' received an object from __aenter__ "
5488 "that does not implement __await__: %.100s",
5489 type->tp_name);
5490 }
5491 else if (prevopcode == WITH_EXCEPT_START || (prevopcode == CALL_FUNCTION && prevprevopcode == DUP_TOP)) {
5492 _PyErr_Format(tstate, PyExc_TypeError,
5493 "'async with' received an object from __aexit__ "
5494 "that does not implement __await__: %.100s",
5495 type->tp_name);
5496 }
5497 }
5498 }
5499
5500 static PyObject *
unicode_concatenate(PyThreadState * tstate,PyObject * v,PyObject * w,PyFrameObject * f,const _Py_CODEUNIT * next_instr)5501 unicode_concatenate(PyThreadState *tstate, PyObject *v, PyObject *w,
5502 PyFrameObject *f, const _Py_CODEUNIT *next_instr)
5503 {
5504 PyObject *res;
5505 if (Py_REFCNT(v) == 2) {
5506 /* In the common case, there are 2 references to the value
5507 * stored in 'variable' when the += is performed: one on the
5508 * value stack (in 'v') and one still stored in the
5509 * 'variable'. We try to delete the variable now to reduce
5510 * the refcnt to 1.
5511 */
5512 int opcode, oparg;
5513 NEXTOPARG();
5514 switch (opcode) {
5515 case STORE_FAST:
5516 {
5517 PyObject **fastlocals = f->f_localsplus;
5518 if (GETLOCAL(oparg) == v)
5519 SETLOCAL(oparg, NULL);
5520 break;
5521 }
5522 case STORE_DEREF:
5523 {
5524 PyObject **freevars = (f->f_localsplus +
5525 f->f_code->co_nlocals);
5526 PyObject *c = freevars[oparg];
5527 if (PyCell_GET(c) == v) {
5528 PyCell_SET(c, NULL);
5529 Py_DECREF(v);
5530 }
5531 break;
5532 }
5533 case STORE_NAME:
5534 {
5535 PyObject *names = f->f_code->co_names;
5536 PyObject *name = GETITEM(names, oparg);
5537 PyObject *locals = f->f_locals;
5538 if (locals && PyDict_CheckExact(locals)) {
5539 PyObject *w = PyDict_GetItemWithError(locals, name);
5540 if ((w == v && PyDict_DelItem(locals, name) != 0) ||
5541 (w == NULL && _PyErr_Occurred(tstate)))
5542 {
5543 Py_DECREF(v);
5544 return NULL;
5545 }
5546 }
5547 break;
5548 }
5549 }
5550 }
5551 res = v;
5552 PyUnicode_Append(&res, w);
5553 return res;
5554 }
5555
5556 #ifdef DYNAMIC_EXECUTION_PROFILE
5557
5558 static PyObject *
getarray(long a[256])5559 getarray(long a[256])
5560 {
5561 int i;
5562 PyObject *l = PyList_New(256);
5563 if (l == NULL) return NULL;
5564 for (i = 0; i < 256; i++) {
5565 PyObject *x = PyLong_FromLong(a[i]);
5566 if (x == NULL) {
5567 Py_DECREF(l);
5568 return NULL;
5569 }
5570 PyList_SET_ITEM(l, i, x);
5571 }
5572 for (i = 0; i < 256; i++)
5573 a[i] = 0;
5574 return l;
5575 }
5576
5577 PyObject *
_Py_GetDXProfile(PyObject * self,PyObject * args)5578 _Py_GetDXProfile(PyObject *self, PyObject *args)
5579 {
5580 #ifndef DXPAIRS
5581 return getarray(dxp);
5582 #else
5583 int i;
5584 PyObject *l = PyList_New(257);
5585 if (l == NULL) return NULL;
5586 for (i = 0; i < 257; i++) {
5587 PyObject *x = getarray(dxpairs[i]);
5588 if (x == NULL) {
5589 Py_DECREF(l);
5590 return NULL;
5591 }
5592 PyList_SET_ITEM(l, i, x);
5593 }
5594 return l;
5595 #endif
5596 }
5597
5598 #endif
5599
5600 Py_ssize_t
_PyEval_RequestCodeExtraIndex(freefunc free)5601 _PyEval_RequestCodeExtraIndex(freefunc free)
5602 {
5603 PyInterpreterState *interp = _PyInterpreterState_GET();
5604 Py_ssize_t new_index;
5605
5606 if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
5607 return -1;
5608 }
5609 new_index = interp->co_extra_user_count++;
5610 interp->co_extra_freefuncs[new_index] = free;
5611 return new_index;
5612 }
5613
5614 static void
dtrace_function_entry(PyFrameObject * f)5615 dtrace_function_entry(PyFrameObject *f)
5616 {
5617 const char *filename;
5618 const char *funcname;
5619 int lineno;
5620
5621 PyCodeObject *code = f->f_code;
5622 filename = PyUnicode_AsUTF8(code->co_filename);
5623 funcname = PyUnicode_AsUTF8(code->co_name);
5624 lineno = PyCode_Addr2Line(code, f->f_lasti);
5625
5626 PyDTrace_FUNCTION_ENTRY(filename, funcname, lineno);
5627 }
5628
5629 static void
dtrace_function_return(PyFrameObject * f)5630 dtrace_function_return(PyFrameObject *f)
5631 {
5632 const char *filename;
5633 const char *funcname;
5634 int lineno;
5635
5636 PyCodeObject *code = f->f_code;
5637 filename = PyUnicode_AsUTF8(code->co_filename);
5638 funcname = PyUnicode_AsUTF8(code->co_name);
5639 lineno = PyCode_Addr2Line(code, f->f_lasti);
5640
5641 PyDTrace_FUNCTION_RETURN(filename, funcname, lineno);
5642 }
5643
5644 /* DTrace equivalent of maybe_call_line_trace. */
5645 static void
maybe_dtrace_line(PyFrameObject * frame,int * instr_lb,int * instr_ub,int * instr_prev)5646 maybe_dtrace_line(PyFrameObject *frame,
5647 int *instr_lb, int *instr_ub, int *instr_prev)
5648 {
5649 int line = frame->f_lineno;
5650 const char *co_filename, *co_name;
5651
5652 /* If the last instruction executed isn't in the current
5653 instruction window, reset the window.
5654 */
5655 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
5656 PyAddrPair bounds;
5657 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
5658 &bounds);
5659 *instr_lb = bounds.ap_lower;
5660 *instr_ub = bounds.ap_upper;
5661 }
5662 /* If the last instruction falls at the start of a line or if
5663 it represents a jump backwards, update the frame's line
5664 number and call the trace function. */
5665 if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
5666 frame->f_lineno = line;
5667 co_filename = PyUnicode_AsUTF8(frame->f_code->co_filename);
5668 if (!co_filename)
5669 co_filename = "?";
5670 co_name = PyUnicode_AsUTF8(frame->f_code->co_name);
5671 if (!co_name)
5672 co_name = "?";
5673 PyDTrace_LINE(co_filename, co_name, line);
5674 }
5675 *instr_prev = frame->f_lasti;
5676 }
5677
5678
5679 /* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
5680 for the limited API. */
5681
5682 #undef Py_EnterRecursiveCall
5683
Py_EnterRecursiveCall(const char * where)5684 int Py_EnterRecursiveCall(const char *where)
5685 {
5686 return _Py_EnterRecursiveCall_inline(where);
5687 }
5688
5689 #undef Py_LeaveRecursiveCall
5690
Py_LeaveRecursiveCall(void)5691 void Py_LeaveRecursiveCall(void)
5692 {
5693 _Py_LeaveRecursiveCall_inline();
5694 }
5695