1 /* Execute compiled code */
2
3 /* XXX TO DO:
4 XXX speed up searching for keywords by using a dictionary
5 XXX document it!
6 */
7
8 #include "Python.h"
9 #include "pycore_abstract.h" // _PyIndex_Check()
10 #include "pycore_call.h" // _PyObject_FastCallDictTstate()
11 #include "pycore_ceval.h" // _PyEval_SignalAsyncExc()
12 #include "pycore_code.h"
13 #include "pycore_function.h"
14 #include "pycore_initconfig.h" // _PyStatus_OK()
15 #include "pycore_long.h" // _PyLong_GetZero()
16 #include "pycore_object.h" // _PyObject_GC_TRACK()
17 #include "pycore_moduleobject.h" // PyModuleObject
18 #include "pycore_opcode.h" // EXTRA_CASES
19 #include "pycore_pyerrors.h" // _PyErr_Fetch()
20 #include "pycore_pylifecycle.h" // _PyErr_Print()
21 #include "pycore_pymem.h" // _PyMem_IsPtrFreed()
22 #include "pycore_pystate.h" // _PyInterpreterState_GET()
23 #include "pycore_sysmodule.h" // _PySys_Audit()
24 #include "pycore_tuple.h" // _PyTuple_ITEMS()
25 #include "pycore_emscripten_signal.h" // _Py_CHECK_EMSCRIPTEN_SIGNALS
26
27 #include "pycore_dict.h"
28 #include "dictobject.h"
29 #include "pycore_frame.h"
30 #include "opcode.h"
31 #include "pydtrace.h"
32 #include "setobject.h"
33 #include "structmember.h" // struct PyMemberDef, T_OFFSET_EX
34
35 #include <ctype.h>
36 #include <stdbool.h>
37
38 #ifdef Py_DEBUG
39 /* For debugging the interpreter: */
40 # define LLTRACE 1 /* Low-level trace feature */
41 #endif
42
43 #if !defined(Py_BUILD_CORE)
44 # error "ceval.c must be build with Py_BUILD_CORE define for best performance"
45 #endif
46
47 #if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
48 // GH-89279: The MSVC compiler does not inline these static inline functions
49 // in PGO build in _PyEval_EvalFrameDefault(), because this function is over
50 // the limit of PGO, and that limit cannot be configured.
51 // Define them as macros to make sure that they are always inlined by the
52 // preprocessor.
53
54 #undef Py_DECREF
55 #define Py_DECREF(arg) \
56 do { \
57 PyObject *op = _PyObject_CAST(arg); \
58 if (--op->ob_refcnt == 0) { \
59 destructor dealloc = Py_TYPE(op)->tp_dealloc; \
60 (*dealloc)(op); \
61 } \
62 } while (0)
63
64 #undef Py_XDECREF
65 #define Py_XDECREF(arg) \
66 do { \
67 PyObject *xop = _PyObject_CAST(arg); \
68 if (xop != NULL) { \
69 Py_DECREF(xop); \
70 } \
71 } while (0)
72
73 #undef Py_IS_TYPE
74 #define Py_IS_TYPE(ob, type) \
75 (_PyObject_CAST(ob)->ob_type == (type))
76
77 #undef _Py_DECREF_SPECIALIZED
78 #define _Py_DECREF_SPECIALIZED(arg, dealloc) \
79 do { \
80 PyObject *op = _PyObject_CAST(arg); \
81 if (--op->ob_refcnt == 0) { \
82 destructor d = (destructor)(dealloc); \
83 d(op); \
84 } \
85 } while (0)
86 #endif
87
88 // GH-89279: Similar to above, force inlining by using a macro.
89 #if defined(_MSC_VER) && SIZEOF_INT == 4
90 #define _Py_atomic_load_relaxed_int32(ATOMIC_VAL) (assert(sizeof((ATOMIC_VAL)->_value) == 4), *((volatile int*)&((ATOMIC_VAL)->_value)))
91 #else
92 #define _Py_atomic_load_relaxed_int32(ATOMIC_VAL) _Py_atomic_load_relaxed(ATOMIC_VAL)
93 #endif
94
95
96 /* Forward declarations */
97 static PyObject *trace_call_function(
98 PyThreadState *tstate, PyObject *callable, PyObject **stack,
99 Py_ssize_t oparg, PyObject *kwnames);
100 static PyObject * do_call_core(
101 PyThreadState *tstate, PyObject *func,
102 PyObject *callargs, PyObject *kwdict, int use_tracing);
103
104 #ifdef LLTRACE
105 static void
dump_stack(_PyInterpreterFrame * frame,PyObject ** stack_pointer)106 dump_stack(_PyInterpreterFrame *frame, PyObject **stack_pointer)
107 {
108 PyObject **stack_base = _PyFrame_Stackbase(frame);
109 PyObject *type, *value, *traceback;
110 PyErr_Fetch(&type, &value, &traceback);
111 printf(" stack=[");
112 for (PyObject **ptr = stack_base; ptr < stack_pointer; ptr++) {
113 if (ptr != stack_base) {
114 printf(", ");
115 }
116 if (PyObject_Print(*ptr, stdout, 0) != 0) {
117 PyErr_Clear();
118 printf("<%s object at %p>",
119 Py_TYPE(*ptr)->tp_name, (void *)(*ptr));
120 }
121 }
122 printf("]\n");
123 fflush(stdout);
124 PyErr_Restore(type, value, traceback);
125 }
126
127 static void
lltrace_instruction(_PyInterpreterFrame * frame,PyObject ** stack_pointer,_Py_CODEUNIT * next_instr)128 lltrace_instruction(_PyInterpreterFrame *frame,
129 PyObject **stack_pointer,
130 _Py_CODEUNIT *next_instr)
131 {
132 dump_stack(frame, stack_pointer);
133 int oparg = _Py_OPARG(*next_instr);
134 int opcode = _Py_OPCODE(*next_instr);
135 const char *opname = _PyOpcode_OpName[opcode];
136 assert(opname != NULL);
137 int offset = (int)(next_instr - _PyCode_CODE(frame->f_code));
138 if (HAS_ARG(opcode)) {
139 printf("%d: %s %d\n", offset * 2, opname, oparg);
140 }
141 else {
142 printf("%d: %s\n", offset * 2, opname);
143 }
144 fflush(stdout);
145 }
146 static void
lltrace_resume_frame(_PyInterpreterFrame * frame)147 lltrace_resume_frame(_PyInterpreterFrame *frame)
148 {
149 PyFunctionObject *f = frame->f_func;
150 if (f == NULL) {
151 printf("\nResuming frame.");
152 return;
153 }
154 PyObject *type, *value, *traceback;
155 PyErr_Fetch(&type, &value, &traceback);
156 PyObject *name = f->func_qualname;
157 if (name == NULL) {
158 name = f->func_name;
159 }
160 printf("\nResuming frame");
161 if (name) {
162 printf(" for ");
163 if (PyObject_Print(name, stdout, 0) < 0) {
164 PyErr_Clear();
165 }
166 }
167 if (f->func_module) {
168 printf(" in module ");
169 if (PyObject_Print(f->func_module, stdout, 0) < 0) {
170 PyErr_Clear();
171 }
172 }
173 printf("\n");
174 fflush(stdout);
175 PyErr_Restore(type, value, traceback);
176 }
177 #endif
178 static int call_trace(Py_tracefunc, PyObject *,
179 PyThreadState *, _PyInterpreterFrame *,
180 int, PyObject *);
181 static int call_trace_protected(Py_tracefunc, PyObject *,
182 PyThreadState *, _PyInterpreterFrame *,
183 int, PyObject *);
184 static void call_exc_trace(Py_tracefunc, PyObject *,
185 PyThreadState *, _PyInterpreterFrame *);
186 static int maybe_call_line_trace(Py_tracefunc, PyObject *,
187 PyThreadState *, _PyInterpreterFrame *, int);
188 static void maybe_dtrace_line(_PyInterpreterFrame *, PyTraceInfo *, int);
189 static void dtrace_function_entry(_PyInterpreterFrame *);
190 static void dtrace_function_return(_PyInterpreterFrame *);
191
192 static PyObject * import_name(PyThreadState *, _PyInterpreterFrame *,
193 PyObject *, PyObject *, PyObject *);
194 static PyObject * import_from(PyThreadState *, PyObject *, PyObject *);
195 static int import_all_from(PyThreadState *, PyObject *, PyObject *);
196 static void format_exc_check_arg(PyThreadState *, PyObject *, const char *, PyObject *);
197 static void format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
198 static int check_args_iterable(PyThreadState *, PyObject *func, PyObject *vararg);
199 static int check_except_type_valid(PyThreadState *tstate, PyObject* right);
200 static int check_except_star_type_valid(PyThreadState *tstate, PyObject* right);
201 static void format_kwargs_error(PyThreadState *, PyObject *func, PyObject *kwargs);
202 static void format_awaitable_error(PyThreadState *, PyTypeObject *, int);
203 static int get_exception_handler(PyCodeObject *, int, int*, int*, int*);
204 static _PyInterpreterFrame *
205 _PyEvalFramePushAndInit(PyThreadState *tstate, PyFunctionObject *func,
206 PyObject *locals, PyObject* const* args,
207 size_t argcount, PyObject *kwnames);
208 static void
209 _PyEvalFrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame *frame);
210
211 #define NAME_ERROR_MSG \
212 "name '%.200s' is not defined"
213 #define UNBOUNDLOCAL_ERROR_MSG \
214 "cannot access local variable '%s' where it is not associated with a value"
215 #define UNBOUNDFREE_ERROR_MSG \
216 "cannot access free variable '%s' where it is not associated with a" \
217 " value in enclosing scope"
218
219 #ifndef NDEBUG
220 /* Ensure that tstate is valid: sanity check for PyEval_AcquireThread() and
221 PyEval_RestoreThread(). Detect if tstate memory was freed. It can happen
222 when a thread continues to run after Python finalization, especially
223 daemon threads. */
224 static int
is_tstate_valid(PyThreadState * tstate)225 is_tstate_valid(PyThreadState *tstate)
226 {
227 assert(!_PyMem_IsPtrFreed(tstate));
228 assert(!_PyMem_IsPtrFreed(tstate->interp));
229 return 1;
230 }
231 #endif
232
233
234 /* This can set eval_breaker to 0 even though gil_drop_request became
235 1. We believe this is all right because the eval loop will release
236 the GIL eventually anyway. */
237 static inline void
COMPUTE_EVAL_BREAKER(PyInterpreterState * interp,struct _ceval_runtime_state * ceval,struct _ceval_state * ceval2)238 COMPUTE_EVAL_BREAKER(PyInterpreterState *interp,
239 struct _ceval_runtime_state *ceval,
240 struct _ceval_state *ceval2)
241 {
242 _Py_atomic_store_relaxed(&ceval2->eval_breaker,
243 _Py_atomic_load_relaxed_int32(&ceval2->gil_drop_request)
244 | (_Py_atomic_load_relaxed_int32(&ceval->signals_pending)
245 && _Py_ThreadCanHandleSignals(interp))
246 | (_Py_atomic_load_relaxed_int32(&ceval2->pending.calls_to_do)
247 && _Py_ThreadCanHandlePendingCalls())
248 | ceval2->pending.async_exc);
249 }
250
251
252 static inline void
SET_GIL_DROP_REQUEST(PyInterpreterState * interp)253 SET_GIL_DROP_REQUEST(PyInterpreterState *interp)
254 {
255 struct _ceval_state *ceval2 = &interp->ceval;
256 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 1);
257 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
258 }
259
260
261 static inline void
RESET_GIL_DROP_REQUEST(PyInterpreterState * interp)262 RESET_GIL_DROP_REQUEST(PyInterpreterState *interp)
263 {
264 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
265 struct _ceval_state *ceval2 = &interp->ceval;
266 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 0);
267 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
268 }
269
270
271 static inline void
SIGNAL_PENDING_CALLS(PyInterpreterState * interp)272 SIGNAL_PENDING_CALLS(PyInterpreterState *interp)
273 {
274 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
275 struct _ceval_state *ceval2 = &interp->ceval;
276 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 1);
277 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
278 }
279
280
281 static inline void
UNSIGNAL_PENDING_CALLS(PyInterpreterState * interp)282 UNSIGNAL_PENDING_CALLS(PyInterpreterState *interp)
283 {
284 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
285 struct _ceval_state *ceval2 = &interp->ceval;
286 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 0);
287 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
288 }
289
290
291 static inline void
SIGNAL_PENDING_SIGNALS(PyInterpreterState * interp,int force)292 SIGNAL_PENDING_SIGNALS(PyInterpreterState *interp, int force)
293 {
294 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
295 struct _ceval_state *ceval2 = &interp->ceval;
296 _Py_atomic_store_relaxed(&ceval->signals_pending, 1);
297 if (force) {
298 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
299 }
300 else {
301 /* eval_breaker is not set to 1 if thread_can_handle_signals() is false */
302 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
303 }
304 }
305
306
307 static inline void
UNSIGNAL_PENDING_SIGNALS(PyInterpreterState * interp)308 UNSIGNAL_PENDING_SIGNALS(PyInterpreterState *interp)
309 {
310 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
311 struct _ceval_state *ceval2 = &interp->ceval;
312 _Py_atomic_store_relaxed(&ceval->signals_pending, 0);
313 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
314 }
315
316
317 static inline void
SIGNAL_ASYNC_EXC(PyInterpreterState * interp)318 SIGNAL_ASYNC_EXC(PyInterpreterState *interp)
319 {
320 struct _ceval_state *ceval2 = &interp->ceval;
321 ceval2->pending.async_exc = 1;
322 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
323 }
324
325
326 static inline void
UNSIGNAL_ASYNC_EXC(PyInterpreterState * interp)327 UNSIGNAL_ASYNC_EXC(PyInterpreterState *interp)
328 {
329 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
330 struct _ceval_state *ceval2 = &interp->ceval;
331 ceval2->pending.async_exc = 0;
332 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
333 }
334
335
336 #ifdef HAVE_ERRNO_H
337 #include <errno.h>
338 #endif
339 #include "ceval_gil.h"
340
341 void _Py_NO_RETURN
_Py_FatalError_TstateNULL(const char * func)342 _Py_FatalError_TstateNULL(const char *func)
343 {
344 _Py_FatalErrorFunc(func,
345 "the function must be called with the GIL held, "
346 "but the GIL is released "
347 "(the current Python thread state is NULL)");
348 }
349
350 int
_PyEval_ThreadsInitialized(_PyRuntimeState * runtime)351 _PyEval_ThreadsInitialized(_PyRuntimeState *runtime)
352 {
353 return gil_created(&runtime->ceval.gil);
354 }
355
356 int
PyEval_ThreadsInitialized(void)357 PyEval_ThreadsInitialized(void)
358 {
359 _PyRuntimeState *runtime = &_PyRuntime;
360 return _PyEval_ThreadsInitialized(runtime);
361 }
362
363 PyStatus
_PyEval_InitGIL(PyThreadState * tstate)364 _PyEval_InitGIL(PyThreadState *tstate)
365 {
366 if (!_Py_IsMainInterpreter(tstate->interp)) {
367 /* Currently, the GIL is shared by all interpreters,
368 and only the main interpreter is responsible to create
369 and destroy it. */
370 return _PyStatus_OK();
371 }
372
373 struct _gil_runtime_state *gil = &tstate->interp->runtime->ceval.gil;
374 assert(!gil_created(gil));
375
376 PyThread_init_thread();
377 create_gil(gil);
378
379 take_gil(tstate);
380
381 assert(gil_created(gil));
382 return _PyStatus_OK();
383 }
384
385 void
_PyEval_FiniGIL(PyInterpreterState * interp)386 _PyEval_FiniGIL(PyInterpreterState *interp)
387 {
388 if (!_Py_IsMainInterpreter(interp)) {
389 /* Currently, the GIL is shared by all interpreters,
390 and only the main interpreter is responsible to create
391 and destroy it. */
392 return;
393 }
394
395 struct _gil_runtime_state *gil = &interp->runtime->ceval.gil;
396 if (!gil_created(gil)) {
397 /* First Py_InitializeFromConfig() call: the GIL doesn't exist
398 yet: do nothing. */
399 return;
400 }
401
402 destroy_gil(gil);
403 assert(!gil_created(gil));
404 }
405
406 void
PyEval_InitThreads(void)407 PyEval_InitThreads(void)
408 {
409 /* Do nothing: kept for backward compatibility */
410 }
411
412 void
_PyEval_Fini(void)413 _PyEval_Fini(void)
414 {
415 #ifdef Py_STATS
416 _Py_PrintSpecializationStats(1);
417 #endif
418 }
419
420 void
PyEval_AcquireLock(void)421 PyEval_AcquireLock(void)
422 {
423 _PyRuntimeState *runtime = &_PyRuntime;
424 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
425 _Py_EnsureTstateNotNULL(tstate);
426
427 take_gil(tstate);
428 }
429
430 void
PyEval_ReleaseLock(void)431 PyEval_ReleaseLock(void)
432 {
433 _PyRuntimeState *runtime = &_PyRuntime;
434 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
435 /* This function must succeed when the current thread state is NULL.
436 We therefore avoid PyThreadState_Get() which dumps a fatal error
437 in debug mode. */
438 struct _ceval_runtime_state *ceval = &runtime->ceval;
439 struct _ceval_state *ceval2 = &tstate->interp->ceval;
440 drop_gil(ceval, ceval2, tstate);
441 }
442
443 void
_PyEval_ReleaseLock(PyThreadState * tstate)444 _PyEval_ReleaseLock(PyThreadState *tstate)
445 {
446 struct _ceval_runtime_state *ceval = &tstate->interp->runtime->ceval;
447 struct _ceval_state *ceval2 = &tstate->interp->ceval;
448 drop_gil(ceval, ceval2, tstate);
449 }
450
451 void
PyEval_AcquireThread(PyThreadState * tstate)452 PyEval_AcquireThread(PyThreadState *tstate)
453 {
454 _Py_EnsureTstateNotNULL(tstate);
455
456 take_gil(tstate);
457
458 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
459 if (_PyThreadState_Swap(gilstate, tstate) != NULL) {
460 Py_FatalError("non-NULL old thread state");
461 }
462 }
463
464 void
PyEval_ReleaseThread(PyThreadState * tstate)465 PyEval_ReleaseThread(PyThreadState *tstate)
466 {
467 assert(is_tstate_valid(tstate));
468
469 _PyRuntimeState *runtime = tstate->interp->runtime;
470 PyThreadState *new_tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
471 if (new_tstate != tstate) {
472 Py_FatalError("wrong thread state");
473 }
474 struct _ceval_runtime_state *ceval = &runtime->ceval;
475 struct _ceval_state *ceval2 = &tstate->interp->ceval;
476 drop_gil(ceval, ceval2, tstate);
477 }
478
479 #ifdef HAVE_FORK
480 /* This function is called from PyOS_AfterFork_Child to destroy all threads
481 which are not running in the child process, and clear internal locks
482 which might be held by those threads. */
483 PyStatus
_PyEval_ReInitThreads(PyThreadState * tstate)484 _PyEval_ReInitThreads(PyThreadState *tstate)
485 {
486 _PyRuntimeState *runtime = tstate->interp->runtime;
487
488 struct _gil_runtime_state *gil = &runtime->ceval.gil;
489 if (!gil_created(gil)) {
490 return _PyStatus_OK();
491 }
492 recreate_gil(gil);
493
494 take_gil(tstate);
495
496 struct _pending_calls *pending = &tstate->interp->ceval.pending;
497 if (_PyThread_at_fork_reinit(&pending->lock) < 0) {
498 return _PyStatus_ERR("Can't reinitialize pending calls lock");
499 }
500
501 /* Destroy all threads except the current one */
502 _PyThreadState_DeleteExcept(runtime, tstate);
503 return _PyStatus_OK();
504 }
505 #endif
506
507 /* This function is used to signal that async exceptions are waiting to be
508 raised. */
509
510 void
_PyEval_SignalAsyncExc(PyInterpreterState * interp)511 _PyEval_SignalAsyncExc(PyInterpreterState *interp)
512 {
513 SIGNAL_ASYNC_EXC(interp);
514 }
515
516 PyThreadState *
PyEval_SaveThread(void)517 PyEval_SaveThread(void)
518 {
519 _PyRuntimeState *runtime = &_PyRuntime;
520 PyThreadState *tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
521 _Py_EnsureTstateNotNULL(tstate);
522
523 struct _ceval_runtime_state *ceval = &runtime->ceval;
524 struct _ceval_state *ceval2 = &tstate->interp->ceval;
525 assert(gil_created(&ceval->gil));
526 drop_gil(ceval, ceval2, tstate);
527 return tstate;
528 }
529
530 void
PyEval_RestoreThread(PyThreadState * tstate)531 PyEval_RestoreThread(PyThreadState *tstate)
532 {
533 _Py_EnsureTstateNotNULL(tstate);
534
535 take_gil(tstate);
536
537 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
538 _PyThreadState_Swap(gilstate, tstate);
539 }
540
541
542 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
543 signal handlers or Mac I/O completion routines) can schedule calls
544 to a function to be called synchronously.
545 The synchronous function is called with one void* argument.
546 It should return 0 for success or -1 for failure -- failure should
547 be accompanied by an exception.
548
549 If registry succeeds, the registry function returns 0; if it fails
550 (e.g. due to too many pending calls) it returns -1 (without setting
551 an exception condition).
552
553 Note that because registry may occur from within signal handlers,
554 or other asynchronous events, calling malloc() is unsafe!
555
556 Any thread can schedule pending calls, but only the main thread
557 will execute them.
558 There is no facility to schedule calls to a particular thread, but
559 that should be easy to change, should that ever be required. In
560 that case, the static variables here should go into the python
561 threadstate.
562 */
563
564 void
_PyEval_SignalReceived(PyInterpreterState * interp)565 _PyEval_SignalReceived(PyInterpreterState *interp)
566 {
567 #ifdef MS_WINDOWS
568 // bpo-42296: On Windows, _PyEval_SignalReceived() is called from a signal
569 // handler which can run in a thread different than the Python thread, in
570 // which case _Py_ThreadCanHandleSignals() is wrong. Ignore
571 // _Py_ThreadCanHandleSignals() and always set eval_breaker to 1.
572 //
573 // The next eval_frame_handle_pending() call will call
574 // _Py_ThreadCanHandleSignals() to recompute eval_breaker.
575 int force = 1;
576 #else
577 int force = 0;
578 #endif
579 /* bpo-30703: Function called when the C signal handler of Python gets a
580 signal. We cannot queue a callback using _PyEval_AddPendingCall() since
581 that function is not async-signal-safe. */
582 SIGNAL_PENDING_SIGNALS(interp, force);
583 }
584
585 /* Push one item onto the queue while holding the lock. */
586 static int
_push_pending_call(struct _pending_calls * pending,int (* func)(void *),void * arg)587 _push_pending_call(struct _pending_calls *pending,
588 int (*func)(void *), void *arg)
589 {
590 int i = pending->last;
591 int j = (i + 1) % NPENDINGCALLS;
592 if (j == pending->first) {
593 return -1; /* Queue full */
594 }
595 pending->calls[i].func = func;
596 pending->calls[i].arg = arg;
597 pending->last = j;
598 return 0;
599 }
600
601 /* Pop one item off the queue while holding the lock. */
602 static void
_pop_pending_call(struct _pending_calls * pending,int (** func)(void *),void ** arg)603 _pop_pending_call(struct _pending_calls *pending,
604 int (**func)(void *), void **arg)
605 {
606 int i = pending->first;
607 if (i == pending->last) {
608 return; /* Queue empty */
609 }
610
611 *func = pending->calls[i].func;
612 *arg = pending->calls[i].arg;
613 pending->first = (i + 1) % NPENDINGCALLS;
614 }
615
616 /* This implementation is thread-safe. It allows
617 scheduling to be made from any thread, and even from an executing
618 callback.
619 */
620
621 int
_PyEval_AddPendingCall(PyInterpreterState * interp,int (* func)(void *),void * arg)622 _PyEval_AddPendingCall(PyInterpreterState *interp,
623 int (*func)(void *), void *arg)
624 {
625 struct _pending_calls *pending = &interp->ceval.pending;
626
627 /* Ensure that _PyEval_InitPendingCalls() was called
628 and that _PyEval_FiniPendingCalls() is not called yet. */
629 assert(pending->lock != NULL);
630
631 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
632 int result = _push_pending_call(pending, func, arg);
633 PyThread_release_lock(pending->lock);
634
635 /* signal main loop */
636 SIGNAL_PENDING_CALLS(interp);
637 return result;
638 }
639
640 int
Py_AddPendingCall(int (* func)(void *),void * arg)641 Py_AddPendingCall(int (*func)(void *), void *arg)
642 {
643 /* Best-effort to support subinterpreters and calls with the GIL released.
644
645 First attempt _PyThreadState_GET() since it supports subinterpreters.
646
647 If the GIL is released, _PyThreadState_GET() returns NULL . In this
648 case, use PyGILState_GetThisThreadState() which works even if the GIL
649 is released.
650
651 Sadly, PyGILState_GetThisThreadState() doesn't support subinterpreters:
652 see bpo-10915 and bpo-15751.
653
654 Py_AddPendingCall() doesn't require the caller to hold the GIL. */
655 PyThreadState *tstate = _PyThreadState_GET();
656 if (tstate == NULL) {
657 tstate = PyGILState_GetThisThreadState();
658 }
659
660 PyInterpreterState *interp;
661 if (tstate != NULL) {
662 interp = tstate->interp;
663 }
664 else {
665 /* Last resort: use the main interpreter */
666 interp = _PyInterpreterState_Main();
667 }
668 return _PyEval_AddPendingCall(interp, func, arg);
669 }
670
671 static int
handle_signals(PyThreadState * tstate)672 handle_signals(PyThreadState *tstate)
673 {
674 assert(is_tstate_valid(tstate));
675 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
676 return 0;
677 }
678
679 UNSIGNAL_PENDING_SIGNALS(tstate->interp);
680 if (_PyErr_CheckSignalsTstate(tstate) < 0) {
681 /* On failure, re-schedule a call to handle_signals(). */
682 SIGNAL_PENDING_SIGNALS(tstate->interp, 0);
683 return -1;
684 }
685 return 0;
686 }
687
688 static int
make_pending_calls(PyInterpreterState * interp)689 make_pending_calls(PyInterpreterState *interp)
690 {
691 /* only execute pending calls on main thread */
692 if (!_Py_ThreadCanHandlePendingCalls()) {
693 return 0;
694 }
695
696 /* don't perform recursive pending calls */
697 static int busy = 0;
698 if (busy) {
699 return 0;
700 }
701 busy = 1;
702
703 /* unsignal before starting to call callbacks, so that any callback
704 added in-between re-signals */
705 UNSIGNAL_PENDING_CALLS(interp);
706 int res = 0;
707
708 /* perform a bounded number of calls, in case of recursion */
709 struct _pending_calls *pending = &interp->ceval.pending;
710 for (int i=0; i<NPENDINGCALLS; i++) {
711 int (*func)(void *) = NULL;
712 void *arg = NULL;
713
714 /* pop one item off the queue while holding the lock */
715 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
716 _pop_pending_call(pending, &func, &arg);
717 PyThread_release_lock(pending->lock);
718
719 /* having released the lock, perform the callback */
720 if (func == NULL) {
721 break;
722 }
723 res = func(arg);
724 if (res) {
725 goto error;
726 }
727 }
728
729 busy = 0;
730 return res;
731
732 error:
733 busy = 0;
734 SIGNAL_PENDING_CALLS(interp);
735 return res;
736 }
737
738 void
_Py_FinishPendingCalls(PyThreadState * tstate)739 _Py_FinishPendingCalls(PyThreadState *tstate)
740 {
741 assert(PyGILState_Check());
742 assert(is_tstate_valid(tstate));
743
744 struct _pending_calls *pending = &tstate->interp->ceval.pending;
745
746 if (!_Py_atomic_load_relaxed_int32(&(pending->calls_to_do))) {
747 return;
748 }
749
750 if (make_pending_calls(tstate->interp) < 0) {
751 PyObject *exc, *val, *tb;
752 _PyErr_Fetch(tstate, &exc, &val, &tb);
753 PyErr_BadInternalCall();
754 _PyErr_ChainExceptions(exc, val, tb);
755 _PyErr_Print(tstate);
756 }
757 }
758
759 /* Py_MakePendingCalls() is a simple wrapper for the sake
760 of backward-compatibility. */
761 int
Py_MakePendingCalls(void)762 Py_MakePendingCalls(void)
763 {
764 assert(PyGILState_Check());
765
766 PyThreadState *tstate = _PyThreadState_GET();
767 assert(is_tstate_valid(tstate));
768
769 /* Python signal handler doesn't really queue a callback: it only signals
770 that a signal was received, see _PyEval_SignalReceived(). */
771 int res = handle_signals(tstate);
772 if (res != 0) {
773 return res;
774 }
775
776 res = make_pending_calls(tstate->interp);
777 if (res != 0) {
778 return res;
779 }
780
781 return 0;
782 }
783
784 /* The interpreter's recursion limit */
785
786 void
_PyEval_InitRuntimeState(struct _ceval_runtime_state * ceval)787 _PyEval_InitRuntimeState(struct _ceval_runtime_state *ceval)
788 {
789 _gil_initialize(&ceval->gil);
790 }
791
792 void
_PyEval_InitState(struct _ceval_state * ceval,PyThread_type_lock pending_lock)793 _PyEval_InitState(struct _ceval_state *ceval, PyThread_type_lock pending_lock)
794 {
795 struct _pending_calls *pending = &ceval->pending;
796 assert(pending->lock == NULL);
797
798 pending->lock = pending_lock;
799 }
800
801 void
_PyEval_FiniState(struct _ceval_state * ceval)802 _PyEval_FiniState(struct _ceval_state *ceval)
803 {
804 struct _pending_calls *pending = &ceval->pending;
805 if (pending->lock != NULL) {
806 PyThread_free_lock(pending->lock);
807 pending->lock = NULL;
808 }
809 }
810
811 int
Py_GetRecursionLimit(void)812 Py_GetRecursionLimit(void)
813 {
814 PyInterpreterState *interp = _PyInterpreterState_GET();
815 return interp->ceval.recursion_limit;
816 }
817
818 void
Py_SetRecursionLimit(int new_limit)819 Py_SetRecursionLimit(int new_limit)
820 {
821 PyInterpreterState *interp = _PyInterpreterState_GET();
822 interp->ceval.recursion_limit = new_limit;
823 for (PyThreadState *p = interp->threads.head; p != NULL; p = p->next) {
824 int depth = p->recursion_limit - p->recursion_remaining;
825 p->recursion_limit = new_limit;
826 p->recursion_remaining = new_limit - depth;
827 }
828 }
829
830 /* The function _Py_EnterRecursiveCallTstate() only calls _Py_CheckRecursiveCall()
831 if the recursion_depth reaches recursion_limit. */
832 int
_Py_CheckRecursiveCall(PyThreadState * tstate,const char * where)833 _Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
834 {
835 /* Check against global limit first. */
836 int depth = tstate->recursion_limit - tstate->recursion_remaining;
837 if (depth < tstate->interp->ceval.recursion_limit) {
838 tstate->recursion_limit = tstate->interp->ceval.recursion_limit;
839 tstate->recursion_remaining = tstate->recursion_limit - depth;
840 assert(tstate->recursion_remaining > 0);
841 return 0;
842 }
843 #ifdef USE_STACKCHECK
844 if (PyOS_CheckStack()) {
845 ++tstate->recursion_remaining;
846 _PyErr_SetString(tstate, PyExc_MemoryError, "Stack overflow");
847 return -1;
848 }
849 #endif
850 if (tstate->recursion_headroom) {
851 if (tstate->recursion_remaining < -50) {
852 /* Overflowing while handling an overflow. Give up. */
853 Py_FatalError("Cannot recover from stack overflow.");
854 }
855 }
856 else {
857 if (tstate->recursion_remaining <= 0) {
858 tstate->recursion_headroom++;
859 _PyErr_Format(tstate, PyExc_RecursionError,
860 "maximum recursion depth exceeded%s",
861 where);
862 tstate->recursion_headroom--;
863 ++tstate->recursion_remaining;
864 return -1;
865 }
866 }
867 return 0;
868 }
869
870
871 static const binaryfunc binary_ops[] = {
872 [NB_ADD] = PyNumber_Add,
873 [NB_AND] = PyNumber_And,
874 [NB_FLOOR_DIVIDE] = PyNumber_FloorDivide,
875 [NB_LSHIFT] = PyNumber_Lshift,
876 [NB_MATRIX_MULTIPLY] = PyNumber_MatrixMultiply,
877 [NB_MULTIPLY] = PyNumber_Multiply,
878 [NB_REMAINDER] = PyNumber_Remainder,
879 [NB_OR] = PyNumber_Or,
880 [NB_POWER] = _PyNumber_PowerNoMod,
881 [NB_RSHIFT] = PyNumber_Rshift,
882 [NB_SUBTRACT] = PyNumber_Subtract,
883 [NB_TRUE_DIVIDE] = PyNumber_TrueDivide,
884 [NB_XOR] = PyNumber_Xor,
885 [NB_INPLACE_ADD] = PyNumber_InPlaceAdd,
886 [NB_INPLACE_AND] = PyNumber_InPlaceAnd,
887 [NB_INPLACE_FLOOR_DIVIDE] = PyNumber_InPlaceFloorDivide,
888 [NB_INPLACE_LSHIFT] = PyNumber_InPlaceLshift,
889 [NB_INPLACE_MATRIX_MULTIPLY] = PyNumber_InPlaceMatrixMultiply,
890 [NB_INPLACE_MULTIPLY] = PyNumber_InPlaceMultiply,
891 [NB_INPLACE_REMAINDER] = PyNumber_InPlaceRemainder,
892 [NB_INPLACE_OR] = PyNumber_InPlaceOr,
893 [NB_INPLACE_POWER] = _PyNumber_InPlacePowerNoMod,
894 [NB_INPLACE_RSHIFT] = PyNumber_InPlaceRshift,
895 [NB_INPLACE_SUBTRACT] = PyNumber_InPlaceSubtract,
896 [NB_INPLACE_TRUE_DIVIDE] = PyNumber_InPlaceTrueDivide,
897 [NB_INPLACE_XOR] = PyNumber_InPlaceXor,
898 };
899
900
901 // PEP 634: Structural Pattern Matching
902
903
904 // Return a tuple of values corresponding to keys, with error checks for
905 // duplicate/missing keys.
906 static PyObject*
match_keys(PyThreadState * tstate,PyObject * map,PyObject * keys)907 match_keys(PyThreadState *tstate, PyObject *map, PyObject *keys)
908 {
909 assert(PyTuple_CheckExact(keys));
910 Py_ssize_t nkeys = PyTuple_GET_SIZE(keys);
911 if (!nkeys) {
912 // No keys means no items.
913 return PyTuple_New(0);
914 }
915 PyObject *seen = NULL;
916 PyObject *dummy = NULL;
917 PyObject *values = NULL;
918 PyObject *get = NULL;
919 // We use the two argument form of map.get(key, default) for two reasons:
920 // - Atomically check for a key and get its value without error handling.
921 // - Don't cause key creation or resizing in dict subclasses like
922 // collections.defaultdict that define __missing__ (or similar).
923 int meth_found = _PyObject_GetMethod(map, &_Py_ID(get), &get);
924 if (get == NULL) {
925 goto fail;
926 }
927 seen = PySet_New(NULL);
928 if (seen == NULL) {
929 goto fail;
930 }
931 // dummy = object()
932 dummy = _PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
933 if (dummy == NULL) {
934 goto fail;
935 }
936 values = PyTuple_New(nkeys);
937 if (values == NULL) {
938 goto fail;
939 }
940 for (Py_ssize_t i = 0; i < nkeys; i++) {
941 PyObject *key = PyTuple_GET_ITEM(keys, i);
942 if (PySet_Contains(seen, key) || PySet_Add(seen, key)) {
943 if (!_PyErr_Occurred(tstate)) {
944 // Seen it before!
945 _PyErr_Format(tstate, PyExc_ValueError,
946 "mapping pattern checks duplicate key (%R)", key);
947 }
948 goto fail;
949 }
950 PyObject *args[] = { map, key, dummy };
951 PyObject *value = NULL;
952 if (meth_found) {
953 value = PyObject_Vectorcall(get, args, 3, NULL);
954 }
955 else {
956 value = PyObject_Vectorcall(get, &args[1], 2, NULL);
957 }
958 if (value == NULL) {
959 goto fail;
960 }
961 if (value == dummy) {
962 // key not in map!
963 Py_DECREF(value);
964 Py_DECREF(values);
965 // Return None:
966 Py_INCREF(Py_None);
967 values = Py_None;
968 goto done;
969 }
970 PyTuple_SET_ITEM(values, i, value);
971 }
972 // Success:
973 done:
974 Py_DECREF(get);
975 Py_DECREF(seen);
976 Py_DECREF(dummy);
977 return values;
978 fail:
979 Py_XDECREF(get);
980 Py_XDECREF(seen);
981 Py_XDECREF(dummy);
982 Py_XDECREF(values);
983 return NULL;
984 }
985
986 // Extract a named attribute from the subject, with additional bookkeeping to
987 // raise TypeErrors for repeated lookups. On failure, return NULL (with no
988 // error set). Use _PyErr_Occurred(tstate) to disambiguate.
989 static PyObject*
match_class_attr(PyThreadState * tstate,PyObject * subject,PyObject * type,PyObject * name,PyObject * seen)990 match_class_attr(PyThreadState *tstate, PyObject *subject, PyObject *type,
991 PyObject *name, PyObject *seen)
992 {
993 assert(PyUnicode_CheckExact(name));
994 assert(PySet_CheckExact(seen));
995 if (PySet_Contains(seen, name) || PySet_Add(seen, name)) {
996 if (!_PyErr_Occurred(tstate)) {
997 // Seen it before!
998 _PyErr_Format(tstate, PyExc_TypeError,
999 "%s() got multiple sub-patterns for attribute %R",
1000 ((PyTypeObject*)type)->tp_name, name);
1001 }
1002 return NULL;
1003 }
1004 PyObject *attr = PyObject_GetAttr(subject, name);
1005 if (attr == NULL && _PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
1006 _PyErr_Clear(tstate);
1007 }
1008 return attr;
1009 }
1010
1011 // On success (match), return a tuple of extracted attributes. On failure (no
1012 // match), return NULL. Use _PyErr_Occurred(tstate) to disambiguate.
1013 static PyObject*
match_class(PyThreadState * tstate,PyObject * subject,PyObject * type,Py_ssize_t nargs,PyObject * kwargs)1014 match_class(PyThreadState *tstate, PyObject *subject, PyObject *type,
1015 Py_ssize_t nargs, PyObject *kwargs)
1016 {
1017 if (!PyType_Check(type)) {
1018 const char *e = "called match pattern must be a type";
1019 _PyErr_Format(tstate, PyExc_TypeError, e);
1020 return NULL;
1021 }
1022 assert(PyTuple_CheckExact(kwargs));
1023 // First, an isinstance check:
1024 if (PyObject_IsInstance(subject, type) <= 0) {
1025 return NULL;
1026 }
1027 // So far so good:
1028 PyObject *seen = PySet_New(NULL);
1029 if (seen == NULL) {
1030 return NULL;
1031 }
1032 PyObject *attrs = PyList_New(0);
1033 if (attrs == NULL) {
1034 Py_DECREF(seen);
1035 return NULL;
1036 }
1037 // NOTE: From this point on, goto fail on failure:
1038 PyObject *match_args = NULL;
1039 // First, the positional subpatterns:
1040 if (nargs) {
1041 int match_self = 0;
1042 match_args = PyObject_GetAttrString(type, "__match_args__");
1043 if (match_args) {
1044 if (!PyTuple_CheckExact(match_args)) {
1045 const char *e = "%s.__match_args__ must be a tuple (got %s)";
1046 _PyErr_Format(tstate, PyExc_TypeError, e,
1047 ((PyTypeObject *)type)->tp_name,
1048 Py_TYPE(match_args)->tp_name);
1049 goto fail;
1050 }
1051 }
1052 else if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
1053 _PyErr_Clear(tstate);
1054 // _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
1055 // define __match_args__. This is natural behavior for subclasses:
1056 // it's as if __match_args__ is some "magic" value that is lost as
1057 // soon as they redefine it.
1058 match_args = PyTuple_New(0);
1059 match_self = PyType_HasFeature((PyTypeObject*)type,
1060 _Py_TPFLAGS_MATCH_SELF);
1061 }
1062 else {
1063 goto fail;
1064 }
1065 assert(PyTuple_CheckExact(match_args));
1066 Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
1067 if (allowed < nargs) {
1068 const char *plural = (allowed == 1) ? "" : "s";
1069 _PyErr_Format(tstate, PyExc_TypeError,
1070 "%s() accepts %d positional sub-pattern%s (%d given)",
1071 ((PyTypeObject*)type)->tp_name,
1072 allowed, plural, nargs);
1073 goto fail;
1074 }
1075 if (match_self) {
1076 // Easy. Copy the subject itself, and move on to kwargs.
1077 PyList_Append(attrs, subject);
1078 }
1079 else {
1080 for (Py_ssize_t i = 0; i < nargs; i++) {
1081 PyObject *name = PyTuple_GET_ITEM(match_args, i);
1082 if (!PyUnicode_CheckExact(name)) {
1083 _PyErr_Format(tstate, PyExc_TypeError,
1084 "__match_args__ elements must be strings "
1085 "(got %s)", Py_TYPE(name)->tp_name);
1086 goto fail;
1087 }
1088 PyObject *attr = match_class_attr(tstate, subject, type, name,
1089 seen);
1090 if (attr == NULL) {
1091 goto fail;
1092 }
1093 PyList_Append(attrs, attr);
1094 Py_DECREF(attr);
1095 }
1096 }
1097 Py_CLEAR(match_args);
1098 }
1099 // Finally, the keyword subpatterns:
1100 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
1101 PyObject *name = PyTuple_GET_ITEM(kwargs, i);
1102 PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
1103 if (attr == NULL) {
1104 goto fail;
1105 }
1106 PyList_Append(attrs, attr);
1107 Py_DECREF(attr);
1108 }
1109 Py_SETREF(attrs, PyList_AsTuple(attrs));
1110 Py_DECREF(seen);
1111 return attrs;
1112 fail:
1113 // We really don't care whether an error was raised or not... that's our
1114 // caller's problem. All we know is that the match failed.
1115 Py_XDECREF(match_args);
1116 Py_DECREF(seen);
1117 Py_DECREF(attrs);
1118 return NULL;
1119 }
1120
1121
1122 static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
1123 static int exception_group_match(
1124 PyObject* exc_value, PyObject *match_type,
1125 PyObject **match, PyObject **rest);
1126
1127 static int unpack_iterable(PyThreadState *, PyObject *, int, int, PyObject **);
1128
1129 PyObject *
PyEval_EvalCode(PyObject * co,PyObject * globals,PyObject * locals)1130 PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
1131 {
1132 PyThreadState *tstate = _PyThreadState_GET();
1133 if (locals == NULL) {
1134 locals = globals;
1135 }
1136 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
1137 if (builtins == NULL) {
1138 return NULL;
1139 }
1140 PyFrameConstructor desc = {
1141 .fc_globals = globals,
1142 .fc_builtins = builtins,
1143 .fc_name = ((PyCodeObject *)co)->co_name,
1144 .fc_qualname = ((PyCodeObject *)co)->co_name,
1145 .fc_code = co,
1146 .fc_defaults = NULL,
1147 .fc_kwdefaults = NULL,
1148 .fc_closure = NULL
1149 };
1150 PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
1151 if (func == NULL) {
1152 return NULL;
1153 }
1154 PyObject *res = _PyEval_Vector(tstate, func, locals, NULL, 0, NULL);
1155 Py_DECREF(func);
1156 return res;
1157 }
1158
1159
1160 /* Interpreter main loop */
1161
1162 PyObject *
PyEval_EvalFrame(PyFrameObject * f)1163 PyEval_EvalFrame(PyFrameObject *f)
1164 {
1165 /* Function kept for backward compatibility */
1166 PyThreadState *tstate = _PyThreadState_GET();
1167 return _PyEval_EvalFrame(tstate, f->f_frame, 0);
1168 }
1169
1170 PyObject *
PyEval_EvalFrameEx(PyFrameObject * f,int throwflag)1171 PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
1172 {
1173 PyThreadState *tstate = _PyThreadState_GET();
1174 return _PyEval_EvalFrame(tstate, f->f_frame, throwflag);
1175 }
1176
1177
1178 /* Handle signals, pending calls, GIL drop request
1179 and asynchronous exception */
1180 static int
eval_frame_handle_pending(PyThreadState * tstate)1181 eval_frame_handle_pending(PyThreadState *tstate)
1182 {
1183 _PyRuntimeState * const runtime = &_PyRuntime;
1184 struct _ceval_runtime_state *ceval = &runtime->ceval;
1185
1186 /* Pending signals */
1187 if (_Py_atomic_load_relaxed_int32(&ceval->signals_pending)) {
1188 if (handle_signals(tstate) != 0) {
1189 return -1;
1190 }
1191 }
1192
1193 /* Pending calls */
1194 struct _ceval_state *ceval2 = &tstate->interp->ceval;
1195 if (_Py_atomic_load_relaxed_int32(&ceval2->pending.calls_to_do)) {
1196 if (make_pending_calls(tstate->interp) != 0) {
1197 return -1;
1198 }
1199 }
1200
1201 /* GIL drop request */
1202 if (_Py_atomic_load_relaxed_int32(&ceval2->gil_drop_request)) {
1203 /* Give another thread a chance */
1204 if (_PyThreadState_Swap(&runtime->gilstate, NULL) != tstate) {
1205 Py_FatalError("tstate mix-up");
1206 }
1207 drop_gil(ceval, ceval2, tstate);
1208
1209 /* Other threads may run now */
1210
1211 take_gil(tstate);
1212
1213 if (_PyThreadState_Swap(&runtime->gilstate, tstate) != NULL) {
1214 Py_FatalError("orphan tstate");
1215 }
1216 }
1217
1218 /* Check for asynchronous exception. */
1219 if (tstate->async_exc != NULL) {
1220 PyObject *exc = tstate->async_exc;
1221 tstate->async_exc = NULL;
1222 UNSIGNAL_ASYNC_EXC(tstate->interp);
1223 _PyErr_SetNone(tstate, exc);
1224 Py_DECREF(exc);
1225 return -1;
1226 }
1227
1228 #ifdef MS_WINDOWS
1229 // bpo-42296: On Windows, _PyEval_SignalReceived() can be called in a
1230 // different thread than the Python thread, in which case
1231 // _Py_ThreadCanHandleSignals() is wrong. Recompute eval_breaker in the
1232 // current Python thread with the correct _Py_ThreadCanHandleSignals()
1233 // value. It prevents to interrupt the eval loop at every instruction if
1234 // the current Python thread cannot handle signals (if
1235 // _Py_ThreadCanHandleSignals() is false).
1236 COMPUTE_EVAL_BREAKER(tstate->interp, ceval, ceval2);
1237 #endif
1238
1239 return 0;
1240 }
1241
1242
1243 /* Computed GOTOs, or
1244 the-optimization-commonly-but-improperly-known-as-"threaded code"
1245 using gcc's labels-as-values extension
1246 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
1247
1248 The traditional bytecode evaluation loop uses a "switch" statement, which
1249 decent compilers will optimize as a single indirect branch instruction
1250 combined with a lookup table of jump addresses. However, since the
1251 indirect jump instruction is shared by all opcodes, the CPU will have a
1252 hard time making the right prediction for where to jump next (actually,
1253 it will be always wrong except in the uncommon case of a sequence of
1254 several identical opcodes).
1255
1256 "Threaded code" in contrast, uses an explicit jump table and an explicit
1257 indirect jump instruction at the end of each opcode. Since the jump
1258 instruction is at a different address for each opcode, the CPU will make a
1259 separate prediction for each of these instructions, which is equivalent to
1260 predicting the second opcode of each opcode pair. These predictions have
1261 a much better chance to turn out valid, especially in small bytecode loops.
1262
1263 A mispredicted branch on a modern CPU flushes the whole pipeline and
1264 can cost several CPU cycles (depending on the pipeline depth),
1265 and potentially many more instructions (depending on the pipeline width).
1266 A correctly predicted branch, however, is nearly free.
1267
1268 At the time of this writing, the "threaded code" version is up to 15-20%
1269 faster than the normal "switch" version, depending on the compiler and the
1270 CPU architecture.
1271
1272 NOTE: care must be taken that the compiler doesn't try to "optimize" the
1273 indirect jumps by sharing them between all opcodes. Such optimizations
1274 can be disabled on gcc by using the -fno-gcse flag (or possibly
1275 -fno-crossjumping).
1276 */
1277
1278 /* Use macros rather than inline functions, to make it as clear as possible
1279 * to the C compiler that the tracing check is a simple test then branch.
1280 * We want to be sure that the compiler knows this before it generates
1281 * the CFG.
1282 */
1283
1284 #ifdef WITH_DTRACE
1285 #define OR_DTRACE_LINE | (PyDTrace_LINE_ENABLED() ? 255 : 0)
1286 #else
1287 #define OR_DTRACE_LINE
1288 #endif
1289
1290 #ifdef HAVE_COMPUTED_GOTOS
1291 #ifndef USE_COMPUTED_GOTOS
1292 #define USE_COMPUTED_GOTOS 1
1293 #endif
1294 #else
1295 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
1296 #error "Computed gotos are not supported on this compiler."
1297 #endif
1298 #undef USE_COMPUTED_GOTOS
1299 #define USE_COMPUTED_GOTOS 0
1300 #endif
1301
1302 #ifdef Py_STATS
1303 #define INSTRUCTION_START(op) \
1304 do { \
1305 frame->prev_instr = next_instr++; \
1306 OPCODE_EXE_INC(op); \
1307 _py_stats.opcode_stats[lastopcode].pair_count[op]++; \
1308 lastopcode = op; \
1309 } while (0)
1310 #else
1311 #define INSTRUCTION_START(op) (frame->prev_instr = next_instr++)
1312 #endif
1313
1314 #if USE_COMPUTED_GOTOS
1315 #define TARGET(op) TARGET_##op: INSTRUCTION_START(op);
1316 #define DISPATCH_GOTO() goto *opcode_targets[opcode]
1317 #else
1318 #define TARGET(op) case op: INSTRUCTION_START(op);
1319 #define DISPATCH_GOTO() goto dispatch_opcode
1320 #endif
1321
1322 /* PRE_DISPATCH_GOTO() does lltrace if enabled. Normally a no-op */
1323 #ifdef LLTRACE
1324 #define PRE_DISPATCH_GOTO() if (lltrace) { \
1325 lltrace_instruction(frame, stack_pointer, next_instr); }
1326 #else
1327 #define PRE_DISPATCH_GOTO() ((void)0)
1328 #endif
1329
1330
1331 /* Do interpreter dispatch accounting for tracing and instrumentation */
1332 #define DISPATCH() \
1333 { \
1334 NEXTOPARG(); \
1335 PRE_DISPATCH_GOTO(); \
1336 assert(cframe.use_tracing == 0 || cframe.use_tracing == 255); \
1337 opcode |= cframe.use_tracing OR_DTRACE_LINE; \
1338 DISPATCH_GOTO(); \
1339 }
1340
1341 #define DISPATCH_SAME_OPARG() \
1342 { \
1343 opcode = _Py_OPCODE(*next_instr); \
1344 PRE_DISPATCH_GOTO(); \
1345 opcode |= cframe.use_tracing OR_DTRACE_LINE; \
1346 DISPATCH_GOTO(); \
1347 }
1348
1349 #define CHECK_EVAL_BREAKER() \
1350 _Py_CHECK_EMSCRIPTEN_SIGNALS_PERIODICALLY(); \
1351 if (_Py_atomic_load_relaxed_int32(eval_breaker)) { \
1352 goto handle_eval_breaker; \
1353 }
1354
1355
1356 /* Tuple access macros */
1357
1358 #ifndef Py_DEBUG
1359 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
1360 #else
1361 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
1362 #endif
1363
1364 /* Code access macros */
1365
1366 /* The integer overflow is checked by an assertion below. */
1367 #define INSTR_OFFSET() ((int)(next_instr - first_instr))
1368 #define NEXTOPARG() do { \
1369 _Py_CODEUNIT word = *next_instr; \
1370 opcode = _Py_OPCODE(word); \
1371 oparg = _Py_OPARG(word); \
1372 } while (0)
1373 #define JUMPTO(x) (next_instr = first_instr + (x))
1374 #define JUMPBY(x) (next_instr += (x))
1375
1376 // Skip from a PRECALL over a CALL to the next instruction:
1377 #define SKIP_CALL() \
1378 JUMPBY(INLINE_CACHE_ENTRIES_PRECALL + 1 + INLINE_CACHE_ENTRIES_CALL)
1379
1380 /* Get opcode and oparg from original instructions, not quickened form. */
1381 #define TRACING_NEXTOPARG() do { \
1382 NEXTOPARG(); \
1383 opcode = _PyOpcode_Deopt[opcode]; \
1384 } while (0)
1385
1386 /* OpCode prediction macros
1387 Some opcodes tend to come in pairs thus making it possible to
1388 predict the second code when the first is run. For example,
1389 COMPARE_OP is often followed by POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE.
1390
1391 Verifying the prediction costs a single high-speed test of a register
1392 variable against a constant. If the pairing was good, then the
1393 processor's own internal branch predication has a high likelihood of
1394 success, resulting in a nearly zero-overhead transition to the
1395 next opcode. A successful prediction saves a trip through the eval-loop
1396 including its unpredictable switch-case branch. Combined with the
1397 processor's internal branch prediction, a successful PREDICT has the
1398 effect of making the two opcodes run as if they were a single new opcode
1399 with the bodies combined.
1400
1401 If collecting opcode statistics, your choices are to either keep the
1402 predictions turned-on and interpret the results as if some opcodes
1403 had been combined or turn-off predictions so that the opcode frequency
1404 counter updates for both opcodes.
1405
1406 Opcode prediction is disabled with threaded code, since the latter allows
1407 the CPU to record separate branch prediction information for each
1408 opcode.
1409
1410 */
1411
1412 #define PREDICT_ID(op) PRED_##op
1413
1414 #if USE_COMPUTED_GOTOS
1415 #define PREDICT(op) if (0) goto PREDICT_ID(op)
1416 #else
1417 #define PREDICT(op) \
1418 do { \
1419 _Py_CODEUNIT word = *next_instr; \
1420 opcode = _Py_OPCODE(word) | cframe.use_tracing OR_DTRACE_LINE; \
1421 if (opcode == op) { \
1422 oparg = _Py_OPARG(word); \
1423 INSTRUCTION_START(op); \
1424 goto PREDICT_ID(op); \
1425 } \
1426 } while(0)
1427 #endif
1428 #define PREDICTED(op) PREDICT_ID(op):
1429
1430
1431 /* Stack manipulation macros */
1432
1433 /* The stack can grow at most MAXINT deep, as co_nlocals and
1434 co_stacksize are ints. */
1435 #define STACK_LEVEL() ((int)(stack_pointer - _PyFrame_Stackbase(frame)))
1436 #define STACK_SIZE() (frame->f_code->co_stacksize)
1437 #define EMPTY() (STACK_LEVEL() == 0)
1438 #define TOP() (stack_pointer[-1])
1439 #define SECOND() (stack_pointer[-2])
1440 #define THIRD() (stack_pointer[-3])
1441 #define FOURTH() (stack_pointer[-4])
1442 #define PEEK(n) (stack_pointer[-(n)])
1443 #define SET_TOP(v) (stack_pointer[-1] = (v))
1444 #define SET_SECOND(v) (stack_pointer[-2] = (v))
1445 #define BASIC_STACKADJ(n) (stack_pointer += n)
1446 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
1447 #define BASIC_POP() (*--stack_pointer)
1448
1449 #ifdef Py_DEBUG
1450 #define PUSH(v) do { \
1451 BASIC_PUSH(v); \
1452 assert(STACK_LEVEL() <= STACK_SIZE()); \
1453 } while (0)
1454 #define POP() (assert(STACK_LEVEL() > 0), BASIC_POP())
1455 #define STACK_GROW(n) do { \
1456 assert(n >= 0); \
1457 BASIC_STACKADJ(n); \
1458 assert(STACK_LEVEL() <= STACK_SIZE()); \
1459 } while (0)
1460 #define STACK_SHRINK(n) do { \
1461 assert(n >= 0); \
1462 assert(STACK_LEVEL() >= n); \
1463 BASIC_STACKADJ(-(n)); \
1464 } while (0)
1465 #else
1466 #define PUSH(v) BASIC_PUSH(v)
1467 #define POP() BASIC_POP()
1468 #define STACK_GROW(n) BASIC_STACKADJ(n)
1469 #define STACK_SHRINK(n) BASIC_STACKADJ(-(n))
1470 #endif
1471
1472 /* Local variable macros */
1473
1474 #define GETLOCAL(i) (frame->localsplus[i])
1475
1476 /* The SETLOCAL() macro must not DECREF the local variable in-place and
1477 then store the new value; it must copy the old value to a temporary
1478 value, then store the new value, and then DECREF the temporary value.
1479 This is because it is possible that during the DECREF the frame is
1480 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1481 variable would be pointing to already-freed memory. */
1482 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
1483 GETLOCAL(i) = value; \
1484 Py_XDECREF(tmp); } while (0)
1485
1486 #define JUMP_TO_INSTRUCTION(op) goto PREDICT_ID(op)
1487
1488
1489 #define DEOPT_IF(cond, instname) if (cond) { goto miss; }
1490
1491
1492 #define GLOBALS() frame->f_globals
1493 #define BUILTINS() frame->f_builtins
1494 #define LOCALS() frame->f_locals
1495
1496 /* Shared opcode macros */
1497
1498 // shared by LOAD_ATTR_MODULE and LOAD_METHOD_MODULE
1499 #define LOAD_MODULE_ATTR_OR_METHOD(attr_or_method) \
1500 _PyAttrCache *cache = (_PyAttrCache *)next_instr; \
1501 DEOPT_IF(!PyModule_CheckExact(owner), LOAD_##attr_or_method); \
1502 PyDictObject *dict = (PyDictObject *)((PyModuleObject *)owner)->md_dict; \
1503 assert(dict != NULL); \
1504 DEOPT_IF(dict->ma_keys->dk_version != read_u32(cache->version), \
1505 LOAD_##attr_or_method); \
1506 assert(dict->ma_keys->dk_kind == DICT_KEYS_UNICODE); \
1507 assert(cache->index < dict->ma_keys->dk_nentries); \
1508 PyDictUnicodeEntry *ep = DK_UNICODE_ENTRIES(dict->ma_keys) + cache->index; \
1509 res = ep->me_value; \
1510 DEOPT_IF(res == NULL, LOAD_##attr_or_method); \
1511 STAT_INC(LOAD_##attr_or_method, hit); \
1512 Py_INCREF(res);
1513
1514 #define TRACE_FUNCTION_EXIT() \
1515 if (cframe.use_tracing) { \
1516 if (trace_function_exit(tstate, frame, retval)) { \
1517 Py_DECREF(retval); \
1518 goto exit_unwind; \
1519 } \
1520 }
1521
1522 #define DTRACE_FUNCTION_EXIT() \
1523 if (PyDTrace_FUNCTION_RETURN_ENABLED()) { \
1524 dtrace_function_return(frame); \
1525 }
1526
1527 #define TRACE_FUNCTION_UNWIND() \
1528 if (cframe.use_tracing) { \
1529 /* Since we are already unwinding, \
1530 * we don't care if this raises */ \
1531 trace_function_exit(tstate, frame, NULL); \
1532 }
1533
1534 #define TRACE_FUNCTION_ENTRY() \
1535 if (cframe.use_tracing) { \
1536 _PyFrame_SetStackPointer(frame, stack_pointer); \
1537 int err = trace_function_entry(tstate, frame); \
1538 stack_pointer = _PyFrame_GetStackPointer(frame); \
1539 frame->stacktop = -1; \
1540 if (err) { \
1541 goto error; \
1542 } \
1543 }
1544
1545 #define TRACE_FUNCTION_THROW_ENTRY() \
1546 if (cframe.use_tracing) { \
1547 assert(frame->stacktop >= 0); \
1548 if (trace_function_entry(tstate, frame)) { \
1549 goto exit_unwind; \
1550 } \
1551 }
1552
1553 #define DTRACE_FUNCTION_ENTRY() \
1554 if (PyDTrace_FUNCTION_ENTRY_ENABLED()) { \
1555 dtrace_function_entry(frame); \
1556 }
1557
1558 #define ADAPTIVE_COUNTER_IS_ZERO(cache) \
1559 (cache)->counter < (1<<ADAPTIVE_BACKOFF_BITS)
1560
1561 #define DECREMENT_ADAPTIVE_COUNTER(cache) \
1562 (cache)->counter -= (1<<ADAPTIVE_BACKOFF_BITS)
1563
1564 static int
trace_function_entry(PyThreadState * tstate,_PyInterpreterFrame * frame)1565 trace_function_entry(PyThreadState *tstate, _PyInterpreterFrame *frame)
1566 {
1567 if (tstate->c_tracefunc != NULL) {
1568 /* tstate->c_tracefunc, if defined, is a
1569 function that will be called on *every* entry
1570 to a code block. Its return value, if not
1571 None, is a function that will be called at
1572 the start of each executed line of code.
1573 (Actually, the function must return itself
1574 in order to continue tracing.) The trace
1575 functions are called with three arguments:
1576 a pointer to the current frame, a string
1577 indicating why the function is called, and
1578 an argument which depends on the situation.
1579 The global trace function is also called
1580 whenever an exception is detected. */
1581 if (call_trace_protected(tstate->c_tracefunc,
1582 tstate->c_traceobj,
1583 tstate, frame,
1584 PyTrace_CALL, Py_None)) {
1585 /* Trace function raised an error */
1586 return -1;
1587 }
1588 }
1589 if (tstate->c_profilefunc != NULL) {
1590 /* Similar for c_profilefunc, except it needn't
1591 return itself and isn't called for "line" events */
1592 if (call_trace_protected(tstate->c_profilefunc,
1593 tstate->c_profileobj,
1594 tstate, frame,
1595 PyTrace_CALL, Py_None)) {
1596 /* Profile function raised an error */
1597 return -1;
1598 }
1599 }
1600 return 0;
1601 }
1602
1603 static int
trace_function_exit(PyThreadState * tstate,_PyInterpreterFrame * frame,PyObject * retval)1604 trace_function_exit(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *retval)
1605 {
1606 if (tstate->c_tracefunc) {
1607 if (call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj,
1608 tstate, frame, PyTrace_RETURN, retval)) {
1609 return -1;
1610 }
1611 }
1612 if (tstate->c_profilefunc) {
1613 if (call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj,
1614 tstate, frame, PyTrace_RETURN, retval)) {
1615 return -1;
1616 }
1617 }
1618 return 0;
1619 }
1620
1621 /* It is only between the PRECALL instruction and the following CALL,
1622 * that this has any meaning.
1623 */
1624 typedef struct {
1625 PyObject *kwnames;
1626 } CallShape;
1627
1628 // GH-89279: Must be a macro to be sure it's inlined by MSVC.
1629 #define is_method(stack_pointer, args) (PEEK((args)+2) != NULL)
1630
1631 #define KWNAMES_LEN() \
1632 (call_shape.kwnames == NULL ? 0 : ((int)PyTuple_GET_SIZE(call_shape.kwnames)))
1633
1634 PyObject* _Py_HOT_FUNCTION
_PyEval_EvalFrameDefault(PyThreadState * tstate,_PyInterpreterFrame * frame,int throwflag)1635 _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
1636 {
1637 _Py_EnsureTstateNotNULL(tstate);
1638 CALL_STAT_INC(pyeval_calls);
1639
1640 #if USE_COMPUTED_GOTOS
1641 /* Import the static jump table */
1642 #include "opcode_targets.h"
1643 #endif
1644
1645 #ifdef Py_STATS
1646 int lastopcode = 0;
1647 #endif
1648 // opcode is an 8-bit value to improve the code generated by MSVC
1649 // for the big switch below (in combination with the EXTRA_CASES macro).
1650 uint8_t opcode; /* Current opcode */
1651 int oparg; /* Current opcode argument, if any */
1652 _Py_atomic_int * const eval_breaker = &tstate->interp->ceval.eval_breaker;
1653 #ifdef LLTRACE
1654 int lltrace = 0;
1655 #endif
1656
1657 _PyCFrame cframe;
1658 CallShape call_shape;
1659 call_shape.kwnames = NULL; // Borrowed reference. Reset by CALL instructions.
1660
1661 /* WARNING: Because the _PyCFrame lives on the C stack,
1662 * but can be accessed from a heap allocated object (tstate)
1663 * strict stack discipline must be maintained.
1664 */
1665 _PyCFrame *prev_cframe = tstate->cframe;
1666 cframe.use_tracing = prev_cframe->use_tracing;
1667 cframe.previous = prev_cframe;
1668 tstate->cframe = &cframe;
1669
1670 frame->is_entry = true;
1671 /* Push frame */
1672 frame->previous = prev_cframe->current_frame;
1673 cframe.current_frame = frame;
1674
1675 /* support for generator.throw() */
1676 if (throwflag) {
1677 if (_Py_EnterRecursiveCallTstate(tstate, "")) {
1678 tstate->recursion_remaining--;
1679 goto exit_unwind;
1680 }
1681 TRACE_FUNCTION_THROW_ENTRY();
1682 DTRACE_FUNCTION_ENTRY();
1683 goto resume_with_error;
1684 }
1685
1686 /* Local "register" variables.
1687 * These are cached values from the frame and code object. */
1688
1689 PyObject *names;
1690 PyObject *consts;
1691 _Py_CODEUNIT *first_instr;
1692 _Py_CODEUNIT *next_instr;
1693 PyObject **stack_pointer;
1694
1695 /* Sets the above local variables from the frame */
1696 #define SET_LOCALS_FROM_FRAME() \
1697 { \
1698 PyCodeObject *co = frame->f_code; \
1699 names = co->co_names; \
1700 consts = co->co_consts; \
1701 first_instr = _PyCode_CODE(co); \
1702 } \
1703 assert(_PyInterpreterFrame_LASTI(frame) >= -1); \
1704 /* Jump back to the last instruction executed... */ \
1705 next_instr = frame->prev_instr + 1; \
1706 stack_pointer = _PyFrame_GetStackPointer(frame); \
1707 /* Set stackdepth to -1. \
1708 Update when returning or calling trace function. \
1709 Having stackdepth <= 0 ensures that invalid \
1710 values are not visible to the cycle GC. \
1711 We choose -1 rather than 0 to assist debugging. \
1712 */ \
1713 frame->stacktop = -1;
1714
1715
1716 start_frame:
1717 if (_Py_EnterRecursiveCallTstate(tstate, "")) {
1718 tstate->recursion_remaining--;
1719 goto exit_unwind;
1720 }
1721
1722 resume_frame:
1723 SET_LOCALS_FROM_FRAME();
1724
1725 #ifdef LLTRACE
1726 {
1727 int r = PyDict_Contains(GLOBALS(), &_Py_ID(__lltrace__));
1728 if (r < 0) {
1729 goto exit_unwind;
1730 }
1731 lltrace = r;
1732 }
1733 if (lltrace) {
1734 lltrace_resume_frame(frame);
1735 }
1736 #endif
1737
1738 #ifdef Py_DEBUG
1739 /* _PyEval_EvalFrameDefault() must not be called with an exception set,
1740 because it can clear it (directly or indirectly) and so the
1741 caller loses its exception */
1742 assert(!_PyErr_Occurred(tstate));
1743 #endif
1744
1745 DISPATCH();
1746
1747 handle_eval_breaker:
1748
1749 /* Do periodic things, like check for signals and async I/0.
1750 * We need to do reasonably frequently, but not too frequently.
1751 * All loops should include a check of the eval breaker.
1752 * We also check on return from any builtin function.
1753 */
1754 if (eval_frame_handle_pending(tstate) != 0) {
1755 goto error;
1756 }
1757 DISPATCH();
1758
1759 {
1760 /* Start instructions */
1761 #if USE_COMPUTED_GOTOS
1762 {
1763 #else
1764 dispatch_opcode:
1765 switch (opcode) {
1766 #endif
1767
1768 /* BEWARE!
1769 It is essential that any operation that fails must goto error
1770 and that all operation that succeed call DISPATCH() ! */
1771
1772 TARGET(NOP) {
1773 DISPATCH();
1774 }
1775
1776 TARGET(RESUME) {
1777 _PyCode_Warmup(frame->f_code);
1778 JUMP_TO_INSTRUCTION(RESUME_QUICK);
1779 }
1780
1781 TARGET(RESUME_QUICK) {
1782 PREDICTED(RESUME_QUICK);
1783 assert(tstate->cframe == &cframe);
1784 assert(frame == cframe.current_frame);
1785 if (_Py_atomic_load_relaxed_int32(eval_breaker) && oparg < 2) {
1786 goto handle_eval_breaker;
1787 }
1788 DISPATCH();
1789 }
1790
1791 TARGET(LOAD_CLOSURE) {
1792 /* We keep LOAD_CLOSURE so that the bytecode stays more readable. */
1793 PyObject *value = GETLOCAL(oparg);
1794 if (value == NULL) {
1795 goto unbound_local_error;
1796 }
1797 Py_INCREF(value);
1798 PUSH(value);
1799 DISPATCH();
1800 }
1801
1802 TARGET(LOAD_FAST) {
1803 PyObject *value = GETLOCAL(oparg);
1804 if (value == NULL) {
1805 goto unbound_local_error;
1806 }
1807 Py_INCREF(value);
1808 PUSH(value);
1809 DISPATCH();
1810 }
1811
1812 TARGET(LOAD_CONST) {
1813 PREDICTED(LOAD_CONST);
1814 PyObject *value = GETITEM(consts, oparg);
1815 Py_INCREF(value);
1816 PUSH(value);
1817 DISPATCH();
1818 }
1819
1820 TARGET(STORE_FAST) {
1821 PREDICTED(STORE_FAST);
1822 PyObject *value = POP();
1823 SETLOCAL(oparg, value);
1824 DISPATCH();
1825 }
1826
1827 TARGET(LOAD_FAST__LOAD_FAST) {
1828 PyObject *value = GETLOCAL(oparg);
1829 if (value == NULL) {
1830 goto unbound_local_error;
1831 }
1832 NEXTOPARG();
1833 next_instr++;
1834 Py_INCREF(value);
1835 PUSH(value);
1836 value = GETLOCAL(oparg);
1837 if (value == NULL) {
1838 goto unbound_local_error;
1839 }
1840 Py_INCREF(value);
1841 PUSH(value);
1842 DISPATCH();
1843 }
1844
1845 TARGET(LOAD_FAST__LOAD_CONST) {
1846 PyObject *value = GETLOCAL(oparg);
1847 if (value == NULL) {
1848 goto unbound_local_error;
1849 }
1850 NEXTOPARG();
1851 next_instr++;
1852 Py_INCREF(value);
1853 PUSH(value);
1854 value = GETITEM(consts, oparg);
1855 Py_INCREF(value);
1856 PUSH(value);
1857 DISPATCH();
1858 }
1859
1860 TARGET(STORE_FAST__LOAD_FAST) {
1861 PyObject *value = POP();
1862 SETLOCAL(oparg, value);
1863 NEXTOPARG();
1864 next_instr++;
1865 value = GETLOCAL(oparg);
1866 if (value == NULL) {
1867 goto unbound_local_error;
1868 }
1869 Py_INCREF(value);
1870 PUSH(value);
1871 DISPATCH();
1872 }
1873
1874 TARGET(STORE_FAST__STORE_FAST) {
1875 PyObject *value = POP();
1876 SETLOCAL(oparg, value);
1877 NEXTOPARG();
1878 next_instr++;
1879 value = POP();
1880 SETLOCAL(oparg, value);
1881 DISPATCH();
1882 }
1883
1884 TARGET(LOAD_CONST__LOAD_FAST) {
1885 PyObject *value = GETITEM(consts, oparg);
1886 NEXTOPARG();
1887 next_instr++;
1888 Py_INCREF(value);
1889 PUSH(value);
1890 value = GETLOCAL(oparg);
1891 if (value == NULL) {
1892 goto unbound_local_error;
1893 }
1894 Py_INCREF(value);
1895 PUSH(value);
1896 DISPATCH();
1897 }
1898
1899 TARGET(POP_TOP) {
1900 PyObject *value = POP();
1901 Py_DECREF(value);
1902 DISPATCH();
1903 }
1904
1905 TARGET(PUSH_NULL) {
1906 /* Use BASIC_PUSH as NULL is not a valid object pointer */
1907 BASIC_PUSH(NULL);
1908 DISPATCH();
1909 }
1910
1911 TARGET(UNARY_POSITIVE) {
1912 PyObject *value = TOP();
1913 PyObject *res = PyNumber_Positive(value);
1914 Py_DECREF(value);
1915 SET_TOP(res);
1916 if (res == NULL)
1917 goto error;
1918 DISPATCH();
1919 }
1920
1921 TARGET(UNARY_NEGATIVE) {
1922 PyObject *value = TOP();
1923 PyObject *res = PyNumber_Negative(value);
1924 Py_DECREF(value);
1925 SET_TOP(res);
1926 if (res == NULL)
1927 goto error;
1928 DISPATCH();
1929 }
1930
1931 TARGET(UNARY_NOT) {
1932 PyObject *value = TOP();
1933 int err = PyObject_IsTrue(value);
1934 Py_DECREF(value);
1935 if (err == 0) {
1936 Py_INCREF(Py_True);
1937 SET_TOP(Py_True);
1938 DISPATCH();
1939 }
1940 else if (err > 0) {
1941 Py_INCREF(Py_False);
1942 SET_TOP(Py_False);
1943 DISPATCH();
1944 }
1945 STACK_SHRINK(1);
1946 goto error;
1947 }
1948
1949 TARGET(UNARY_INVERT) {
1950 PyObject *value = TOP();
1951 PyObject *res = PyNumber_Invert(value);
1952 Py_DECREF(value);
1953 SET_TOP(res);
1954 if (res == NULL)
1955 goto error;
1956 DISPATCH();
1957 }
1958
1959 TARGET(BINARY_OP_MULTIPLY_INT) {
1960 assert(cframe.use_tracing == 0);
1961 PyObject *left = SECOND();
1962 PyObject *right = TOP();
1963 DEOPT_IF(!PyLong_CheckExact(left), BINARY_OP);
1964 DEOPT_IF(!PyLong_CheckExact(right), BINARY_OP);
1965 STAT_INC(BINARY_OP, hit);
1966 PyObject *prod = _PyLong_Multiply((PyLongObject *)left, (PyLongObject *)right);
1967 SET_SECOND(prod);
1968 _Py_DECREF_SPECIALIZED(right, (destructor)PyObject_Free);
1969 _Py_DECREF_SPECIALIZED(left, (destructor)PyObject_Free);
1970 STACK_SHRINK(1);
1971 if (prod == NULL) {
1972 goto error;
1973 }
1974 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
1975 DISPATCH();
1976 }
1977
1978 TARGET(BINARY_OP_MULTIPLY_FLOAT) {
1979 assert(cframe.use_tracing == 0);
1980 PyObject *left = SECOND();
1981 PyObject *right = TOP();
1982 DEOPT_IF(!PyFloat_CheckExact(left), BINARY_OP);
1983 DEOPT_IF(!PyFloat_CheckExact(right), BINARY_OP);
1984 STAT_INC(BINARY_OP, hit);
1985 double dprod = ((PyFloatObject *)left)->ob_fval *
1986 ((PyFloatObject *)right)->ob_fval;
1987 PyObject *prod = PyFloat_FromDouble(dprod);
1988 SET_SECOND(prod);
1989 _Py_DECREF_SPECIALIZED(right, _PyFloat_ExactDealloc);
1990 _Py_DECREF_SPECIALIZED(left, _PyFloat_ExactDealloc);
1991 STACK_SHRINK(1);
1992 if (prod == NULL) {
1993 goto error;
1994 }
1995 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
1996 DISPATCH();
1997 }
1998
1999 TARGET(BINARY_OP_SUBTRACT_INT) {
2000 assert(cframe.use_tracing == 0);
2001 PyObject *left = SECOND();
2002 PyObject *right = TOP();
2003 DEOPT_IF(!PyLong_CheckExact(left), BINARY_OP);
2004 DEOPT_IF(!PyLong_CheckExact(right), BINARY_OP);
2005 STAT_INC(BINARY_OP, hit);
2006 PyObject *sub = _PyLong_Subtract((PyLongObject *)left, (PyLongObject *)right);
2007 SET_SECOND(sub);
2008 _Py_DECREF_SPECIALIZED(right, (destructor)PyObject_Free);
2009 _Py_DECREF_SPECIALIZED(left, (destructor)PyObject_Free);
2010 STACK_SHRINK(1);
2011 if (sub == NULL) {
2012 goto error;
2013 }
2014 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
2015 DISPATCH();
2016 }
2017
2018 TARGET(BINARY_OP_SUBTRACT_FLOAT) {
2019 assert(cframe.use_tracing == 0);
2020 PyObject *left = SECOND();
2021 PyObject *right = TOP();
2022 DEOPT_IF(!PyFloat_CheckExact(left), BINARY_OP);
2023 DEOPT_IF(!PyFloat_CheckExact(right), BINARY_OP);
2024 STAT_INC(BINARY_OP, hit);
2025 double dsub = ((PyFloatObject *)left)->ob_fval - ((PyFloatObject *)right)->ob_fval;
2026 PyObject *sub = PyFloat_FromDouble(dsub);
2027 SET_SECOND(sub);
2028 _Py_DECREF_SPECIALIZED(right, _PyFloat_ExactDealloc);
2029 _Py_DECREF_SPECIALIZED(left, _PyFloat_ExactDealloc);
2030 STACK_SHRINK(1);
2031 if (sub == NULL) {
2032 goto error;
2033 }
2034 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
2035 DISPATCH();
2036 }
2037
2038 TARGET(BINARY_OP_ADD_UNICODE) {
2039 assert(cframe.use_tracing == 0);
2040 PyObject *left = SECOND();
2041 PyObject *right = TOP();
2042 DEOPT_IF(!PyUnicode_CheckExact(left), BINARY_OP);
2043 DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP);
2044 STAT_INC(BINARY_OP, hit);
2045 PyObject *res = PyUnicode_Concat(left, right);
2046 STACK_SHRINK(1);
2047 SET_TOP(res);
2048 _Py_DECREF_SPECIALIZED(left, _PyUnicode_ExactDealloc);
2049 _Py_DECREF_SPECIALIZED(right, _PyUnicode_ExactDealloc);
2050 if (TOP() == NULL) {
2051 goto error;
2052 }
2053 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
2054 DISPATCH();
2055 }
2056
2057 TARGET(BINARY_OP_INPLACE_ADD_UNICODE) {
2058 assert(cframe.use_tracing == 0);
2059 PyObject *left = SECOND();
2060 PyObject *right = TOP();
2061 DEOPT_IF(!PyUnicode_CheckExact(left), BINARY_OP);
2062 DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP);
2063 _Py_CODEUNIT true_next = next_instr[INLINE_CACHE_ENTRIES_BINARY_OP];
2064 assert(_Py_OPCODE(true_next) == STORE_FAST ||
2065 _Py_OPCODE(true_next) == STORE_FAST__LOAD_FAST);
2066 PyObject **target_local = &GETLOCAL(_Py_OPARG(true_next));
2067 DEOPT_IF(*target_local != left, BINARY_OP);
2068 STAT_INC(BINARY_OP, hit);
2069 /* Handle `left = left + right` or `left += right` for str.
2070 *
2071 * When possible, extend `left` in place rather than
2072 * allocating a new PyUnicodeObject. This attempts to avoid
2073 * quadratic behavior when one neglects to use str.join().
2074 *
2075 * If `left` has only two references remaining (one from
2076 * the stack, one in the locals), DECREFing `left` leaves
2077 * only the locals reference, so PyUnicode_Append knows
2078 * that the string is safe to mutate.
2079 */
2080 assert(Py_REFCNT(left) >= 2);
2081 _Py_DECREF_NO_DEALLOC(left);
2082 STACK_SHRINK(2);
2083 PyUnicode_Append(target_local, right);
2084 _Py_DECREF_SPECIALIZED(right, _PyUnicode_ExactDealloc);
2085 if (*target_local == NULL) {
2086 goto error;
2087 }
2088 // The STORE_FAST is already done.
2089 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP + 1);
2090 DISPATCH();
2091 }
2092
2093 TARGET(BINARY_OP_ADD_FLOAT) {
2094 assert(cframe.use_tracing == 0);
2095 PyObject *left = SECOND();
2096 PyObject *right = TOP();
2097 DEOPT_IF(!PyFloat_CheckExact(left), BINARY_OP);
2098 DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP);
2099 STAT_INC(BINARY_OP, hit);
2100 double dsum = ((PyFloatObject *)left)->ob_fval +
2101 ((PyFloatObject *)right)->ob_fval;
2102 PyObject *sum = PyFloat_FromDouble(dsum);
2103 SET_SECOND(sum);
2104 _Py_DECREF_SPECIALIZED(right, _PyFloat_ExactDealloc);
2105 _Py_DECREF_SPECIALIZED(left, _PyFloat_ExactDealloc);
2106 STACK_SHRINK(1);
2107 if (sum == NULL) {
2108 goto error;
2109 }
2110 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
2111 DISPATCH();
2112 }
2113
2114 TARGET(BINARY_OP_ADD_INT) {
2115 assert(cframe.use_tracing == 0);
2116 PyObject *left = SECOND();
2117 PyObject *right = TOP();
2118 DEOPT_IF(!PyLong_CheckExact(left), BINARY_OP);
2119 DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP);
2120 STAT_INC(BINARY_OP, hit);
2121 PyObject *sum = _PyLong_Add((PyLongObject *)left, (PyLongObject *)right);
2122 SET_SECOND(sum);
2123 _Py_DECREF_SPECIALIZED(right, (destructor)PyObject_Free);
2124 _Py_DECREF_SPECIALIZED(left, (destructor)PyObject_Free);
2125 STACK_SHRINK(1);
2126 if (sum == NULL) {
2127 goto error;
2128 }
2129 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
2130 DISPATCH();
2131 }
2132
2133 TARGET(BINARY_SUBSCR) {
2134 PREDICTED(BINARY_SUBSCR);
2135 PyObject *sub = POP();
2136 PyObject *container = TOP();
2137 PyObject *res = PyObject_GetItem(container, sub);
2138 Py_DECREF(container);
2139 Py_DECREF(sub);
2140 SET_TOP(res);
2141 if (res == NULL)
2142 goto error;
2143 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_SUBSCR);
2144 DISPATCH();
2145 }
2146
2147 TARGET(BINARY_SUBSCR_ADAPTIVE) {
2148 _PyBinarySubscrCache *cache = (_PyBinarySubscrCache *)next_instr;
2149 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
2150 PyObject *sub = TOP();
2151 PyObject *container = SECOND();
2152 next_instr--;
2153 if (_Py_Specialize_BinarySubscr(container, sub, next_instr) < 0) {
2154 next_instr++;
2155 goto error;
2156 }
2157 DISPATCH_SAME_OPARG();
2158 }
2159 else {
2160 STAT_INC(BINARY_SUBSCR, deferred);
2161 DECREMENT_ADAPTIVE_COUNTER(cache);
2162 JUMP_TO_INSTRUCTION(BINARY_SUBSCR);
2163 }
2164 }
2165
2166 TARGET(BINARY_SUBSCR_LIST_INT) {
2167 assert(cframe.use_tracing == 0);
2168 PyObject *sub = TOP();
2169 PyObject *list = SECOND();
2170 DEOPT_IF(!PyLong_CheckExact(sub), BINARY_SUBSCR);
2171 DEOPT_IF(!PyList_CheckExact(list), BINARY_SUBSCR);
2172
2173 // Deopt unless 0 <= sub < PyList_Size(list)
2174 Py_ssize_t signed_magnitude = Py_SIZE(sub);
2175 DEOPT_IF(((size_t)signed_magnitude) > 1, BINARY_SUBSCR);
2176 assert(((PyLongObject *)_PyLong_GetZero())->ob_digit[0] == 0);
2177 Py_ssize_t index = ((PyLongObject*)sub)->ob_digit[0];
2178 DEOPT_IF(index >= PyList_GET_SIZE(list), BINARY_SUBSCR);
2179 STAT_INC(BINARY_SUBSCR, hit);
2180 PyObject *res = PyList_GET_ITEM(list, index);
2181 assert(res != NULL);
2182 Py_INCREF(res);
2183 STACK_SHRINK(1);
2184 _Py_DECREF_SPECIALIZED(sub, (destructor)PyObject_Free);
2185 SET_TOP(res);
2186 Py_DECREF(list);
2187 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_SUBSCR);
2188 DISPATCH();
2189 }
2190
2191 TARGET(BINARY_SUBSCR_TUPLE_INT) {
2192 assert(cframe.use_tracing == 0);
2193 PyObject *sub = TOP();
2194 PyObject *tuple = SECOND();
2195 DEOPT_IF(!PyLong_CheckExact(sub), BINARY_SUBSCR);
2196 DEOPT_IF(!PyTuple_CheckExact(tuple), BINARY_SUBSCR);
2197
2198 // Deopt unless 0 <= sub < PyTuple_Size(list)
2199 Py_ssize_t signed_magnitude = Py_SIZE(sub);
2200 DEOPT_IF(((size_t)signed_magnitude) > 1, BINARY_SUBSCR);
2201 assert(((PyLongObject *)_PyLong_GetZero())->ob_digit[0] == 0);
2202 Py_ssize_t index = ((PyLongObject*)sub)->ob_digit[0];
2203 DEOPT_IF(index >= PyTuple_GET_SIZE(tuple), BINARY_SUBSCR);
2204 STAT_INC(BINARY_SUBSCR, hit);
2205 PyObject *res = PyTuple_GET_ITEM(tuple, index);
2206 assert(res != NULL);
2207 Py_INCREF(res);
2208 STACK_SHRINK(1);
2209 _Py_DECREF_SPECIALIZED(sub, (destructor)PyObject_Free);
2210 SET_TOP(res);
2211 Py_DECREF(tuple);
2212 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_SUBSCR);
2213 DISPATCH();
2214 }
2215
2216 TARGET(BINARY_SUBSCR_DICT) {
2217 assert(cframe.use_tracing == 0);
2218 PyObject *dict = SECOND();
2219 DEOPT_IF(!PyDict_CheckExact(SECOND()), BINARY_SUBSCR);
2220 STAT_INC(BINARY_SUBSCR, hit);
2221 PyObject *sub = TOP();
2222 PyObject *res = PyDict_GetItemWithError(dict, sub);
2223 if (res == NULL) {
2224 goto binary_subscr_dict_error;
2225 }
2226 Py_INCREF(res);
2227 STACK_SHRINK(1);
2228 Py_DECREF(sub);
2229 SET_TOP(res);
2230 Py_DECREF(dict);
2231 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_SUBSCR);
2232 DISPATCH();
2233 }
2234
2235 TARGET(BINARY_SUBSCR_GETITEM) {
2236 DEOPT_IF(tstate->interp->eval_frame, BINARY_SUBSCR);
2237 PyObject *sub = TOP();
2238 PyObject *container = SECOND();
2239 _PyBinarySubscrCache *cache = (_PyBinarySubscrCache *)next_instr;
2240 uint32_t type_version = read_u32(cache->type_version);
2241 PyTypeObject *tp = Py_TYPE(container);
2242 DEOPT_IF(tp->tp_version_tag != type_version, BINARY_SUBSCR);
2243 assert(tp->tp_flags & Py_TPFLAGS_HEAPTYPE);
2244 PyObject *cached = ((PyHeapTypeObject *)tp)->_spec_cache.getitem;
2245 assert(PyFunction_Check(cached));
2246 PyFunctionObject *getitem = (PyFunctionObject *)cached;
2247 DEOPT_IF(getitem->func_version != cache->func_version, BINARY_SUBSCR);
2248 PyCodeObject *code = (PyCodeObject *)getitem->func_code;
2249 size_t size = code->co_nlocalsplus + code->co_stacksize + FRAME_SPECIALS_SIZE;
2250 assert(code->co_argcount == 2);
2251 _PyInterpreterFrame *new_frame = _PyThreadState_BumpFramePointer(tstate, size);
2252 if (new_frame == NULL) {
2253 goto error;
2254 }
2255 CALL_STAT_INC(frames_pushed);
2256 Py_INCREF(getitem);
2257 _PyFrame_InitializeSpecials(new_frame, getitem,
2258 NULL, code->co_nlocalsplus);
2259 STACK_SHRINK(2);
2260 new_frame->localsplus[0] = container;
2261 new_frame->localsplus[1] = sub;
2262 for (int i = 2; i < code->co_nlocalsplus; i++) {
2263 new_frame->localsplus[i] = NULL;
2264 }
2265 _PyFrame_SetStackPointer(frame, stack_pointer);
2266 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_SUBSCR);
2267 frame->prev_instr = next_instr - 1;
2268 new_frame->previous = frame;
2269 frame = cframe.current_frame = new_frame;
2270 CALL_STAT_INC(inlined_py_calls);
2271 goto start_frame;
2272 }
2273
2274 TARGET(LIST_APPEND) {
2275 PyObject *v = POP();
2276 PyObject *list = PEEK(oparg);
2277 if (_PyList_AppendTakeRef((PyListObject *)list, v) < 0)
2278 goto error;
2279 PREDICT(JUMP_BACKWARD_QUICK);
2280 DISPATCH();
2281 }
2282
2283 TARGET(SET_ADD) {
2284 PyObject *v = POP();
2285 PyObject *set = PEEK(oparg);
2286 int err;
2287 err = PySet_Add(set, v);
2288 Py_DECREF(v);
2289 if (err != 0)
2290 goto error;
2291 PREDICT(JUMP_BACKWARD_QUICK);
2292 DISPATCH();
2293 }
2294
2295 TARGET(STORE_SUBSCR) {
2296 PREDICTED(STORE_SUBSCR);
2297 PyObject *sub = TOP();
2298 PyObject *container = SECOND();
2299 PyObject *v = THIRD();
2300 int err;
2301 STACK_SHRINK(3);
2302 /* container[sub] = v */
2303 err = PyObject_SetItem(container, sub, v);
2304 Py_DECREF(v);
2305 Py_DECREF(container);
2306 Py_DECREF(sub);
2307 if (err != 0) {
2308 goto error;
2309 }
2310 JUMPBY(INLINE_CACHE_ENTRIES_STORE_SUBSCR);
2311 DISPATCH();
2312 }
2313
2314 TARGET(STORE_SUBSCR_ADAPTIVE) {
2315 _PyStoreSubscrCache *cache = (_PyStoreSubscrCache *)next_instr;
2316 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
2317 PyObject *sub = TOP();
2318 PyObject *container = SECOND();
2319 next_instr--;
2320 if (_Py_Specialize_StoreSubscr(container, sub, next_instr) < 0) {
2321 next_instr++;
2322 goto error;
2323 }
2324 DISPATCH_SAME_OPARG();
2325 }
2326 else {
2327 STAT_INC(STORE_SUBSCR, deferred);
2328 DECREMENT_ADAPTIVE_COUNTER(cache);
2329 JUMP_TO_INSTRUCTION(STORE_SUBSCR);
2330 }
2331 }
2332
2333 TARGET(STORE_SUBSCR_LIST_INT) {
2334 assert(cframe.use_tracing == 0);
2335 PyObject *sub = TOP();
2336 PyObject *list = SECOND();
2337 PyObject *value = THIRD();
2338 DEOPT_IF(!PyLong_CheckExact(sub), STORE_SUBSCR);
2339 DEOPT_IF(!PyList_CheckExact(list), STORE_SUBSCR);
2340
2341 // Ensure nonnegative, zero-or-one-digit ints.
2342 DEOPT_IF(((size_t)Py_SIZE(sub)) > 1, STORE_SUBSCR);
2343 Py_ssize_t index = ((PyLongObject*)sub)->ob_digit[0];
2344 // Ensure index < len(list)
2345 DEOPT_IF(index >= PyList_GET_SIZE(list), STORE_SUBSCR);
2346 STAT_INC(STORE_SUBSCR, hit);
2347
2348 PyObject *old_value = PyList_GET_ITEM(list, index);
2349 PyList_SET_ITEM(list, index, value);
2350 STACK_SHRINK(3);
2351 assert(old_value != NULL);
2352 Py_DECREF(old_value);
2353 _Py_DECREF_SPECIALIZED(sub, (destructor)PyObject_Free);
2354 Py_DECREF(list);
2355 JUMPBY(INLINE_CACHE_ENTRIES_STORE_SUBSCR);
2356 DISPATCH();
2357 }
2358
2359 TARGET(STORE_SUBSCR_DICT) {
2360 assert(cframe.use_tracing == 0);
2361 PyObject *sub = TOP();
2362 PyObject *dict = SECOND();
2363 PyObject *value = THIRD();
2364 DEOPT_IF(!PyDict_CheckExact(dict), STORE_SUBSCR);
2365 STACK_SHRINK(3);
2366 STAT_INC(STORE_SUBSCR, hit);
2367 int err = _PyDict_SetItem_Take2((PyDictObject *)dict, sub, value);
2368 Py_DECREF(dict);
2369 if (err != 0) {
2370 goto error;
2371 }
2372 JUMPBY(INLINE_CACHE_ENTRIES_STORE_SUBSCR);
2373 DISPATCH();
2374 }
2375
2376 TARGET(DELETE_SUBSCR) {
2377 PyObject *sub = TOP();
2378 PyObject *container = SECOND();
2379 int err;
2380 STACK_SHRINK(2);
2381 /* del container[sub] */
2382 err = PyObject_DelItem(container, sub);
2383 Py_DECREF(container);
2384 Py_DECREF(sub);
2385 if (err != 0)
2386 goto error;
2387 DISPATCH();
2388 }
2389
2390 TARGET(PRINT_EXPR) {
2391 PyObject *value = POP();
2392 PyObject *hook = _PySys_GetAttr(tstate, &_Py_ID(displayhook));
2393 PyObject *res;
2394 if (hook == NULL) {
2395 _PyErr_SetString(tstate, PyExc_RuntimeError,
2396 "lost sys.displayhook");
2397 Py_DECREF(value);
2398 goto error;
2399 }
2400 res = PyObject_CallOneArg(hook, value);
2401 Py_DECREF(value);
2402 if (res == NULL)
2403 goto error;
2404 Py_DECREF(res);
2405 DISPATCH();
2406 }
2407
2408 TARGET(RAISE_VARARGS) {
2409 PyObject *cause = NULL, *exc = NULL;
2410 switch (oparg) {
2411 case 2:
2412 cause = POP(); /* cause */
2413 /* fall through */
2414 case 1:
2415 exc = POP(); /* exc */
2416 /* fall through */
2417 case 0:
2418 if (do_raise(tstate, exc, cause)) {
2419 goto exception_unwind;
2420 }
2421 break;
2422 default:
2423 _PyErr_SetString(tstate, PyExc_SystemError,
2424 "bad RAISE_VARARGS oparg");
2425 break;
2426 }
2427 goto error;
2428 }
2429
2430 TARGET(RETURN_VALUE) {
2431 PyObject *retval = POP();
2432 assert(EMPTY());
2433 _PyFrame_SetStackPointer(frame, stack_pointer);
2434 TRACE_FUNCTION_EXIT();
2435 DTRACE_FUNCTION_EXIT();
2436 _Py_LeaveRecursiveCallTstate(tstate);
2437 if (!frame->is_entry) {
2438 // GH-99729: We need to unlink the frame *before* clearing it:
2439 _PyInterpreterFrame *dying = frame;
2440 frame = cframe.current_frame = dying->previous;
2441 _PyEvalFrameClearAndPop(tstate, dying);
2442 _PyFrame_StackPush(frame, retval);
2443 goto resume_frame;
2444 }
2445 /* Restore previous cframe and return. */
2446 tstate->cframe = cframe.previous;
2447 tstate->cframe->use_tracing = cframe.use_tracing;
2448 assert(tstate->cframe->current_frame == frame->previous);
2449 assert(!_PyErr_Occurred(tstate));
2450 return retval;
2451 }
2452
2453 TARGET(GET_AITER) {
2454 unaryfunc getter = NULL;
2455 PyObject *iter = NULL;
2456 PyObject *obj = TOP();
2457 PyTypeObject *type = Py_TYPE(obj);
2458
2459 if (type->tp_as_async != NULL) {
2460 getter = type->tp_as_async->am_aiter;
2461 }
2462
2463 if (getter != NULL) {
2464 iter = (*getter)(obj);
2465 Py_DECREF(obj);
2466 if (iter == NULL) {
2467 SET_TOP(NULL);
2468 goto error;
2469 }
2470 }
2471 else {
2472 SET_TOP(NULL);
2473 _PyErr_Format(tstate, PyExc_TypeError,
2474 "'async for' requires an object with "
2475 "__aiter__ method, got %.100s",
2476 type->tp_name);
2477 Py_DECREF(obj);
2478 goto error;
2479 }
2480
2481 if (Py_TYPE(iter)->tp_as_async == NULL ||
2482 Py_TYPE(iter)->tp_as_async->am_anext == NULL) {
2483
2484 SET_TOP(NULL);
2485 _PyErr_Format(tstate, PyExc_TypeError,
2486 "'async for' received an object from __aiter__ "
2487 "that does not implement __anext__: %.100s",
2488 Py_TYPE(iter)->tp_name);
2489 Py_DECREF(iter);
2490 goto error;
2491 }
2492
2493 SET_TOP(iter);
2494 DISPATCH();
2495 }
2496
2497 TARGET(GET_ANEXT) {
2498 unaryfunc getter = NULL;
2499 PyObject *next_iter = NULL;
2500 PyObject *awaitable = NULL;
2501 PyObject *aiter = TOP();
2502 PyTypeObject *type = Py_TYPE(aiter);
2503
2504 if (PyAsyncGen_CheckExact(aiter)) {
2505 awaitable = type->tp_as_async->am_anext(aiter);
2506 if (awaitable == NULL) {
2507 goto error;
2508 }
2509 } else {
2510 if (type->tp_as_async != NULL){
2511 getter = type->tp_as_async->am_anext;
2512 }
2513
2514 if (getter != NULL) {
2515 next_iter = (*getter)(aiter);
2516 if (next_iter == NULL) {
2517 goto error;
2518 }
2519 }
2520 else {
2521 _PyErr_Format(tstate, PyExc_TypeError,
2522 "'async for' requires an iterator with "
2523 "__anext__ method, got %.100s",
2524 type->tp_name);
2525 goto error;
2526 }
2527
2528 awaitable = _PyCoro_GetAwaitableIter(next_iter);
2529 if (awaitable == NULL) {
2530 _PyErr_FormatFromCause(
2531 PyExc_TypeError,
2532 "'async for' received an invalid object "
2533 "from __anext__: %.100s",
2534 Py_TYPE(next_iter)->tp_name);
2535
2536 Py_DECREF(next_iter);
2537 goto error;
2538 } else {
2539 Py_DECREF(next_iter);
2540 }
2541 }
2542
2543 PUSH(awaitable);
2544 PREDICT(LOAD_CONST);
2545 DISPATCH();
2546 }
2547
2548 TARGET(GET_AWAITABLE) {
2549 PREDICTED(GET_AWAITABLE);
2550 PyObject *iterable = TOP();
2551 PyObject *iter = _PyCoro_GetAwaitableIter(iterable);
2552
2553 if (iter == NULL) {
2554 format_awaitable_error(tstate, Py_TYPE(iterable), oparg);
2555 }
2556
2557 Py_DECREF(iterable);
2558
2559 if (iter != NULL && PyCoro_CheckExact(iter)) {
2560 PyObject *yf = _PyGen_yf((PyGenObject*)iter);
2561 if (yf != NULL) {
2562 /* `iter` is a coroutine object that is being
2563 awaited, `yf` is a pointer to the current awaitable
2564 being awaited on. */
2565 Py_DECREF(yf);
2566 Py_CLEAR(iter);
2567 _PyErr_SetString(tstate, PyExc_RuntimeError,
2568 "coroutine is being awaited already");
2569 /* The code below jumps to `error` if `iter` is NULL. */
2570 }
2571 }
2572
2573 SET_TOP(iter); /* Even if it's NULL */
2574
2575 if (iter == NULL) {
2576 goto error;
2577 }
2578
2579 PREDICT(LOAD_CONST);
2580 DISPATCH();
2581 }
2582
2583 TARGET(SEND) {
2584 assert(frame->is_entry);
2585 assert(STACK_LEVEL() >= 2);
2586 PyObject *v = POP();
2587 PyObject *receiver = TOP();
2588 PySendResult gen_status;
2589 PyObject *retval;
2590 if (tstate->c_tracefunc == NULL) {
2591 gen_status = PyIter_Send(receiver, v, &retval);
2592 } else {
2593 if (Py_IsNone(v) && PyIter_Check(receiver)) {
2594 retval = Py_TYPE(receiver)->tp_iternext(receiver);
2595 }
2596 else {
2597 retval = PyObject_CallMethodOneArg(receiver, &_Py_ID(send), v);
2598 }
2599 if (retval == NULL) {
2600 if (tstate->c_tracefunc != NULL
2601 && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
2602 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, frame);
2603 if (_PyGen_FetchStopIterationValue(&retval) == 0) {
2604 gen_status = PYGEN_RETURN;
2605 }
2606 else {
2607 gen_status = PYGEN_ERROR;
2608 }
2609 }
2610 else {
2611 gen_status = PYGEN_NEXT;
2612 }
2613 }
2614 Py_DECREF(v);
2615 if (gen_status == PYGEN_ERROR) {
2616 assert(retval == NULL);
2617 goto error;
2618 }
2619 if (gen_status == PYGEN_RETURN) {
2620 assert(retval != NULL);
2621 Py_DECREF(receiver);
2622 SET_TOP(retval);
2623 JUMPBY(oparg);
2624 DISPATCH();
2625 }
2626 assert(gen_status == PYGEN_NEXT);
2627 assert(retval != NULL);
2628 PUSH(retval);
2629 DISPATCH();
2630 }
2631
2632 TARGET(ASYNC_GEN_WRAP) {
2633 PyObject *v = TOP();
2634 assert(frame->f_code->co_flags & CO_ASYNC_GENERATOR);
2635 PyObject *w = _PyAsyncGenValueWrapperNew(v);
2636 if (w == NULL) {
2637 goto error;
2638 }
2639 SET_TOP(w);
2640 Py_DECREF(v);
2641 DISPATCH();
2642 }
2643
2644 TARGET(YIELD_VALUE) {
2645 assert(frame->is_entry);
2646 PyObject *retval = POP();
2647 _PyFrame_GetGenerator(frame)->gi_frame_state = FRAME_SUSPENDED;
2648 _PyFrame_SetStackPointer(frame, stack_pointer);
2649 TRACE_FUNCTION_EXIT();
2650 DTRACE_FUNCTION_EXIT();
2651 _Py_LeaveRecursiveCallTstate(tstate);
2652 /* Restore previous cframe and return. */
2653 tstate->cframe = cframe.previous;
2654 tstate->cframe->use_tracing = cframe.use_tracing;
2655 assert(tstate->cframe->current_frame == frame->previous);
2656 assert(!_PyErr_Occurred(tstate));
2657 return retval;
2658 }
2659
2660 TARGET(POP_EXCEPT) {
2661 _PyErr_StackItem *exc_info = tstate->exc_info;
2662 PyObject *value = exc_info->exc_value;
2663 exc_info->exc_value = POP();
2664 Py_XDECREF(value);
2665 DISPATCH();
2666 }
2667
2668 TARGET(RERAISE) {
2669 if (oparg) {
2670 PyObject *lasti = PEEK(oparg + 1);
2671 if (PyLong_Check(lasti)) {
2672 frame->prev_instr = first_instr + PyLong_AsLong(lasti);
2673 assert(!_PyErr_Occurred(tstate));
2674 }
2675 else {
2676 assert(PyLong_Check(lasti));
2677 _PyErr_SetString(tstate, PyExc_SystemError, "lasti is not an int");
2678 goto error;
2679 }
2680 }
2681 PyObject *val = POP();
2682 assert(val && PyExceptionInstance_Check(val));
2683 PyObject *exc = Py_NewRef(PyExceptionInstance_Class(val));
2684 PyObject *tb = PyException_GetTraceback(val);
2685 _PyErr_Restore(tstate, exc, val, tb);
2686 goto exception_unwind;
2687 }
2688
2689 TARGET(PREP_RERAISE_STAR) {
2690 PyObject *excs = POP();
2691 assert(PyList_Check(excs));
2692 PyObject *orig = POP();
2693
2694 PyObject *val = _PyExc_PrepReraiseStar(orig, excs);
2695 Py_DECREF(excs);
2696 Py_DECREF(orig);
2697
2698 if (val == NULL) {
2699 goto error;
2700 }
2701
2702 PUSH(val);
2703 DISPATCH();
2704 }
2705
2706 TARGET(END_ASYNC_FOR) {
2707 PyObject *val = POP();
2708 assert(val && PyExceptionInstance_Check(val));
2709 if (PyErr_GivenExceptionMatches(val, PyExc_StopAsyncIteration)) {
2710 Py_DECREF(val);
2711 Py_DECREF(POP());
2712 DISPATCH();
2713 }
2714 else {
2715 PyObject *exc = Py_NewRef(PyExceptionInstance_Class(val));
2716 PyObject *tb = PyException_GetTraceback(val);
2717 _PyErr_Restore(tstate, exc, val, tb);
2718 goto exception_unwind;
2719 }
2720 }
2721
2722 TARGET(LOAD_ASSERTION_ERROR) {
2723 PyObject *value = PyExc_AssertionError;
2724 Py_INCREF(value);
2725 PUSH(value);
2726 DISPATCH();
2727 }
2728
2729 TARGET(LOAD_BUILD_CLASS) {
2730 PyObject *bc;
2731 if (PyDict_CheckExact(BUILTINS())) {
2732 bc = _PyDict_GetItemWithError(BUILTINS(),
2733 &_Py_ID(__build_class__));
2734 if (bc == NULL) {
2735 if (!_PyErr_Occurred(tstate)) {
2736 _PyErr_SetString(tstate, PyExc_NameError,
2737 "__build_class__ not found");
2738 }
2739 goto error;
2740 }
2741 Py_INCREF(bc);
2742 }
2743 else {
2744 bc = PyObject_GetItem(BUILTINS(), &_Py_ID(__build_class__));
2745 if (bc == NULL) {
2746 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
2747 _PyErr_SetString(tstate, PyExc_NameError,
2748 "__build_class__ not found");
2749 goto error;
2750 }
2751 }
2752 PUSH(bc);
2753 DISPATCH();
2754 }
2755
2756 TARGET(STORE_NAME) {
2757 PyObject *name = GETITEM(names, oparg);
2758 PyObject *v = POP();
2759 PyObject *ns = LOCALS();
2760 int err;
2761 if (ns == NULL) {
2762 _PyErr_Format(tstate, PyExc_SystemError,
2763 "no locals found when storing %R", name);
2764 Py_DECREF(v);
2765 goto error;
2766 }
2767 if (PyDict_CheckExact(ns))
2768 err = PyDict_SetItem(ns, name, v);
2769 else
2770 err = PyObject_SetItem(ns, name, v);
2771 Py_DECREF(v);
2772 if (err != 0)
2773 goto error;
2774 DISPATCH();
2775 }
2776
2777 TARGET(DELETE_NAME) {
2778 PyObject *name = GETITEM(names, oparg);
2779 PyObject *ns = LOCALS();
2780 int err;
2781 if (ns == NULL) {
2782 _PyErr_Format(tstate, PyExc_SystemError,
2783 "no locals when deleting %R", name);
2784 goto error;
2785 }
2786 err = PyObject_DelItem(ns, name);
2787 if (err != 0) {
2788 format_exc_check_arg(tstate, PyExc_NameError,
2789 NAME_ERROR_MSG,
2790 name);
2791 goto error;
2792 }
2793 DISPATCH();
2794 }
2795
2796 TARGET(UNPACK_SEQUENCE) {
2797 PREDICTED(UNPACK_SEQUENCE);
2798 PyObject *seq = POP();
2799 PyObject **top = stack_pointer + oparg;
2800 if (!unpack_iterable(tstate, seq, oparg, -1, top)) {
2801 Py_DECREF(seq);
2802 goto error;
2803 }
2804 STACK_GROW(oparg);
2805 Py_DECREF(seq);
2806 JUMPBY(INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE);
2807 DISPATCH();
2808 }
2809
2810 TARGET(UNPACK_SEQUENCE_ADAPTIVE) {
2811 assert(cframe.use_tracing == 0);
2812 _PyUnpackSequenceCache *cache = (_PyUnpackSequenceCache *)next_instr;
2813 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
2814 PyObject *seq = TOP();
2815 next_instr--;
2816 _Py_Specialize_UnpackSequence(seq, next_instr, oparg);
2817 DISPATCH_SAME_OPARG();
2818 }
2819 else {
2820 STAT_INC(UNPACK_SEQUENCE, deferred);
2821 DECREMENT_ADAPTIVE_COUNTER(cache);
2822 JUMP_TO_INSTRUCTION(UNPACK_SEQUENCE);
2823 }
2824 }
2825
2826 TARGET(UNPACK_SEQUENCE_TWO_TUPLE) {
2827 PyObject *seq = TOP();
2828 DEOPT_IF(!PyTuple_CheckExact(seq), UNPACK_SEQUENCE);
2829 DEOPT_IF(PyTuple_GET_SIZE(seq) != 2, UNPACK_SEQUENCE);
2830 STAT_INC(UNPACK_SEQUENCE, hit);
2831 SET_TOP(Py_NewRef(PyTuple_GET_ITEM(seq, 1)));
2832 PUSH(Py_NewRef(PyTuple_GET_ITEM(seq, 0)));
2833 Py_DECREF(seq);
2834 JUMPBY(INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE);
2835 DISPATCH();
2836 }
2837
2838 TARGET(UNPACK_SEQUENCE_TUPLE) {
2839 PyObject *seq = TOP();
2840 DEOPT_IF(!PyTuple_CheckExact(seq), UNPACK_SEQUENCE);
2841 DEOPT_IF(PyTuple_GET_SIZE(seq) != oparg, UNPACK_SEQUENCE);
2842 STAT_INC(UNPACK_SEQUENCE, hit);
2843 STACK_SHRINK(1);
2844 PyObject **items = _PyTuple_ITEMS(seq);
2845 while (oparg--) {
2846 PUSH(Py_NewRef(items[oparg]));
2847 }
2848 Py_DECREF(seq);
2849 JUMPBY(INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE);
2850 DISPATCH();
2851 }
2852
2853 TARGET(UNPACK_SEQUENCE_LIST) {
2854 PyObject *seq = TOP();
2855 DEOPT_IF(!PyList_CheckExact(seq), UNPACK_SEQUENCE);
2856 DEOPT_IF(PyList_GET_SIZE(seq) != oparg, UNPACK_SEQUENCE);
2857 STAT_INC(UNPACK_SEQUENCE, hit);
2858 STACK_SHRINK(1);
2859 PyObject **items = _PyList_ITEMS(seq);
2860 while (oparg--) {
2861 PUSH(Py_NewRef(items[oparg]));
2862 }
2863 Py_DECREF(seq);
2864 JUMPBY(INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE);
2865 DISPATCH();
2866 }
2867
2868 TARGET(UNPACK_EX) {
2869 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
2870 PyObject *seq = POP();
2871 PyObject **top = stack_pointer + totalargs;
2872 if (!unpack_iterable(tstate, seq, oparg & 0xFF, oparg >> 8, top)) {
2873 Py_DECREF(seq);
2874 goto error;
2875 }
2876 STACK_GROW(totalargs);
2877 Py_DECREF(seq);
2878 DISPATCH();
2879 }
2880
2881 TARGET(STORE_ATTR) {
2882 PREDICTED(STORE_ATTR);
2883 PyObject *name = GETITEM(names, oparg);
2884 PyObject *owner = TOP();
2885 PyObject *v = SECOND();
2886 int err;
2887 STACK_SHRINK(2);
2888 err = PyObject_SetAttr(owner, name, v);
2889 Py_DECREF(v);
2890 Py_DECREF(owner);
2891 if (err != 0) {
2892 goto error;
2893 }
2894 JUMPBY(INLINE_CACHE_ENTRIES_STORE_ATTR);
2895 DISPATCH();
2896 }
2897
2898 TARGET(DELETE_ATTR) {
2899 PyObject *name = GETITEM(names, oparg);
2900 PyObject *owner = POP();
2901 int err;
2902 err = PyObject_SetAttr(owner, name, (PyObject *)NULL);
2903 Py_DECREF(owner);
2904 if (err != 0)
2905 goto error;
2906 DISPATCH();
2907 }
2908
2909 TARGET(STORE_GLOBAL) {
2910 PyObject *name = GETITEM(names, oparg);
2911 PyObject *v = POP();
2912 int err;
2913 err = PyDict_SetItem(GLOBALS(), name, v);
2914 Py_DECREF(v);
2915 if (err != 0)
2916 goto error;
2917 DISPATCH();
2918 }
2919
2920 TARGET(DELETE_GLOBAL) {
2921 PyObject *name = GETITEM(names, oparg);
2922 int err;
2923 err = PyDict_DelItem(GLOBALS(), name);
2924 if (err != 0) {
2925 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2926 format_exc_check_arg(tstate, PyExc_NameError,
2927 NAME_ERROR_MSG, name);
2928 }
2929 goto error;
2930 }
2931 DISPATCH();
2932 }
2933
2934 TARGET(LOAD_NAME) {
2935 PyObject *name = GETITEM(names, oparg);
2936 PyObject *locals = LOCALS();
2937 PyObject *v;
2938 if (locals == NULL) {
2939 _PyErr_Format(tstate, PyExc_SystemError,
2940 "no locals when loading %R", name);
2941 goto error;
2942 }
2943 if (PyDict_CheckExact(locals)) {
2944 v = PyDict_GetItemWithError(locals, name);
2945 if (v != NULL) {
2946 Py_INCREF(v);
2947 }
2948 else if (_PyErr_Occurred(tstate)) {
2949 goto error;
2950 }
2951 }
2952 else {
2953 v = PyObject_GetItem(locals, name);
2954 if (v == NULL) {
2955 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
2956 goto error;
2957 _PyErr_Clear(tstate);
2958 }
2959 }
2960 if (v == NULL) {
2961 v = PyDict_GetItemWithError(GLOBALS(), name);
2962 if (v != NULL) {
2963 Py_INCREF(v);
2964 }
2965 else if (_PyErr_Occurred(tstate)) {
2966 goto error;
2967 }
2968 else {
2969 if (PyDict_CheckExact(BUILTINS())) {
2970 v = PyDict_GetItemWithError(BUILTINS(), name);
2971 if (v == NULL) {
2972 if (!_PyErr_Occurred(tstate)) {
2973 format_exc_check_arg(
2974 tstate, PyExc_NameError,
2975 NAME_ERROR_MSG, name);
2976 }
2977 goto error;
2978 }
2979 Py_INCREF(v);
2980 }
2981 else {
2982 v = PyObject_GetItem(BUILTINS(), name);
2983 if (v == NULL) {
2984 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2985 format_exc_check_arg(
2986 tstate, PyExc_NameError,
2987 NAME_ERROR_MSG, name);
2988 }
2989 goto error;
2990 }
2991 }
2992 }
2993 }
2994 PUSH(v);
2995 DISPATCH();
2996 }
2997
2998 TARGET(LOAD_GLOBAL) {
2999 PREDICTED(LOAD_GLOBAL);
3000 int push_null = oparg & 1;
3001 PEEK(0) = NULL;
3002 PyObject *name = GETITEM(names, oparg>>1);
3003 PyObject *v;
3004 if (PyDict_CheckExact(GLOBALS())
3005 && PyDict_CheckExact(BUILTINS()))
3006 {
3007 v = _PyDict_LoadGlobal((PyDictObject *)GLOBALS(),
3008 (PyDictObject *)BUILTINS(),
3009 name);
3010 if (v == NULL) {
3011 if (!_PyErr_Occurred(tstate)) {
3012 /* _PyDict_LoadGlobal() returns NULL without raising
3013 * an exception if the key doesn't exist */
3014 format_exc_check_arg(tstate, PyExc_NameError,
3015 NAME_ERROR_MSG, name);
3016 }
3017 goto error;
3018 }
3019 Py_INCREF(v);
3020 }
3021 else {
3022 /* Slow-path if globals or builtins is not a dict */
3023
3024 /* namespace 1: globals */
3025 v = PyObject_GetItem(GLOBALS(), name);
3026 if (v == NULL) {
3027 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
3028 goto error;
3029 }
3030 _PyErr_Clear(tstate);
3031
3032 /* namespace 2: builtins */
3033 v = PyObject_GetItem(BUILTINS(), name);
3034 if (v == NULL) {
3035 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
3036 format_exc_check_arg(
3037 tstate, PyExc_NameError,
3038 NAME_ERROR_MSG, name);
3039 }
3040 goto error;
3041 }
3042 }
3043 }
3044 /* Skip over inline cache */
3045 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_GLOBAL);
3046 STACK_GROW(push_null);
3047 PUSH(v);
3048 DISPATCH();
3049 }
3050
3051 TARGET(LOAD_GLOBAL_ADAPTIVE) {
3052 assert(cframe.use_tracing == 0);
3053 _PyLoadGlobalCache *cache = (_PyLoadGlobalCache *)next_instr;
3054 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
3055 PyObject *name = GETITEM(names, oparg>>1);
3056 next_instr--;
3057 if (_Py_Specialize_LoadGlobal(GLOBALS(), BUILTINS(), next_instr, name) < 0) {
3058 next_instr++;
3059 goto error;
3060 }
3061 DISPATCH_SAME_OPARG();
3062 }
3063 else {
3064 STAT_INC(LOAD_GLOBAL, deferred);
3065 DECREMENT_ADAPTIVE_COUNTER(cache);
3066 JUMP_TO_INSTRUCTION(LOAD_GLOBAL);
3067 }
3068 }
3069
3070 TARGET(LOAD_GLOBAL_MODULE) {
3071 assert(cframe.use_tracing == 0);
3072 DEOPT_IF(!PyDict_CheckExact(GLOBALS()), LOAD_GLOBAL);
3073 PyDictObject *dict = (PyDictObject *)GLOBALS();
3074 _PyLoadGlobalCache *cache = (_PyLoadGlobalCache *)next_instr;
3075 uint32_t version = read_u32(cache->module_keys_version);
3076 DEOPT_IF(dict->ma_keys->dk_version != version, LOAD_GLOBAL);
3077 assert(DK_IS_UNICODE(dict->ma_keys));
3078 PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(dict->ma_keys);
3079 PyObject *res = entries[cache->index].me_value;
3080 DEOPT_IF(res == NULL, LOAD_GLOBAL);
3081 int push_null = oparg & 1;
3082 PEEK(0) = NULL;
3083 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_GLOBAL);
3084 STAT_INC(LOAD_GLOBAL, hit);
3085 STACK_GROW(push_null+1);
3086 Py_INCREF(res);
3087 SET_TOP(res);
3088 DISPATCH();
3089 }
3090
3091 TARGET(LOAD_GLOBAL_BUILTIN) {
3092 assert(cframe.use_tracing == 0);
3093 DEOPT_IF(!PyDict_CheckExact(GLOBALS()), LOAD_GLOBAL);
3094 DEOPT_IF(!PyDict_CheckExact(BUILTINS()), LOAD_GLOBAL);
3095 PyDictObject *mdict = (PyDictObject *)GLOBALS();
3096 PyDictObject *bdict = (PyDictObject *)BUILTINS();
3097 _PyLoadGlobalCache *cache = (_PyLoadGlobalCache *)next_instr;
3098 uint32_t mod_version = read_u32(cache->module_keys_version);
3099 uint16_t bltn_version = cache->builtin_keys_version;
3100 DEOPT_IF(mdict->ma_keys->dk_version != mod_version, LOAD_GLOBAL);
3101 DEOPT_IF(bdict->ma_keys->dk_version != bltn_version, LOAD_GLOBAL);
3102 assert(DK_IS_UNICODE(bdict->ma_keys));
3103 PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(bdict->ma_keys);
3104 PyObject *res = entries[cache->index].me_value;
3105 DEOPT_IF(res == NULL, LOAD_GLOBAL);
3106 int push_null = oparg & 1;
3107 PEEK(0) = NULL;
3108 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_GLOBAL);
3109 STAT_INC(LOAD_GLOBAL, hit);
3110 STACK_GROW(push_null+1);
3111 Py_INCREF(res);
3112 SET_TOP(res);
3113 DISPATCH();
3114 }
3115
3116 TARGET(DELETE_FAST) {
3117 PyObject *v = GETLOCAL(oparg);
3118 if (v != NULL) {
3119 SETLOCAL(oparg, NULL);
3120 DISPATCH();
3121 }
3122 goto unbound_local_error;
3123 }
3124
3125 TARGET(MAKE_CELL) {
3126 // "initial" is probably NULL but not if it's an arg (or set
3127 // via PyFrame_LocalsToFast() before MAKE_CELL has run).
3128 PyObject *initial = GETLOCAL(oparg);
3129 PyObject *cell = PyCell_New(initial);
3130 if (cell == NULL) {
3131 goto resume_with_error;
3132 }
3133 SETLOCAL(oparg, cell);
3134 DISPATCH();
3135 }
3136
3137 TARGET(DELETE_DEREF) {
3138 PyObject *cell = GETLOCAL(oparg);
3139 PyObject *oldobj = PyCell_GET(cell);
3140 if (oldobj != NULL) {
3141 PyCell_SET(cell, NULL);
3142 Py_DECREF(oldobj);
3143 DISPATCH();
3144 }
3145 format_exc_unbound(tstate, frame->f_code, oparg);
3146 goto error;
3147 }
3148
3149 TARGET(LOAD_CLASSDEREF) {
3150 PyObject *name, *value, *locals = LOCALS();
3151 assert(locals);
3152 assert(oparg >= 0 && oparg < frame->f_code->co_nlocalsplus);
3153 name = PyTuple_GET_ITEM(frame->f_code->co_localsplusnames, oparg);
3154 if (PyDict_CheckExact(locals)) {
3155 value = PyDict_GetItemWithError(locals, name);
3156 if (value != NULL) {
3157 Py_INCREF(value);
3158 }
3159 else if (_PyErr_Occurred(tstate)) {
3160 goto error;
3161 }
3162 }
3163 else {
3164 value = PyObject_GetItem(locals, name);
3165 if (value == NULL) {
3166 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
3167 goto error;
3168 }
3169 _PyErr_Clear(tstate);
3170 }
3171 }
3172 if (!value) {
3173 PyObject *cell = GETLOCAL(oparg);
3174 value = PyCell_GET(cell);
3175 if (value == NULL) {
3176 format_exc_unbound(tstate, frame->f_code, oparg);
3177 goto error;
3178 }
3179 Py_INCREF(value);
3180 }
3181 PUSH(value);
3182 DISPATCH();
3183 }
3184
3185 TARGET(LOAD_DEREF) {
3186 PyObject *cell = GETLOCAL(oparg);
3187 PyObject *value = PyCell_GET(cell);
3188 if (value == NULL) {
3189 format_exc_unbound(tstate, frame->f_code, oparg);
3190 goto error;
3191 }
3192 Py_INCREF(value);
3193 PUSH(value);
3194 DISPATCH();
3195 }
3196
3197 TARGET(STORE_DEREF) {
3198 PyObject *v = POP();
3199 PyObject *cell = GETLOCAL(oparg);
3200 PyObject *oldobj = PyCell_GET(cell);
3201 PyCell_SET(cell, v);
3202 Py_XDECREF(oldobj);
3203 DISPATCH();
3204 }
3205
3206 TARGET(COPY_FREE_VARS) {
3207 /* Copy closure variables to free variables */
3208 PyCodeObject *co = frame->f_code;
3209 PyObject *closure = frame->f_func->func_closure;
3210 int offset = co->co_nlocals + co->co_nplaincellvars;
3211 assert(oparg == co->co_nfreevars);
3212 for (int i = 0; i < oparg; ++i) {
3213 PyObject *o = PyTuple_GET_ITEM(closure, i);
3214 Py_INCREF(o);
3215 frame->localsplus[offset + i] = o;
3216 }
3217 DISPATCH();
3218 }
3219
3220 TARGET(BUILD_STRING) {
3221 PyObject *str;
3222 str = _PyUnicode_JoinArray(&_Py_STR(empty),
3223 stack_pointer - oparg, oparg);
3224 if (str == NULL)
3225 goto error;
3226 while (--oparg >= 0) {
3227 PyObject *item = POP();
3228 Py_DECREF(item);
3229 }
3230 PUSH(str);
3231 DISPATCH();
3232 }
3233
3234 TARGET(BUILD_TUPLE) {
3235 PyObject *tup = PyTuple_New(oparg);
3236 if (tup == NULL)
3237 goto error;
3238 while (--oparg >= 0) {
3239 PyObject *item = POP();
3240 PyTuple_SET_ITEM(tup, oparg, item);
3241 }
3242 PUSH(tup);
3243 DISPATCH();
3244 }
3245
3246 TARGET(BUILD_LIST) {
3247 PyObject *list = PyList_New(oparg);
3248 if (list == NULL)
3249 goto error;
3250 while (--oparg >= 0) {
3251 PyObject *item = POP();
3252 PyList_SET_ITEM(list, oparg, item);
3253 }
3254 PUSH(list);
3255 DISPATCH();
3256 }
3257
3258 TARGET(LIST_TO_TUPLE) {
3259 PyObject *list = POP();
3260 PyObject *tuple = PyList_AsTuple(list);
3261 Py_DECREF(list);
3262 if (tuple == NULL) {
3263 goto error;
3264 }
3265 PUSH(tuple);
3266 DISPATCH();
3267 }
3268
3269 TARGET(LIST_EXTEND) {
3270 PyObject *iterable = POP();
3271 PyObject *list = PEEK(oparg);
3272 PyObject *none_val = _PyList_Extend((PyListObject *)list, iterable);
3273 if (none_val == NULL) {
3274 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
3275 (Py_TYPE(iterable)->tp_iter == NULL && !PySequence_Check(iterable)))
3276 {
3277 _PyErr_Clear(tstate);
3278 _PyErr_Format(tstate, PyExc_TypeError,
3279 "Value after * must be an iterable, not %.200s",
3280 Py_TYPE(iterable)->tp_name);
3281 }
3282 Py_DECREF(iterable);
3283 goto error;
3284 }
3285 Py_DECREF(none_val);
3286 Py_DECREF(iterable);
3287 DISPATCH();
3288 }
3289
3290 TARGET(SET_UPDATE) {
3291 PyObject *iterable = POP();
3292 PyObject *set = PEEK(oparg);
3293 int err = _PySet_Update(set, iterable);
3294 Py_DECREF(iterable);
3295 if (err < 0) {
3296 goto error;
3297 }
3298 DISPATCH();
3299 }
3300
3301 TARGET(BUILD_SET) {
3302 PyObject *set = PySet_New(NULL);
3303 int err = 0;
3304 int i;
3305 if (set == NULL)
3306 goto error;
3307 for (i = oparg; i > 0; i--) {
3308 PyObject *item = PEEK(i);
3309 if (err == 0)
3310 err = PySet_Add(set, item);
3311 Py_DECREF(item);
3312 }
3313 STACK_SHRINK(oparg);
3314 if (err != 0) {
3315 Py_DECREF(set);
3316 goto error;
3317 }
3318 PUSH(set);
3319 DISPATCH();
3320 }
3321
3322 TARGET(BUILD_MAP) {
3323 PyObject *map = _PyDict_FromItems(
3324 &PEEK(2*oparg), 2,
3325 &PEEK(2*oparg - 1), 2,
3326 oparg);
3327 if (map == NULL)
3328 goto error;
3329
3330 while (oparg--) {
3331 Py_DECREF(POP());
3332 Py_DECREF(POP());
3333 }
3334 PUSH(map);
3335 DISPATCH();
3336 }
3337
3338 TARGET(SETUP_ANNOTATIONS) {
3339 int err;
3340 PyObject *ann_dict;
3341 if (LOCALS() == NULL) {
3342 _PyErr_Format(tstate, PyExc_SystemError,
3343 "no locals found when setting up annotations");
3344 goto error;
3345 }
3346 /* check if __annotations__ in locals()... */
3347 if (PyDict_CheckExact(LOCALS())) {
3348 ann_dict = _PyDict_GetItemWithError(LOCALS(),
3349 &_Py_ID(__annotations__));
3350 if (ann_dict == NULL) {
3351 if (_PyErr_Occurred(tstate)) {
3352 goto error;
3353 }
3354 /* ...if not, create a new one */
3355 ann_dict = PyDict_New();
3356 if (ann_dict == NULL) {
3357 goto error;
3358 }
3359 err = PyDict_SetItem(LOCALS(), &_Py_ID(__annotations__),
3360 ann_dict);
3361 Py_DECREF(ann_dict);
3362 if (err != 0) {
3363 goto error;
3364 }
3365 }
3366 }
3367 else {
3368 /* do the same if locals() is not a dict */
3369 ann_dict = PyObject_GetItem(LOCALS(), &_Py_ID(__annotations__));
3370 if (ann_dict == NULL) {
3371 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
3372 goto error;
3373 }
3374 _PyErr_Clear(tstate);
3375 ann_dict = PyDict_New();
3376 if (ann_dict == NULL) {
3377 goto error;
3378 }
3379 err = PyObject_SetItem(LOCALS(), &_Py_ID(__annotations__),
3380 ann_dict);
3381 Py_DECREF(ann_dict);
3382 if (err != 0) {
3383 goto error;
3384 }
3385 }
3386 else {
3387 Py_DECREF(ann_dict);
3388 }
3389 }
3390 DISPATCH();
3391 }
3392
3393 TARGET(BUILD_CONST_KEY_MAP) {
3394 PyObject *map;
3395 PyObject *keys = TOP();
3396 if (!PyTuple_CheckExact(keys) ||
3397 PyTuple_GET_SIZE(keys) != (Py_ssize_t)oparg) {
3398 _PyErr_SetString(tstate, PyExc_SystemError,
3399 "bad BUILD_CONST_KEY_MAP keys argument");
3400 goto error;
3401 }
3402 map = _PyDict_FromItems(
3403 &PyTuple_GET_ITEM(keys, 0), 1,
3404 &PEEK(oparg + 1), 1, oparg);
3405 if (map == NULL) {
3406 goto error;
3407 }
3408
3409 Py_DECREF(POP());
3410 while (oparg--) {
3411 Py_DECREF(POP());
3412 }
3413 PUSH(map);
3414 DISPATCH();
3415 }
3416
3417 TARGET(DICT_UPDATE) {
3418 PyObject *update = POP();
3419 PyObject *dict = PEEK(oparg);
3420 if (PyDict_Update(dict, update) < 0) {
3421 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
3422 _PyErr_Format(tstate, PyExc_TypeError,
3423 "'%.200s' object is not a mapping",
3424 Py_TYPE(update)->tp_name);
3425 }
3426 Py_DECREF(update);
3427 goto error;
3428 }
3429 Py_DECREF(update);
3430 DISPATCH();
3431 }
3432
3433 TARGET(DICT_MERGE) {
3434 PyObject *update = POP();
3435 PyObject *dict = PEEK(oparg);
3436
3437 if (_PyDict_MergeEx(dict, update, 2) < 0) {
3438 format_kwargs_error(tstate, PEEK(2 + oparg), update);
3439 Py_DECREF(update);
3440 goto error;
3441 }
3442 Py_DECREF(update);
3443 PREDICT(CALL_FUNCTION_EX);
3444 DISPATCH();
3445 }
3446
3447 TARGET(MAP_ADD) {
3448 PyObject *value = TOP();
3449 PyObject *key = SECOND();
3450 PyObject *map;
3451 STACK_SHRINK(2);
3452 map = PEEK(oparg); /* dict */
3453 assert(PyDict_CheckExact(map));
3454 /* map[key] = value */
3455 if (_PyDict_SetItem_Take2((PyDictObject *)map, key, value) != 0) {
3456 goto error;
3457 }
3458 PREDICT(JUMP_BACKWARD_QUICK);
3459 DISPATCH();
3460 }
3461
3462 TARGET(LOAD_ATTR) {
3463 PREDICTED(LOAD_ATTR);
3464 PyObject *name = GETITEM(names, oparg);
3465 PyObject *owner = TOP();
3466 PyObject *res = PyObject_GetAttr(owner, name);
3467 if (res == NULL) {
3468 goto error;
3469 }
3470 Py_DECREF(owner);
3471 SET_TOP(res);
3472 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_ATTR);
3473 DISPATCH();
3474 }
3475
3476 TARGET(LOAD_ATTR_ADAPTIVE) {
3477 assert(cframe.use_tracing == 0);
3478 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3479 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
3480 PyObject *owner = TOP();
3481 PyObject *name = GETITEM(names, oparg);
3482 next_instr--;
3483 if (_Py_Specialize_LoadAttr(owner, next_instr, name) < 0) {
3484 next_instr++;
3485 goto error;
3486 }
3487 DISPATCH_SAME_OPARG();
3488 }
3489 else {
3490 STAT_INC(LOAD_ATTR, deferred);
3491 DECREMENT_ADAPTIVE_COUNTER(cache);
3492 JUMP_TO_INSTRUCTION(LOAD_ATTR);
3493 }
3494 }
3495
3496 TARGET(LOAD_ATTR_INSTANCE_VALUE) {
3497 assert(cframe.use_tracing == 0);
3498 PyObject *owner = TOP();
3499 PyObject *res;
3500 PyTypeObject *tp = Py_TYPE(owner);
3501 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3502 uint32_t type_version = read_u32(cache->version);
3503 assert(type_version != 0);
3504 DEOPT_IF(tp->tp_version_tag != type_version, LOAD_ATTR);
3505 assert(tp->tp_dictoffset < 0);
3506 assert(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
3507 PyDictValues *values = *_PyObject_ValuesPointer(owner);
3508 DEOPT_IF(values == NULL, LOAD_ATTR);
3509 res = values->values[cache->index];
3510 DEOPT_IF(res == NULL, LOAD_ATTR);
3511 STAT_INC(LOAD_ATTR, hit);
3512 Py_INCREF(res);
3513 SET_TOP(res);
3514 Py_DECREF(owner);
3515 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_ATTR);
3516 DISPATCH();
3517 }
3518
3519 TARGET(LOAD_ATTR_MODULE) {
3520 assert(cframe.use_tracing == 0);
3521 // shared with LOAD_METHOD_MODULE
3522 PyObject *owner = TOP();
3523 PyObject *res;
3524 LOAD_MODULE_ATTR_OR_METHOD(ATTR);
3525 SET_TOP(res);
3526 Py_DECREF(owner);
3527 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_ATTR);
3528 DISPATCH();
3529 }
3530
3531 TARGET(LOAD_ATTR_WITH_HINT) {
3532 assert(cframe.use_tracing == 0);
3533 PyObject *owner = TOP();
3534 PyObject *res;
3535 PyTypeObject *tp = Py_TYPE(owner);
3536 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3537 uint32_t type_version = read_u32(cache->version);
3538 assert(type_version != 0);
3539 DEOPT_IF(tp->tp_version_tag != type_version, LOAD_ATTR);
3540 assert(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
3541 PyDictObject *dict = *(PyDictObject **)_PyObject_ManagedDictPointer(owner);
3542 DEOPT_IF(dict == NULL, LOAD_ATTR);
3543 assert(PyDict_CheckExact((PyObject *)dict));
3544 PyObject *name = GETITEM(names, oparg);
3545 uint16_t hint = cache->index;
3546 DEOPT_IF(hint >= (size_t)dict->ma_keys->dk_nentries, LOAD_ATTR);
3547 if (DK_IS_UNICODE(dict->ma_keys)) {
3548 PyDictUnicodeEntry *ep = DK_UNICODE_ENTRIES(dict->ma_keys) + hint;
3549 DEOPT_IF(ep->me_key != name, LOAD_ATTR);
3550 res = ep->me_value;
3551 }
3552 else {
3553 PyDictKeyEntry *ep = DK_ENTRIES(dict->ma_keys) + hint;
3554 DEOPT_IF(ep->me_key != name, LOAD_ATTR);
3555 res = ep->me_value;
3556 }
3557 DEOPT_IF(res == NULL, LOAD_ATTR);
3558 STAT_INC(LOAD_ATTR, hit);
3559 Py_INCREF(res);
3560 SET_TOP(res);
3561 Py_DECREF(owner);
3562 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_ATTR);
3563 DISPATCH();
3564 }
3565
3566 TARGET(LOAD_ATTR_SLOT) {
3567 assert(cframe.use_tracing == 0);
3568 PyObject *owner = TOP();
3569 PyObject *res;
3570 PyTypeObject *tp = Py_TYPE(owner);
3571 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3572 uint32_t type_version = read_u32(cache->version);
3573 assert(type_version != 0);
3574 DEOPT_IF(tp->tp_version_tag != type_version, LOAD_ATTR);
3575 char *addr = (char *)owner + cache->index;
3576 res = *(PyObject **)addr;
3577 DEOPT_IF(res == NULL, LOAD_ATTR);
3578 STAT_INC(LOAD_ATTR, hit);
3579 Py_INCREF(res);
3580 SET_TOP(res);
3581 Py_DECREF(owner);
3582 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_ATTR);
3583 DISPATCH();
3584 }
3585
3586 TARGET(STORE_ATTR_ADAPTIVE) {
3587 assert(cframe.use_tracing == 0);
3588 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3589 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
3590 PyObject *owner = TOP();
3591 PyObject *name = GETITEM(names, oparg);
3592 next_instr--;
3593 if (_Py_Specialize_StoreAttr(owner, next_instr, name) < 0) {
3594 next_instr++;
3595 goto error;
3596 }
3597 DISPATCH_SAME_OPARG();
3598 }
3599 else {
3600 STAT_INC(STORE_ATTR, deferred);
3601 DECREMENT_ADAPTIVE_COUNTER(cache);
3602 JUMP_TO_INSTRUCTION(STORE_ATTR);
3603 }
3604 }
3605
3606 TARGET(STORE_ATTR_INSTANCE_VALUE) {
3607 assert(cframe.use_tracing == 0);
3608 PyObject *owner = TOP();
3609 PyTypeObject *tp = Py_TYPE(owner);
3610 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3611 uint32_t type_version = read_u32(cache->version);
3612 assert(type_version != 0);
3613 DEOPT_IF(tp->tp_version_tag != type_version, STORE_ATTR);
3614 assert(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
3615 PyDictValues *values = *_PyObject_ValuesPointer(owner);
3616 DEOPT_IF(values == NULL, STORE_ATTR);
3617 STAT_INC(STORE_ATTR, hit);
3618 Py_ssize_t index = cache->index;
3619 STACK_SHRINK(1);
3620 PyObject *value = POP();
3621 PyObject *old_value = values->values[index];
3622 values->values[index] = value;
3623 if (old_value == NULL) {
3624 _PyDictValues_AddToInsertionOrder(values, index);
3625 }
3626 else {
3627 Py_DECREF(old_value);
3628 }
3629 Py_DECREF(owner);
3630 JUMPBY(INLINE_CACHE_ENTRIES_STORE_ATTR);
3631 DISPATCH();
3632 }
3633
3634 TARGET(STORE_ATTR_WITH_HINT) {
3635 assert(cframe.use_tracing == 0);
3636 PyObject *owner = TOP();
3637 PyTypeObject *tp = Py_TYPE(owner);
3638 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3639 uint32_t type_version = read_u32(cache->version);
3640 assert(type_version != 0);
3641 DEOPT_IF(tp->tp_version_tag != type_version, STORE_ATTR);
3642 assert(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
3643 PyDictObject *dict = *(PyDictObject **)_PyObject_ManagedDictPointer(owner);
3644 DEOPT_IF(dict == NULL, STORE_ATTR);
3645 assert(PyDict_CheckExact((PyObject *)dict));
3646 PyObject *name = GETITEM(names, oparg);
3647 uint16_t hint = cache->index;
3648 DEOPT_IF(hint >= (size_t)dict->ma_keys->dk_nentries, STORE_ATTR);
3649 PyObject *value, *old_value;
3650 if (DK_IS_UNICODE(dict->ma_keys)) {
3651 PyDictUnicodeEntry *ep = DK_UNICODE_ENTRIES(dict->ma_keys) + hint;
3652 DEOPT_IF(ep->me_key != name, STORE_ATTR);
3653 old_value = ep->me_value;
3654 DEOPT_IF(old_value == NULL, STORE_ATTR);
3655 STACK_SHRINK(1);
3656 value = POP();
3657 ep->me_value = value;
3658 }
3659 else {
3660 PyDictKeyEntry *ep = DK_ENTRIES(dict->ma_keys) + hint;
3661 DEOPT_IF(ep->me_key != name, STORE_ATTR);
3662 old_value = ep->me_value;
3663 DEOPT_IF(old_value == NULL, STORE_ATTR);
3664 STACK_SHRINK(1);
3665 value = POP();
3666 ep->me_value = value;
3667 }
3668 Py_DECREF(old_value);
3669 STAT_INC(STORE_ATTR, hit);
3670 /* Ensure dict is GC tracked if it needs to be */
3671 if (!_PyObject_GC_IS_TRACKED(dict) && _PyObject_GC_MAY_BE_TRACKED(value)) {
3672 _PyObject_GC_TRACK(dict);
3673 }
3674 /* PEP 509 */
3675 dict->ma_version_tag = DICT_NEXT_VERSION();
3676 Py_DECREF(owner);
3677 JUMPBY(INLINE_CACHE_ENTRIES_STORE_ATTR);
3678 DISPATCH();
3679 }
3680
3681 TARGET(STORE_ATTR_SLOT) {
3682 assert(cframe.use_tracing == 0);
3683 PyObject *owner = TOP();
3684 PyTypeObject *tp = Py_TYPE(owner);
3685 _PyAttrCache *cache = (_PyAttrCache *)next_instr;
3686 uint32_t type_version = read_u32(cache->version);
3687 assert(type_version != 0);
3688 DEOPT_IF(tp->tp_version_tag != type_version, STORE_ATTR);
3689 char *addr = (char *)owner + cache->index;
3690 STAT_INC(STORE_ATTR, hit);
3691 STACK_SHRINK(1);
3692 PyObject *value = POP();
3693 PyObject *old_value = *(PyObject **)addr;
3694 *(PyObject **)addr = value;
3695 Py_XDECREF(old_value);
3696 Py_DECREF(owner);
3697 JUMPBY(INLINE_CACHE_ENTRIES_STORE_ATTR);
3698 DISPATCH();
3699 }
3700
3701 TARGET(COMPARE_OP) {
3702 PREDICTED(COMPARE_OP);
3703 assert(oparg <= Py_GE);
3704 PyObject *right = POP();
3705 PyObject *left = TOP();
3706 PyObject *res = PyObject_RichCompare(left, right, oparg);
3707 SET_TOP(res);
3708 Py_DECREF(left);
3709 Py_DECREF(right);
3710 if (res == NULL) {
3711 goto error;
3712 }
3713 JUMPBY(INLINE_CACHE_ENTRIES_COMPARE_OP);
3714 DISPATCH();
3715 }
3716
3717 TARGET(COMPARE_OP_ADAPTIVE) {
3718 assert(cframe.use_tracing == 0);
3719 _PyCompareOpCache *cache = (_PyCompareOpCache *)next_instr;
3720 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
3721 PyObject *right = TOP();
3722 PyObject *left = SECOND();
3723 next_instr--;
3724 _Py_Specialize_CompareOp(left, right, next_instr, oparg);
3725 DISPATCH_SAME_OPARG();
3726 }
3727 else {
3728 STAT_INC(COMPARE_OP, deferred);
3729 DECREMENT_ADAPTIVE_COUNTER(cache);
3730 JUMP_TO_INSTRUCTION(COMPARE_OP);
3731 }
3732 }
3733
3734 TARGET(COMPARE_OP_FLOAT_JUMP) {
3735 assert(cframe.use_tracing == 0);
3736 // Combined: COMPARE_OP (float ? float) + POP_JUMP_(direction)_IF_(true/false)
3737 _PyCompareOpCache *cache = (_PyCompareOpCache *)next_instr;
3738 int when_to_jump_mask = cache->mask;
3739 PyObject *right = TOP();
3740 PyObject *left = SECOND();
3741 DEOPT_IF(!PyFloat_CheckExact(left), COMPARE_OP);
3742 DEOPT_IF(!PyFloat_CheckExact(right), COMPARE_OP);
3743 double dleft = PyFloat_AS_DOUBLE(left);
3744 double dright = PyFloat_AS_DOUBLE(right);
3745 int sign = (dleft > dright) - (dleft < dright);
3746 DEOPT_IF(isnan(dleft), COMPARE_OP);
3747 DEOPT_IF(isnan(dright), COMPARE_OP);
3748 STAT_INC(COMPARE_OP, hit);
3749 JUMPBY(INLINE_CACHE_ENTRIES_COMPARE_OP);
3750 NEXTOPARG();
3751 STACK_SHRINK(2);
3752 _Py_DECREF_SPECIALIZED(left, _PyFloat_ExactDealloc);
3753 _Py_DECREF_SPECIALIZED(right, _PyFloat_ExactDealloc);
3754 assert(opcode == POP_JUMP_FORWARD_IF_FALSE ||
3755 opcode == POP_JUMP_BACKWARD_IF_FALSE ||
3756 opcode == POP_JUMP_FORWARD_IF_TRUE ||
3757 opcode == POP_JUMP_BACKWARD_IF_TRUE);
3758 int jump = (9 << (sign + 1)) & when_to_jump_mask;
3759 if (!jump) {
3760 next_instr++;
3761 }
3762 else if (jump >= 8) {
3763 assert(opcode == POP_JUMP_BACKWARD_IF_TRUE ||
3764 opcode == POP_JUMP_BACKWARD_IF_FALSE);
3765 JUMPBY(1 - oparg);
3766 CHECK_EVAL_BREAKER();
3767 }
3768 else {
3769 assert(opcode == POP_JUMP_FORWARD_IF_TRUE ||
3770 opcode == POP_JUMP_FORWARD_IF_FALSE);
3771 JUMPBY(1 + oparg);
3772 }
3773 DISPATCH();
3774 }
3775
3776 TARGET(COMPARE_OP_INT_JUMP) {
3777 assert(cframe.use_tracing == 0);
3778 // Combined: COMPARE_OP (int ? int) + POP_JUMP_(direction)_IF_(true/false)
3779 _PyCompareOpCache *cache = (_PyCompareOpCache *)next_instr;
3780 int when_to_jump_mask = cache->mask;
3781 PyObject *right = TOP();
3782 PyObject *left = SECOND();
3783 DEOPT_IF(!PyLong_CheckExact(left), COMPARE_OP);
3784 DEOPT_IF(!PyLong_CheckExact(right), COMPARE_OP);
3785 DEOPT_IF((size_t)(Py_SIZE(left) + 1) > 2, COMPARE_OP);
3786 DEOPT_IF((size_t)(Py_SIZE(right) + 1) > 2, COMPARE_OP);
3787 STAT_INC(COMPARE_OP, hit);
3788 assert(Py_ABS(Py_SIZE(left)) <= 1 && Py_ABS(Py_SIZE(right)) <= 1);
3789 Py_ssize_t ileft = Py_SIZE(left) * ((PyLongObject *)left)->ob_digit[0];
3790 Py_ssize_t iright = Py_SIZE(right) * ((PyLongObject *)right)->ob_digit[0];
3791 int sign = (ileft > iright) - (ileft < iright);
3792 JUMPBY(INLINE_CACHE_ENTRIES_COMPARE_OP);
3793 NEXTOPARG();
3794 STACK_SHRINK(2);
3795 _Py_DECREF_SPECIALIZED(left, (destructor)PyObject_Free);
3796 _Py_DECREF_SPECIALIZED(right, (destructor)PyObject_Free);
3797 assert(opcode == POP_JUMP_FORWARD_IF_FALSE ||
3798 opcode == POP_JUMP_BACKWARD_IF_FALSE ||
3799 opcode == POP_JUMP_FORWARD_IF_TRUE ||
3800 opcode == POP_JUMP_BACKWARD_IF_TRUE);
3801 int jump = (9 << (sign + 1)) & when_to_jump_mask;
3802 if (!jump) {
3803 next_instr++;
3804 }
3805 else if (jump >= 8) {
3806 assert(opcode == POP_JUMP_BACKWARD_IF_TRUE ||
3807 opcode == POP_JUMP_BACKWARD_IF_FALSE);
3808 JUMPBY(1 - oparg);
3809 CHECK_EVAL_BREAKER();
3810 }
3811 else {
3812 assert(opcode == POP_JUMP_FORWARD_IF_TRUE ||
3813 opcode == POP_JUMP_FORWARD_IF_FALSE);
3814 JUMPBY(1 + oparg);
3815 }
3816 DISPATCH();
3817 }
3818
3819 TARGET(COMPARE_OP_STR_JUMP) {
3820 assert(cframe.use_tracing == 0);
3821 // Combined: COMPARE_OP (str == str or str != str) + POP_JUMP_(direction)_IF_(true/false)
3822 _PyCompareOpCache *cache = (_PyCompareOpCache *)next_instr;
3823 int when_to_jump_mask = cache->mask;
3824 PyObject *right = TOP();
3825 PyObject *left = SECOND();
3826 DEOPT_IF(!PyUnicode_CheckExact(left), COMPARE_OP);
3827 DEOPT_IF(!PyUnicode_CheckExact(right), COMPARE_OP);
3828 STAT_INC(COMPARE_OP, hit);
3829 int res = _PyUnicode_Equal(left, right);
3830 if (res < 0) {
3831 goto error;
3832 }
3833 assert(oparg == Py_EQ || oparg == Py_NE);
3834 JUMPBY(INLINE_CACHE_ENTRIES_COMPARE_OP);
3835 NEXTOPARG();
3836 assert(opcode == POP_JUMP_FORWARD_IF_FALSE ||
3837 opcode == POP_JUMP_BACKWARD_IF_FALSE ||
3838 opcode == POP_JUMP_FORWARD_IF_TRUE ||
3839 opcode == POP_JUMP_BACKWARD_IF_TRUE);
3840 STACK_SHRINK(2);
3841 _Py_DECREF_SPECIALIZED(left, _PyUnicode_ExactDealloc);
3842 _Py_DECREF_SPECIALIZED(right, _PyUnicode_ExactDealloc);
3843 assert(res == 0 || res == 1);
3844 int sign = 1 - res;
3845 int jump = (9 << (sign + 1)) & when_to_jump_mask;
3846 if (!jump) {
3847 next_instr++;
3848 }
3849 else if (jump >= 8) {
3850 assert(opcode == POP_JUMP_BACKWARD_IF_TRUE ||
3851 opcode == POP_JUMP_BACKWARD_IF_FALSE);
3852 JUMPBY(1 - oparg);
3853 CHECK_EVAL_BREAKER();
3854 }
3855 else {
3856 assert(opcode == POP_JUMP_FORWARD_IF_TRUE ||
3857 opcode == POP_JUMP_FORWARD_IF_FALSE);
3858 JUMPBY(1 + oparg);
3859 }
3860 DISPATCH();
3861 }
3862
3863 TARGET(IS_OP) {
3864 PyObject *right = POP();
3865 PyObject *left = TOP();
3866 int res = Py_Is(left, right) ^ oparg;
3867 PyObject *b = res ? Py_True : Py_False;
3868 Py_INCREF(b);
3869 SET_TOP(b);
3870 Py_DECREF(left);
3871 Py_DECREF(right);
3872 DISPATCH();
3873 }
3874
3875 TARGET(CONTAINS_OP) {
3876 PyObject *right = POP();
3877 PyObject *left = POP();
3878 int res = PySequence_Contains(right, left);
3879 Py_DECREF(left);
3880 Py_DECREF(right);
3881 if (res < 0) {
3882 goto error;
3883 }
3884 PyObject *b = (res^oparg) ? Py_True : Py_False;
3885 Py_INCREF(b);
3886 PUSH(b);
3887 DISPATCH();
3888 }
3889
3890 TARGET(CHECK_EG_MATCH) {
3891 PyObject *match_type = POP();
3892 if (check_except_star_type_valid(tstate, match_type) < 0) {
3893 Py_DECREF(match_type);
3894 goto error;
3895 }
3896
3897 PyObject *exc_value = TOP();
3898 PyObject *match = NULL, *rest = NULL;
3899 int res = exception_group_match(exc_value, match_type,
3900 &match, &rest);
3901 Py_DECREF(match_type);
3902 if (res < 0) {
3903 goto error;
3904 }
3905
3906 if (match == NULL || rest == NULL) {
3907 assert(match == NULL);
3908 assert(rest == NULL);
3909 goto error;
3910 }
3911 if (Py_IsNone(match)) {
3912 PUSH(match);
3913 Py_XDECREF(rest);
3914 }
3915 else {
3916 /* Total or partial match - update the stack from
3917 * [val]
3918 * to
3919 * [rest, match]
3920 * (rest can be Py_None)
3921 */
3922
3923 SET_TOP(rest);
3924 PUSH(match);
3925 PyErr_SetExcInfo(NULL, Py_NewRef(match), NULL);
3926 Py_DECREF(exc_value);
3927 }
3928 DISPATCH();
3929 }
3930
3931 TARGET(CHECK_EXC_MATCH) {
3932 PyObject *right = POP();
3933 PyObject *left = TOP();
3934 assert(PyExceptionInstance_Check(left));
3935 if (check_except_type_valid(tstate, right) < 0) {
3936 Py_DECREF(right);
3937 goto error;
3938 }
3939
3940 int res = PyErr_GivenExceptionMatches(left, right);
3941 Py_DECREF(right);
3942 PUSH(Py_NewRef(res ? Py_True : Py_False));
3943 DISPATCH();
3944 }
3945
3946 TARGET(IMPORT_NAME) {
3947 PyObject *name = GETITEM(names, oparg);
3948 PyObject *fromlist = POP();
3949 PyObject *level = TOP();
3950 PyObject *res;
3951 res = import_name(tstate, frame, name, fromlist, level);
3952 Py_DECREF(level);
3953 Py_DECREF(fromlist);
3954 SET_TOP(res);
3955 if (res == NULL)
3956 goto error;
3957 DISPATCH();
3958 }
3959
3960 TARGET(IMPORT_STAR) {
3961 PyObject *from = POP(), *locals;
3962 int err;
3963 if (_PyFrame_FastToLocalsWithError(frame) < 0) {
3964 Py_DECREF(from);
3965 goto error;
3966 }
3967
3968 locals = LOCALS();
3969 if (locals == NULL) {
3970 _PyErr_SetString(tstate, PyExc_SystemError,
3971 "no locals found during 'import *'");
3972 Py_DECREF(from);
3973 goto error;
3974 }
3975 err = import_all_from(tstate, locals, from);
3976 _PyFrame_LocalsToFast(frame, 0);
3977 Py_DECREF(from);
3978 if (err != 0)
3979 goto error;
3980 DISPATCH();
3981 }
3982
3983 TARGET(IMPORT_FROM) {
3984 PyObject *name = GETITEM(names, oparg);
3985 PyObject *from = TOP();
3986 PyObject *res;
3987 res = import_from(tstate, from, name);
3988 PUSH(res);
3989 if (res == NULL)
3990 goto error;
3991 DISPATCH();
3992 }
3993
3994 TARGET(JUMP_FORWARD) {
3995 JUMPBY(oparg);
3996 DISPATCH();
3997 }
3998
3999 TARGET(JUMP_BACKWARD) {
4000 _PyCode_Warmup(frame->f_code);
4001 JUMP_TO_INSTRUCTION(JUMP_BACKWARD_QUICK);
4002 }
4003
4004 TARGET(POP_JUMP_BACKWARD_IF_FALSE) {
4005 PREDICTED(POP_JUMP_BACKWARD_IF_FALSE);
4006 PyObject *cond = POP();
4007 if (Py_IsTrue(cond)) {
4008 _Py_DECREF_NO_DEALLOC(cond);
4009 DISPATCH();
4010 }
4011 if (Py_IsFalse(cond)) {
4012 _Py_DECREF_NO_DEALLOC(cond);
4013 JUMPBY(-oparg);
4014 CHECK_EVAL_BREAKER();
4015 DISPATCH();
4016 }
4017 int err = PyObject_IsTrue(cond);
4018 Py_DECREF(cond);
4019 if (err > 0)
4020 ;
4021 else if (err == 0) {
4022 JUMPBY(-oparg);
4023 CHECK_EVAL_BREAKER();
4024 }
4025 else
4026 goto error;
4027 DISPATCH();
4028 }
4029
4030 TARGET(POP_JUMP_FORWARD_IF_FALSE) {
4031 PREDICTED(POP_JUMP_FORWARD_IF_FALSE);
4032 PyObject *cond = POP();
4033 if (Py_IsTrue(cond)) {
4034 _Py_DECREF_NO_DEALLOC(cond);
4035 }
4036 else if (Py_IsFalse(cond)) {
4037 _Py_DECREF_NO_DEALLOC(cond);
4038 JUMPBY(oparg);
4039 }
4040 else {
4041 int err = PyObject_IsTrue(cond);
4042 Py_DECREF(cond);
4043 if (err > 0)
4044 ;
4045 else if (err == 0) {
4046 JUMPBY(oparg);
4047 }
4048 else
4049 goto error;
4050 }
4051 DISPATCH();
4052 }
4053
4054 TARGET(POP_JUMP_BACKWARD_IF_TRUE) {
4055 PyObject *cond = POP();
4056 if (Py_IsFalse(cond)) {
4057 _Py_DECREF_NO_DEALLOC(cond);
4058 DISPATCH();
4059 }
4060 if (Py_IsTrue(cond)) {
4061 _Py_DECREF_NO_DEALLOC(cond);
4062 JUMPBY(-oparg);
4063 CHECK_EVAL_BREAKER();
4064 DISPATCH();
4065 }
4066 int err = PyObject_IsTrue(cond);
4067 Py_DECREF(cond);
4068 if (err > 0) {
4069 JUMPBY(-oparg);
4070 CHECK_EVAL_BREAKER();
4071 }
4072 else if (err == 0)
4073 ;
4074 else
4075 goto error;
4076 DISPATCH();
4077 }
4078
4079 TARGET(POP_JUMP_FORWARD_IF_TRUE) {
4080 PyObject *cond = POP();
4081 if (Py_IsFalse(cond)) {
4082 _Py_DECREF_NO_DEALLOC(cond);
4083 }
4084 else if (Py_IsTrue(cond)) {
4085 _Py_DECREF_NO_DEALLOC(cond);
4086 JUMPBY(oparg);
4087 }
4088 else {
4089 int err = PyObject_IsTrue(cond);
4090 Py_DECREF(cond);
4091 if (err > 0) {
4092 JUMPBY(oparg);
4093 }
4094 else if (err == 0)
4095 ;
4096 else
4097 goto error;
4098 }
4099 DISPATCH();
4100 }
4101
4102 TARGET(POP_JUMP_BACKWARD_IF_NOT_NONE) {
4103 PyObject *value = POP();
4104 if (!Py_IsNone(value)) {
4105 Py_DECREF(value);
4106 JUMPBY(-oparg);
4107 CHECK_EVAL_BREAKER();
4108 DISPATCH();
4109 }
4110 _Py_DECREF_NO_DEALLOC(value);
4111 DISPATCH();
4112 }
4113
4114 TARGET(POP_JUMP_FORWARD_IF_NOT_NONE) {
4115 PyObject *value = POP();
4116 if (!Py_IsNone(value)) {
4117 JUMPBY(oparg);
4118 }
4119 Py_DECREF(value);
4120 DISPATCH();
4121 }
4122
4123 TARGET(POP_JUMP_BACKWARD_IF_NONE) {
4124 PyObject *value = POP();
4125 if (Py_IsNone(value)) {
4126 _Py_DECREF_NO_DEALLOC(value);
4127 JUMPBY(-oparg);
4128 CHECK_EVAL_BREAKER();
4129 }
4130 else {
4131 Py_DECREF(value);
4132 }
4133 DISPATCH();
4134 }
4135
4136 TARGET(POP_JUMP_FORWARD_IF_NONE) {
4137 PyObject *value = POP();
4138 if (Py_IsNone(value)) {
4139 _Py_DECREF_NO_DEALLOC(value);
4140 JUMPBY(oparg);
4141 }
4142 else {
4143 Py_DECREF(value);
4144 }
4145 DISPATCH();
4146 }
4147
4148 TARGET(JUMP_IF_FALSE_OR_POP) {
4149 PyObject *cond = TOP();
4150 int err;
4151 if (Py_IsTrue(cond)) {
4152 STACK_SHRINK(1);
4153 _Py_DECREF_NO_DEALLOC(cond);
4154 DISPATCH();
4155 }
4156 if (Py_IsFalse(cond)) {
4157 JUMPBY(oparg);
4158 DISPATCH();
4159 }
4160 err = PyObject_IsTrue(cond);
4161 if (err > 0) {
4162 STACK_SHRINK(1);
4163 Py_DECREF(cond);
4164 }
4165 else if (err == 0)
4166 JUMPBY(oparg);
4167 else
4168 goto error;
4169 DISPATCH();
4170 }
4171
4172 TARGET(JUMP_IF_TRUE_OR_POP) {
4173 PyObject *cond = TOP();
4174 int err;
4175 if (Py_IsFalse(cond)) {
4176 STACK_SHRINK(1);
4177 _Py_DECREF_NO_DEALLOC(cond);
4178 DISPATCH();
4179 }
4180 if (Py_IsTrue(cond)) {
4181 JUMPBY(oparg);
4182 DISPATCH();
4183 }
4184 err = PyObject_IsTrue(cond);
4185 if (err > 0) {
4186 JUMPBY(oparg);
4187 }
4188 else if (err == 0) {
4189 STACK_SHRINK(1);
4190 Py_DECREF(cond);
4191 }
4192 else
4193 goto error;
4194 DISPATCH();
4195 }
4196
4197 TARGET(JUMP_BACKWARD_NO_INTERRUPT) {
4198 /* This bytecode is used in the `yield from` or `await` loop.
4199 * If there is an interrupt, we want it handled in the innermost
4200 * generator or coroutine, so we deliberately do not check it here.
4201 * (see bpo-30039).
4202 */
4203 JUMPBY(-oparg);
4204 DISPATCH();
4205 }
4206
4207 TARGET(JUMP_BACKWARD_QUICK) {
4208 PREDICTED(JUMP_BACKWARD_QUICK);
4209 assert(oparg < INSTR_OFFSET());
4210 JUMPBY(-oparg);
4211 CHECK_EVAL_BREAKER();
4212 DISPATCH();
4213 }
4214
4215 TARGET(GET_LEN) {
4216 // PUSH(len(TOS))
4217 Py_ssize_t len_i = PyObject_Length(TOP());
4218 if (len_i < 0) {
4219 goto error;
4220 }
4221 PyObject *len_o = PyLong_FromSsize_t(len_i);
4222 if (len_o == NULL) {
4223 goto error;
4224 }
4225 PUSH(len_o);
4226 DISPATCH();
4227 }
4228
4229 TARGET(MATCH_CLASS) {
4230 // Pop TOS and TOS1. Set TOS to a tuple of attributes on success, or
4231 // None on failure.
4232 PyObject *names = POP();
4233 PyObject *type = POP();
4234 PyObject *subject = TOP();
4235 assert(PyTuple_CheckExact(names));
4236 PyObject *attrs = match_class(tstate, subject, type, oparg, names);
4237 Py_DECREF(names);
4238 Py_DECREF(type);
4239 if (attrs) {
4240 // Success!
4241 assert(PyTuple_CheckExact(attrs));
4242 SET_TOP(attrs);
4243 }
4244 else if (_PyErr_Occurred(tstate)) {
4245 // Error!
4246 goto error;
4247 }
4248 else {
4249 // Failure!
4250 Py_INCREF(Py_None);
4251 SET_TOP(Py_None);
4252 }
4253 Py_DECREF(subject);
4254 DISPATCH();
4255 }
4256
4257 TARGET(MATCH_MAPPING) {
4258 PyObject *subject = TOP();
4259 int match = Py_TYPE(subject)->tp_flags & Py_TPFLAGS_MAPPING;
4260 PyObject *res = match ? Py_True : Py_False;
4261 Py_INCREF(res);
4262 PUSH(res);
4263 PREDICT(POP_JUMP_FORWARD_IF_FALSE);
4264 PREDICT(POP_JUMP_BACKWARD_IF_FALSE);
4265 DISPATCH();
4266 }
4267
4268 TARGET(MATCH_SEQUENCE) {
4269 PyObject *subject = TOP();
4270 int match = Py_TYPE(subject)->tp_flags & Py_TPFLAGS_SEQUENCE;
4271 PyObject *res = match ? Py_True : Py_False;
4272 Py_INCREF(res);
4273 PUSH(res);
4274 PREDICT(POP_JUMP_FORWARD_IF_FALSE);
4275 PREDICT(POP_JUMP_BACKWARD_IF_FALSE);
4276 DISPATCH();
4277 }
4278
4279 TARGET(MATCH_KEYS) {
4280 // On successful match, PUSH(values). Otherwise, PUSH(None).
4281 PyObject *keys = TOP();
4282 PyObject *subject = SECOND();
4283 PyObject *values_or_none = match_keys(tstate, subject, keys);
4284 if (values_or_none == NULL) {
4285 goto error;
4286 }
4287 PUSH(values_or_none);
4288 DISPATCH();
4289 }
4290
4291 TARGET(GET_ITER) {
4292 /* before: [obj]; after [getiter(obj)] */
4293 PyObject *iterable = TOP();
4294 PyObject *iter = PyObject_GetIter(iterable);
4295 Py_DECREF(iterable);
4296 SET_TOP(iter);
4297 if (iter == NULL)
4298 goto error;
4299 PREDICT(FOR_ITER);
4300 DISPATCH();
4301 }
4302
4303 TARGET(GET_YIELD_FROM_ITER) {
4304 /* before: [obj]; after [getiter(obj)] */
4305 PyObject *iterable = TOP();
4306 PyObject *iter;
4307 if (PyCoro_CheckExact(iterable)) {
4308 /* `iterable` is a coroutine */
4309 if (!(frame->f_code->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))) {
4310 /* and it is used in a 'yield from' expression of a
4311 regular generator. */
4312 Py_DECREF(iterable);
4313 SET_TOP(NULL);
4314 _PyErr_SetString(tstate, PyExc_TypeError,
4315 "cannot 'yield from' a coroutine object "
4316 "in a non-coroutine generator");
4317 goto error;
4318 }
4319 }
4320 else if (!PyGen_CheckExact(iterable)) {
4321 /* `iterable` is not a generator. */
4322 iter = PyObject_GetIter(iterable);
4323 Py_DECREF(iterable);
4324 SET_TOP(iter);
4325 if (iter == NULL)
4326 goto error;
4327 }
4328 PREDICT(LOAD_CONST);
4329 DISPATCH();
4330 }
4331
4332 TARGET(FOR_ITER) {
4333 PREDICTED(FOR_ITER);
4334 /* before: [iter]; after: [iter, iter()] *or* [] */
4335 PyObject *iter = TOP();
4336 #ifdef Py_STATS
4337 extern int _PySpecialization_ClassifyIterator(PyObject *);
4338 _py_stats.opcode_stats[FOR_ITER].specialization.failure++;
4339 _py_stats.opcode_stats[FOR_ITER].specialization.failure_kinds[_PySpecialization_ClassifyIterator(iter)]++;
4340 #endif
4341 PyObject *next = (*Py_TYPE(iter)->tp_iternext)(iter);
4342 if (next != NULL) {
4343 PUSH(next);
4344 PREDICT(STORE_FAST);
4345 PREDICT(UNPACK_SEQUENCE);
4346 DISPATCH();
4347 }
4348 if (_PyErr_Occurred(tstate)) {
4349 if (!_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
4350 goto error;
4351 }
4352 else if (tstate->c_tracefunc != NULL) {
4353 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, frame);
4354 }
4355 _PyErr_Clear(tstate);
4356 }
4357 /* iterator ended normally */
4358 STACK_SHRINK(1);
4359 Py_DECREF(iter);
4360 JUMPBY(oparg);
4361 DISPATCH();
4362 }
4363
4364 TARGET(BEFORE_ASYNC_WITH) {
4365 PyObject *mgr = TOP();
4366 PyObject *res;
4367 PyObject *enter = _PyObject_LookupSpecial(mgr, &_Py_ID(__aenter__));
4368 if (enter == NULL) {
4369 if (!_PyErr_Occurred(tstate)) {
4370 _PyErr_Format(tstate, PyExc_TypeError,
4371 "'%.200s' object does not support the "
4372 "asynchronous context manager protocol",
4373 Py_TYPE(mgr)->tp_name);
4374 }
4375 goto error;
4376 }
4377 PyObject *exit = _PyObject_LookupSpecial(mgr, &_Py_ID(__aexit__));
4378 if (exit == NULL) {
4379 if (!_PyErr_Occurred(tstate)) {
4380 _PyErr_Format(tstate, PyExc_TypeError,
4381 "'%.200s' object does not support the "
4382 "asynchronous context manager protocol "
4383 "(missed __aexit__ method)",
4384 Py_TYPE(mgr)->tp_name);
4385 }
4386 Py_DECREF(enter);
4387 goto error;
4388 }
4389 SET_TOP(exit);
4390 Py_DECREF(mgr);
4391 res = _PyObject_CallNoArgs(enter);
4392 Py_DECREF(enter);
4393 if (res == NULL)
4394 goto error;
4395 PUSH(res);
4396 PREDICT(GET_AWAITABLE);
4397 DISPATCH();
4398 }
4399
4400 TARGET(BEFORE_WITH) {
4401 PyObject *mgr = TOP();
4402 PyObject *res;
4403 PyObject *enter = _PyObject_LookupSpecial(mgr, &_Py_ID(__enter__));
4404 if (enter == NULL) {
4405 if (!_PyErr_Occurred(tstate)) {
4406 _PyErr_Format(tstate, PyExc_TypeError,
4407 "'%.200s' object does not support the "
4408 "context manager protocol",
4409 Py_TYPE(mgr)->tp_name);
4410 }
4411 goto error;
4412 }
4413 PyObject *exit = _PyObject_LookupSpecial(mgr, &_Py_ID(__exit__));
4414 if (exit == NULL) {
4415 if (!_PyErr_Occurred(tstate)) {
4416 _PyErr_Format(tstate, PyExc_TypeError,
4417 "'%.200s' object does not support the "
4418 "context manager protocol "
4419 "(missed __exit__ method)",
4420 Py_TYPE(mgr)->tp_name);
4421 }
4422 Py_DECREF(enter);
4423 goto error;
4424 }
4425 SET_TOP(exit);
4426 Py_DECREF(mgr);
4427 res = _PyObject_CallNoArgs(enter);
4428 Py_DECREF(enter);
4429 if (res == NULL) {
4430 goto error;
4431 }
4432 PUSH(res);
4433 DISPATCH();
4434 }
4435
4436 TARGET(WITH_EXCEPT_START) {
4437 /* At the top of the stack are 4 values:
4438 - TOP = exc_info()
4439 - SECOND = previous exception
4440 - THIRD: lasti of exception in exc_info()
4441 - FOURTH: the context.__exit__ bound method
4442 We call FOURTH(type(TOP), TOP, GetTraceback(TOP)).
4443 Then we push the __exit__ return value.
4444 */
4445 PyObject *exit_func;
4446 PyObject *exc, *val, *tb, *res;
4447
4448 val = TOP();
4449 assert(val && PyExceptionInstance_Check(val));
4450 exc = PyExceptionInstance_Class(val);
4451 tb = PyException_GetTraceback(val);
4452 Py_XDECREF(tb);
4453 assert(PyLong_Check(PEEK(3)));
4454 exit_func = PEEK(4);
4455 PyObject *stack[4] = {NULL, exc, val, tb};
4456 res = PyObject_Vectorcall(exit_func, stack + 1,
4457 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
4458 if (res == NULL)
4459 goto error;
4460
4461 PUSH(res);
4462 DISPATCH();
4463 }
4464
4465 TARGET(PUSH_EXC_INFO) {
4466 PyObject *value = TOP();
4467
4468 _PyErr_StackItem *exc_info = tstate->exc_info;
4469 if (exc_info->exc_value != NULL) {
4470 SET_TOP(exc_info->exc_value);
4471 }
4472 else {
4473 Py_INCREF(Py_None);
4474 SET_TOP(Py_None);
4475 }
4476
4477 Py_INCREF(value);
4478 PUSH(value);
4479 assert(PyExceptionInstance_Check(value));
4480 exc_info->exc_value = value;
4481
4482 DISPATCH();
4483 }
4484
4485 TARGET(LOAD_METHOD) {
4486 PREDICTED(LOAD_METHOD);
4487 /* Designed to work in tandem with PRECALL. */
4488 PyObject *name = GETITEM(names, oparg);
4489 PyObject *obj = TOP();
4490 PyObject *meth = NULL;
4491
4492 int meth_found = _PyObject_GetMethod(obj, name, &meth);
4493
4494 if (meth == NULL) {
4495 /* Most likely attribute wasn't found. */
4496 goto error;
4497 }
4498
4499 if (meth_found) {
4500 /* We can bypass temporary bound method object.
4501 meth is unbound method and obj is self.
4502
4503 meth | self | arg1 | ... | argN
4504 */
4505 SET_TOP(meth);
4506 PUSH(obj); // self
4507 }
4508 else {
4509 /* meth is not an unbound method (but a regular attr, or
4510 something was returned by a descriptor protocol). Set
4511 the second element of the stack to NULL, to signal
4512 PRECALL that it's not a method call.
4513
4514 NULL | meth | arg1 | ... | argN
4515 */
4516 SET_TOP(NULL);
4517 Py_DECREF(obj);
4518 PUSH(meth);
4519 }
4520 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_METHOD);
4521 DISPATCH();
4522 }
4523
4524 TARGET(LOAD_METHOD_ADAPTIVE) {
4525 assert(cframe.use_tracing == 0);
4526 _PyLoadMethodCache *cache = (_PyLoadMethodCache *)next_instr;
4527 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
4528 PyObject *owner = TOP();
4529 PyObject *name = GETITEM(names, oparg);
4530 next_instr--;
4531 if (_Py_Specialize_LoadMethod(owner, next_instr, name) < 0) {
4532 next_instr++;
4533 goto error;
4534 }
4535 DISPATCH_SAME_OPARG();
4536 }
4537 else {
4538 STAT_INC(LOAD_METHOD, deferred);
4539 DECREMENT_ADAPTIVE_COUNTER(cache);
4540 JUMP_TO_INSTRUCTION(LOAD_METHOD);
4541 }
4542 }
4543
4544 TARGET(LOAD_METHOD_WITH_VALUES) {
4545 /* LOAD_METHOD, with cached method object */
4546 assert(cframe.use_tracing == 0);
4547 PyObject *self = TOP();
4548 PyTypeObject *self_cls = Py_TYPE(self);
4549 _PyLoadMethodCache *cache = (_PyLoadMethodCache *)next_instr;
4550 uint32_t type_version = read_u32(cache->type_version);
4551 assert(type_version != 0);
4552 DEOPT_IF(self_cls->tp_version_tag != type_version, LOAD_METHOD);
4553 assert(self_cls->tp_flags & Py_TPFLAGS_MANAGED_DICT);
4554 PyDictObject *dict = *(PyDictObject**)_PyObject_ManagedDictPointer(self);
4555 DEOPT_IF(dict != NULL, LOAD_METHOD);
4556 PyHeapTypeObject *self_heap_type = (PyHeapTypeObject *)self_cls;
4557 DEOPT_IF(self_heap_type->ht_cached_keys->dk_version !=
4558 read_u32(cache->keys_version), LOAD_METHOD);
4559 STAT_INC(LOAD_METHOD, hit);
4560 PyObject *res = read_obj(cache->descr);
4561 assert(res != NULL);
4562 assert(_PyType_HasFeature(Py_TYPE(res), Py_TPFLAGS_METHOD_DESCRIPTOR));
4563 Py_INCREF(res);
4564 SET_TOP(res);
4565 PUSH(self);
4566 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_METHOD);
4567 DISPATCH();
4568 }
4569
4570 TARGET(LOAD_METHOD_WITH_DICT) {
4571 /* LOAD_METHOD, with a dict
4572 Can be either a managed dict, or a tp_dictoffset offset.*/
4573 assert(cframe.use_tracing == 0);
4574 PyObject *self = TOP();
4575 PyTypeObject *self_cls = Py_TYPE(self);
4576 _PyLoadMethodCache *cache = (_PyLoadMethodCache *)next_instr;
4577
4578 DEOPT_IF(self_cls->tp_version_tag != read_u32(cache->type_version),
4579 LOAD_METHOD);
4580 /* Treat index as a signed 16 bit value */
4581 int dictoffset = *(int16_t *)&cache->dict_offset;
4582 PyDictObject **dictptr = (PyDictObject**)(((char *)self)+dictoffset);
4583 assert(
4584 dictoffset == MANAGED_DICT_OFFSET ||
4585 (dictoffset == self_cls->tp_dictoffset && dictoffset > 0)
4586 );
4587 PyDictObject *dict = *dictptr;
4588 DEOPT_IF(dict == NULL, LOAD_METHOD);
4589 DEOPT_IF(dict->ma_keys->dk_version != read_u32(cache->keys_version),
4590 LOAD_METHOD);
4591 STAT_INC(LOAD_METHOD, hit);
4592 PyObject *res = read_obj(cache->descr);
4593 assert(res != NULL);
4594 assert(_PyType_HasFeature(Py_TYPE(res), Py_TPFLAGS_METHOD_DESCRIPTOR));
4595 Py_INCREF(res);
4596 SET_TOP(res);
4597 PUSH(self);
4598 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_METHOD);
4599 DISPATCH();
4600 }
4601
4602 TARGET(LOAD_METHOD_NO_DICT) {
4603 assert(cframe.use_tracing == 0);
4604 PyObject *self = TOP();
4605 PyTypeObject *self_cls = Py_TYPE(self);
4606 _PyLoadMethodCache *cache = (_PyLoadMethodCache *)next_instr;
4607 uint32_t type_version = read_u32(cache->type_version);
4608 DEOPT_IF(self_cls->tp_version_tag != type_version, LOAD_METHOD);
4609 assert(self_cls->tp_dictoffset == 0);
4610 STAT_INC(LOAD_METHOD, hit);
4611 PyObject *res = read_obj(cache->descr);
4612 assert(res != NULL);
4613 assert(_PyType_HasFeature(Py_TYPE(res), Py_TPFLAGS_METHOD_DESCRIPTOR));
4614 Py_INCREF(res);
4615 SET_TOP(res);
4616 PUSH(self);
4617 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_METHOD);
4618 DISPATCH();
4619 }
4620
4621 TARGET(LOAD_METHOD_MODULE) {
4622 /* LOAD_METHOD, for module methods */
4623 assert(cframe.use_tracing == 0);
4624 PyObject *owner = TOP();
4625 PyObject *res;
4626 LOAD_MODULE_ATTR_OR_METHOD(METHOD);
4627 SET_TOP(NULL);
4628 Py_DECREF(owner);
4629 PUSH(res);
4630 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_METHOD);
4631 DISPATCH();
4632 }
4633
4634 TARGET(LOAD_METHOD_CLASS) {
4635 /* LOAD_METHOD, for class methods */
4636 assert(cframe.use_tracing == 0);
4637 _PyLoadMethodCache *cache = (_PyLoadMethodCache *)next_instr;
4638
4639 PyObject *cls = TOP();
4640 DEOPT_IF(!PyType_Check(cls), LOAD_METHOD);
4641 uint32_t type_version = read_u32(cache->type_version);
4642 DEOPT_IF(((PyTypeObject *)cls)->tp_version_tag != type_version,
4643 LOAD_METHOD);
4644 assert(type_version != 0);
4645
4646 STAT_INC(LOAD_METHOD, hit);
4647 PyObject *res = read_obj(cache->descr);
4648 assert(res != NULL);
4649 Py_INCREF(res);
4650 SET_TOP(NULL);
4651 Py_DECREF(cls);
4652 PUSH(res);
4653 JUMPBY(INLINE_CACHE_ENTRIES_LOAD_METHOD);
4654 DISPATCH();
4655 }
4656
4657 TARGET(PRECALL) {
4658 PREDICTED(PRECALL);
4659 /* Designed to work in tamdem with LOAD_METHOD. */
4660 /* `meth` is NULL when LOAD_METHOD thinks that it's not
4661 a method call.
4662
4663 Stack layout:
4664
4665 ... | NULL | callable | arg1 | ... | argN
4666 ^- TOP()
4667 ^- (-oparg)
4668 ^- (-oparg-1)
4669 ^- (-oparg-2)
4670
4671 `callable` will be POPed by call_function.
4672 NULL will will be POPed manually later.
4673 If `meth` isn't NULL, it's a method call. Stack layout:
4674
4675 ... | method | self | arg1 | ... | argN
4676 ^- TOP()
4677 ^- (-oparg)
4678 ^- (-oparg-1)
4679 ^- (-oparg-2)
4680
4681 `self` and `method` will be POPed by call_function.
4682 We'll be passing `oparg + 1` to call_function, to
4683 make it accept the `self` as a first argument.
4684 */
4685 int is_meth = is_method(stack_pointer, oparg);
4686 int nargs = oparg + is_meth;
4687 /* Move ownership of reference from stack to call_shape
4688 * and make sure that NULL is cleared from stack */
4689 PyObject *function = PEEK(nargs + 1);
4690 if (!is_meth && Py_TYPE(function) == &PyMethod_Type) {
4691 PyObject *meth = ((PyMethodObject *)function)->im_func;
4692 PyObject *self = ((PyMethodObject *)function)->im_self;
4693 Py_INCREF(meth);
4694 Py_INCREF(self);
4695 PEEK(oparg+1) = self;
4696 PEEK(oparg+2) = meth;
4697 Py_DECREF(function);
4698 }
4699 JUMPBY(INLINE_CACHE_ENTRIES_PRECALL);
4700 DISPATCH();
4701 }
4702
4703 TARGET(PRECALL_BOUND_METHOD) {
4704 DEOPT_IF(is_method(stack_pointer, oparg), PRECALL);
4705 PyObject *function = PEEK(oparg + 1);
4706 DEOPT_IF(Py_TYPE(function) != &PyMethod_Type, PRECALL);
4707 STAT_INC(PRECALL, hit);
4708 PyObject *meth = ((PyMethodObject *)function)->im_func;
4709 PyObject *self = ((PyMethodObject *)function)->im_self;
4710 Py_INCREF(meth);
4711 Py_INCREF(self);
4712 PEEK(oparg + 1) = self;
4713 PEEK(oparg + 2) = meth;
4714 Py_DECREF(function);
4715 JUMPBY(INLINE_CACHE_ENTRIES_PRECALL);
4716 DISPATCH();
4717 }
4718
4719 TARGET(PRECALL_PYFUNC) {
4720 int nargs = oparg + is_method(stack_pointer, oparg);
4721 PyObject *function = PEEK(nargs + 1);
4722 DEOPT_IF(Py_TYPE(function) != &PyFunction_Type, PRECALL);
4723 STAT_INC(PRECALL, hit);
4724 JUMPBY(INLINE_CACHE_ENTRIES_PRECALL);
4725 DISPATCH();
4726 }
4727
4728 TARGET(KW_NAMES) {
4729 assert(call_shape.kwnames == NULL);
4730 assert(oparg < PyTuple_GET_SIZE(consts));
4731 call_shape.kwnames = GETITEM(consts, oparg);
4732 DISPATCH();
4733 }
4734
4735 TARGET(CALL) {
4736 int is_meth;
4737 call_function:
4738 is_meth = is_method(stack_pointer, oparg);
4739 int total_args = oparg + is_meth;
4740 PyObject *function = PEEK(total_args + 1);
4741 int positional_args = total_args - KWNAMES_LEN();
4742 // Check if the call can be inlined or not
4743 if (Py_TYPE(function) == &PyFunction_Type && tstate->interp->eval_frame == NULL) {
4744 int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(function))->co_flags;
4745 PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : PyFunction_GET_GLOBALS(function);
4746 STACK_SHRINK(total_args);
4747 _PyInterpreterFrame *new_frame = _PyEvalFramePushAndInit(
4748 tstate, (PyFunctionObject *)function, locals,
4749 stack_pointer, positional_args, call_shape.kwnames
4750 );
4751 call_shape.kwnames = NULL;
4752 STACK_SHRINK(2-is_meth);
4753 // The frame has stolen all the arguments from the stack,
4754 // so there is no need to clean them up.
4755 if (new_frame == NULL) {
4756 goto error;
4757 }
4758 _PyFrame_SetStackPointer(frame, stack_pointer);
4759 JUMPBY(INLINE_CACHE_ENTRIES_CALL);
4760 frame->prev_instr = next_instr - 1;
4761 new_frame->previous = frame;
4762 cframe.current_frame = frame = new_frame;
4763 CALL_STAT_INC(inlined_py_calls);
4764 goto start_frame;
4765 }
4766 /* Callable is not a normal Python function */
4767 PyObject *res;
4768 if (cframe.use_tracing) {
4769 res = trace_call_function(
4770 tstate, function, stack_pointer-total_args,
4771 positional_args, call_shape.kwnames);
4772 }
4773 else {
4774 res = PyObject_Vectorcall(
4775 function, stack_pointer-total_args,
4776 positional_args | PY_VECTORCALL_ARGUMENTS_OFFSET,
4777 call_shape.kwnames);
4778 }
4779 call_shape.kwnames = NULL;
4780 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
4781 Py_DECREF(function);
4782 /* Clear the stack */
4783 STACK_SHRINK(total_args);
4784 for (int i = 0; i < total_args; i++) {
4785 Py_DECREF(stack_pointer[i]);
4786 }
4787 STACK_SHRINK(2-is_meth);
4788 PUSH(res);
4789 if (res == NULL) {
4790 goto error;
4791 }
4792 JUMPBY(INLINE_CACHE_ENTRIES_CALL);
4793 CHECK_EVAL_BREAKER();
4794 DISPATCH();
4795 }
4796
4797 TARGET(PRECALL_ADAPTIVE) {
4798 _PyPrecallCache *cache = (_PyPrecallCache *)next_instr;
4799 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
4800 next_instr--;
4801 int is_meth = is_method(stack_pointer, oparg);
4802 int nargs = oparg + is_meth;
4803 PyObject *callable = PEEK(nargs + 1);
4804 int err = _Py_Specialize_Precall(callable, next_instr, nargs,
4805 call_shape.kwnames, oparg);
4806 if (err < 0) {
4807 next_instr++;
4808 goto error;
4809 }
4810 DISPATCH_SAME_OPARG();
4811 }
4812 else {
4813 STAT_INC(PRECALL, deferred);
4814 DECREMENT_ADAPTIVE_COUNTER(cache);
4815 JUMP_TO_INSTRUCTION(PRECALL);
4816 }
4817 }
4818
4819 TARGET(CALL_ADAPTIVE) {
4820 _PyCallCache *cache = (_PyCallCache *)next_instr;
4821 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
4822 next_instr--;
4823 int is_meth = is_method(stack_pointer, oparg);
4824 int nargs = oparg + is_meth;
4825 PyObject *callable = PEEK(nargs + 1);
4826 int err = _Py_Specialize_Call(callable, next_instr, nargs,
4827 call_shape.kwnames);
4828 if (err < 0) {
4829 next_instr++;
4830 goto error;
4831 }
4832 DISPATCH_SAME_OPARG();
4833 }
4834 else {
4835 STAT_INC(CALL, deferred);
4836 DECREMENT_ADAPTIVE_COUNTER(cache);
4837 goto call_function;
4838 }
4839 }
4840
4841 TARGET(CALL_PY_EXACT_ARGS) {
4842 assert(call_shape.kwnames == NULL);
4843 DEOPT_IF(tstate->interp->eval_frame, CALL);
4844 _PyCallCache *cache = (_PyCallCache *)next_instr;
4845 int is_meth = is_method(stack_pointer, oparg);
4846 int argcount = oparg + is_meth;
4847 PyObject *callable = PEEK(argcount + 1);
4848 DEOPT_IF(!PyFunction_Check(callable), CALL);
4849 PyFunctionObject *func = (PyFunctionObject *)callable;
4850 DEOPT_IF(func->func_version != read_u32(cache->func_version), CALL);
4851 PyCodeObject *code = (PyCodeObject *)func->func_code;
4852 DEOPT_IF(code->co_argcount != argcount, CALL);
4853 STAT_INC(CALL, hit);
4854 _PyInterpreterFrame *new_frame = _PyFrame_Push(tstate, func);
4855 if (new_frame == NULL) {
4856 goto error;
4857 }
4858 CALL_STAT_INC(inlined_py_calls);
4859 STACK_SHRINK(argcount);
4860 for (int i = 0; i < argcount; i++) {
4861 new_frame->localsplus[i] = stack_pointer[i];
4862 }
4863 for (int i = argcount; i < code->co_nlocalsplus; i++) {
4864 new_frame->localsplus[i] = NULL;
4865 }
4866 STACK_SHRINK(2-is_meth);
4867 _PyFrame_SetStackPointer(frame, stack_pointer);
4868 JUMPBY(INLINE_CACHE_ENTRIES_CALL);
4869 frame->prev_instr = next_instr - 1;
4870 new_frame->previous = frame;
4871 frame = cframe.current_frame = new_frame;
4872 goto start_frame;
4873 }
4874
4875 TARGET(CALL_PY_WITH_DEFAULTS) {
4876 assert(call_shape.kwnames == NULL);
4877 DEOPT_IF(tstate->interp->eval_frame, CALL);
4878 _PyCallCache *cache = (_PyCallCache *)next_instr;
4879 int is_meth = is_method(stack_pointer, oparg);
4880 int argcount = oparg + is_meth;
4881 PyObject *callable = PEEK(argcount + 1);
4882 DEOPT_IF(!PyFunction_Check(callable), CALL);
4883 PyFunctionObject *func = (PyFunctionObject *)callable;
4884 DEOPT_IF(func->func_version != read_u32(cache->func_version), CALL);
4885 PyCodeObject *code = (PyCodeObject *)func->func_code;
4886 DEOPT_IF(argcount > code->co_argcount, CALL);
4887 int minargs = cache->min_args;
4888 DEOPT_IF(argcount < minargs, CALL);
4889 STAT_INC(CALL, hit);
4890 _PyInterpreterFrame *new_frame = _PyFrame_Push(tstate, func);
4891 if (new_frame == NULL) {
4892 goto error;
4893 }
4894 CALL_STAT_INC(inlined_py_calls);
4895 STACK_SHRINK(argcount);
4896 for (int i = 0; i < argcount; i++) {
4897 new_frame->localsplus[i] = stack_pointer[i];
4898 }
4899 for (int i = argcount; i < code->co_argcount; i++) {
4900 PyObject *def = PyTuple_GET_ITEM(func->func_defaults,
4901 i - minargs);
4902 Py_INCREF(def);
4903 new_frame->localsplus[i] = def;
4904 }
4905 for (int i = code->co_argcount; i < code->co_nlocalsplus; i++) {
4906 new_frame->localsplus[i] = NULL;
4907 }
4908 STACK_SHRINK(2-is_meth);
4909 _PyFrame_SetStackPointer(frame, stack_pointer);
4910 JUMPBY(INLINE_CACHE_ENTRIES_CALL);
4911 frame->prev_instr = next_instr - 1;
4912 new_frame->previous = frame;
4913 frame = cframe.current_frame = new_frame;
4914 goto start_frame;
4915 }
4916
4917 TARGET(PRECALL_NO_KW_TYPE_1) {
4918 assert(call_shape.kwnames == NULL);
4919 assert(cframe.use_tracing == 0);
4920 assert(oparg == 1);
4921 DEOPT_IF(is_method(stack_pointer, 1), PRECALL);
4922 PyObject *obj = TOP();
4923 PyObject *callable = SECOND();
4924 DEOPT_IF(callable != (PyObject *)&PyType_Type, PRECALL);
4925 STAT_INC(PRECALL, hit);
4926 SKIP_CALL();
4927 PyObject *res = Py_NewRef(Py_TYPE(obj));
4928 Py_DECREF(callable);
4929 Py_DECREF(obj);
4930 STACK_SHRINK(2);
4931 SET_TOP(res);
4932 DISPATCH();
4933 }
4934
4935 TARGET(PRECALL_NO_KW_STR_1) {
4936 assert(call_shape.kwnames == NULL);
4937 assert(cframe.use_tracing == 0);
4938 assert(oparg == 1);
4939 DEOPT_IF(is_method(stack_pointer, 1), PRECALL);
4940 PyObject *callable = PEEK(2);
4941 DEOPT_IF(callable != (PyObject *)&PyUnicode_Type, PRECALL);
4942 STAT_INC(PRECALL, hit);
4943 SKIP_CALL();
4944 PyObject *arg = TOP();
4945 PyObject *res = PyObject_Str(arg);
4946 Py_DECREF(arg);
4947 Py_DECREF(&PyUnicode_Type);
4948 STACK_SHRINK(2);
4949 SET_TOP(res);
4950 if (res == NULL) {
4951 goto error;
4952 }
4953 CHECK_EVAL_BREAKER();
4954 DISPATCH();
4955 }
4956
4957 TARGET(PRECALL_NO_KW_TUPLE_1) {
4958 assert(call_shape.kwnames == NULL);
4959 assert(oparg == 1);
4960 DEOPT_IF(is_method(stack_pointer, 1), PRECALL);
4961 PyObject *callable = PEEK(2);
4962 DEOPT_IF(callable != (PyObject *)&PyTuple_Type, PRECALL);
4963 STAT_INC(PRECALL, hit);
4964 SKIP_CALL();
4965 PyObject *arg = TOP();
4966 PyObject *res = PySequence_Tuple(arg);
4967 Py_DECREF(arg);
4968 Py_DECREF(&PyTuple_Type);
4969 STACK_SHRINK(2);
4970 SET_TOP(res);
4971 if (res == NULL) {
4972 goto error;
4973 }
4974 CHECK_EVAL_BREAKER();
4975 DISPATCH();
4976 }
4977
4978 TARGET(PRECALL_BUILTIN_CLASS) {
4979 int is_meth = is_method(stack_pointer, oparg);
4980 int total_args = oparg + is_meth;
4981 int kwnames_len = KWNAMES_LEN();
4982 PyObject *callable = PEEK(total_args + 1);
4983 DEOPT_IF(!PyType_Check(callable), PRECALL);
4984 PyTypeObject *tp = (PyTypeObject *)callable;
4985 DEOPT_IF(tp->tp_vectorcall == NULL, PRECALL);
4986 STAT_INC(PRECALL, hit);
4987 SKIP_CALL();
4988 STACK_SHRINK(total_args);
4989 PyObject *res = tp->tp_vectorcall((PyObject *)tp, stack_pointer,
4990 total_args-kwnames_len, call_shape.kwnames);
4991 call_shape.kwnames = NULL;
4992 /* Free the arguments. */
4993 for (int i = 0; i < total_args; i++) {
4994 Py_DECREF(stack_pointer[i]);
4995 }
4996 Py_DECREF(tp);
4997 STACK_SHRINK(1-is_meth);
4998 SET_TOP(res);
4999 if (res == NULL) {
5000 goto error;
5001 }
5002 CHECK_EVAL_BREAKER();
5003 DISPATCH();
5004 }
5005
5006 TARGET(PRECALL_NO_KW_BUILTIN_O) {
5007 assert(cframe.use_tracing == 0);
5008 /* Builtin METH_O functions */
5009 assert(call_shape.kwnames == NULL);
5010 int is_meth = is_method(stack_pointer, oparg);
5011 int total_args = oparg + is_meth;
5012 DEOPT_IF(total_args != 1, PRECALL);
5013 PyObject *callable = PEEK(total_args + 1);
5014 DEOPT_IF(!PyCFunction_CheckExact(callable), PRECALL);
5015 DEOPT_IF(PyCFunction_GET_FLAGS(callable) != METH_O, PRECALL);
5016 STAT_INC(PRECALL, hit);
5017 SKIP_CALL();
5018 PyCFunction cfunc = PyCFunction_GET_FUNCTION(callable);
5019 // This is slower but CPython promises to check all non-vectorcall
5020 // function calls.
5021 if (_Py_EnterRecursiveCallTstate(tstate, " while calling a Python object")) {
5022 goto error;
5023 }
5024 PyObject *arg = TOP();
5025 PyObject *res = _PyCFunction_TrampolineCall(cfunc, PyCFunction_GET_SELF(callable), arg);
5026 _Py_LeaveRecursiveCallTstate(tstate);
5027 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5028
5029 Py_DECREF(arg);
5030 Py_DECREF(callable);
5031 STACK_SHRINK(2-is_meth);
5032 SET_TOP(res);
5033 if (res == NULL) {
5034 goto error;
5035 }
5036 CHECK_EVAL_BREAKER();
5037 DISPATCH();
5038 }
5039
5040 TARGET(PRECALL_NO_KW_BUILTIN_FAST) {
5041 assert(cframe.use_tracing == 0);
5042 /* Builtin METH_FASTCALL functions, without keywords */
5043 assert(call_shape.kwnames == NULL);
5044 int is_meth = is_method(stack_pointer, oparg);
5045 int total_args = oparg + is_meth;
5046 PyObject *callable = PEEK(total_args + 1);
5047 DEOPT_IF(!PyCFunction_CheckExact(callable), PRECALL);
5048 DEOPT_IF(PyCFunction_GET_FLAGS(callable) != METH_FASTCALL,
5049 PRECALL);
5050 STAT_INC(PRECALL, hit);
5051 SKIP_CALL();
5052 PyCFunction cfunc = PyCFunction_GET_FUNCTION(callable);
5053 STACK_SHRINK(total_args);
5054 /* res = func(self, args, nargs) */
5055 PyObject *res = ((_PyCFunctionFast)(void(*)(void))cfunc)(
5056 PyCFunction_GET_SELF(callable),
5057 stack_pointer,
5058 total_args);
5059 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5060
5061 /* Free the arguments. */
5062 for (int i = 0; i < total_args; i++) {
5063 Py_DECREF(stack_pointer[i]);
5064 }
5065 STACK_SHRINK(2-is_meth);
5066 PUSH(res);
5067 Py_DECREF(callable);
5068 if (res == NULL) {
5069 /* Not deopting because this doesn't mean our optimization was
5070 wrong. `res` can be NULL for valid reasons. Eg. getattr(x,
5071 'invalid'). In those cases an exception is set, so we must
5072 handle it.
5073 */
5074 goto error;
5075 }
5076 CHECK_EVAL_BREAKER();
5077 DISPATCH();
5078 }
5079
5080 TARGET(PRECALL_BUILTIN_FAST_WITH_KEYWORDS) {
5081 assert(cframe.use_tracing == 0);
5082 /* Builtin METH_FASTCALL | METH_KEYWORDS functions */
5083 int is_meth = is_method(stack_pointer, oparg);
5084 int total_args = oparg + is_meth;
5085 PyObject *callable = PEEK(total_args + 1);
5086 DEOPT_IF(!PyCFunction_CheckExact(callable), PRECALL);
5087 DEOPT_IF(PyCFunction_GET_FLAGS(callable) !=
5088 (METH_FASTCALL | METH_KEYWORDS), PRECALL);
5089 STAT_INC(PRECALL, hit);
5090 SKIP_CALL();
5091 STACK_SHRINK(total_args);
5092 /* res = func(self, args, nargs, kwnames) */
5093 _PyCFunctionFastWithKeywords cfunc =
5094 (_PyCFunctionFastWithKeywords)(void(*)(void))
5095 PyCFunction_GET_FUNCTION(callable);
5096 PyObject *res = cfunc(
5097 PyCFunction_GET_SELF(callable),
5098 stack_pointer,
5099 total_args - KWNAMES_LEN(),
5100 call_shape.kwnames
5101 );
5102 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5103 call_shape.kwnames = NULL;
5104
5105 /* Free the arguments. */
5106 for (int i = 0; i < total_args; i++) {
5107 Py_DECREF(stack_pointer[i]);
5108 }
5109 STACK_SHRINK(2-is_meth);
5110 PUSH(res);
5111 Py_DECREF(callable);
5112 if (res == NULL) {
5113 goto error;
5114 }
5115 CHECK_EVAL_BREAKER();
5116 DISPATCH();
5117 }
5118
5119 TARGET(PRECALL_NO_KW_LEN) {
5120 assert(cframe.use_tracing == 0);
5121 assert(call_shape.kwnames == NULL);
5122 /* len(o) */
5123 int is_meth = is_method(stack_pointer, oparg);
5124 int total_args = oparg + is_meth;
5125 DEOPT_IF(total_args != 1, PRECALL);
5126 PyObject *callable = PEEK(total_args + 1);
5127 PyInterpreterState *interp = _PyInterpreterState_GET();
5128 DEOPT_IF(callable != interp->callable_cache.len, PRECALL);
5129 STAT_INC(PRECALL, hit);
5130 SKIP_CALL();
5131 PyObject *arg = TOP();
5132 Py_ssize_t len_i = PyObject_Length(arg);
5133 if (len_i < 0) {
5134 goto error;
5135 }
5136 PyObject *res = PyLong_FromSsize_t(len_i);
5137 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5138
5139 STACK_SHRINK(2-is_meth);
5140 SET_TOP(res);
5141 Py_DECREF(callable);
5142 Py_DECREF(arg);
5143 if (res == NULL) {
5144 goto error;
5145 }
5146 DISPATCH();
5147 }
5148
5149 TARGET(PRECALL_NO_KW_ISINSTANCE) {
5150 assert(cframe.use_tracing == 0);
5151 assert(call_shape.kwnames == NULL);
5152 /* isinstance(o, o2) */
5153 int is_meth = is_method(stack_pointer, oparg);
5154 int total_args = oparg + is_meth;
5155 PyObject *callable = PEEK(total_args + 1);
5156 DEOPT_IF(total_args != 2, PRECALL);
5157 PyInterpreterState *interp = _PyInterpreterState_GET();
5158 DEOPT_IF(callable != interp->callable_cache.isinstance, PRECALL);
5159 STAT_INC(PRECALL, hit);
5160 SKIP_CALL();
5161 PyObject *cls = POP();
5162 PyObject *inst = TOP();
5163 int retval = PyObject_IsInstance(inst, cls);
5164 if (retval < 0) {
5165 Py_DECREF(cls);
5166 goto error;
5167 }
5168 PyObject *res = PyBool_FromLong(retval);
5169 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5170
5171 STACK_SHRINK(2-is_meth);
5172 SET_TOP(res);
5173 Py_DECREF(inst);
5174 Py_DECREF(cls);
5175 Py_DECREF(callable);
5176 if (res == NULL) {
5177 goto error;
5178 }
5179 DISPATCH();
5180 }
5181
5182 TARGET(PRECALL_NO_KW_LIST_APPEND) {
5183 assert(cframe.use_tracing == 0);
5184 assert(call_shape.kwnames == NULL);
5185 assert(oparg == 1);
5186 PyObject *callable = PEEK(3);
5187 PyInterpreterState *interp = _PyInterpreterState_GET();
5188 DEOPT_IF(callable != interp->callable_cache.list_append, PRECALL);
5189 PyObject *list = SECOND();
5190 DEOPT_IF(!PyList_Check(list), PRECALL);
5191 STAT_INC(PRECALL, hit);
5192 PyObject *arg = POP();
5193 if (_PyList_AppendTakeRef((PyListObject *)list, arg) < 0) {
5194 goto error;
5195 }
5196 STACK_SHRINK(2);
5197 Py_DECREF(list);
5198 Py_DECREF(callable);
5199 // PRECALL + CALL + POP_TOP
5200 JUMPBY(INLINE_CACHE_ENTRIES_PRECALL + 1 + INLINE_CACHE_ENTRIES_CALL + 1);
5201 assert(_Py_OPCODE(next_instr[-1]) == POP_TOP);
5202 DISPATCH();
5203 }
5204
5205 TARGET(PRECALL_NO_KW_METHOD_DESCRIPTOR_O) {
5206 assert(call_shape.kwnames == NULL);
5207 int is_meth = is_method(stack_pointer, oparg);
5208 int total_args = oparg + is_meth;
5209 PyMethodDescrObject *callable =
5210 (PyMethodDescrObject *)PEEK(total_args + 1);
5211 DEOPT_IF(total_args != 2, PRECALL);
5212 DEOPT_IF(!Py_IS_TYPE(callable, &PyMethodDescr_Type), PRECALL);
5213 PyMethodDef *meth = callable->d_method;
5214 DEOPT_IF(meth->ml_flags != METH_O, PRECALL);
5215 PyObject *arg = TOP();
5216 PyObject *self = SECOND();
5217 DEOPT_IF(!Py_IS_TYPE(self, callable->d_common.d_type), PRECALL);
5218 STAT_INC(PRECALL, hit);
5219 SKIP_CALL();
5220 PyCFunction cfunc = meth->ml_meth;
5221 // This is slower but CPython promises to check all non-vectorcall
5222 // function calls.
5223 if (_Py_EnterRecursiveCallTstate(tstate, " while calling a Python object")) {
5224 goto error;
5225 }
5226 PyObject *res = _PyCFunction_TrampolineCall(cfunc, self, arg);
5227 _Py_LeaveRecursiveCallTstate(tstate);
5228 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5229 Py_DECREF(self);
5230 Py_DECREF(arg);
5231 STACK_SHRINK(oparg + 1);
5232 SET_TOP(res);
5233 Py_DECREF(callable);
5234 if (res == NULL) {
5235 goto error;
5236 }
5237 CHECK_EVAL_BREAKER();
5238 DISPATCH();
5239 }
5240
5241 TARGET(PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS) {
5242 int is_meth = is_method(stack_pointer, oparg);
5243 int total_args = oparg + is_meth;
5244 PyMethodDescrObject *callable =
5245 (PyMethodDescrObject *)PEEK(total_args + 1);
5246 DEOPT_IF(!Py_IS_TYPE(callable, &PyMethodDescr_Type), PRECALL);
5247 PyMethodDef *meth = callable->d_method;
5248 DEOPT_IF(meth->ml_flags != (METH_FASTCALL|METH_KEYWORDS), PRECALL);
5249 PyTypeObject *d_type = callable->d_common.d_type;
5250 PyObject *self = PEEK(total_args);
5251 DEOPT_IF(!Py_IS_TYPE(self, d_type), PRECALL);
5252 STAT_INC(PRECALL, hit);
5253 SKIP_CALL();
5254 int nargs = total_args-1;
5255 STACK_SHRINK(nargs);
5256 _PyCFunctionFastWithKeywords cfunc =
5257 (_PyCFunctionFastWithKeywords)(void(*)(void))meth->ml_meth;
5258 PyObject *res = cfunc(self, stack_pointer, nargs - KWNAMES_LEN(),
5259 call_shape.kwnames);
5260 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5261 call_shape.kwnames = NULL;
5262
5263 /* Free the arguments. */
5264 for (int i = 0; i < nargs; i++) {
5265 Py_DECREF(stack_pointer[i]);
5266 }
5267 Py_DECREF(self);
5268 STACK_SHRINK(2-is_meth);
5269 SET_TOP(res);
5270 Py_DECREF(callable);
5271 if (res == NULL) {
5272 goto error;
5273 }
5274 CHECK_EVAL_BREAKER();
5275 DISPATCH();
5276 }
5277
5278 TARGET(PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS) {
5279 assert(call_shape.kwnames == NULL);
5280 assert(oparg == 0 || oparg == 1);
5281 int is_meth = is_method(stack_pointer, oparg);
5282 int total_args = oparg + is_meth;
5283 DEOPT_IF(total_args != 1, PRECALL);
5284 PyMethodDescrObject *callable = (PyMethodDescrObject *)SECOND();
5285 DEOPT_IF(!Py_IS_TYPE(callable, &PyMethodDescr_Type), PRECALL);
5286 PyMethodDef *meth = callable->d_method;
5287 PyObject *self = TOP();
5288 DEOPT_IF(!Py_IS_TYPE(self, callable->d_common.d_type), PRECALL);
5289 DEOPT_IF(meth->ml_flags != METH_NOARGS, PRECALL);
5290 STAT_INC(PRECALL, hit);
5291 SKIP_CALL();
5292 PyCFunction cfunc = meth->ml_meth;
5293 // This is slower but CPython promises to check all non-vectorcall
5294 // function calls.
5295 if (_Py_EnterRecursiveCallTstate(tstate, " while calling a Python object")) {
5296 goto error;
5297 }
5298 PyObject *res = _PyCFunction_TrampolineCall(cfunc, self, NULL);
5299 _Py_LeaveRecursiveCallTstate(tstate);
5300 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5301 Py_DECREF(self);
5302 STACK_SHRINK(oparg + 1);
5303 SET_TOP(res);
5304 Py_DECREF(callable);
5305 if (res == NULL) {
5306 goto error;
5307 }
5308 CHECK_EVAL_BREAKER();
5309 DISPATCH();
5310 }
5311
5312 TARGET(PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST) {
5313 assert(call_shape.kwnames == NULL);
5314 int is_meth = is_method(stack_pointer, oparg);
5315 int total_args = oparg + is_meth;
5316 PyMethodDescrObject *callable =
5317 (PyMethodDescrObject *)PEEK(total_args + 1);
5318 /* Builtin METH_FASTCALL methods, without keywords */
5319 DEOPT_IF(!Py_IS_TYPE(callable, &PyMethodDescr_Type), PRECALL);
5320 PyMethodDef *meth = callable->d_method;
5321 DEOPT_IF(meth->ml_flags != METH_FASTCALL, PRECALL);
5322 PyObject *self = PEEK(total_args);
5323 DEOPT_IF(!Py_IS_TYPE(self, callable->d_common.d_type), PRECALL);
5324 STAT_INC(PRECALL, hit);
5325 SKIP_CALL();
5326 _PyCFunctionFast cfunc =
5327 (_PyCFunctionFast)(void(*)(void))meth->ml_meth;
5328 int nargs = total_args-1;
5329 STACK_SHRINK(nargs);
5330 PyObject *res = cfunc(self, stack_pointer, nargs);
5331 assert((res != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
5332 /* Clear the stack of the arguments. */
5333 for (int i = 0; i < nargs; i++) {
5334 Py_DECREF(stack_pointer[i]);
5335 }
5336 Py_DECREF(self);
5337 STACK_SHRINK(2-is_meth);
5338 SET_TOP(res);
5339 Py_DECREF(callable);
5340 if (res == NULL) {
5341 goto error;
5342 }
5343 CHECK_EVAL_BREAKER();
5344 DISPATCH();
5345 }
5346
5347 TARGET(CALL_FUNCTION_EX) {
5348 PREDICTED(CALL_FUNCTION_EX);
5349 PyObject *func, *callargs, *kwargs = NULL, *result;
5350 if (oparg & 0x01) {
5351 kwargs = POP();
5352 if (!PyDict_CheckExact(kwargs)) {
5353 PyObject *d = PyDict_New();
5354 if (d == NULL)
5355 goto error;
5356 if (_PyDict_MergeEx(d, kwargs, 2) < 0) {
5357 Py_DECREF(d);
5358 format_kwargs_error(tstate, SECOND(), kwargs);
5359 Py_DECREF(kwargs);
5360 goto error;
5361 }
5362 Py_DECREF(kwargs);
5363 kwargs = d;
5364 }
5365 assert(PyDict_CheckExact(kwargs));
5366 }
5367 callargs = POP();
5368 func = TOP();
5369 if (!PyTuple_CheckExact(callargs)) {
5370 if (check_args_iterable(tstate, func, callargs) < 0) {
5371 Py_DECREF(callargs);
5372 goto error;
5373 }
5374 Py_SETREF(callargs, PySequence_Tuple(callargs));
5375 if (callargs == NULL) {
5376 goto error;
5377 }
5378 }
5379 assert(PyTuple_CheckExact(callargs));
5380
5381 result = do_call_core(tstate, func, callargs, kwargs, cframe.use_tracing);
5382 Py_DECREF(func);
5383 Py_DECREF(callargs);
5384 Py_XDECREF(kwargs);
5385
5386 STACK_SHRINK(1);
5387 assert(TOP() == NULL);
5388 SET_TOP(result);
5389 if (result == NULL) {
5390 goto error;
5391 }
5392 CHECK_EVAL_BREAKER();
5393 DISPATCH();
5394 }
5395
5396 TARGET(MAKE_FUNCTION) {
5397 PyObject *codeobj = POP();
5398 PyFunctionObject *func = (PyFunctionObject *)
5399 PyFunction_New(codeobj, GLOBALS());
5400
5401 Py_DECREF(codeobj);
5402 if (func == NULL) {
5403 goto error;
5404 }
5405
5406 if (oparg & 0x08) {
5407 assert(PyTuple_CheckExact(TOP()));
5408 func->func_closure = POP();
5409 }
5410 if (oparg & 0x04) {
5411 assert(PyTuple_CheckExact(TOP()));
5412 func->func_annotations = POP();
5413 }
5414 if (oparg & 0x02) {
5415 assert(PyDict_CheckExact(TOP()));
5416 func->func_kwdefaults = POP();
5417 }
5418 if (oparg & 0x01) {
5419 assert(PyTuple_CheckExact(TOP()));
5420 func->func_defaults = POP();
5421 }
5422
5423 PUSH((PyObject *)func);
5424 DISPATCH();
5425 }
5426
5427 TARGET(RETURN_GENERATOR) {
5428 PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(frame->f_func);
5429 if (gen == NULL) {
5430 goto error;
5431 }
5432 assert(EMPTY());
5433 _PyFrame_SetStackPointer(frame, stack_pointer);
5434 _PyInterpreterFrame *gen_frame = (_PyInterpreterFrame *)gen->gi_iframe;
5435 _PyFrame_Copy(frame, gen_frame);
5436 assert(frame->frame_obj == NULL);
5437 gen->gi_frame_state = FRAME_CREATED;
5438 gen_frame->owner = FRAME_OWNED_BY_GENERATOR;
5439 _Py_LeaveRecursiveCallTstate(tstate);
5440 if (!frame->is_entry) {
5441 _PyInterpreterFrame *prev = frame->previous;
5442 _PyThreadState_PopFrame(tstate, frame);
5443 frame = cframe.current_frame = prev;
5444 _PyFrame_StackPush(frame, (PyObject *)gen);
5445 goto resume_frame;
5446 }
5447 /* Make sure that frame is in a valid state */
5448 frame->stacktop = 0;
5449 frame->f_locals = NULL;
5450 Py_INCREF(frame->f_func);
5451 Py_INCREF(frame->f_code);
5452 /* Restore previous cframe and return. */
5453 tstate->cframe = cframe.previous;
5454 tstate->cframe->use_tracing = cframe.use_tracing;
5455 assert(tstate->cframe->current_frame == frame->previous);
5456 assert(!_PyErr_Occurred(tstate));
5457 return (PyObject *)gen;
5458 }
5459
5460 TARGET(BUILD_SLICE) {
5461 PyObject *start, *stop, *step, *slice;
5462 if (oparg == 3)
5463 step = POP();
5464 else
5465 step = NULL;
5466 stop = POP();
5467 start = TOP();
5468 slice = PySlice_New(start, stop, step);
5469 Py_DECREF(start);
5470 Py_DECREF(stop);
5471 Py_XDECREF(step);
5472 SET_TOP(slice);
5473 if (slice == NULL)
5474 goto error;
5475 DISPATCH();
5476 }
5477
5478 TARGET(FORMAT_VALUE) {
5479 /* Handles f-string value formatting. */
5480 PyObject *result;
5481 PyObject *fmt_spec;
5482 PyObject *value;
5483 PyObject *(*conv_fn)(PyObject *);
5484 int which_conversion = oparg & FVC_MASK;
5485 int have_fmt_spec = (oparg & FVS_MASK) == FVS_HAVE_SPEC;
5486
5487 fmt_spec = have_fmt_spec ? POP() : NULL;
5488 value = POP();
5489
5490 /* See if any conversion is specified. */
5491 switch (which_conversion) {
5492 case FVC_NONE: conv_fn = NULL; break;
5493 case FVC_STR: conv_fn = PyObject_Str; break;
5494 case FVC_REPR: conv_fn = PyObject_Repr; break;
5495 case FVC_ASCII: conv_fn = PyObject_ASCII; break;
5496 default:
5497 _PyErr_Format(tstate, PyExc_SystemError,
5498 "unexpected conversion flag %d",
5499 which_conversion);
5500 goto error;
5501 }
5502
5503 /* If there's a conversion function, call it and replace
5504 value with that result. Otherwise, just use value,
5505 without conversion. */
5506 if (conv_fn != NULL) {
5507 result = conv_fn(value);
5508 Py_DECREF(value);
5509 if (result == NULL) {
5510 Py_XDECREF(fmt_spec);
5511 goto error;
5512 }
5513 value = result;
5514 }
5515
5516 /* If value is a unicode object, and there's no fmt_spec,
5517 then we know the result of format(value) is value
5518 itself. In that case, skip calling format(). I plan to
5519 move this optimization in to PyObject_Format()
5520 itself. */
5521 if (PyUnicode_CheckExact(value) && fmt_spec == NULL) {
5522 /* Do nothing, just transfer ownership to result. */
5523 result = value;
5524 } else {
5525 /* Actually call format(). */
5526 result = PyObject_Format(value, fmt_spec);
5527 Py_DECREF(value);
5528 Py_XDECREF(fmt_spec);
5529 if (result == NULL) {
5530 goto error;
5531 }
5532 }
5533
5534 PUSH(result);
5535 DISPATCH();
5536 }
5537
5538 TARGET(COPY) {
5539 assert(oparg != 0);
5540 PyObject *peek = PEEK(oparg);
5541 Py_INCREF(peek);
5542 PUSH(peek);
5543 DISPATCH();
5544 }
5545
5546 TARGET(BINARY_OP) {
5547 PREDICTED(BINARY_OP);
5548 PyObject *rhs = POP();
5549 PyObject *lhs = TOP();
5550 assert(0 <= oparg);
5551 assert((unsigned)oparg < Py_ARRAY_LENGTH(binary_ops));
5552 assert(binary_ops[oparg]);
5553 PyObject *res = binary_ops[oparg](lhs, rhs);
5554 Py_DECREF(lhs);
5555 Py_DECREF(rhs);
5556 SET_TOP(res);
5557 if (res == NULL) {
5558 goto error;
5559 }
5560 JUMPBY(INLINE_CACHE_ENTRIES_BINARY_OP);
5561 DISPATCH();
5562 }
5563
5564 TARGET(BINARY_OP_ADAPTIVE) {
5565 assert(cframe.use_tracing == 0);
5566 _PyBinaryOpCache *cache = (_PyBinaryOpCache *)next_instr;
5567 if (ADAPTIVE_COUNTER_IS_ZERO(cache)) {
5568 PyObject *lhs = SECOND();
5569 PyObject *rhs = TOP();
5570 next_instr--;
5571 _Py_Specialize_BinaryOp(lhs, rhs, next_instr, oparg, &GETLOCAL(0));
5572 DISPATCH_SAME_OPARG();
5573 }
5574 else {
5575 STAT_INC(BINARY_OP, deferred);
5576 DECREMENT_ADAPTIVE_COUNTER(cache);
5577 JUMP_TO_INSTRUCTION(BINARY_OP);
5578 }
5579 }
5580
5581 TARGET(SWAP) {
5582 assert(oparg != 0);
5583 PyObject *top = TOP();
5584 SET_TOP(PEEK(oparg));
5585 PEEK(oparg) = top;
5586 DISPATCH();
5587 }
5588
5589 TARGET(EXTENDED_ARG) {
5590 assert(oparg);
5591 oparg <<= 8;
5592 oparg |= _Py_OPARG(*next_instr);
5593 // We might be tracing. To avoid breaking tracing guarantees in
5594 // quickened instructions, always deoptimize the next opcode:
5595 opcode = _PyOpcode_Deopt[_Py_OPCODE(*next_instr)];
5596 PRE_DISPATCH_GOTO();
5597 // CPython hasn't traced the following instruction historically
5598 // (DO_TRACING would clobber our extended oparg anyways), so just
5599 // skip our usual cframe.use_tracing check before dispatch. Also,
5600 // make sure the next instruction isn't a RESUME, since that needs
5601 // to trace properly (and shouldn't have an extended arg anyways):
5602 assert(opcode != RESUME);
5603 DISPATCH_GOTO();
5604 }
5605
5606 TARGET(EXTENDED_ARG_QUICK) {
5607 assert(cframe.use_tracing == 0);
5608 assert(oparg);
5609 int oldoparg = oparg;
5610 NEXTOPARG();
5611 oparg |= oldoparg << 8;
5612 DISPATCH_GOTO();
5613 }
5614
5615 TARGET(CACHE) {
5616 Py_UNREACHABLE();
5617 }
5618
5619 #if USE_COMPUTED_GOTOS
5620 TARGET_DO_TRACING:
5621 #else
5622 case DO_TRACING:
5623 #endif
5624 {
5625 assert(cframe.use_tracing);
5626 assert(tstate->tracing == 0);
5627 if (INSTR_OFFSET() >= frame->f_code->_co_firsttraceable) {
5628 int instr_prev = _PyInterpreterFrame_LASTI(frame);
5629 frame->prev_instr = next_instr;
5630 TRACING_NEXTOPARG();
5631 if (opcode == RESUME) {
5632 if (oparg < 2) {
5633 CHECK_EVAL_BREAKER();
5634 }
5635 /* Call tracing */
5636 TRACE_FUNCTION_ENTRY();
5637 DTRACE_FUNCTION_ENTRY();
5638 }
5639 else {
5640 /* line-by-line tracing support */
5641 if (PyDTrace_LINE_ENABLED()) {
5642 maybe_dtrace_line(frame, &tstate->trace_info, instr_prev);
5643 }
5644
5645 if (cframe.use_tracing &&
5646 tstate->c_tracefunc != NULL && !tstate->tracing) {
5647 int err;
5648 /* see maybe_call_line_trace()
5649 for expository comments */
5650 _PyFrame_SetStackPointer(frame, stack_pointer);
5651
5652 err = maybe_call_line_trace(tstate->c_tracefunc,
5653 tstate->c_traceobj,
5654 tstate, frame, instr_prev);
5655 // Reload possibly changed frame fields:
5656 stack_pointer = _PyFrame_GetStackPointer(frame);
5657 frame->stacktop = -1;
5658 // next_instr is only reloaded if tracing *does not* raise.
5659 // This is consistent with the behavior of older Python
5660 // versions. If a trace function sets a new f_lineno and
5661 // *then* raises, we use the *old* location when searching
5662 // for an exception handler, displaying the traceback, and
5663 // so on:
5664 if (err) {
5665 // next_instr wasn't incremented at the start of this
5666 // instruction. Increment it before handling the error,
5667 // so that it looks the same as a "normal" instruction:
5668 next_instr++;
5669 goto error;
5670 }
5671 // Reload next_instr. Don't increment it, though, since
5672 // we're going to re-dispatch to the "true" instruction now:
5673 next_instr = frame->prev_instr;
5674 }
5675 }
5676 }
5677 TRACING_NEXTOPARG();
5678 PRE_DISPATCH_GOTO();
5679 DISPATCH_GOTO();
5680 }
5681
5682 #if USE_COMPUTED_GOTOS
5683 _unknown_opcode:
5684 #else
5685 EXTRA_CASES // From opcode.h, a 'case' for each unused opcode
5686 #endif
5687 /* Tell C compilers not to hold the opcode variable in the loop.
5688 next_instr points the current instruction without TARGET(). */
5689 opcode = _Py_OPCODE(*next_instr);
5690 fprintf(stderr, "XXX lineno: %d, opcode: %d\n",
5691 _PyInterpreterFrame_GetLine(frame), opcode);
5692 _PyErr_SetString(tstate, PyExc_SystemError, "unknown opcode");
5693 goto error;
5694
5695 } /* End instructions */
5696
5697 /* This should never be reached. Every opcode should end with DISPATCH()
5698 or goto error. */
5699 Py_UNREACHABLE();
5700
5701 /* Specialization misses */
5702
5703 miss:
5704 {
5705 STAT_INC(opcode, miss);
5706 opcode = _PyOpcode_Deopt[opcode];
5707 STAT_INC(opcode, miss);
5708 /* The counter is always the first cache entry: */
5709 _Py_CODEUNIT *counter = (_Py_CODEUNIT *)next_instr;
5710 *counter -= 1;
5711 if (*counter == 0) {
5712 int adaptive_opcode = _PyOpcode_Adaptive[opcode];
5713 assert(adaptive_opcode);
5714 _Py_SET_OPCODE(next_instr[-1], adaptive_opcode);
5715 STAT_INC(opcode, deopt);
5716 *counter = adaptive_counter_start();
5717 }
5718 next_instr--;
5719 DISPATCH_GOTO();
5720 }
5721
5722 binary_subscr_dict_error:
5723 {
5724 PyObject *sub = POP();
5725 if (!_PyErr_Occurred(tstate)) {
5726 _PyErr_SetKeyError(sub);
5727 }
5728 Py_DECREF(sub);
5729 goto error;
5730 }
5731
5732 unbound_local_error:
5733 {
5734 format_exc_check_arg(tstate, PyExc_UnboundLocalError,
5735 UNBOUNDLOCAL_ERROR_MSG,
5736 PyTuple_GetItem(frame->f_code->co_localsplusnames, oparg)
5737 );
5738 goto error;
5739 }
5740
5741 error:
5742 call_shape.kwnames = NULL;
5743 /* Double-check exception status. */
5744 #ifdef NDEBUG
5745 if (!_PyErr_Occurred(tstate)) {
5746 _PyErr_SetString(tstate, PyExc_SystemError,
5747 "error return without exception set");
5748 }
5749 #else
5750 assert(_PyErr_Occurred(tstate));
5751 #endif
5752
5753 /* Log traceback info. */
5754 if (!_PyFrame_IsIncomplete(frame)) {
5755 PyFrameObject *f = _PyFrame_GetFrameObject(frame);
5756 if (f != NULL) {
5757 PyTraceBack_Here(f);
5758 }
5759 }
5760
5761 if (tstate->c_tracefunc != NULL) {
5762 /* Make sure state is set to FRAME_UNWINDING for tracing */
5763 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj,
5764 tstate, frame);
5765 }
5766
5767 exception_unwind:
5768 {
5769 /* We can't use frame->f_lasti here, as RERAISE may have set it */
5770 int offset = INSTR_OFFSET()-1;
5771 int level, handler, lasti;
5772 if (get_exception_handler(frame->f_code, offset, &level, &handler, &lasti) == 0) {
5773 // No handlers, so exit.
5774 assert(_PyErr_Occurred(tstate));
5775
5776 /* Pop remaining stack entries. */
5777 PyObject **stackbase = _PyFrame_Stackbase(frame);
5778 while (stack_pointer > stackbase) {
5779 PyObject *o = POP();
5780 Py_XDECREF(o);
5781 }
5782 assert(STACK_LEVEL() == 0);
5783 _PyFrame_SetStackPointer(frame, stack_pointer);
5784 TRACE_FUNCTION_UNWIND();
5785 DTRACE_FUNCTION_EXIT();
5786 goto exit_unwind;
5787 }
5788
5789 assert(STACK_LEVEL() >= level);
5790 PyObject **new_top = _PyFrame_Stackbase(frame) + level;
5791 while (stack_pointer > new_top) {
5792 PyObject *v = POP();
5793 Py_XDECREF(v);
5794 }
5795 PyObject *exc, *val, *tb;
5796 if (lasti) {
5797 int frame_lasti = _PyInterpreterFrame_LASTI(frame);
5798 PyObject *lasti = PyLong_FromLong(frame_lasti);
5799 if (lasti == NULL) {
5800 goto exception_unwind;
5801 }
5802 PUSH(lasti);
5803 }
5804 _PyErr_Fetch(tstate, &exc, &val, &tb);
5805 /* Make the raw exception data
5806 available to the handler,
5807 so a program can emulate the
5808 Python main loop. */
5809 _PyErr_NormalizeException(tstate, &exc, &val, &tb);
5810 if (tb != NULL)
5811 PyException_SetTraceback(val, tb);
5812 else
5813 PyException_SetTraceback(val, Py_None);
5814 Py_XDECREF(tb);
5815 Py_XDECREF(exc);
5816 PUSH(val);
5817 JUMPTO(handler);
5818 /* Resume normal execution */
5819 DISPATCH();
5820 }
5821 }
5822
5823 exit_unwind:
5824 assert(_PyErr_Occurred(tstate));
5825 _Py_LeaveRecursiveCallTstate(tstate);
5826 if (frame->is_entry) {
5827 /* Restore previous cframe and exit */
5828 tstate->cframe = cframe.previous;
5829 tstate->cframe->use_tracing = cframe.use_tracing;
5830 assert(tstate->cframe->current_frame == frame->previous);
5831 return NULL;
5832 }
5833 // GH-99729: We need to unlink the frame *before* clearing it:
5834 _PyInterpreterFrame *dying = frame;
5835 frame = cframe.current_frame = dying->previous;
5836 _PyEvalFrameClearAndPop(tstate, dying);
5837
5838 resume_with_error:
5839 SET_LOCALS_FROM_FRAME();
5840 goto error;
5841
5842 }
5843
5844 static void
5845 format_missing(PyThreadState *tstate, const char *kind,
5846 PyCodeObject *co, PyObject *names, PyObject *qualname)
5847 {
5848 int err;
5849 Py_ssize_t len = PyList_GET_SIZE(names);
5850 PyObject *name_str, *comma, *tail, *tmp;
5851
5852 assert(PyList_CheckExact(names));
5853 assert(len >= 1);
5854 /* Deal with the joys of natural language. */
5855 switch (len) {
5856 case 1:
5857 name_str = PyList_GET_ITEM(names, 0);
5858 Py_INCREF(name_str);
5859 break;
5860 case 2:
5861 name_str = PyUnicode_FromFormat("%U and %U",
5862 PyList_GET_ITEM(names, len - 2),
5863 PyList_GET_ITEM(names, len - 1));
5864 break;
5865 default:
5866 tail = PyUnicode_FromFormat(", %U, and %U",
5867 PyList_GET_ITEM(names, len - 2),
5868 PyList_GET_ITEM(names, len - 1));
5869 if (tail == NULL)
5870 return;
5871 /* Chop off the last two objects in the list. This shouldn't actually
5872 fail, but we can't be too careful. */
5873 err = PyList_SetSlice(names, len - 2, len, NULL);
5874 if (err == -1) {
5875 Py_DECREF(tail);
5876 return;
5877 }
5878 /* Stitch everything up into a nice comma-separated list. */
5879 comma = PyUnicode_FromString(", ");
5880 if (comma == NULL) {
5881 Py_DECREF(tail);
5882 return;
5883 }
5884 tmp = PyUnicode_Join(comma, names);
5885 Py_DECREF(comma);
5886 if (tmp == NULL) {
5887 Py_DECREF(tail);
5888 return;
5889 }
5890 name_str = PyUnicode_Concat(tmp, tail);
5891 Py_DECREF(tmp);
5892 Py_DECREF(tail);
5893 break;
5894 }
5895 if (name_str == NULL)
5896 return;
5897 _PyErr_Format(tstate, PyExc_TypeError,
5898 "%U() missing %i required %s argument%s: %U",
5899 qualname,
5900 len,
5901 kind,
5902 len == 1 ? "" : "s",
5903 name_str);
5904 Py_DECREF(name_str);
5905 }
5906
5907 static void
5908 missing_arguments(PyThreadState *tstate, PyCodeObject *co,
5909 Py_ssize_t missing, Py_ssize_t defcount,
5910 PyObject **localsplus, PyObject *qualname)
5911 {
5912 Py_ssize_t i, j = 0;
5913 Py_ssize_t start, end;
5914 int positional = (defcount != -1);
5915 const char *kind = positional ? "positional" : "keyword-only";
5916 PyObject *missing_names;
5917
5918 /* Compute the names of the arguments that are missing. */
5919 missing_names = PyList_New(missing);
5920 if (missing_names == NULL)
5921 return;
5922 if (positional) {
5923 start = 0;
5924 end = co->co_argcount - defcount;
5925 }
5926 else {
5927 start = co->co_argcount;
5928 end = start + co->co_kwonlyargcount;
5929 }
5930 for (i = start; i < end; i++) {
5931 if (localsplus[i] == NULL) {
5932 PyObject *raw = PyTuple_GET_ITEM(co->co_localsplusnames, i);
5933 PyObject *name = PyObject_Repr(raw);
5934 if (name == NULL) {
5935 Py_DECREF(missing_names);
5936 return;
5937 }
5938 PyList_SET_ITEM(missing_names, j++, name);
5939 }
5940 }
5941 assert(j == missing);
5942 format_missing(tstate, kind, co, missing_names, qualname);
5943 Py_DECREF(missing_names);
5944 }
5945
5946 static void
5947 too_many_positional(PyThreadState *tstate, PyCodeObject *co,
5948 Py_ssize_t given, PyObject *defaults,
5949 PyObject **localsplus, PyObject *qualname)
5950 {
5951 int plural;
5952 Py_ssize_t kwonly_given = 0;
5953 Py_ssize_t i;
5954 PyObject *sig, *kwonly_sig;
5955 Py_ssize_t co_argcount = co->co_argcount;
5956
5957 assert((co->co_flags & CO_VARARGS) == 0);
5958 /* Count missing keyword-only args. */
5959 for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
5960 if (localsplus[i] != NULL) {
5961 kwonly_given++;
5962 }
5963 }
5964 Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
5965 if (defcount) {
5966 Py_ssize_t atleast = co_argcount - defcount;
5967 plural = 1;
5968 sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
5969 }
5970 else {
5971 plural = (co_argcount != 1);
5972 sig = PyUnicode_FromFormat("%zd", co_argcount);
5973 }
5974 if (sig == NULL)
5975 return;
5976 if (kwonly_given) {
5977 const char *format = " positional argument%s (and %zd keyword-only argument%s)";
5978 kwonly_sig = PyUnicode_FromFormat(format,
5979 given != 1 ? "s" : "",
5980 kwonly_given,
5981 kwonly_given != 1 ? "s" : "");
5982 if (kwonly_sig == NULL) {
5983 Py_DECREF(sig);
5984 return;
5985 }
5986 }
5987 else {
5988 /* This will not fail. */
5989 kwonly_sig = PyUnicode_FromString("");
5990 assert(kwonly_sig != NULL);
5991 }
5992 _PyErr_Format(tstate, PyExc_TypeError,
5993 "%U() takes %U positional argument%s but %zd%U %s given",
5994 qualname,
5995 sig,
5996 plural ? "s" : "",
5997 given,
5998 kwonly_sig,
5999 given == 1 && !kwonly_given ? "was" : "were");
6000 Py_DECREF(sig);
6001 Py_DECREF(kwonly_sig);
6002 }
6003
6004 static int
6005 positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
6006 Py_ssize_t kwcount, PyObject* kwnames,
6007 PyObject *qualname)
6008 {
6009 int posonly_conflicts = 0;
6010 PyObject* posonly_names = PyList_New(0);
6011 if (posonly_names == NULL) {
6012 goto fail;
6013 }
6014 for(int k=0; k < co->co_posonlyargcount; k++){
6015 PyObject* posonly_name = PyTuple_GET_ITEM(co->co_localsplusnames, k);
6016
6017 for (int k2=0; k2<kwcount; k2++){
6018 /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
6019 PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
6020 if (kwname == posonly_name){
6021 if(PyList_Append(posonly_names, kwname) != 0) {
6022 goto fail;
6023 }
6024 posonly_conflicts++;
6025 continue;
6026 }
6027
6028 int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
6029
6030 if ( cmp > 0) {
6031 if(PyList_Append(posonly_names, kwname) != 0) {
6032 goto fail;
6033 }
6034 posonly_conflicts++;
6035 } else if (cmp < 0) {
6036 goto fail;
6037 }
6038
6039 }
6040 }
6041 if (posonly_conflicts) {
6042 PyObject* comma = PyUnicode_FromString(", ");
6043 if (comma == NULL) {
6044 goto fail;
6045 }
6046 PyObject* error_names = PyUnicode_Join(comma, posonly_names);
6047 Py_DECREF(comma);
6048 if (error_names == NULL) {
6049 goto fail;
6050 }
6051 _PyErr_Format(tstate, PyExc_TypeError,
6052 "%U() got some positional-only arguments passed"
6053 " as keyword arguments: '%U'",
6054 qualname, error_names);
6055 Py_DECREF(error_names);
6056 goto fail;
6057 }
6058
6059 Py_DECREF(posonly_names);
6060 return 0;
6061
6062 fail:
6063 Py_XDECREF(posonly_names);
6064 return 1;
6065
6066 }
6067
6068
6069 static inline unsigned char *
6070 scan_back_to_entry_start(unsigned char *p) {
6071 for (; (p[0]&128) == 0; p--);
6072 return p;
6073 }
6074
6075 static inline unsigned char *
6076 skip_to_next_entry(unsigned char *p, unsigned char *end) {
6077 while (p < end && ((p[0] & 128) == 0)) {
6078 p++;
6079 }
6080 return p;
6081 }
6082
6083
6084 #define MAX_LINEAR_SEARCH 40
6085
6086 static int
6087 get_exception_handler(PyCodeObject *code, int index, int *level, int *handler, int *lasti)
6088 {
6089 unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code->co_exceptiontable);
6090 unsigned char *end = start + PyBytes_GET_SIZE(code->co_exceptiontable);
6091 /* Invariants:
6092 * start_table == end_table OR
6093 * start_table points to a legal entry and end_table points
6094 * beyond the table or to a legal entry that is after index.
6095 */
6096 if (end - start > MAX_LINEAR_SEARCH) {
6097 int offset;
6098 parse_varint(start, &offset);
6099 if (offset > index) {
6100 return 0;
6101 }
6102 do {
6103 unsigned char * mid = start + ((end-start)>>1);
6104 mid = scan_back_to_entry_start(mid);
6105 parse_varint(mid, &offset);
6106 if (offset > index) {
6107 end = mid;
6108 }
6109 else {
6110 start = mid;
6111 }
6112
6113 } while (end - start > MAX_LINEAR_SEARCH);
6114 }
6115 unsigned char *scan = start;
6116 while (scan < end) {
6117 int start_offset, size;
6118 scan = parse_varint(scan, &start_offset);
6119 if (start_offset > index) {
6120 break;
6121 }
6122 scan = parse_varint(scan, &size);
6123 if (start_offset + size > index) {
6124 scan = parse_varint(scan, handler);
6125 int depth_and_lasti;
6126 parse_varint(scan, &depth_and_lasti);
6127 *level = depth_and_lasti >> 1;
6128 *lasti = depth_and_lasti & 1;
6129 return 1;
6130 }
6131 scan = skip_to_next_entry(scan, end);
6132 }
6133 return 0;
6134 }
6135
6136 static int
6137 initialize_locals(PyThreadState *tstate, PyFunctionObject *func,
6138 PyObject **localsplus, PyObject *const *args,
6139 Py_ssize_t argcount, PyObject *kwnames)
6140 {
6141 PyCodeObject *co = (PyCodeObject*)func->func_code;
6142 const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
6143
6144 /* Create a dictionary for keyword parameters (**kwags) */
6145 PyObject *kwdict;
6146 Py_ssize_t i;
6147 if (co->co_flags & CO_VARKEYWORDS) {
6148 kwdict = PyDict_New();
6149 if (kwdict == NULL) {
6150 goto fail_pre_positional;
6151 }
6152 i = total_args;
6153 if (co->co_flags & CO_VARARGS) {
6154 i++;
6155 }
6156 assert(localsplus[i] == NULL);
6157 localsplus[i] = kwdict;
6158 }
6159 else {
6160 kwdict = NULL;
6161 }
6162
6163 /* Copy all positional arguments into local variables */
6164 Py_ssize_t j, n;
6165 if (argcount > co->co_argcount) {
6166 n = co->co_argcount;
6167 }
6168 else {
6169 n = argcount;
6170 }
6171 for (j = 0; j < n; j++) {
6172 PyObject *x = args[j];
6173 assert(localsplus[j] == NULL);
6174 localsplus[j] = x;
6175 }
6176
6177 /* Pack other positional arguments into the *args argument */
6178 if (co->co_flags & CO_VARARGS) {
6179 PyObject *u = NULL;
6180 if (argcount == n) {
6181 u = Py_NewRef(&_Py_SINGLETON(tuple_empty));
6182 }
6183 else {
6184 assert(args != NULL);
6185 u = _PyTuple_FromArraySteal(args + n, argcount - n);
6186 }
6187 if (u == NULL) {
6188 goto fail_post_positional;
6189 }
6190 assert(localsplus[total_args] == NULL);
6191 localsplus[total_args] = u;
6192 }
6193 else if (argcount > n) {
6194 /* Too many postional args. Error is reported later */
6195 for (j = n; j < argcount; j++) {
6196 Py_DECREF(args[j]);
6197 }
6198 }
6199
6200 /* Handle keyword arguments */
6201 if (kwnames != NULL) {
6202 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
6203 for (i = 0; i < kwcount; i++) {
6204 PyObject **co_varnames;
6205 PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
6206 PyObject *value = args[i+argcount];
6207 Py_ssize_t j;
6208
6209 if (keyword == NULL || !PyUnicode_Check(keyword)) {
6210 _PyErr_Format(tstate, PyExc_TypeError,
6211 "%U() keywords must be strings",
6212 func->func_qualname);
6213 goto kw_fail;
6214 }
6215
6216 /* Speed hack: do raw pointer compares. As names are
6217 normally interned this should almost always hit. */
6218 co_varnames = ((PyTupleObject *)(co->co_localsplusnames))->ob_item;
6219 for (j = co->co_posonlyargcount; j < total_args; j++) {
6220 PyObject *varname = co_varnames[j];
6221 if (varname == keyword) {
6222 goto kw_found;
6223 }
6224 }
6225
6226 /* Slow fallback, just in case */
6227 for (j = co->co_posonlyargcount; j < total_args; j++) {
6228 PyObject *varname = co_varnames[j];
6229 int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
6230 if (cmp > 0) {
6231 goto kw_found;
6232 }
6233 else if (cmp < 0) {
6234 goto kw_fail;
6235 }
6236 }
6237
6238 assert(j >= total_args);
6239 if (kwdict == NULL) {
6240
6241 if (co->co_posonlyargcount
6242 && positional_only_passed_as_keyword(tstate, co,
6243 kwcount, kwnames,
6244 func->func_qualname))
6245 {
6246 goto kw_fail;
6247 }
6248
6249 _PyErr_Format(tstate, PyExc_TypeError,
6250 "%U() got an unexpected keyword argument '%S'",
6251 func->func_qualname, keyword);
6252 goto kw_fail;
6253 }
6254
6255 if (PyDict_SetItem(kwdict, keyword, value) == -1) {
6256 goto kw_fail;
6257 }
6258 Py_DECREF(value);
6259 continue;
6260
6261 kw_fail:
6262 for (;i < kwcount; i++) {
6263 PyObject *value = args[i+argcount];
6264 Py_DECREF(value);
6265 }
6266 goto fail_post_args;
6267
6268 kw_found:
6269 if (localsplus[j] != NULL) {
6270 _PyErr_Format(tstate, PyExc_TypeError,
6271 "%U() got multiple values for argument '%S'",
6272 func->func_qualname, keyword);
6273 goto kw_fail;
6274 }
6275 localsplus[j] = value;
6276 }
6277 }
6278
6279 /* Check the number of positional arguments */
6280 if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
6281 too_many_positional(tstate, co, argcount, func->func_defaults, localsplus,
6282 func->func_qualname);
6283 goto fail_post_args;
6284 }
6285
6286 /* Add missing positional arguments (copy default values from defs) */
6287 if (argcount < co->co_argcount) {
6288 Py_ssize_t defcount = func->func_defaults == NULL ? 0 : PyTuple_GET_SIZE(func->func_defaults);
6289 Py_ssize_t m = co->co_argcount - defcount;
6290 Py_ssize_t missing = 0;
6291 for (i = argcount; i < m; i++) {
6292 if (localsplus[i] == NULL) {
6293 missing++;
6294 }
6295 }
6296 if (missing) {
6297 missing_arguments(tstate, co, missing, defcount, localsplus,
6298 func->func_qualname);
6299 goto fail_post_args;
6300 }
6301 if (n > m)
6302 i = n - m;
6303 else
6304 i = 0;
6305 if (defcount) {
6306 PyObject **defs = &PyTuple_GET_ITEM(func->func_defaults, 0);
6307 for (; i < defcount; i++) {
6308 if (localsplus[m+i] == NULL) {
6309 PyObject *def = defs[i];
6310 Py_INCREF(def);
6311 localsplus[m+i] = def;
6312 }
6313 }
6314 }
6315 }
6316
6317 /* Add missing keyword arguments (copy default values from kwdefs) */
6318 if (co->co_kwonlyargcount > 0) {
6319 Py_ssize_t missing = 0;
6320 for (i = co->co_argcount; i < total_args; i++) {
6321 if (localsplus[i] != NULL)
6322 continue;
6323 PyObject *varname = PyTuple_GET_ITEM(co->co_localsplusnames, i);
6324 if (func->func_kwdefaults != NULL) {
6325 PyObject *def = PyDict_GetItemWithError(func->func_kwdefaults, varname);
6326 if (def) {
6327 Py_INCREF(def);
6328 localsplus[i] = def;
6329 continue;
6330 }
6331 else if (_PyErr_Occurred(tstate)) {
6332 goto fail_post_args;
6333 }
6334 }
6335 missing++;
6336 }
6337 if (missing) {
6338 missing_arguments(tstate, co, missing, -1, localsplus,
6339 func->func_qualname);
6340 goto fail_post_args;
6341 }
6342 }
6343 return 0;
6344
6345 fail_pre_positional:
6346 for (j = 0; j < argcount; j++) {
6347 Py_DECREF(args[j]);
6348 }
6349 /* fall through */
6350 fail_post_positional:
6351 if (kwnames) {
6352 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
6353 for (j = argcount; j < argcount+kwcount; j++) {
6354 Py_DECREF(args[j]);
6355 }
6356 }
6357 /* fall through */
6358 fail_post_args:
6359 return -1;
6360 }
6361
6362 /* Consumes references to func and all the args */
6363 static _PyInterpreterFrame *
6364 _PyEvalFramePushAndInit(PyThreadState *tstate, PyFunctionObject *func,
6365 PyObject *locals, PyObject* const* args,
6366 size_t argcount, PyObject *kwnames)
6367 {
6368 PyCodeObject * code = (PyCodeObject *)func->func_code;
6369 size_t size = code->co_nlocalsplus + code->co_stacksize + FRAME_SPECIALS_SIZE;
6370 CALL_STAT_INC(frames_pushed);
6371 _PyInterpreterFrame *frame = _PyThreadState_BumpFramePointer(tstate, size);
6372 if (frame == NULL) {
6373 goto fail;
6374 }
6375 _PyFrame_InitializeSpecials(frame, func, locals, code->co_nlocalsplus);
6376 PyObject **localsarray = &frame->localsplus[0];
6377 for (int i = 0; i < code->co_nlocalsplus; i++) {
6378 localsarray[i] = NULL;
6379 }
6380 if (initialize_locals(tstate, func, localsarray, args, argcount, kwnames)) {
6381 assert(frame->owner != FRAME_OWNED_BY_GENERATOR);
6382 _PyEvalFrameClearAndPop(tstate, frame);
6383 return NULL;
6384 }
6385 return frame;
6386 fail:
6387 /* Consume the references */
6388 for (size_t i = 0; i < argcount; i++) {
6389 Py_DECREF(args[i]);
6390 }
6391 if (kwnames) {
6392 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
6393 for (Py_ssize_t i = 0; i < kwcount; i++) {
6394 Py_DECREF(args[i+argcount]);
6395 }
6396 }
6397 PyErr_NoMemory();
6398 return NULL;
6399 }
6400
6401 static void
6402 _PyEvalFrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame)
6403 {
6404 // Make sure that this is, indeed, the top frame. We can't check this in
6405 // _PyThreadState_PopFrame, since f_code is already cleared at that point:
6406 assert((PyObject **)frame + frame->f_code->co_nlocalsplus +
6407 frame->f_code->co_stacksize + FRAME_SPECIALS_SIZE == tstate->datastack_top);
6408 tstate->recursion_remaining--;
6409 assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
6410 assert(frame->owner == FRAME_OWNED_BY_THREAD);
6411 _PyFrame_Clear(frame);
6412 tstate->recursion_remaining++;
6413 _PyThreadState_PopFrame(tstate, frame);
6414 }
6415
6416 PyObject *
6417 _PyEval_Vector(PyThreadState *tstate, PyFunctionObject *func,
6418 PyObject *locals,
6419 PyObject* const* args, size_t argcount,
6420 PyObject *kwnames)
6421 {
6422 /* _PyEvalFramePushAndInit consumes the references
6423 * to func and all its arguments */
6424 Py_INCREF(func);
6425 for (size_t i = 0; i < argcount; i++) {
6426 Py_INCREF(args[i]);
6427 }
6428 if (kwnames) {
6429 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
6430 for (Py_ssize_t i = 0; i < kwcount; i++) {
6431 Py_INCREF(args[i+argcount]);
6432 }
6433 }
6434 _PyInterpreterFrame *frame = _PyEvalFramePushAndInit(
6435 tstate, func, locals, args, argcount, kwnames);
6436 if (frame == NULL) {
6437 return NULL;
6438 }
6439 PyObject *retval = _PyEval_EvalFrame(tstate, frame, 0);
6440 assert(
6441 _PyFrame_GetStackPointer(frame) == _PyFrame_Stackbase(frame) ||
6442 _PyFrame_GetStackPointer(frame) == frame->localsplus
6443 );
6444 _PyEvalFrameClearAndPop(tstate, frame);
6445 return retval;
6446 }
6447
6448 /* Legacy API */
6449 PyObject *
6450 PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
6451 PyObject *const *args, int argcount,
6452 PyObject *const *kws, int kwcount,
6453 PyObject *const *defs, int defcount,
6454 PyObject *kwdefs, PyObject *closure)
6455 {
6456 PyThreadState *tstate = _PyThreadState_GET();
6457 PyObject *res = NULL;
6458 PyObject *defaults = _PyTuple_FromArray(defs, defcount);
6459 if (defaults == NULL) {
6460 return NULL;
6461 }
6462 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
6463 if (builtins == NULL) {
6464 Py_DECREF(defaults);
6465 return NULL;
6466 }
6467 if (locals == NULL) {
6468 locals = globals;
6469 }
6470 PyObject *kwnames = NULL;
6471 PyObject *const *allargs;
6472 PyObject **newargs = NULL;
6473 PyFunctionObject *func = NULL;
6474 if (kwcount == 0) {
6475 allargs = args;
6476 }
6477 else {
6478 kwnames = PyTuple_New(kwcount);
6479 if (kwnames == NULL) {
6480 goto fail;
6481 }
6482 newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
6483 if (newargs == NULL) {
6484 goto fail;
6485 }
6486 for (int i = 0; i < argcount; i++) {
6487 newargs[i] = args[i];
6488 }
6489 for (int i = 0; i < kwcount; i++) {
6490 Py_INCREF(kws[2*i]);
6491 PyTuple_SET_ITEM(kwnames, i, kws[2*i]);
6492 newargs[argcount+i] = kws[2*i+1];
6493 }
6494 allargs = newargs;
6495 }
6496 PyFrameConstructor constr = {
6497 .fc_globals = globals,
6498 .fc_builtins = builtins,
6499 .fc_name = ((PyCodeObject *)_co)->co_name,
6500 .fc_qualname = ((PyCodeObject *)_co)->co_name,
6501 .fc_code = _co,
6502 .fc_defaults = defaults,
6503 .fc_kwdefaults = kwdefs,
6504 .fc_closure = closure
6505 };
6506 func = _PyFunction_FromConstructor(&constr);
6507 if (func == NULL) {
6508 goto fail;
6509 }
6510 res = _PyEval_Vector(tstate, func, locals,
6511 allargs, argcount,
6512 kwnames);
6513 fail:
6514 Py_XDECREF(func);
6515 Py_XDECREF(kwnames);
6516 PyMem_Free(newargs);
6517 Py_DECREF(defaults);
6518 return res;
6519 }
6520
6521
6522 /* Logic for the raise statement (too complicated for inlining).
6523 This *consumes* a reference count to each of its arguments. */
6524 static int
6525 do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
6526 {
6527 PyObject *type = NULL, *value = NULL;
6528
6529 if (exc == NULL) {
6530 /* Reraise */
6531 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
6532 value = exc_info->exc_value;
6533 if (Py_IsNone(value) || value == NULL) {
6534 _PyErr_SetString(tstate, PyExc_RuntimeError,
6535 "No active exception to reraise");
6536 return 0;
6537 }
6538 assert(PyExceptionInstance_Check(value));
6539 type = PyExceptionInstance_Class(value);
6540 Py_XINCREF(type);
6541 Py_XINCREF(value);
6542 PyObject *tb = PyException_GetTraceback(value); /* new ref */
6543 _PyErr_Restore(tstate, type, value, tb);
6544 return 1;
6545 }
6546
6547 /* We support the following forms of raise:
6548 raise
6549 raise <instance>
6550 raise <type> */
6551
6552 if (PyExceptionClass_Check(exc)) {
6553 type = exc;
6554 value = _PyObject_CallNoArgs(exc);
6555 if (value == NULL)
6556 goto raise_error;
6557 if (!PyExceptionInstance_Check(value)) {
6558 _PyErr_Format(tstate, PyExc_TypeError,
6559 "calling %R should have returned an instance of "
6560 "BaseException, not %R",
6561 type, Py_TYPE(value));
6562 goto raise_error;
6563 }
6564 }
6565 else if (PyExceptionInstance_Check(exc)) {
6566 value = exc;
6567 type = PyExceptionInstance_Class(exc);
6568 Py_INCREF(type);
6569 }
6570 else {
6571 /* Not something you can raise. You get an exception
6572 anyway, just not what you specified :-) */
6573 Py_DECREF(exc);
6574 _PyErr_SetString(tstate, PyExc_TypeError,
6575 "exceptions must derive from BaseException");
6576 goto raise_error;
6577 }
6578
6579 assert(type != NULL);
6580 assert(value != NULL);
6581
6582 if (cause) {
6583 PyObject *fixed_cause;
6584 if (PyExceptionClass_Check(cause)) {
6585 fixed_cause = _PyObject_CallNoArgs(cause);
6586 if (fixed_cause == NULL)
6587 goto raise_error;
6588 Py_DECREF(cause);
6589 }
6590 else if (PyExceptionInstance_Check(cause)) {
6591 fixed_cause = cause;
6592 }
6593 else if (Py_IsNone(cause)) {
6594 Py_DECREF(cause);
6595 fixed_cause = NULL;
6596 }
6597 else {
6598 _PyErr_SetString(tstate, PyExc_TypeError,
6599 "exception causes must derive from "
6600 "BaseException");
6601 goto raise_error;
6602 }
6603 PyException_SetCause(value, fixed_cause);
6604 }
6605
6606 _PyErr_SetObject(tstate, type, value);
6607 /* _PyErr_SetObject incref's its arguments */
6608 Py_DECREF(value);
6609 Py_DECREF(type);
6610 return 0;
6611
6612 raise_error:
6613 Py_XDECREF(value);
6614 Py_XDECREF(type);
6615 Py_XDECREF(cause);
6616 return 0;
6617 }
6618
6619 /* Logic for matching an exception in an except* clause (too
6620 complicated for inlining).
6621 */
6622
6623 static int
6624 exception_group_match(PyObject* exc_value, PyObject *match_type,
6625 PyObject **match, PyObject **rest)
6626 {
6627 if (Py_IsNone(exc_value)) {
6628 *match = Py_NewRef(Py_None);
6629 *rest = Py_NewRef(Py_None);
6630 return 0;
6631 }
6632 assert(PyExceptionInstance_Check(exc_value));
6633
6634 if (PyErr_GivenExceptionMatches(exc_value, match_type)) {
6635 /* Full match of exc itself */
6636 bool is_eg = _PyBaseExceptionGroup_Check(exc_value);
6637 if (is_eg) {
6638 *match = Py_NewRef(exc_value);
6639 }
6640 else {
6641 /* naked exception - wrap it */
6642 PyObject *excs = PyTuple_Pack(1, exc_value);
6643 if (excs == NULL) {
6644 return -1;
6645 }
6646 PyObject *wrapped = _PyExc_CreateExceptionGroup("", excs);
6647 Py_DECREF(excs);
6648 if (wrapped == NULL) {
6649 return -1;
6650 }
6651 *match = wrapped;
6652 }
6653 *rest = Py_NewRef(Py_None);
6654 return 0;
6655 }
6656
6657 /* exc_value does not match match_type.
6658 * Check for partial match if it's an exception group.
6659 */
6660 if (_PyBaseExceptionGroup_Check(exc_value)) {
6661 PyObject *pair = PyObject_CallMethod(exc_value, "split", "(O)",
6662 match_type);
6663 if (pair == NULL) {
6664 return -1;
6665 }
6666 assert(PyTuple_CheckExact(pair));
6667 assert(PyTuple_GET_SIZE(pair) == 2);
6668 *match = Py_NewRef(PyTuple_GET_ITEM(pair, 0));
6669 *rest = Py_NewRef(PyTuple_GET_ITEM(pair, 1));
6670 Py_DECREF(pair);
6671 return 0;
6672 }
6673 /* no match */
6674 *match = Py_NewRef(Py_None);
6675 *rest = Py_NewRef(Py_None);
6676 return 0;
6677 }
6678
6679 /* Iterate v argcnt times and store the results on the stack (via decreasing
6680 sp). Return 1 for success, 0 if error.
6681
6682 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
6683 with a variable target.
6684 */
6685
6686 static int
6687 unpack_iterable(PyThreadState *tstate, PyObject *v,
6688 int argcnt, int argcntafter, PyObject **sp)
6689 {
6690 int i = 0, j = 0;
6691 Py_ssize_t ll = 0;
6692 PyObject *it; /* iter(v) */
6693 PyObject *w;
6694 PyObject *l = NULL; /* variable list */
6695
6696 assert(v != NULL);
6697
6698 it = PyObject_GetIter(v);
6699 if (it == NULL) {
6700 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
6701 Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
6702 {
6703 _PyErr_Format(tstate, PyExc_TypeError,
6704 "cannot unpack non-iterable %.200s object",
6705 Py_TYPE(v)->tp_name);
6706 }
6707 return 0;
6708 }
6709
6710 for (; i < argcnt; i++) {
6711 w = PyIter_Next(it);
6712 if (w == NULL) {
6713 /* Iterator done, via error or exhaustion. */
6714 if (!_PyErr_Occurred(tstate)) {
6715 if (argcntafter == -1) {
6716 _PyErr_Format(tstate, PyExc_ValueError,
6717 "not enough values to unpack "
6718 "(expected %d, got %d)",
6719 argcnt, i);
6720 }
6721 else {
6722 _PyErr_Format(tstate, PyExc_ValueError,
6723 "not enough values to unpack "
6724 "(expected at least %d, got %d)",
6725 argcnt + argcntafter, i);
6726 }
6727 }
6728 goto Error;
6729 }
6730 *--sp = w;
6731 }
6732
6733 if (argcntafter == -1) {
6734 /* We better have exhausted the iterator now. */
6735 w = PyIter_Next(it);
6736 if (w == NULL) {
6737 if (_PyErr_Occurred(tstate))
6738 goto Error;
6739 Py_DECREF(it);
6740 return 1;
6741 }
6742 Py_DECREF(w);
6743 _PyErr_Format(tstate, PyExc_ValueError,
6744 "too many values to unpack (expected %d)",
6745 argcnt);
6746 goto Error;
6747 }
6748
6749 l = PySequence_List(it);
6750 if (l == NULL)
6751 goto Error;
6752 *--sp = l;
6753 i++;
6754
6755 ll = PyList_GET_SIZE(l);
6756 if (ll < argcntafter) {
6757 _PyErr_Format(tstate, PyExc_ValueError,
6758 "not enough values to unpack (expected at least %d, got %zd)",
6759 argcnt + argcntafter, argcnt + ll);
6760 goto Error;
6761 }
6762
6763 /* Pop the "after-variable" args off the list. */
6764 for (j = argcntafter; j > 0; j--, i++) {
6765 *--sp = PyList_GET_ITEM(l, ll - j);
6766 }
6767 /* Resize the list. */
6768 Py_SET_SIZE(l, ll - argcntafter);
6769 Py_DECREF(it);
6770 return 1;
6771
6772 Error:
6773 for (; i > 0; i--, sp++)
6774 Py_DECREF(*sp);
6775 Py_XDECREF(it);
6776 return 0;
6777 }
6778
6779 static void
6780 call_exc_trace(Py_tracefunc func, PyObject *self,
6781 PyThreadState *tstate,
6782 _PyInterpreterFrame *f)
6783 {
6784 PyObject *type, *value, *traceback, *orig_traceback, *arg;
6785 int err;
6786 _PyErr_Fetch(tstate, &type, &value, &orig_traceback);
6787 if (value == NULL) {
6788 value = Py_None;
6789 Py_INCREF(value);
6790 }
6791 _PyErr_NormalizeException(tstate, &type, &value, &orig_traceback);
6792 traceback = (orig_traceback != NULL) ? orig_traceback : Py_None;
6793 arg = PyTuple_Pack(3, type, value, traceback);
6794 if (arg == NULL) {
6795 _PyErr_Restore(tstate, type, value, orig_traceback);
6796 return;
6797 }
6798 err = call_trace(func, self, tstate, f, PyTrace_EXCEPTION, arg);
6799 Py_DECREF(arg);
6800 if (err == 0) {
6801 _PyErr_Restore(tstate, type, value, orig_traceback);
6802 }
6803 else {
6804 Py_XDECREF(type);
6805 Py_XDECREF(value);
6806 Py_XDECREF(orig_traceback);
6807 }
6808 }
6809
6810 static int
6811 call_trace_protected(Py_tracefunc func, PyObject *obj,
6812 PyThreadState *tstate, _PyInterpreterFrame *frame,
6813 int what, PyObject *arg)
6814 {
6815 PyObject *type, *value, *traceback;
6816 int err;
6817 _PyErr_Fetch(tstate, &type, &value, &traceback);
6818 err = call_trace(func, obj, tstate, frame, what, arg);
6819 if (err == 0)
6820 {
6821 _PyErr_Restore(tstate, type, value, traceback);
6822 return 0;
6823 }
6824 else {
6825 Py_XDECREF(type);
6826 Py_XDECREF(value);
6827 Py_XDECREF(traceback);
6828 return -1;
6829 }
6830 }
6831
6832 static void
6833 initialize_trace_info(PyTraceInfo *trace_info, _PyInterpreterFrame *frame)
6834 {
6835 PyCodeObject *code = frame->f_code;
6836 if (trace_info->code != code) {
6837 trace_info->code = code;
6838 _PyCode_InitAddressRange(code, &trace_info->bounds);
6839 }
6840 }
6841
6842 void
6843 PyThreadState_EnterTracing(PyThreadState *tstate)
6844 {
6845 tstate->tracing++;
6846 tstate->cframe->use_tracing = 0;
6847 }
6848
6849 void
6850 PyThreadState_LeaveTracing(PyThreadState *tstate)
6851 {
6852 assert(tstate->tracing > 0 && tstate->cframe->use_tracing == 0);
6853 tstate->tracing--;
6854 _PyThreadState_UpdateTracingState(tstate);
6855 }
6856
6857 static int
6858 call_trace(Py_tracefunc func, PyObject *obj,
6859 PyThreadState *tstate, _PyInterpreterFrame *frame,
6860 int what, PyObject *arg)
6861 {
6862 int result;
6863 if (tstate->tracing) {
6864 return 0;
6865 }
6866 PyFrameObject *f = _PyFrame_GetFrameObject(frame);
6867 if (f == NULL) {
6868 return -1;
6869 }
6870 int old_what = tstate->tracing_what;
6871 tstate->tracing_what = what;
6872 PyThreadState_EnterTracing(tstate);
6873 assert(_PyInterpreterFrame_LASTI(frame) >= 0);
6874 if (_PyCode_InitLineArray(frame->f_code)) {
6875 return -1;
6876 }
6877 f->f_lineno = _PyCode_LineNumberFromArray(frame->f_code, _PyInterpreterFrame_LASTI(frame));
6878 result = func(obj, f, what, arg);
6879 f->f_lineno = 0;
6880 PyThreadState_LeaveTracing(tstate);
6881 tstate->tracing_what = old_what;
6882 return result;
6883 }
6884
6885 PyObject*
6886 _PyEval_CallTracing(PyObject *func, PyObject *args)
6887 {
6888 // Save and disable tracing
6889 PyThreadState *tstate = _PyThreadState_GET();
6890 int save_tracing = tstate->tracing;
6891 int save_use_tracing = tstate->cframe->use_tracing;
6892 tstate->tracing = 0;
6893
6894 // Call the tracing function
6895 PyObject *result = PyObject_Call(func, args, NULL);
6896
6897 // Restore tracing
6898 tstate->tracing = save_tracing;
6899 tstate->cframe->use_tracing = save_use_tracing;
6900 return result;
6901 }
6902
6903 /* See Objects/lnotab_notes.txt for a description of how tracing works. */
6904 static int
6905 maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
6906 PyThreadState *tstate, _PyInterpreterFrame *frame, int instr_prev)
6907 {
6908 int result = 0;
6909
6910 /* If the last instruction falls at the start of a line or if it
6911 represents a jump backwards, update the frame's line number and
6912 then call the trace function if we're tracing source lines.
6913 */
6914 if (_PyCode_InitLineArray(frame->f_code)) {
6915 return -1;
6916 }
6917 int lastline;
6918 if (instr_prev <= frame->f_code->_co_firsttraceable) {
6919 lastline = -1;
6920 }
6921 else {
6922 lastline = _PyCode_LineNumberFromArray(frame->f_code, instr_prev);
6923 }
6924 int line = _PyCode_LineNumberFromArray(frame->f_code, _PyInterpreterFrame_LASTI(frame));
6925 PyFrameObject *f = _PyFrame_GetFrameObject(frame);
6926 if (f == NULL) {
6927 return -1;
6928 }
6929 if (line != -1 && f->f_trace_lines) {
6930 /* Trace backward edges (except in 'yield from') or if line number has changed */
6931 int trace = line != lastline ||
6932 (_PyInterpreterFrame_LASTI(frame) < instr_prev &&
6933 // SEND has no quickened forms, so no need to use _PyOpcode_Deopt
6934 // here:
6935 _Py_OPCODE(*frame->prev_instr) != SEND);
6936 if (trace) {
6937 result = call_trace(func, obj, tstate, frame, PyTrace_LINE, Py_None);
6938 }
6939 }
6940 /* Always emit an opcode event if we're tracing all opcodes. */
6941 if (f->f_trace_opcodes && result == 0) {
6942 result = call_trace(func, obj, tstate, frame, PyTrace_OPCODE, Py_None);
6943 }
6944 return result;
6945 }
6946
6947 int
6948 _PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
6949 {
6950 assert(is_tstate_valid(tstate));
6951 /* The caller must hold the GIL */
6952 assert(PyGILState_Check());
6953
6954 static int reentrant = 0;
6955 if (reentrant) {
6956 _PyErr_SetString(tstate, PyExc_RuntimeError, "Cannot install a profile function "
6957 "while another profile function is being installed");
6958 reentrant = 0;
6959 return -1;
6960 }
6961 reentrant = 1;
6962
6963 /* Call _PySys_Audit() in the context of the current thread state,
6964 even if tstate is not the current thread state. */
6965 PyThreadState *current_tstate = _PyThreadState_GET();
6966 if (_PySys_Audit(current_tstate, "sys.setprofile", NULL) < 0) {
6967 reentrant = 0;
6968 return -1;
6969 }
6970
6971 PyObject *profileobj = tstate->c_profileobj;
6972
6973 tstate->c_profilefunc = NULL;
6974 tstate->c_profileobj = NULL;
6975 /* Must make sure that tracing is not ignored if 'profileobj' is freed */
6976 _PyThreadState_UpdateTracingState(tstate);
6977 Py_XDECREF(profileobj);
6978
6979 Py_XINCREF(arg);
6980 tstate->c_profileobj = arg;
6981 tstate->c_profilefunc = func;
6982
6983 /* Flag that tracing or profiling is turned on */
6984 _PyThreadState_UpdateTracingState(tstate);
6985 reentrant = 0;
6986 return 0;
6987 }
6988
6989 void
6990 PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
6991 {
6992 PyThreadState *tstate = _PyThreadState_GET();
6993 if (_PyEval_SetProfile(tstate, func, arg) < 0) {
6994 /* Log _PySys_Audit() error */
6995 _PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL);
6996 }
6997 }
6998
6999 int
7000 _PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
7001 {
7002 assert(is_tstate_valid(tstate));
7003 /* The caller must hold the GIL */
7004 assert(PyGILState_Check());
7005
7006 static int reentrant = 0;
7007
7008 if (reentrant) {
7009 _PyErr_SetString(tstate, PyExc_RuntimeError, "Cannot install a trace function "
7010 "while another trace function is being installed");
7011 reentrant = 0;
7012 return -1;
7013 }
7014 reentrant = 1;
7015
7016 /* Call _PySys_Audit() in the context of the current thread state,
7017 even if tstate is not the current thread state. */
7018 PyThreadState *current_tstate = _PyThreadState_GET();
7019 if (_PySys_Audit(current_tstate, "sys.settrace", NULL) < 0) {
7020 reentrant = 0;
7021 return -1;
7022 }
7023
7024 PyObject *traceobj = tstate->c_traceobj;
7025
7026 tstate->c_tracefunc = NULL;
7027 tstate->c_traceobj = NULL;
7028 /* Must make sure that profiling is not ignored if 'traceobj' is freed */
7029 _PyThreadState_UpdateTracingState(tstate);
7030 Py_XINCREF(arg);
7031 Py_XDECREF(traceobj);
7032 tstate->c_traceobj = arg;
7033 tstate->c_tracefunc = func;
7034
7035 /* Flag that tracing or profiling is turned on */
7036 _PyThreadState_UpdateTracingState(tstate);
7037
7038 reentrant = 0;
7039 return 0;
7040 }
7041
7042 void
7043 PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
7044 {
7045 PyThreadState *tstate = _PyThreadState_GET();
7046 if (_PyEval_SetTrace(tstate, func, arg) < 0) {
7047 /* Log _PySys_Audit() error */
7048 _PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL);
7049 }
7050 }
7051
7052
7053 int
7054 _PyEval_SetCoroutineOriginTrackingDepth(int depth)
7055 {
7056 PyThreadState *tstate = _PyThreadState_GET();
7057 if (depth < 0) {
7058 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
7059 return -1;
7060 }
7061 tstate->coroutine_origin_tracking_depth = depth;
7062 return 0;
7063 }
7064
7065
7066 int
7067 _PyEval_GetCoroutineOriginTrackingDepth(void)
7068 {
7069 PyThreadState *tstate = _PyThreadState_GET();
7070 return tstate->coroutine_origin_tracking_depth;
7071 }
7072
7073 int
7074 _PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
7075 {
7076 PyThreadState *tstate = _PyThreadState_GET();
7077
7078 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
7079 return -1;
7080 }
7081
7082 Py_XINCREF(firstiter);
7083 Py_XSETREF(tstate->async_gen_firstiter, firstiter);
7084 return 0;
7085 }
7086
7087 PyObject *
7088 _PyEval_GetAsyncGenFirstiter(void)
7089 {
7090 PyThreadState *tstate = _PyThreadState_GET();
7091 return tstate->async_gen_firstiter;
7092 }
7093
7094 int
7095 _PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
7096 {
7097 PyThreadState *tstate = _PyThreadState_GET();
7098
7099 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
7100 return -1;
7101 }
7102
7103 Py_XINCREF(finalizer);
7104 Py_XSETREF(tstate->async_gen_finalizer, finalizer);
7105 return 0;
7106 }
7107
7108 PyObject *
7109 _PyEval_GetAsyncGenFinalizer(void)
7110 {
7111 PyThreadState *tstate = _PyThreadState_GET();
7112 return tstate->async_gen_finalizer;
7113 }
7114
7115 _PyInterpreterFrame *
7116 _PyEval_GetFrame(void)
7117 {
7118 PyThreadState *tstate = _PyThreadState_GET();
7119 return tstate->cframe->current_frame;
7120 }
7121
7122 PyFrameObject *
7123 PyEval_GetFrame(void)
7124 {
7125 _PyInterpreterFrame *frame = _PyEval_GetFrame();
7126 while (frame && _PyFrame_IsIncomplete(frame)) {
7127 frame = frame->previous;
7128 }
7129 if (frame == NULL) {
7130 return NULL;
7131 }
7132 PyFrameObject *f = _PyFrame_GetFrameObject(frame);
7133 if (f == NULL) {
7134 PyErr_Clear();
7135 }
7136 return f;
7137 }
7138
7139 PyObject *
7140 _PyEval_GetBuiltins(PyThreadState *tstate)
7141 {
7142 _PyInterpreterFrame *frame = tstate->cframe->current_frame;
7143 if (frame != NULL) {
7144 return frame->f_builtins;
7145 }
7146 return tstate->interp->builtins;
7147 }
7148
7149 PyObject *
7150 PyEval_GetBuiltins(void)
7151 {
7152 PyThreadState *tstate = _PyThreadState_GET();
7153 return _PyEval_GetBuiltins(tstate);
7154 }
7155
7156 /* Convenience function to get a builtin from its name */
7157 PyObject *
7158 _PyEval_GetBuiltin(PyObject *name)
7159 {
7160 PyThreadState *tstate = _PyThreadState_GET();
7161 PyObject *attr = PyDict_GetItemWithError(PyEval_GetBuiltins(), name);
7162 if (attr) {
7163 Py_INCREF(attr);
7164 }
7165 else if (!_PyErr_Occurred(tstate)) {
7166 _PyErr_SetObject(tstate, PyExc_AttributeError, name);
7167 }
7168 return attr;
7169 }
7170
7171 PyObject *
7172 _PyEval_GetBuiltinId(_Py_Identifier *name)
7173 {
7174 return _PyEval_GetBuiltin(_PyUnicode_FromId(name));
7175 }
7176
7177 PyObject *
7178 PyEval_GetLocals(void)
7179 {
7180 PyThreadState *tstate = _PyThreadState_GET();
7181 _PyInterpreterFrame *current_frame = tstate->cframe->current_frame;
7182 if (current_frame == NULL) {
7183 _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
7184 return NULL;
7185 }
7186
7187 if (_PyFrame_FastToLocalsWithError(current_frame) < 0) {
7188 return NULL;
7189 }
7190
7191 PyObject *locals = current_frame->f_locals;
7192 assert(locals != NULL);
7193 return locals;
7194 }
7195
7196 PyObject *
7197 PyEval_GetGlobals(void)
7198 {
7199 PyThreadState *tstate = _PyThreadState_GET();
7200 _PyInterpreterFrame *current_frame = tstate->cframe->current_frame;
7201 if (current_frame == NULL) {
7202 return NULL;
7203 }
7204 return current_frame->f_globals;
7205 }
7206
7207 int
7208 PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
7209 {
7210 PyThreadState *tstate = _PyThreadState_GET();
7211 _PyInterpreterFrame *current_frame = tstate->cframe->current_frame;
7212 int result = cf->cf_flags != 0;
7213
7214 if (current_frame != NULL) {
7215 const int codeflags = current_frame->f_code->co_flags;
7216 const int compilerflags = codeflags & PyCF_MASK;
7217 if (compilerflags) {
7218 result = 1;
7219 cf->cf_flags |= compilerflags;
7220 }
7221 }
7222 return result;
7223 }
7224
7225
7226 const char *
7227 PyEval_GetFuncName(PyObject *func)
7228 {
7229 if (PyMethod_Check(func))
7230 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
7231 else if (PyFunction_Check(func))
7232 return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
7233 else if (PyCFunction_Check(func))
7234 return ((PyCFunctionObject*)func)->m_ml->ml_name;
7235 else
7236 return Py_TYPE(func)->tp_name;
7237 }
7238
7239 const char *
7240 PyEval_GetFuncDesc(PyObject *func)
7241 {
7242 if (PyMethod_Check(func))
7243 return "()";
7244 else if (PyFunction_Check(func))
7245 return "()";
7246 else if (PyCFunction_Check(func))
7247 return "()";
7248 else
7249 return " object";
7250 }
7251
7252 #define C_TRACE(x, call) \
7253 if (use_tracing && tstate->c_profilefunc) { \
7254 if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
7255 tstate, tstate->cframe->current_frame, \
7256 PyTrace_C_CALL, func)) { \
7257 x = NULL; \
7258 } \
7259 else { \
7260 x = call; \
7261 if (tstate->c_profilefunc != NULL) { \
7262 if (x == NULL) { \
7263 call_trace_protected(tstate->c_profilefunc, \
7264 tstate->c_profileobj, \
7265 tstate, tstate->cframe->current_frame, \
7266 PyTrace_C_EXCEPTION, func); \
7267 /* XXX should pass (type, value, tb) */ \
7268 } else { \
7269 if (call_trace(tstate->c_profilefunc, \
7270 tstate->c_profileobj, \
7271 tstate, tstate->cframe->current_frame, \
7272 PyTrace_C_RETURN, func)) { \
7273 Py_DECREF(x); \
7274 x = NULL; \
7275 } \
7276 } \
7277 } \
7278 } \
7279 } else { \
7280 x = call; \
7281 }
7282
7283
7284 static PyObject *
7285 trace_call_function(PyThreadState *tstate,
7286 PyObject *func,
7287 PyObject **args, Py_ssize_t nargs,
7288 PyObject *kwnames)
7289 {
7290 int use_tracing = 1;
7291 PyObject *x;
7292 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
7293 C_TRACE(x, PyObject_Vectorcall(func, args, nargs, kwnames));
7294 return x;
7295 }
7296 else if (Py_IS_TYPE(func, &PyMethodDescr_Type) && nargs > 0) {
7297 /* We need to create a temporary bound method as argument
7298 for profiling.
7299
7300 If nargs == 0, then this cannot work because we have no
7301 "self". In any case, the call itself would raise
7302 TypeError (foo needs an argument), so we just skip
7303 profiling. */
7304 PyObject *self = args[0];
7305 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
7306 if (func == NULL) {
7307 return NULL;
7308 }
7309 C_TRACE(x, PyObject_Vectorcall(func,
7310 args+1, nargs-1,
7311 kwnames));
7312 Py_DECREF(func);
7313 return x;
7314 }
7315 return PyObject_Vectorcall(func, args, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
7316 }
7317
7318 static PyObject *
7319 do_call_core(PyThreadState *tstate,
7320 PyObject *func,
7321 PyObject *callargs,
7322 PyObject *kwdict,
7323 int use_tracing
7324 )
7325 {
7326 PyObject *result;
7327
7328 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
7329 C_TRACE(result, PyObject_Call(func, callargs, kwdict));
7330 return result;
7331 }
7332 else if (Py_IS_TYPE(func, &PyMethodDescr_Type)) {
7333 Py_ssize_t nargs = PyTuple_GET_SIZE(callargs);
7334 if (nargs > 0 && use_tracing) {
7335 /* We need to create a temporary bound method as argument
7336 for profiling.
7337
7338 If nargs == 0, then this cannot work because we have no
7339 "self". In any case, the call itself would raise
7340 TypeError (foo needs an argument), so we just skip
7341 profiling. */
7342 PyObject *self = PyTuple_GET_ITEM(callargs, 0);
7343 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
7344 if (func == NULL) {
7345 return NULL;
7346 }
7347
7348 C_TRACE(result, _PyObject_FastCallDictTstate(
7349 tstate, func,
7350 &_PyTuple_ITEMS(callargs)[1],
7351 nargs - 1,
7352 kwdict));
7353 Py_DECREF(func);
7354 return result;
7355 }
7356 }
7357 return PyObject_Call(func, callargs, kwdict);
7358 }
7359
7360 /* Extract a slice index from a PyLong or an object with the
7361 nb_index slot defined, and store in *pi.
7362 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
7363 and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
7364 Return 0 on error, 1 on success.
7365 */
7366 int
7367 _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
7368 {
7369 PyThreadState *tstate = _PyThreadState_GET();
7370 if (!Py_IsNone(v)) {
7371 Py_ssize_t x;
7372 if (_PyIndex_Check(v)) {
7373 x = PyNumber_AsSsize_t(v, NULL);
7374 if (x == -1 && _PyErr_Occurred(tstate))
7375 return 0;
7376 }
7377 else {
7378 _PyErr_SetString(tstate, PyExc_TypeError,
7379 "slice indices must be integers or "
7380 "None or have an __index__ method");
7381 return 0;
7382 }
7383 *pi = x;
7384 }
7385 return 1;
7386 }
7387
7388 int
7389 _PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
7390 {
7391 PyThreadState *tstate = _PyThreadState_GET();
7392 Py_ssize_t x;
7393 if (_PyIndex_Check(v)) {
7394 x = PyNumber_AsSsize_t(v, NULL);
7395 if (x == -1 && _PyErr_Occurred(tstate))
7396 return 0;
7397 }
7398 else {
7399 _PyErr_SetString(tstate, PyExc_TypeError,
7400 "slice indices must be integers or "
7401 "have an __index__ method");
7402 return 0;
7403 }
7404 *pi = x;
7405 return 1;
7406 }
7407
7408 static PyObject *
7409 import_name(PyThreadState *tstate, _PyInterpreterFrame *frame,
7410 PyObject *name, PyObject *fromlist, PyObject *level)
7411 {
7412 PyObject *import_func, *res;
7413 PyObject* stack[5];
7414
7415 import_func = _PyDict_GetItemWithError(frame->f_builtins, &_Py_ID(__import__));
7416 if (import_func == NULL) {
7417 if (!_PyErr_Occurred(tstate)) {
7418 _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
7419 }
7420 return NULL;
7421 }
7422 PyObject *locals = frame->f_locals;
7423 /* Fast path for not overloaded __import__. */
7424 if (import_func == tstate->interp->import_func) {
7425 int ilevel = _PyLong_AsInt(level);
7426 if (ilevel == -1 && _PyErr_Occurred(tstate)) {
7427 return NULL;
7428 }
7429 res = PyImport_ImportModuleLevelObject(
7430 name,
7431 frame->f_globals,
7432 locals == NULL ? Py_None :locals,
7433 fromlist,
7434 ilevel);
7435 return res;
7436 }
7437
7438 Py_INCREF(import_func);
7439
7440 stack[0] = name;
7441 stack[1] = frame->f_globals;
7442 stack[2] = locals == NULL ? Py_None : locals;
7443 stack[3] = fromlist;
7444 stack[4] = level;
7445 res = _PyObject_FastCall(import_func, stack, 5);
7446 Py_DECREF(import_func);
7447 return res;
7448 }
7449
7450 static PyObject *
7451 import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
7452 {
7453 PyObject *x;
7454 PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg;
7455
7456 if (_PyObject_LookupAttr(v, name, &x) != 0) {
7457 return x;
7458 }
7459 /* Issue #17636: in case this failed because of a circular relative
7460 import, try to fallback on reading the module directly from
7461 sys.modules. */
7462 pkgname = PyObject_GetAttr(v, &_Py_ID(__name__));
7463 if (pkgname == NULL) {
7464 goto error;
7465 }
7466 if (!PyUnicode_Check(pkgname)) {
7467 Py_CLEAR(pkgname);
7468 goto error;
7469 }
7470 fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
7471 if (fullmodname == NULL) {
7472 Py_DECREF(pkgname);
7473 return NULL;
7474 }
7475 x = PyImport_GetModule(fullmodname);
7476 Py_DECREF(fullmodname);
7477 if (x == NULL && !_PyErr_Occurred(tstate)) {
7478 goto error;
7479 }
7480 Py_DECREF(pkgname);
7481 return x;
7482 error:
7483 pkgpath = PyModule_GetFilenameObject(v);
7484 if (pkgname == NULL) {
7485 pkgname_or_unknown = PyUnicode_FromString("<unknown module name>");
7486 if (pkgname_or_unknown == NULL) {
7487 Py_XDECREF(pkgpath);
7488 return NULL;
7489 }
7490 } else {
7491 pkgname_or_unknown = pkgname;
7492 }
7493
7494 if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
7495 _PyErr_Clear(tstate);
7496 errmsg = PyUnicode_FromFormat(
7497 "cannot import name %R from %R (unknown location)",
7498 name, pkgname_or_unknown
7499 );
7500 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
7501 PyErr_SetImportError(errmsg, pkgname, NULL);
7502 }
7503 else {
7504 PyObject *spec = PyObject_GetAttr(v, &_Py_ID(__spec__));
7505 const char *fmt =
7506 _PyModuleSpec_IsInitializing(spec) ?
7507 "cannot import name %R from partially initialized module %R "
7508 "(most likely due to a circular import) (%S)" :
7509 "cannot import name %R from %R (%S)";
7510 Py_XDECREF(spec);
7511
7512 errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
7513 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
7514 PyErr_SetImportError(errmsg, pkgname, pkgpath);
7515 }
7516
7517 Py_XDECREF(errmsg);
7518 Py_XDECREF(pkgname_or_unknown);
7519 Py_XDECREF(pkgpath);
7520 return NULL;
7521 }
7522
7523 static int
7524 import_all_from(PyThreadState *tstate, PyObject *locals, PyObject *v)
7525 {
7526 PyObject *all, *dict, *name, *value;
7527 int skip_leading_underscores = 0;
7528 int pos, err;
7529
7530 if (_PyObject_LookupAttr(v, &_Py_ID(__all__), &all) < 0) {
7531 return -1; /* Unexpected error */
7532 }
7533 if (all == NULL) {
7534 if (_PyObject_LookupAttr(v, &_Py_ID(__dict__), &dict) < 0) {
7535 return -1;
7536 }
7537 if (dict == NULL) {
7538 _PyErr_SetString(tstate, PyExc_ImportError,
7539 "from-import-* object has no __dict__ and no __all__");
7540 return -1;
7541 }
7542 all = PyMapping_Keys(dict);
7543 Py_DECREF(dict);
7544 if (all == NULL)
7545 return -1;
7546 skip_leading_underscores = 1;
7547 }
7548
7549 for (pos = 0, err = 0; ; pos++) {
7550 name = PySequence_GetItem(all, pos);
7551 if (name == NULL) {
7552 if (!_PyErr_ExceptionMatches(tstate, PyExc_IndexError)) {
7553 err = -1;
7554 }
7555 else {
7556 _PyErr_Clear(tstate);
7557 }
7558 break;
7559 }
7560 if (!PyUnicode_Check(name)) {
7561 PyObject *modname = PyObject_GetAttr(v, &_Py_ID(__name__));
7562 if (modname == NULL) {
7563 Py_DECREF(name);
7564 err = -1;
7565 break;
7566 }
7567 if (!PyUnicode_Check(modname)) {
7568 _PyErr_Format(tstate, PyExc_TypeError,
7569 "module __name__ must be a string, not %.100s",
7570 Py_TYPE(modname)->tp_name);
7571 }
7572 else {
7573 _PyErr_Format(tstate, PyExc_TypeError,
7574 "%s in %U.%s must be str, not %.100s",
7575 skip_leading_underscores ? "Key" : "Item",
7576 modname,
7577 skip_leading_underscores ? "__dict__" : "__all__",
7578 Py_TYPE(name)->tp_name);
7579 }
7580 Py_DECREF(modname);
7581 Py_DECREF(name);
7582 err = -1;
7583 break;
7584 }
7585 if (skip_leading_underscores) {
7586 if (PyUnicode_READY(name) == -1) {
7587 Py_DECREF(name);
7588 err = -1;
7589 break;
7590 }
7591 if (PyUnicode_READ_CHAR(name, 0) == '_') {
7592 Py_DECREF(name);
7593 continue;
7594 }
7595 }
7596 value = PyObject_GetAttr(v, name);
7597 if (value == NULL)
7598 err = -1;
7599 else if (PyDict_CheckExact(locals))
7600 err = PyDict_SetItem(locals, name, value);
7601 else
7602 err = PyObject_SetItem(locals, name, value);
7603 Py_DECREF(name);
7604 Py_XDECREF(value);
7605 if (err != 0)
7606 break;
7607 }
7608 Py_DECREF(all);
7609 return err;
7610 }
7611
7612 #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
7613 "BaseException is not allowed"
7614
7615 #define CANNOT_EXCEPT_STAR_EG "catching ExceptionGroup with except* "\
7616 "is not allowed. Use except instead."
7617
7618 static int
7619 check_except_type_valid(PyThreadState *tstate, PyObject* right)
7620 {
7621 if (PyTuple_Check(right)) {
7622 Py_ssize_t i, length;
7623 length = PyTuple_GET_SIZE(right);
7624 for (i = 0; i < length; i++) {
7625 PyObject *exc = PyTuple_GET_ITEM(right, i);
7626 if (!PyExceptionClass_Check(exc)) {
7627 _PyErr_SetString(tstate, PyExc_TypeError,
7628 CANNOT_CATCH_MSG);
7629 return -1;
7630 }
7631 }
7632 }
7633 else {
7634 if (!PyExceptionClass_Check(right)) {
7635 _PyErr_SetString(tstate, PyExc_TypeError,
7636 CANNOT_CATCH_MSG);
7637 return -1;
7638 }
7639 }
7640 return 0;
7641 }
7642
7643 static int
7644 check_except_star_type_valid(PyThreadState *tstate, PyObject* right)
7645 {
7646 if (check_except_type_valid(tstate, right) < 0) {
7647 return -1;
7648 }
7649
7650 /* reject except *ExceptionGroup */
7651
7652 int is_subclass = 0;
7653 if (PyTuple_Check(right)) {
7654 Py_ssize_t length = PyTuple_GET_SIZE(right);
7655 for (Py_ssize_t i = 0; i < length; i++) {
7656 PyObject *exc = PyTuple_GET_ITEM(right, i);
7657 is_subclass = PyObject_IsSubclass(exc, PyExc_BaseExceptionGroup);
7658 if (is_subclass < 0) {
7659 return -1;
7660 }
7661 if (is_subclass) {
7662 break;
7663 }
7664 }
7665 }
7666 else {
7667 is_subclass = PyObject_IsSubclass(right, PyExc_BaseExceptionGroup);
7668 if (is_subclass < 0) {
7669 return -1;
7670 }
7671 }
7672 if (is_subclass) {
7673 _PyErr_SetString(tstate, PyExc_TypeError,
7674 CANNOT_EXCEPT_STAR_EG);
7675 return -1;
7676 }
7677 return 0;
7678 }
7679
7680 static int
7681 check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
7682 {
7683 if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
7684 /* check_args_iterable() may be called with a live exception:
7685 * clear it to prevent calling _PyObject_FunctionStr() with an
7686 * exception set. */
7687 _PyErr_Clear(tstate);
7688 PyObject *funcstr = _PyObject_FunctionStr(func);
7689 if (funcstr != NULL) {
7690 _PyErr_Format(tstate, PyExc_TypeError,
7691 "%U argument after * must be an iterable, not %.200s",
7692 funcstr, Py_TYPE(args)->tp_name);
7693 Py_DECREF(funcstr);
7694 }
7695 return -1;
7696 }
7697 return 0;
7698 }
7699
7700 static void
7701 format_kwargs_error(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
7702 {
7703 /* _PyDict_MergeEx raises attribute
7704 * error (percolated from an attempt
7705 * to get 'keys' attribute) instead of
7706 * a type error if its second argument
7707 * is not a mapping.
7708 */
7709 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
7710 _PyErr_Clear(tstate);
7711 PyObject *funcstr = _PyObject_FunctionStr(func);
7712 if (funcstr != NULL) {
7713 _PyErr_Format(
7714 tstate, PyExc_TypeError,
7715 "%U argument after ** must be a mapping, not %.200s",
7716 funcstr, Py_TYPE(kwargs)->tp_name);
7717 Py_DECREF(funcstr);
7718 }
7719 }
7720 else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
7721 PyObject *exc, *val, *tb;
7722 _PyErr_Fetch(tstate, &exc, &val, &tb);
7723 if (val && PyTuple_Check(val) && PyTuple_GET_SIZE(val) == 1) {
7724 _PyErr_Clear(tstate);
7725 PyObject *funcstr = _PyObject_FunctionStr(func);
7726 if (funcstr != NULL) {
7727 PyObject *key = PyTuple_GET_ITEM(val, 0);
7728 _PyErr_Format(
7729 tstate, PyExc_TypeError,
7730 "%U got multiple values for keyword argument '%S'",
7731 funcstr, key);
7732 Py_DECREF(funcstr);
7733 }
7734 Py_XDECREF(exc);
7735 Py_XDECREF(val);
7736 Py_XDECREF(tb);
7737 }
7738 else {
7739 _PyErr_Restore(tstate, exc, val, tb);
7740 }
7741 }
7742 }
7743
7744 static void
7745 format_exc_check_arg(PyThreadState *tstate, PyObject *exc,
7746 const char *format_str, PyObject *obj)
7747 {
7748 const char *obj_str;
7749
7750 if (!obj)
7751 return;
7752
7753 obj_str = PyUnicode_AsUTF8(obj);
7754 if (!obj_str)
7755 return;
7756
7757 _PyErr_Format(tstate, exc, format_str, obj_str);
7758
7759 if (exc == PyExc_NameError) {
7760 // Include the name in the NameError exceptions to offer suggestions later.
7761 PyObject *type, *value, *traceback;
7762 PyErr_Fetch(&type, &value, &traceback);
7763 PyErr_NormalizeException(&type, &value, &traceback);
7764 if (PyErr_GivenExceptionMatches(value, PyExc_NameError)) {
7765 PyNameErrorObject* exc = (PyNameErrorObject*) value;
7766 if (exc->name == NULL) {
7767 // We do not care if this fails because we are going to restore the
7768 // NameError anyway.
7769 (void)PyObject_SetAttr(value, &_Py_ID(name), obj);
7770 }
7771 }
7772 PyErr_Restore(type, value, traceback);
7773 }
7774 }
7775
7776 static void
7777 format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
7778 {
7779 PyObject *name;
7780 /* Don't stomp existing exception */
7781 if (_PyErr_Occurred(tstate))
7782 return;
7783 name = PyTuple_GET_ITEM(co->co_localsplusnames, oparg);
7784 if (oparg < co->co_nplaincellvars + co->co_nlocals) {
7785 format_exc_check_arg(tstate, PyExc_UnboundLocalError,
7786 UNBOUNDLOCAL_ERROR_MSG, name);
7787 } else {
7788 format_exc_check_arg(tstate, PyExc_NameError,
7789 UNBOUNDFREE_ERROR_MSG, name);
7790 }
7791 }
7792
7793 static void
7794 format_awaitable_error(PyThreadState *tstate, PyTypeObject *type, int oparg)
7795 {
7796 if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
7797 if (oparg == 1) {
7798 _PyErr_Format(tstate, PyExc_TypeError,
7799 "'async with' received an object from __aenter__ "
7800 "that does not implement __await__: %.100s",
7801 type->tp_name);
7802 }
7803 else if (oparg == 2) {
7804 _PyErr_Format(tstate, PyExc_TypeError,
7805 "'async with' received an object from __aexit__ "
7806 "that does not implement __await__: %.100s",
7807 type->tp_name);
7808 }
7809 }
7810 }
7811
7812 #ifdef Py_STATS
7813
7814 static PyObject *
7815 getarray(uint64_t a[256])
7816 {
7817 int i;
7818 PyObject *l = PyList_New(256);
7819 if (l == NULL) return NULL;
7820 for (i = 0; i < 256; i++) {
7821 PyObject *x = PyLong_FromUnsignedLongLong(a[i]);
7822 if (x == NULL) {
7823 Py_DECREF(l);
7824 return NULL;
7825 }
7826 PyList_SET_ITEM(l, i, x);
7827 }
7828 for (i = 0; i < 256; i++)
7829 a[i] = 0;
7830 return l;
7831 }
7832
7833 PyObject *
7834 _Py_GetDXProfile(PyObject *self, PyObject *args)
7835 {
7836 int i;
7837 PyObject *l = PyList_New(257);
7838 if (l == NULL) return NULL;
7839 for (i = 0; i < 256; i++) {
7840 PyObject *x = getarray(_py_stats.opcode_stats[i].pair_count);
7841 if (x == NULL) {
7842 Py_DECREF(l);
7843 return NULL;
7844 }
7845 PyList_SET_ITEM(l, i, x);
7846 }
7847 PyObject *counts = PyList_New(256);
7848 if (counts == NULL) {
7849 Py_DECREF(l);
7850 return NULL;
7851 }
7852 for (i = 0; i < 256; i++) {
7853 PyObject *x = PyLong_FromUnsignedLongLong(
7854 _py_stats.opcode_stats[i].execution_count);
7855 if (x == NULL) {
7856 Py_DECREF(counts);
7857 Py_DECREF(l);
7858 return NULL;
7859 }
7860 PyList_SET_ITEM(counts, i, x);
7861 }
7862 PyList_SET_ITEM(l, 256, counts);
7863 return l;
7864 }
7865
7866 #endif
7867
7868 Py_ssize_t
7869 _PyEval_RequestCodeExtraIndex(freefunc free)
7870 {
7871 PyInterpreterState *interp = _PyInterpreterState_GET();
7872 Py_ssize_t new_index;
7873
7874 if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
7875 return -1;
7876 }
7877 new_index = interp->co_extra_user_count++;
7878 interp->co_extra_freefuncs[new_index] = free;
7879 return new_index;
7880 }
7881
7882 static void
7883 dtrace_function_entry(_PyInterpreterFrame *frame)
7884 {
7885 const char *filename;
7886 const char *funcname;
7887 int lineno;
7888
7889 PyCodeObject *code = frame->f_code;
7890 filename = PyUnicode_AsUTF8(code->co_filename);
7891 funcname = PyUnicode_AsUTF8(code->co_name);
7892 lineno = _PyInterpreterFrame_GetLine(frame);
7893
7894 PyDTrace_FUNCTION_ENTRY(filename, funcname, lineno);
7895 }
7896
7897 static void
7898 dtrace_function_return(_PyInterpreterFrame *frame)
7899 {
7900 const char *filename;
7901 const char *funcname;
7902 int lineno;
7903
7904 PyCodeObject *code = frame->f_code;
7905 filename = PyUnicode_AsUTF8(code->co_filename);
7906 funcname = PyUnicode_AsUTF8(code->co_name);
7907 lineno = _PyInterpreterFrame_GetLine(frame);
7908
7909 PyDTrace_FUNCTION_RETURN(filename, funcname, lineno);
7910 }
7911
7912 /* DTrace equivalent of maybe_call_line_trace. */
7913 static void
7914 maybe_dtrace_line(_PyInterpreterFrame *frame,
7915 PyTraceInfo *trace_info,
7916 int instr_prev)
7917 {
7918 const char *co_filename, *co_name;
7919
7920 /* If the last instruction executed isn't in the current
7921 instruction window, reset the window.
7922 */
7923 initialize_trace_info(trace_info, frame);
7924 int lastline = _PyCode_CheckLineNumber(instr_prev*sizeof(_Py_CODEUNIT), &trace_info->bounds);
7925 int addr = _PyInterpreterFrame_LASTI(frame) * sizeof(_Py_CODEUNIT);
7926 int line = _PyCode_CheckLineNumber(addr, &trace_info->bounds);
7927 if (line != -1) {
7928 /* Trace backward edges or first instruction of a new line */
7929 if (_PyInterpreterFrame_LASTI(frame) < instr_prev ||
7930 (line != lastline && addr == trace_info->bounds.ar_start))
7931 {
7932 co_filename = PyUnicode_AsUTF8(frame->f_code->co_filename);
7933 if (!co_filename) {
7934 co_filename = "?";
7935 }
7936 co_name = PyUnicode_AsUTF8(frame->f_code->co_name);
7937 if (!co_name) {
7938 co_name = "?";
7939 }
7940 PyDTrace_LINE(co_filename, co_name, line);
7941 }
7942 }
7943 }
7944
7945 /* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
7946 for the limited API. */
7947
7948 #undef Py_EnterRecursiveCall
7949
7950 int Py_EnterRecursiveCall(const char *where)
7951 {
7952 return _Py_EnterRecursiveCall(where);
7953 }
7954
7955 #undef Py_LeaveRecursiveCall
7956
7957 void Py_LeaveRecursiveCall(void)
7958 {
7959 _Py_LeaveRecursiveCall();
7960 }
7961