1 /* Execute compiled code */
2
3 #define _PY_INTERPRETER
4
5 #include "Python.h"
6 #include "pycore_abstract.h" // _PyIndex_Check()
7 #include "pycore_backoff.h"
8 #include "pycore_call.h" // _PyObject_CallNoArgs()
9 #include "pycore_cell.h" // PyCell_GetRef()
10 #include "pycore_ceval.h"
11 #include "pycore_code.h"
12 #include "pycore_emscripten_signal.h" // _Py_CHECK_EMSCRIPTEN_SIGNALS
13 #include "pycore_function.h"
14 #include "pycore_instruments.h"
15 #include "pycore_intrinsics.h"
16 #include "pycore_jit.h"
17 #include "pycore_long.h" // _PyLong_GetZero()
18 #include "pycore_moduleobject.h" // PyModuleObject
19 #include "pycore_object.h" // _PyObject_GC_TRACK()
20 #include "pycore_opcode_metadata.h" // EXTRA_CASES
21 #include "pycore_optimizer.h" // _PyUOpExecutor_Type
22 #include "pycore_opcode_utils.h" // MAKE_FUNCTION_*
23 #include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_*
24 #include "pycore_pyerrors.h" // _PyErr_GetRaisedException()
25 #include "pycore_pystate.h" // _PyInterpreterState_GET()
26 #include "pycore_range.h" // _PyRangeIterObject
27 #include "pycore_setobject.h" // _PySet_Update()
28 #include "pycore_sliceobject.h" // _PyBuildSlice_ConsumeRefs
29 #include "pycore_sysmodule.h" // _PySys_Audit()
30 #include "pycore_tuple.h" // _PyTuple_ITEMS()
31 #include "pycore_typeobject.h" // _PySuper_Lookup()
32 #include "pycore_uop_ids.h" // Uops
33 #include "pycore_pyerrors.h"
34
35 #include "pycore_dict.h"
36 #include "dictobject.h"
37 #include "pycore_frame.h"
38 #include "frameobject.h" // _PyInterpreterFrame_GetLine
39 #include "opcode.h"
40 #include "pydtrace.h"
41 #include "setobject.h"
42
43 #include <stdbool.h> // bool
44
45 #ifdef Py_DEBUG
46 /* For debugging the interpreter: */
47 # define LLTRACE 1 /* Low-level trace feature */
48 #endif
49
50 #if !defined(Py_BUILD_CORE)
51 # error "ceval.c must be build with Py_BUILD_CORE define for best performance"
52 #endif
53
54 #if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_GIL_DISABLED)
55 // GH-89279: The MSVC compiler does not inline these static inline functions
56 // in PGO build in _PyEval_EvalFrameDefault(), because this function is over
57 // the limit of PGO, and that limit cannot be configured.
58 // Define them as macros to make sure that they are always inlined by the
59 // preprocessor.
60 // TODO: implement Py_DECREF macro for Py_GIL_DISABLED
61
62 #undef Py_DECREF
63 #define Py_DECREF(arg) \
64 do { \
65 PyObject *op = _PyObject_CAST(arg); \
66 if (_Py_IsImmortal(op)) { \
67 break; \
68 } \
69 _Py_DECREF_STAT_INC(); \
70 if (--op->ob_refcnt == 0) { \
71 destructor dealloc = Py_TYPE(op)->tp_dealloc; \
72 (*dealloc)(op); \
73 } \
74 } while (0)
75
76 #undef Py_XDECREF
77 #define Py_XDECREF(arg) \
78 do { \
79 PyObject *xop = _PyObject_CAST(arg); \
80 if (xop != NULL) { \
81 Py_DECREF(xop); \
82 } \
83 } while (0)
84
85 #undef Py_IS_TYPE
86 #define Py_IS_TYPE(ob, type) \
87 (_PyObject_CAST(ob)->ob_type == (type))
88
89 #undef _Py_DECREF_SPECIALIZED
90 #define _Py_DECREF_SPECIALIZED(arg, dealloc) \
91 do { \
92 PyObject *op = _PyObject_CAST(arg); \
93 if (_Py_IsImmortal(op)) { \
94 break; \
95 } \
96 _Py_DECREF_STAT_INC(); \
97 if (--op->ob_refcnt == 0) { \
98 struct _reftracer_runtime_state *tracer = &_PyRuntime.ref_tracer; \
99 if (tracer->tracer_func != NULL) { \
100 void* data = tracer->tracer_data; \
101 tracer->tracer_func(op, PyRefTracer_DESTROY, data); \
102 } \
103 destructor d = (destructor)(dealloc); \
104 d(op); \
105 } \
106 } while (0)
107 #endif
108
109
110 #ifdef LLTRACE
111 static void
dump_stack(_PyInterpreterFrame * frame,PyObject ** stack_pointer)112 dump_stack(_PyInterpreterFrame *frame, PyObject **stack_pointer)
113 {
114 PyObject **stack_base = _PyFrame_Stackbase(frame);
115 PyObject *exc = PyErr_GetRaisedException();
116 printf(" stack=[");
117 for (PyObject **ptr = stack_base; ptr < stack_pointer; ptr++) {
118 if (ptr != stack_base) {
119 printf(", ");
120 }
121 if (*ptr == NULL) {
122 printf("<nil>");
123 continue;
124 }
125 if (
126 *ptr == Py_None
127 || PyBool_Check(*ptr)
128 || PyLong_CheckExact(*ptr)
129 || PyFloat_CheckExact(*ptr)
130 || PyUnicode_CheckExact(*ptr)
131 ) {
132 if (PyObject_Print(*ptr, stdout, 0) == 0) {
133 continue;
134 }
135 PyErr_Clear();
136 }
137 // Don't call __repr__(), it might recurse into the interpreter.
138 printf("<%s at %p>", Py_TYPE(*ptr)->tp_name, (void *)(*ptr));
139 }
140 printf("]\n");
141 fflush(stdout);
142 PyErr_SetRaisedException(exc);
143 }
144
145 static void
lltrace_instruction(_PyInterpreterFrame * frame,PyObject ** stack_pointer,_Py_CODEUNIT * next_instr,int opcode,int oparg)146 lltrace_instruction(_PyInterpreterFrame *frame,
147 PyObject **stack_pointer,
148 _Py_CODEUNIT *next_instr,
149 int opcode,
150 int oparg)
151 {
152 if (frame->owner == FRAME_OWNED_BY_CSTACK) {
153 return;
154 }
155 dump_stack(frame, stack_pointer);
156 const char *opname = _PyOpcode_OpName[opcode];
157 assert(opname != NULL);
158 int offset = (int)(next_instr - _PyCode_CODE(_PyFrame_GetCode(frame)));
159 if (OPCODE_HAS_ARG((int)_PyOpcode_Deopt[opcode])) {
160 printf("%d: %s %d\n", offset * 2, opname, oparg);
161 }
162 else {
163 printf("%d: %s\n", offset * 2, opname);
164 }
165 fflush(stdout);
166 }
167 static void
lltrace_resume_frame(_PyInterpreterFrame * frame)168 lltrace_resume_frame(_PyInterpreterFrame *frame)
169 {
170 PyObject *fobj = frame->f_funcobj;
171 if (!PyCode_Check(frame->f_executable) ||
172 fobj == NULL ||
173 !PyFunction_Check(fobj)
174 ) {
175 printf("\nResuming frame.\n");
176 return;
177 }
178 PyFunctionObject *f = (PyFunctionObject *)fobj;
179 PyObject *exc = PyErr_GetRaisedException();
180 PyObject *name = f->func_qualname;
181 if (name == NULL) {
182 name = f->func_name;
183 }
184 printf("\nResuming frame");
185 if (name) {
186 printf(" for ");
187 if (PyObject_Print(name, stdout, 0) < 0) {
188 PyErr_Clear();
189 }
190 }
191 if (f->func_module) {
192 printf(" in module ");
193 if (PyObject_Print(f->func_module, stdout, 0) < 0) {
194 PyErr_Clear();
195 }
196 }
197 printf("\n");
198 fflush(stdout);
199 PyErr_SetRaisedException(exc);
200 }
201
202 static int
maybe_lltrace_resume_frame(_PyInterpreterFrame * frame,_PyInterpreterFrame * skip_frame,PyObject * globals)203 maybe_lltrace_resume_frame(_PyInterpreterFrame *frame, _PyInterpreterFrame *skip_frame, PyObject *globals)
204 {
205 if (globals == NULL) {
206 return 0;
207 }
208 if (frame == skip_frame) {
209 return 0;
210 }
211 int r = PyDict_Contains(globals, &_Py_ID(__lltrace__));
212 if (r < 0) {
213 return -1;
214 }
215 int lltrace = r * 5; // Levels 1-4 only trace uops
216 if (!lltrace) {
217 // Can also be controlled by environment variable
218 char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
219 if (python_lltrace != NULL && *python_lltrace >= '0') {
220 lltrace = *python_lltrace - '0'; // TODO: Parse an int and all that
221 }
222 }
223 if (lltrace >= 5) {
224 lltrace_resume_frame(frame);
225 }
226 return lltrace;
227 }
228
229 #endif
230
231 static void monitor_reraise(PyThreadState *tstate,
232 _PyInterpreterFrame *frame,
233 _Py_CODEUNIT *instr);
234 static int monitor_stop_iteration(PyThreadState *tstate,
235 _PyInterpreterFrame *frame,
236 _Py_CODEUNIT *instr,
237 PyObject *value);
238 static void monitor_unwind(PyThreadState *tstate,
239 _PyInterpreterFrame *frame,
240 _Py_CODEUNIT *instr);
241 static int monitor_handled(PyThreadState *tstate,
242 _PyInterpreterFrame *frame,
243 _Py_CODEUNIT *instr, PyObject *exc);
244 static void monitor_throw(PyThreadState *tstate,
245 _PyInterpreterFrame *frame,
246 _Py_CODEUNIT *instr);
247
248 static PyObject * import_name(PyThreadState *, _PyInterpreterFrame *,
249 PyObject *, PyObject *, PyObject *);
250 static PyObject * import_from(PyThreadState *, PyObject *, PyObject *);
251 static int check_args_iterable(PyThreadState *, PyObject *func, PyObject *vararg);
252 static int get_exception_handler(PyCodeObject *, int, int*, int*, int*);
253 static _PyInterpreterFrame *
254 _PyEvalFramePushAndInit_Ex(PyThreadState *tstate, PyFunctionObject *func,
255 PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs);
256
257 #ifdef HAVE_ERRNO_H
258 #include <errno.h>
259 #endif
260
261 int
Py_GetRecursionLimit(void)262 Py_GetRecursionLimit(void)
263 {
264 PyInterpreterState *interp = _PyInterpreterState_GET();
265 return interp->ceval.recursion_limit;
266 }
267
268 void
Py_SetRecursionLimit(int new_limit)269 Py_SetRecursionLimit(int new_limit)
270 {
271 PyInterpreterState *interp = _PyInterpreterState_GET();
272 interp->ceval.recursion_limit = new_limit;
273 for (PyThreadState *p = interp->threads.head; p != NULL; p = p->next) {
274 int depth = p->py_recursion_limit - p->py_recursion_remaining;
275 p->py_recursion_limit = new_limit;
276 p->py_recursion_remaining = new_limit - depth;
277 }
278 }
279
280 /* The function _Py_EnterRecursiveCallTstate() only calls _Py_CheckRecursiveCall()
281 if the recursion_depth reaches recursion_limit. */
282 int
_Py_CheckRecursiveCall(PyThreadState * tstate,const char * where)283 _Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
284 {
285 #ifdef USE_STACKCHECK
286 if (PyOS_CheckStack()) {
287 ++tstate->c_recursion_remaining;
288 _PyErr_SetString(tstate, PyExc_MemoryError, "Stack overflow");
289 return -1;
290 }
291 #endif
292 if (tstate->recursion_headroom) {
293 if (tstate->c_recursion_remaining < -50) {
294 /* Overflowing while handling an overflow. Give up. */
295 Py_FatalError("Cannot recover from stack overflow.");
296 }
297 }
298 else {
299 if (tstate->c_recursion_remaining <= 0) {
300 tstate->recursion_headroom++;
301 _PyErr_Format(tstate, PyExc_RecursionError,
302 "maximum recursion depth exceeded%s",
303 where);
304 tstate->recursion_headroom--;
305 ++tstate->c_recursion_remaining;
306 return -1;
307 }
308 }
309 return 0;
310 }
311
312
313 const binaryfunc _PyEval_BinaryOps[] = {
314 [NB_ADD] = PyNumber_Add,
315 [NB_AND] = PyNumber_And,
316 [NB_FLOOR_DIVIDE] = PyNumber_FloorDivide,
317 [NB_LSHIFT] = PyNumber_Lshift,
318 [NB_MATRIX_MULTIPLY] = PyNumber_MatrixMultiply,
319 [NB_MULTIPLY] = PyNumber_Multiply,
320 [NB_REMAINDER] = PyNumber_Remainder,
321 [NB_OR] = PyNumber_Or,
322 [NB_POWER] = _PyNumber_PowerNoMod,
323 [NB_RSHIFT] = PyNumber_Rshift,
324 [NB_SUBTRACT] = PyNumber_Subtract,
325 [NB_TRUE_DIVIDE] = PyNumber_TrueDivide,
326 [NB_XOR] = PyNumber_Xor,
327 [NB_INPLACE_ADD] = PyNumber_InPlaceAdd,
328 [NB_INPLACE_AND] = PyNumber_InPlaceAnd,
329 [NB_INPLACE_FLOOR_DIVIDE] = PyNumber_InPlaceFloorDivide,
330 [NB_INPLACE_LSHIFT] = PyNumber_InPlaceLshift,
331 [NB_INPLACE_MATRIX_MULTIPLY] = PyNumber_InPlaceMatrixMultiply,
332 [NB_INPLACE_MULTIPLY] = PyNumber_InPlaceMultiply,
333 [NB_INPLACE_REMAINDER] = PyNumber_InPlaceRemainder,
334 [NB_INPLACE_OR] = PyNumber_InPlaceOr,
335 [NB_INPLACE_POWER] = _PyNumber_InPlacePowerNoMod,
336 [NB_INPLACE_RSHIFT] = PyNumber_InPlaceRshift,
337 [NB_INPLACE_SUBTRACT] = PyNumber_InPlaceSubtract,
338 [NB_INPLACE_TRUE_DIVIDE] = PyNumber_InPlaceTrueDivide,
339 [NB_INPLACE_XOR] = PyNumber_InPlaceXor,
340 };
341
342 const conversion_func _PyEval_ConversionFuncs[4] = {
343 [FVC_STR] = PyObject_Str,
344 [FVC_REPR] = PyObject_Repr,
345 [FVC_ASCII] = PyObject_ASCII
346 };
347
348
349 // PEP 634: Structural Pattern Matching
350
351
352 // Return a tuple of values corresponding to keys, with error checks for
353 // duplicate/missing keys.
354 PyObject *
_PyEval_MatchKeys(PyThreadState * tstate,PyObject * map,PyObject * keys)355 _PyEval_MatchKeys(PyThreadState *tstate, PyObject *map, PyObject *keys)
356 {
357 assert(PyTuple_CheckExact(keys));
358 Py_ssize_t nkeys = PyTuple_GET_SIZE(keys);
359 if (!nkeys) {
360 // No keys means no items.
361 return PyTuple_New(0);
362 }
363 PyObject *seen = NULL;
364 PyObject *dummy = NULL;
365 PyObject *values = NULL;
366 PyObject *get = NULL;
367 // We use the two argument form of map.get(key, default) for two reasons:
368 // - Atomically check for a key and get its value without error handling.
369 // - Don't cause key creation or resizing in dict subclasses like
370 // collections.defaultdict that define __missing__ (or similar).
371 int meth_found = _PyObject_GetMethod(map, &_Py_ID(get), &get);
372 if (get == NULL) {
373 goto fail;
374 }
375 seen = PySet_New(NULL);
376 if (seen == NULL) {
377 goto fail;
378 }
379 // dummy = object()
380 dummy = _PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
381 if (dummy == NULL) {
382 goto fail;
383 }
384 values = PyTuple_New(nkeys);
385 if (values == NULL) {
386 goto fail;
387 }
388 for (Py_ssize_t i = 0; i < nkeys; i++) {
389 PyObject *key = PyTuple_GET_ITEM(keys, i);
390 if (PySet_Contains(seen, key) || PySet_Add(seen, key)) {
391 if (!_PyErr_Occurred(tstate)) {
392 // Seen it before!
393 _PyErr_Format(tstate, PyExc_ValueError,
394 "mapping pattern checks duplicate key (%R)", key);
395 }
396 goto fail;
397 }
398 PyObject *args[] = { map, key, dummy };
399 PyObject *value = NULL;
400 if (meth_found) {
401 value = PyObject_Vectorcall(get, args, 3, NULL);
402 }
403 else {
404 value = PyObject_Vectorcall(get, &args[1], 2, NULL);
405 }
406 if (value == NULL) {
407 goto fail;
408 }
409 if (value == dummy) {
410 // key not in map!
411 Py_DECREF(value);
412 Py_DECREF(values);
413 // Return None:
414 values = Py_NewRef(Py_None);
415 goto done;
416 }
417 PyTuple_SET_ITEM(values, i, value);
418 }
419 // Success:
420 done:
421 Py_DECREF(get);
422 Py_DECREF(seen);
423 Py_DECREF(dummy);
424 return values;
425 fail:
426 Py_XDECREF(get);
427 Py_XDECREF(seen);
428 Py_XDECREF(dummy);
429 Py_XDECREF(values);
430 return NULL;
431 }
432
433 // Extract a named attribute from the subject, with additional bookkeeping to
434 // raise TypeErrors for repeated lookups. On failure, return NULL (with no
435 // error set). Use _PyErr_Occurred(tstate) to disambiguate.
436 static PyObject *
match_class_attr(PyThreadState * tstate,PyObject * subject,PyObject * type,PyObject * name,PyObject * seen)437 match_class_attr(PyThreadState *tstate, PyObject *subject, PyObject *type,
438 PyObject *name, PyObject *seen)
439 {
440 assert(PyUnicode_CheckExact(name));
441 assert(PySet_CheckExact(seen));
442 if (PySet_Contains(seen, name) || PySet_Add(seen, name)) {
443 if (!_PyErr_Occurred(tstate)) {
444 // Seen it before!
445 _PyErr_Format(tstate, PyExc_TypeError,
446 "%s() got multiple sub-patterns for attribute %R",
447 ((PyTypeObject*)type)->tp_name, name);
448 }
449 return NULL;
450 }
451 PyObject *attr;
452 (void)PyObject_GetOptionalAttr(subject, name, &attr);
453 return attr;
454 }
455
456 // On success (match), return a tuple of extracted attributes. On failure (no
457 // match), return NULL. Use _PyErr_Occurred(tstate) to disambiguate.
458 PyObject*
_PyEval_MatchClass(PyThreadState * tstate,PyObject * subject,PyObject * type,Py_ssize_t nargs,PyObject * kwargs)459 _PyEval_MatchClass(PyThreadState *tstate, PyObject *subject, PyObject *type,
460 Py_ssize_t nargs, PyObject *kwargs)
461 {
462 if (!PyType_Check(type)) {
463 const char *e = "called match pattern must be a class";
464 _PyErr_Format(tstate, PyExc_TypeError, e);
465 return NULL;
466 }
467 assert(PyTuple_CheckExact(kwargs));
468 // First, an isinstance check:
469 if (PyObject_IsInstance(subject, type) <= 0) {
470 return NULL;
471 }
472 // So far so good:
473 PyObject *seen = PySet_New(NULL);
474 if (seen == NULL) {
475 return NULL;
476 }
477 PyObject *attrs = PyList_New(0);
478 if (attrs == NULL) {
479 Py_DECREF(seen);
480 return NULL;
481 }
482 // NOTE: From this point on, goto fail on failure:
483 PyObject *match_args = NULL;
484 // First, the positional subpatterns:
485 if (nargs) {
486 int match_self = 0;
487 if (PyObject_GetOptionalAttr(type, &_Py_ID(__match_args__), &match_args) < 0) {
488 goto fail;
489 }
490 if (match_args) {
491 if (!PyTuple_CheckExact(match_args)) {
492 const char *e = "%s.__match_args__ must be a tuple (got %s)";
493 _PyErr_Format(tstate, PyExc_TypeError, e,
494 ((PyTypeObject *)type)->tp_name,
495 Py_TYPE(match_args)->tp_name);
496 goto fail;
497 }
498 }
499 else {
500 // _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
501 // define __match_args__. This is natural behavior for subclasses:
502 // it's as if __match_args__ is some "magic" value that is lost as
503 // soon as they redefine it.
504 match_args = PyTuple_New(0);
505 match_self = PyType_HasFeature((PyTypeObject*)type,
506 _Py_TPFLAGS_MATCH_SELF);
507 }
508 assert(PyTuple_CheckExact(match_args));
509 Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
510 if (allowed < nargs) {
511 const char *plural = (allowed == 1) ? "" : "s";
512 _PyErr_Format(tstate, PyExc_TypeError,
513 "%s() accepts %d positional sub-pattern%s (%d given)",
514 ((PyTypeObject*)type)->tp_name,
515 allowed, plural, nargs);
516 goto fail;
517 }
518 if (match_self) {
519 // Easy. Copy the subject itself, and move on to kwargs.
520 if (PyList_Append(attrs, subject) < 0) {
521 goto fail;
522 }
523 }
524 else {
525 for (Py_ssize_t i = 0; i < nargs; i++) {
526 PyObject *name = PyTuple_GET_ITEM(match_args, i);
527 if (!PyUnicode_CheckExact(name)) {
528 _PyErr_Format(tstate, PyExc_TypeError,
529 "__match_args__ elements must be strings "
530 "(got %s)", Py_TYPE(name)->tp_name);
531 goto fail;
532 }
533 PyObject *attr = match_class_attr(tstate, subject, type, name,
534 seen);
535 if (attr == NULL) {
536 goto fail;
537 }
538 if (PyList_Append(attrs, attr) < 0) {
539 Py_DECREF(attr);
540 goto fail;
541 }
542 Py_DECREF(attr);
543 }
544 }
545 Py_CLEAR(match_args);
546 }
547 // Finally, the keyword subpatterns:
548 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
549 PyObject *name = PyTuple_GET_ITEM(kwargs, i);
550 PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
551 if (attr == NULL) {
552 goto fail;
553 }
554 if (PyList_Append(attrs, attr) < 0) {
555 Py_DECREF(attr);
556 goto fail;
557 }
558 Py_DECREF(attr);
559 }
560 Py_SETREF(attrs, PyList_AsTuple(attrs));
561 Py_DECREF(seen);
562 return attrs;
563 fail:
564 // We really don't care whether an error was raised or not... that's our
565 // caller's problem. All we know is that the match failed.
566 Py_XDECREF(match_args);
567 Py_DECREF(seen);
568 Py_DECREF(attrs);
569 return NULL;
570 }
571
572
573 static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
574
575 PyObject *
PyEval_EvalCode(PyObject * co,PyObject * globals,PyObject * locals)576 PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
577 {
578 PyThreadState *tstate = _PyThreadState_GET();
579 if (locals == NULL) {
580 locals = globals;
581 }
582 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
583 if (builtins == NULL) {
584 return NULL;
585 }
586 PyFrameConstructor desc = {
587 .fc_globals = globals,
588 .fc_builtins = builtins,
589 .fc_name = ((PyCodeObject *)co)->co_name,
590 .fc_qualname = ((PyCodeObject *)co)->co_name,
591 .fc_code = co,
592 .fc_defaults = NULL,
593 .fc_kwdefaults = NULL,
594 .fc_closure = NULL
595 };
596 PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
597 if (func == NULL) {
598 return NULL;
599 }
600 EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
601 PyObject *res = _PyEval_Vector(tstate, func, locals, NULL, 0, NULL);
602 Py_DECREF(func);
603 return res;
604 }
605
606
607 /* Interpreter main loop */
608
609 PyObject *
PyEval_EvalFrame(PyFrameObject * f)610 PyEval_EvalFrame(PyFrameObject *f)
611 {
612 /* Function kept for backward compatibility */
613 PyThreadState *tstate = _PyThreadState_GET();
614 return _PyEval_EvalFrame(tstate, f->f_frame, 0);
615 }
616
617 PyObject *
PyEval_EvalFrameEx(PyFrameObject * f,int throwflag)618 PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
619 {
620 PyThreadState *tstate = _PyThreadState_GET();
621 return _PyEval_EvalFrame(tstate, f->f_frame, throwflag);
622 }
623
624 #include "ceval_macros.h"
625
_Py_CheckRecursiveCallPy(PyThreadState * tstate)626 int _Py_CheckRecursiveCallPy(
627 PyThreadState *tstate)
628 {
629 if (tstate->recursion_headroom) {
630 if (tstate->py_recursion_remaining < -50) {
631 /* Overflowing while handling an overflow. Give up. */
632 Py_FatalError("Cannot recover from Python stack overflow.");
633 }
634 }
635 else {
636 if (tstate->py_recursion_remaining <= 0) {
637 tstate->recursion_headroom++;
638 _PyErr_Format(tstate, PyExc_RecursionError,
639 "maximum recursion depth exceeded");
640 tstate->recursion_headroom--;
641 return -1;
642 }
643 }
644 return 0;
645 }
646
647 static const _Py_CODEUNIT _Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS[] = {
648 /* Put a NOP at the start, so that the IP points into
649 * the code, rather than before it */
650 { .op.code = NOP, .op.arg = 0 },
651 { .op.code = INTERPRETER_EXIT, .op.arg = 0 }, /* reached on return */
652 { .op.code = NOP, .op.arg = 0 },
653 { .op.code = INTERPRETER_EXIT, .op.arg = 0 }, /* reached on yield */
654 { .op.code = RESUME, .op.arg = RESUME_OPARG_DEPTH1_MASK | RESUME_AT_FUNC_START }
655 };
656
657 extern const struct _PyCode_DEF(8) _Py_InitCleanup;
658
659 #ifdef Py_DEBUG
660 extern void _PyUOpPrint(const _PyUOpInstruction *uop);
661 #endif
662
663
664 /* Disable unused label warnings. They are handy for debugging, even
665 if computed gotos aren't used. */
666
667 /* TBD - what about other compilers? */
668 #if defined(__GNUC__)
669 # pragma GCC diagnostic push
670 # pragma GCC diagnostic ignored "-Wunused-label"
671 #elif defined(_MSC_VER) /* MS_WINDOWS */
672 # pragma warning(push)
673 # pragma warning(disable:4102)
674 #endif
675
676
677 /* _PyEval_EvalFrameDefault() is a *big* function,
678 * so consume 3 units of C stack */
679 #define PY_EVAL_C_STACK_UNITS 2
680
681 PyObject* _Py_HOT_FUNCTION
_PyEval_EvalFrameDefault(PyThreadState * tstate,_PyInterpreterFrame * frame,int throwflag)682 _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
683 {
684 _Py_EnsureTstateNotNULL(tstate);
685 CALL_STAT_INC(pyeval_calls);
686
687 #if USE_COMPUTED_GOTOS
688 /* Import the static jump table */
689 #include "opcode_targets.h"
690 #endif
691
692 #ifdef Py_STATS
693 int lastopcode = 0;
694 #endif
695 uint8_t opcode; /* Current opcode */
696 int oparg; /* Current opcode argument, if any */
697 #ifdef LLTRACE
698 int lltrace = 0;
699 #endif
700
701 _PyInterpreterFrame entry_frame;
702
703
704
705 #ifdef Py_DEBUG
706 /* Set these to invalid but identifiable values for debugging. */
707 entry_frame.f_funcobj = (PyObject*)0xaaa0;
708 entry_frame.f_locals = (PyObject*)0xaaa1;
709 entry_frame.frame_obj = (PyFrameObject*)0xaaa2;
710 entry_frame.f_globals = (PyObject*)0xaaa3;
711 entry_frame.f_builtins = (PyObject*)0xaaa4;
712 #endif
713 entry_frame.f_executable = Py_None;
714 entry_frame.instr_ptr = (_Py_CODEUNIT *)_Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS + 1;
715 entry_frame.stacktop = 0;
716 entry_frame.owner = FRAME_OWNED_BY_CSTACK;
717 entry_frame.return_offset = 0;
718 /* Push frame */
719 entry_frame.previous = tstate->current_frame;
720 frame->previous = &entry_frame;
721 tstate->current_frame = frame;
722
723 tstate->c_recursion_remaining -= (PY_EVAL_C_STACK_UNITS - 1);
724 if (_Py_EnterRecursiveCallTstate(tstate, "")) {
725 tstate->c_recursion_remaining--;
726 tstate->py_recursion_remaining--;
727 goto exit_unwind;
728 }
729
730 /* support for generator.throw() */
731 if (throwflag) {
732 if (_Py_EnterRecursivePy(tstate)) {
733 goto exit_unwind;
734 }
735 /* Because this avoids the RESUME,
736 * we need to update instrumentation */
737 _Py_Instrument(_PyFrame_GetCode(frame), tstate->interp);
738 monitor_throw(tstate, frame, frame->instr_ptr);
739 /* TO DO -- Monitor throw entry. */
740 goto resume_with_error;
741 }
742
743 /* Local "register" variables.
744 * These are cached values from the frame and code object. */
745 _Py_CODEUNIT *next_instr;
746 PyObject **stack_pointer;
747
748 #if defined(_Py_TIER2) && !defined(_Py_JIT)
749 /* Tier 2 interpreter state */
750 _PyExecutorObject *current_executor = NULL;
751 const _PyUOpInstruction *next_uop = NULL;
752 #endif
753
754 start_frame:
755 if (_Py_EnterRecursivePy(tstate)) {
756 goto exit_unwind;
757 }
758
759 next_instr = frame->instr_ptr;
760 resume_frame:
761 stack_pointer = _PyFrame_GetStackPointer(frame);
762
763 #ifdef LLTRACE
764 lltrace = maybe_lltrace_resume_frame(frame, &entry_frame, GLOBALS());
765 if (lltrace < 0) {
766 goto exit_unwind;
767 }
768 #endif
769
770 #ifdef Py_DEBUG
771 /* _PyEval_EvalFrameDefault() must not be called with an exception set,
772 because it can clear it (directly or indirectly) and so the
773 caller loses its exception */
774 assert(!_PyErr_Occurred(tstate));
775 #endif
776
777 DISPATCH();
778
779 {
780 /* Start instructions */
781 #if !USE_COMPUTED_GOTOS
782 dispatch_opcode:
783 switch (opcode)
784 #endif
785 {
786
787 #include "generated_cases.c.h"
788
789 /* INSTRUMENTED_LINE has to be here, rather than in bytecodes.c,
790 * because it needs to capture frame->instr_ptr before it is updated,
791 * as happens in the standard instruction prologue.
792 */
793 #if USE_COMPUTED_GOTOS
794 TARGET_INSTRUMENTED_LINE:
795 #else
796 case INSTRUMENTED_LINE:
797 #endif
798 {
799 _Py_CODEUNIT *prev = frame->instr_ptr;
800 _Py_CODEUNIT *here = frame->instr_ptr = next_instr;
801 int original_opcode = 0;
802 if (tstate->tracing) {
803 PyCodeObject *code = _PyFrame_GetCode(frame);
804 original_opcode = code->_co_monitoring->lines[(int)(here - _PyCode_CODE(code))].original_opcode;
805 } else {
806 _PyFrame_SetStackPointer(frame, stack_pointer);
807 original_opcode = _Py_call_instrumentation_line(
808 tstate, frame, here, prev);
809 stack_pointer = _PyFrame_GetStackPointer(frame);
810 if (original_opcode < 0) {
811 next_instr = here+1;
812 goto error;
813 }
814 next_instr = frame->instr_ptr;
815 if (next_instr != here) {
816 DISPATCH();
817 }
818 }
819 if (_PyOpcode_Caches[original_opcode]) {
820 _PyBinaryOpCache *cache = (_PyBinaryOpCache *)(next_instr+1);
821 /* Prevent the underlying instruction from specializing
822 * and overwriting the instrumentation. */
823 PAUSE_ADAPTIVE_COUNTER(cache->counter);
824 }
825 opcode = original_opcode;
826 DISPATCH_GOTO();
827 }
828
829
830 #if USE_COMPUTED_GOTOS
831 _unknown_opcode:
832 #else
833 EXTRA_CASES // From pycore_opcode_metadata.h, a 'case' for each unused opcode
834 #endif
835 /* Tell C compilers not to hold the opcode variable in the loop.
836 next_instr points the current instruction without TARGET(). */
837 opcode = next_instr->op.code;
838 _PyErr_Format(tstate, PyExc_SystemError,
839 "%U:%d: unknown opcode %d",
840 _PyFrame_GetCode(frame)->co_filename,
841 PyUnstable_InterpreterFrame_GetLine(frame),
842 opcode);
843 goto error;
844
845 } /* End instructions */
846
847 /* This should never be reached. Every opcode should end with DISPATCH()
848 or goto error. */
849 Py_UNREACHABLE();
850
851 pop_4_error:
852 STACK_SHRINK(1);
853 pop_3_error:
854 STACK_SHRINK(1);
855 pop_2_error:
856 STACK_SHRINK(1);
857 pop_1_error:
858 STACK_SHRINK(1);
859 error:
860 /* Double-check exception status. */
861 #ifdef NDEBUG
862 if (!_PyErr_Occurred(tstate)) {
863 _PyErr_SetString(tstate, PyExc_SystemError,
864 "error return without exception set");
865 }
866 #else
867 assert(_PyErr_Occurred(tstate));
868 #endif
869
870 /* Log traceback info. */
871 assert(frame != &entry_frame);
872 if (!_PyFrame_IsIncomplete(frame)) {
873 PyFrameObject *f = _PyFrame_GetFrameObject(frame);
874 if (f != NULL) {
875 PyTraceBack_Here(f);
876 }
877 }
878 _PyEval_MonitorRaise(tstate, frame, next_instr-1);
879 exception_unwind:
880 {
881 /* We can't use frame->instr_ptr here, as RERAISE may have set it */
882 int offset = INSTR_OFFSET()-1;
883 int level, handler, lasti;
884 if (get_exception_handler(_PyFrame_GetCode(frame), offset, &level, &handler, &lasti) == 0) {
885 // No handlers, so exit.
886 assert(_PyErr_Occurred(tstate));
887
888 /* Pop remaining stack entries. */
889 PyObject **stackbase = _PyFrame_Stackbase(frame);
890 while (stack_pointer > stackbase) {
891 PyObject *o = POP();
892 Py_XDECREF(o);
893 }
894 assert(STACK_LEVEL() == 0);
895 _PyFrame_SetStackPointer(frame, stack_pointer);
896 monitor_unwind(tstate, frame, next_instr-1);
897 goto exit_unwind;
898 }
899
900 assert(STACK_LEVEL() >= level);
901 PyObject **new_top = _PyFrame_Stackbase(frame) + level;
902 while (stack_pointer > new_top) {
903 PyObject *v = POP();
904 Py_XDECREF(v);
905 }
906 if (lasti) {
907 int frame_lasti = _PyInterpreterFrame_LASTI(frame);
908 PyObject *lasti = PyLong_FromLong(frame_lasti);
909 if (lasti == NULL) {
910 goto exception_unwind;
911 }
912 PUSH(lasti);
913 }
914
915 /* Make the raw exception data
916 available to the handler,
917 so a program can emulate the
918 Python main loop. */
919 PyObject *exc = _PyErr_GetRaisedException(tstate);
920 PUSH(exc);
921 next_instr = _PyCode_CODE(_PyFrame_GetCode(frame)) + handler;
922
923 if (monitor_handled(tstate, frame, next_instr, exc) < 0) {
924 goto exception_unwind;
925 }
926 /* Resume normal execution */
927 #ifdef LLTRACE
928 if (lltrace >= 5) {
929 lltrace_resume_frame(frame);
930 }
931 #endif
932 DISPATCH();
933 }
934 }
935
936 exit_unwind:
937 assert(_PyErr_Occurred(tstate));
938 _Py_LeaveRecursiveCallPy(tstate);
939 assert(frame != &entry_frame);
940 // GH-99729: We need to unlink the frame *before* clearing it:
941 _PyInterpreterFrame *dying = frame;
942 frame = tstate->current_frame = dying->previous;
943 _PyEval_FrameClearAndPop(tstate, dying);
944 frame->return_offset = 0;
945 if (frame == &entry_frame) {
946 /* Restore previous frame and exit */
947 tstate->current_frame = frame->previous;
948 tstate->c_recursion_remaining += PY_EVAL_C_STACK_UNITS;
949 return NULL;
950 }
951
952 resume_with_error:
953 next_instr = frame->instr_ptr;
954 stack_pointer = _PyFrame_GetStackPointer(frame);
955 goto error;
956
957
958 #ifdef _Py_TIER2
959
960 // Tier 2 is also here!
961 enter_tier_two:
962
963 #ifdef _Py_JIT
964 assert(0);
965 #else
966
967 #undef LOAD_IP
968 #define LOAD_IP(UNUSED) (void)0
969
970 #undef GOTO_ERROR
971 #define GOTO_ERROR(LABEL) goto LABEL ## _tier_two
972
973 #ifdef Py_STATS
974 // Disable these macros that apply to Tier 1 stats when we are in Tier 2
975 #undef STAT_INC
976 #define STAT_INC(opname, name) ((void)0)
977 #undef STAT_DEC
978 #define STAT_DEC(opname, name) ((void)0)
979 #endif
980
981 #undef ENABLE_SPECIALIZATION
982 #define ENABLE_SPECIALIZATION 0
983
984 #ifdef Py_DEBUG
985 #define DPRINTF(level, ...) \
986 if (lltrace >= (level)) { printf(__VA_ARGS__); }
987 #else
988 #define DPRINTF(level, ...)
989 #endif
990
991 ; // dummy statement after a label, before a declaration
992 uint16_t uopcode;
993 #ifdef Py_STATS
994 int lastuop = 0;
995 uint64_t trace_uop_execution_counter = 0;
996 #endif
997
998 assert(next_uop->opcode == _START_EXECUTOR || next_uop->opcode == _COLD_EXIT);
999 tier2_dispatch:
1000 for (;;) {
1001 uopcode = next_uop->opcode;
1002 #ifdef Py_DEBUG
1003 if (lltrace >= 3) {
1004 if (next_uop->opcode == _START_EXECUTOR || next_uop->opcode == _COLD_EXIT) {
1005 printf("%4d uop: ", 0);
1006 }
1007 else {
1008 printf("%4d uop: ", (int)(next_uop - current_executor->trace));
1009 }
1010 _PyUOpPrint(next_uop);
1011 printf(" stack_level=%d\n",
1012 (int)(stack_pointer - _PyFrame_Stackbase(frame)));
1013 }
1014 #endif
1015 next_uop++;
1016 OPT_STAT_INC(uops_executed);
1017 UOP_STAT_INC(uopcode, execution_count);
1018 UOP_PAIR_INC(uopcode, lastuop);
1019 #ifdef Py_STATS
1020 trace_uop_execution_counter++;
1021 #endif
1022
1023 switch (uopcode) {
1024
1025 #include "executor_cases.c.h"
1026
1027 default:
1028 #ifdef Py_DEBUG
1029 {
1030 printf("Unknown uop: ");
1031 _PyUOpPrint(&next_uop[-1]);
1032 printf(" @ %d\n", (int)(next_uop - current_executor->trace - 1));
1033 Py_FatalError("Unknown uop");
1034 }
1035 #else
1036 Py_UNREACHABLE();
1037 #endif
1038
1039 }
1040 }
1041
1042 jump_to_error_target:
1043 #ifdef Py_DEBUG
1044 if (lltrace >= 2) {
1045 printf("Error: [UOp ");
1046 _PyUOpPrint(&next_uop[-1]);
1047 printf(" @ %d -> %s]\n",
1048 (int)(next_uop - current_executor->trace - 1),
1049 _PyOpcode_OpName[frame->instr_ptr->op.code]);
1050 }
1051 #endif
1052 assert (next_uop[-1].format == UOP_FORMAT_JUMP);
1053 uint16_t target = uop_get_error_target(&next_uop[-1]);
1054 next_uop = current_executor->trace + target;
1055 goto tier2_dispatch;
1056
1057 error_tier_two:
1058 OPT_HIST(trace_uop_execution_counter, trace_run_length_hist);
1059 assert(next_uop[-1].format == UOP_FORMAT_TARGET);
1060 frame->return_offset = 0; // Don't leave this random
1061 _PyFrame_SetStackPointer(frame, stack_pointer);
1062 Py_DECREF(current_executor);
1063 tstate->previous_executor = NULL;
1064 goto resume_with_error;
1065
1066 jump_to_jump_target:
1067 assert(next_uop[-1].format == UOP_FORMAT_JUMP);
1068 target = uop_get_jump_target(&next_uop[-1]);
1069 next_uop = current_executor->trace + target;
1070 goto tier2_dispatch;
1071
1072 exit_to_tier1_dynamic:
1073 next_instr = frame->instr_ptr;
1074 goto goto_to_tier1;
1075 exit_to_tier1:
1076 assert(next_uop[-1].format == UOP_FORMAT_TARGET);
1077 next_instr = next_uop[-1].target + _PyCode_CODE(_PyFrame_GetCode(frame));
1078 goto_to_tier1:
1079 #ifdef Py_DEBUG
1080 if (lltrace >= 2) {
1081 printf("DEOPT: [UOp ");
1082 _PyUOpPrint(&next_uop[-1]);
1083 printf(" -> %s]\n",
1084 _PyOpcode_OpName[next_instr->op.code]);
1085 }
1086 #endif
1087 OPT_HIST(trace_uop_execution_counter, trace_run_length_hist);
1088 Py_DECREF(current_executor);
1089 tstate->previous_executor = NULL;
1090 DISPATCH();
1091
1092 exit_to_trace:
1093 assert(next_uop[-1].format == UOP_FORMAT_EXIT);
1094 OPT_HIST(trace_uop_execution_counter, trace_run_length_hist);
1095 uint32_t exit_index = next_uop[-1].exit_index;
1096 assert(exit_index < current_executor->exit_count);
1097 _PyExitData *exit = ¤t_executor->exits[exit_index];
1098 #ifdef Py_DEBUG
1099 if (lltrace >= 2) {
1100 printf("SIDE EXIT: [UOp ");
1101 _PyUOpPrint(&next_uop[-1]);
1102 printf(", exit %u, temp %d, target %d -> %s]\n",
1103 exit_index, exit->temperature.as_counter, exit->target,
1104 _PyOpcode_OpName[_PyCode_CODE(_PyFrame_GetCode(frame))[exit->target].op.code]);
1105 }
1106 #endif
1107 Py_INCREF(exit->executor);
1108 tstate->previous_executor = (PyObject *)current_executor;
1109 GOTO_TIER_TWO(exit->executor);
1110
1111 #endif // _Py_JIT
1112
1113 #endif // _Py_TIER2
1114
1115 }
1116
1117 #if defined(__GNUC__)
1118 # pragma GCC diagnostic pop
1119 #elif defined(_MSC_VER) /* MS_WINDOWS */
1120 # pragma warning(pop)
1121 #endif
1122
1123 static void
format_missing(PyThreadState * tstate,const char * kind,PyCodeObject * co,PyObject * names,PyObject * qualname)1124 format_missing(PyThreadState *tstate, const char *kind,
1125 PyCodeObject *co, PyObject *names, PyObject *qualname)
1126 {
1127 int err;
1128 Py_ssize_t len = PyList_GET_SIZE(names);
1129 PyObject *name_str, *comma, *tail, *tmp;
1130
1131 assert(PyList_CheckExact(names));
1132 assert(len >= 1);
1133 /* Deal with the joys of natural language. */
1134 switch (len) {
1135 case 1:
1136 name_str = PyList_GET_ITEM(names, 0);
1137 Py_INCREF(name_str);
1138 break;
1139 case 2:
1140 name_str = PyUnicode_FromFormat("%U and %U",
1141 PyList_GET_ITEM(names, len - 2),
1142 PyList_GET_ITEM(names, len - 1));
1143 break;
1144 default:
1145 tail = PyUnicode_FromFormat(", %U, and %U",
1146 PyList_GET_ITEM(names, len - 2),
1147 PyList_GET_ITEM(names, len - 1));
1148 if (tail == NULL)
1149 return;
1150 /* Chop off the last two objects in the list. This shouldn't actually
1151 fail, but we can't be too careful. */
1152 err = PyList_SetSlice(names, len - 2, len, NULL);
1153 if (err == -1) {
1154 Py_DECREF(tail);
1155 return;
1156 }
1157 /* Stitch everything up into a nice comma-separated list. */
1158 comma = PyUnicode_FromString(", ");
1159 if (comma == NULL) {
1160 Py_DECREF(tail);
1161 return;
1162 }
1163 tmp = PyUnicode_Join(comma, names);
1164 Py_DECREF(comma);
1165 if (tmp == NULL) {
1166 Py_DECREF(tail);
1167 return;
1168 }
1169 name_str = PyUnicode_Concat(tmp, tail);
1170 Py_DECREF(tmp);
1171 Py_DECREF(tail);
1172 break;
1173 }
1174 if (name_str == NULL)
1175 return;
1176 _PyErr_Format(tstate, PyExc_TypeError,
1177 "%U() missing %i required %s argument%s: %U",
1178 qualname,
1179 len,
1180 kind,
1181 len == 1 ? "" : "s",
1182 name_str);
1183 Py_DECREF(name_str);
1184 }
1185
1186 static void
missing_arguments(PyThreadState * tstate,PyCodeObject * co,Py_ssize_t missing,Py_ssize_t defcount,PyObject ** localsplus,PyObject * qualname)1187 missing_arguments(PyThreadState *tstate, PyCodeObject *co,
1188 Py_ssize_t missing, Py_ssize_t defcount,
1189 PyObject **localsplus, PyObject *qualname)
1190 {
1191 Py_ssize_t i, j = 0;
1192 Py_ssize_t start, end;
1193 int positional = (defcount != -1);
1194 const char *kind = positional ? "positional" : "keyword-only";
1195 PyObject *missing_names;
1196
1197 /* Compute the names of the arguments that are missing. */
1198 missing_names = PyList_New(missing);
1199 if (missing_names == NULL)
1200 return;
1201 if (positional) {
1202 start = 0;
1203 end = co->co_argcount - defcount;
1204 }
1205 else {
1206 start = co->co_argcount;
1207 end = start + co->co_kwonlyargcount;
1208 }
1209 for (i = start; i < end; i++) {
1210 if (localsplus[i] == NULL) {
1211 PyObject *raw = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1212 PyObject *name = PyObject_Repr(raw);
1213 if (name == NULL) {
1214 Py_DECREF(missing_names);
1215 return;
1216 }
1217 PyList_SET_ITEM(missing_names, j++, name);
1218 }
1219 }
1220 assert(j == missing);
1221 format_missing(tstate, kind, co, missing_names, qualname);
1222 Py_DECREF(missing_names);
1223 }
1224
1225 static void
too_many_positional(PyThreadState * tstate,PyCodeObject * co,Py_ssize_t given,PyObject * defaults,PyObject ** localsplus,PyObject * qualname)1226 too_many_positional(PyThreadState *tstate, PyCodeObject *co,
1227 Py_ssize_t given, PyObject *defaults,
1228 PyObject **localsplus, PyObject *qualname)
1229 {
1230 int plural;
1231 Py_ssize_t kwonly_given = 0;
1232 Py_ssize_t i;
1233 PyObject *sig, *kwonly_sig;
1234 Py_ssize_t co_argcount = co->co_argcount;
1235
1236 assert((co->co_flags & CO_VARARGS) == 0);
1237 /* Count missing keyword-only args. */
1238 for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
1239 if (localsplus[i] != NULL) {
1240 kwonly_given++;
1241 }
1242 }
1243 Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
1244 if (defcount) {
1245 Py_ssize_t atleast = co_argcount - defcount;
1246 plural = 1;
1247 sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
1248 }
1249 else {
1250 plural = (co_argcount != 1);
1251 sig = PyUnicode_FromFormat("%zd", co_argcount);
1252 }
1253 if (sig == NULL)
1254 return;
1255 if (kwonly_given) {
1256 const char *format = " positional argument%s (and %zd keyword-only argument%s)";
1257 kwonly_sig = PyUnicode_FromFormat(format,
1258 given != 1 ? "s" : "",
1259 kwonly_given,
1260 kwonly_given != 1 ? "s" : "");
1261 if (kwonly_sig == NULL) {
1262 Py_DECREF(sig);
1263 return;
1264 }
1265 }
1266 else {
1267 /* This will not fail. */
1268 kwonly_sig = PyUnicode_FromString("");
1269 assert(kwonly_sig != NULL);
1270 }
1271 _PyErr_Format(tstate, PyExc_TypeError,
1272 "%U() takes %U positional argument%s but %zd%U %s given",
1273 qualname,
1274 sig,
1275 plural ? "s" : "",
1276 given,
1277 kwonly_sig,
1278 given == 1 && !kwonly_given ? "was" : "were");
1279 Py_DECREF(sig);
1280 Py_DECREF(kwonly_sig);
1281 }
1282
1283 static int
positional_only_passed_as_keyword(PyThreadState * tstate,PyCodeObject * co,Py_ssize_t kwcount,PyObject * kwnames,PyObject * qualname)1284 positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
1285 Py_ssize_t kwcount, PyObject* kwnames,
1286 PyObject *qualname)
1287 {
1288 int posonly_conflicts = 0;
1289 PyObject* posonly_names = PyList_New(0);
1290 if (posonly_names == NULL) {
1291 goto fail;
1292 }
1293 for(int k=0; k < co->co_posonlyargcount; k++){
1294 PyObject* posonly_name = PyTuple_GET_ITEM(co->co_localsplusnames, k);
1295
1296 for (int k2=0; k2<kwcount; k2++){
1297 /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
1298 PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
1299 if (kwname == posonly_name){
1300 if(PyList_Append(posonly_names, kwname) != 0) {
1301 goto fail;
1302 }
1303 posonly_conflicts++;
1304 continue;
1305 }
1306
1307 int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
1308
1309 if ( cmp > 0) {
1310 if(PyList_Append(posonly_names, kwname) != 0) {
1311 goto fail;
1312 }
1313 posonly_conflicts++;
1314 } else if (cmp < 0) {
1315 goto fail;
1316 }
1317
1318 }
1319 }
1320 if (posonly_conflicts) {
1321 PyObject* comma = PyUnicode_FromString(", ");
1322 if (comma == NULL) {
1323 goto fail;
1324 }
1325 PyObject* error_names = PyUnicode_Join(comma, posonly_names);
1326 Py_DECREF(comma);
1327 if (error_names == NULL) {
1328 goto fail;
1329 }
1330 _PyErr_Format(tstate, PyExc_TypeError,
1331 "%U() got some positional-only arguments passed"
1332 " as keyword arguments: '%U'",
1333 qualname, error_names);
1334 Py_DECREF(error_names);
1335 goto fail;
1336 }
1337
1338 Py_DECREF(posonly_names);
1339 return 0;
1340
1341 fail:
1342 Py_XDECREF(posonly_names);
1343 return 1;
1344
1345 }
1346
1347
1348 static inline unsigned char *
scan_back_to_entry_start(unsigned char * p)1349 scan_back_to_entry_start(unsigned char *p) {
1350 for (; (p[0]&128) == 0; p--);
1351 return p;
1352 }
1353
1354 static inline unsigned char *
skip_to_next_entry(unsigned char * p,unsigned char * end)1355 skip_to_next_entry(unsigned char *p, unsigned char *end) {
1356 while (p < end && ((p[0] & 128) == 0)) {
1357 p++;
1358 }
1359 return p;
1360 }
1361
1362
1363 #define MAX_LINEAR_SEARCH 40
1364
1365 static int
get_exception_handler(PyCodeObject * code,int index,int * level,int * handler,int * lasti)1366 get_exception_handler(PyCodeObject *code, int index, int *level, int *handler, int *lasti)
1367 {
1368 unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code->co_exceptiontable);
1369 unsigned char *end = start + PyBytes_GET_SIZE(code->co_exceptiontable);
1370 /* Invariants:
1371 * start_table == end_table OR
1372 * start_table points to a legal entry and end_table points
1373 * beyond the table or to a legal entry that is after index.
1374 */
1375 if (end - start > MAX_LINEAR_SEARCH) {
1376 int offset;
1377 parse_varint(start, &offset);
1378 if (offset > index) {
1379 return 0;
1380 }
1381 do {
1382 unsigned char * mid = start + ((end-start)>>1);
1383 mid = scan_back_to_entry_start(mid);
1384 parse_varint(mid, &offset);
1385 if (offset > index) {
1386 end = mid;
1387 }
1388 else {
1389 start = mid;
1390 }
1391
1392 } while (end - start > MAX_LINEAR_SEARCH);
1393 }
1394 unsigned char *scan = start;
1395 while (scan < end) {
1396 int start_offset, size;
1397 scan = parse_varint(scan, &start_offset);
1398 if (start_offset > index) {
1399 break;
1400 }
1401 scan = parse_varint(scan, &size);
1402 if (start_offset + size > index) {
1403 scan = parse_varint(scan, handler);
1404 int depth_and_lasti;
1405 parse_varint(scan, &depth_and_lasti);
1406 *level = depth_and_lasti >> 1;
1407 *lasti = depth_and_lasti & 1;
1408 return 1;
1409 }
1410 scan = skip_to_next_entry(scan, end);
1411 }
1412 return 0;
1413 }
1414
1415 static int
initialize_locals(PyThreadState * tstate,PyFunctionObject * func,PyObject ** localsplus,PyObject * const * args,Py_ssize_t argcount,PyObject * kwnames)1416 initialize_locals(PyThreadState *tstate, PyFunctionObject *func,
1417 PyObject **localsplus, PyObject *const *args,
1418 Py_ssize_t argcount, PyObject *kwnames)
1419 {
1420 PyCodeObject *co = (PyCodeObject*)func->func_code;
1421 const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
1422
1423 /* Create a dictionary for keyword parameters (**kwags) */
1424 PyObject *kwdict;
1425 Py_ssize_t i;
1426 if (co->co_flags & CO_VARKEYWORDS) {
1427 kwdict = PyDict_New();
1428 if (kwdict == NULL) {
1429 goto fail_pre_positional;
1430 }
1431 i = total_args;
1432 if (co->co_flags & CO_VARARGS) {
1433 i++;
1434 }
1435 assert(localsplus[i] == NULL);
1436 localsplus[i] = kwdict;
1437 }
1438 else {
1439 kwdict = NULL;
1440 }
1441
1442 /* Copy all positional arguments into local variables */
1443 Py_ssize_t j, n;
1444 if (argcount > co->co_argcount) {
1445 n = co->co_argcount;
1446 }
1447 else {
1448 n = argcount;
1449 }
1450 for (j = 0; j < n; j++) {
1451 PyObject *x = args[j];
1452 assert(localsplus[j] == NULL);
1453 localsplus[j] = x;
1454 }
1455
1456 /* Pack other positional arguments into the *args argument */
1457 if (co->co_flags & CO_VARARGS) {
1458 PyObject *u = NULL;
1459 if (argcount == n) {
1460 u = (PyObject *)&_Py_SINGLETON(tuple_empty);
1461 }
1462 else {
1463 assert(args != NULL);
1464 u = _PyTuple_FromArraySteal(args + n, argcount - n);
1465 }
1466 if (u == NULL) {
1467 goto fail_post_positional;
1468 }
1469 assert(localsplus[total_args] == NULL);
1470 localsplus[total_args] = u;
1471 }
1472 else if (argcount > n) {
1473 /* Too many postional args. Error is reported later */
1474 for (j = n; j < argcount; j++) {
1475 Py_DECREF(args[j]);
1476 }
1477 }
1478
1479 /* Handle keyword arguments */
1480 if (kwnames != NULL) {
1481 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1482 for (i = 0; i < kwcount; i++) {
1483 PyObject **co_varnames;
1484 PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
1485 PyObject *value = args[i+argcount];
1486 Py_ssize_t j;
1487
1488 if (keyword == NULL || !PyUnicode_Check(keyword)) {
1489 _PyErr_Format(tstate, PyExc_TypeError,
1490 "%U() keywords must be strings",
1491 func->func_qualname);
1492 goto kw_fail;
1493 }
1494
1495 /* Speed hack: do raw pointer compares. As names are
1496 normally interned this should almost always hit. */
1497 co_varnames = ((PyTupleObject *)(co->co_localsplusnames))->ob_item;
1498 for (j = co->co_posonlyargcount; j < total_args; j++) {
1499 PyObject *varname = co_varnames[j];
1500 if (varname == keyword) {
1501 goto kw_found;
1502 }
1503 }
1504
1505 /* Slow fallback, just in case */
1506 for (j = co->co_posonlyargcount; j < total_args; j++) {
1507 PyObject *varname = co_varnames[j];
1508 int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
1509 if (cmp > 0) {
1510 goto kw_found;
1511 }
1512 else if (cmp < 0) {
1513 goto kw_fail;
1514 }
1515 }
1516
1517 assert(j >= total_args);
1518 if (kwdict == NULL) {
1519
1520 if (co->co_posonlyargcount
1521 && positional_only_passed_as_keyword(tstate, co,
1522 kwcount, kwnames,
1523 func->func_qualname))
1524 {
1525 goto kw_fail;
1526 }
1527
1528 PyObject* suggestion_keyword = NULL;
1529 if (total_args > co->co_posonlyargcount) {
1530 PyObject* possible_keywords = PyList_New(total_args - co->co_posonlyargcount);
1531
1532 if (!possible_keywords) {
1533 PyErr_Clear();
1534 } else {
1535 for (Py_ssize_t k = co->co_posonlyargcount; k < total_args; k++) {
1536 PyList_SET_ITEM(possible_keywords, k - co->co_posonlyargcount, co_varnames[k]);
1537 }
1538
1539 suggestion_keyword = _Py_CalculateSuggestions(possible_keywords, keyword);
1540 Py_DECREF(possible_keywords);
1541 }
1542 }
1543
1544 if (suggestion_keyword) {
1545 _PyErr_Format(tstate, PyExc_TypeError,
1546 "%U() got an unexpected keyword argument '%S'. Did you mean '%S'?",
1547 func->func_qualname, keyword, suggestion_keyword);
1548 Py_DECREF(suggestion_keyword);
1549 } else {
1550 _PyErr_Format(tstate, PyExc_TypeError,
1551 "%U() got an unexpected keyword argument '%S'",
1552 func->func_qualname, keyword);
1553 }
1554
1555 goto kw_fail;
1556 }
1557
1558 if (PyDict_SetItem(kwdict, keyword, value) == -1) {
1559 goto kw_fail;
1560 }
1561 Py_DECREF(value);
1562 continue;
1563
1564 kw_fail:
1565 for (;i < kwcount; i++) {
1566 PyObject *value = args[i+argcount];
1567 Py_DECREF(value);
1568 }
1569 goto fail_post_args;
1570
1571 kw_found:
1572 if (localsplus[j] != NULL) {
1573 _PyErr_Format(tstate, PyExc_TypeError,
1574 "%U() got multiple values for argument '%S'",
1575 func->func_qualname, keyword);
1576 goto kw_fail;
1577 }
1578 localsplus[j] = value;
1579 }
1580 }
1581
1582 /* Check the number of positional arguments */
1583 if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
1584 too_many_positional(tstate, co, argcount, func->func_defaults, localsplus,
1585 func->func_qualname);
1586 goto fail_post_args;
1587 }
1588
1589 /* Add missing positional arguments (copy default values from defs) */
1590 if (argcount < co->co_argcount) {
1591 Py_ssize_t defcount = func->func_defaults == NULL ? 0 : PyTuple_GET_SIZE(func->func_defaults);
1592 Py_ssize_t m = co->co_argcount - defcount;
1593 Py_ssize_t missing = 0;
1594 for (i = argcount; i < m; i++) {
1595 if (localsplus[i] == NULL) {
1596 missing++;
1597 }
1598 }
1599 if (missing) {
1600 missing_arguments(tstate, co, missing, defcount, localsplus,
1601 func->func_qualname);
1602 goto fail_post_args;
1603 }
1604 if (n > m)
1605 i = n - m;
1606 else
1607 i = 0;
1608 if (defcount) {
1609 PyObject **defs = &PyTuple_GET_ITEM(func->func_defaults, 0);
1610 for (; i < defcount; i++) {
1611 if (localsplus[m+i] == NULL) {
1612 PyObject *def = defs[i];
1613 localsplus[m+i] = Py_NewRef(def);
1614 }
1615 }
1616 }
1617 }
1618
1619 /* Add missing keyword arguments (copy default values from kwdefs) */
1620 if (co->co_kwonlyargcount > 0) {
1621 Py_ssize_t missing = 0;
1622 for (i = co->co_argcount; i < total_args; i++) {
1623 if (localsplus[i] != NULL)
1624 continue;
1625 PyObject *varname = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1626 if (func->func_kwdefaults != NULL) {
1627 PyObject *def;
1628 if (PyDict_GetItemRef(func->func_kwdefaults, varname, &def) < 0) {
1629 goto fail_post_args;
1630 }
1631 if (def) {
1632 localsplus[i] = def;
1633 continue;
1634 }
1635 }
1636 missing++;
1637 }
1638 if (missing) {
1639 missing_arguments(tstate, co, missing, -1, localsplus,
1640 func->func_qualname);
1641 goto fail_post_args;
1642 }
1643 }
1644 return 0;
1645
1646 fail_pre_positional:
1647 for (j = 0; j < argcount; j++) {
1648 Py_DECREF(args[j]);
1649 }
1650 /* fall through */
1651 fail_post_positional:
1652 if (kwnames) {
1653 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1654 for (j = argcount; j < argcount+kwcount; j++) {
1655 Py_DECREF(args[j]);
1656 }
1657 }
1658 /* fall through */
1659 fail_post_args:
1660 return -1;
1661 }
1662
1663 static void
clear_thread_frame(PyThreadState * tstate,_PyInterpreterFrame * frame)1664 clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1665 {
1666 assert(frame->owner == FRAME_OWNED_BY_THREAD);
1667 // Make sure that this is, indeed, the top frame. We can't check this in
1668 // _PyThreadState_PopFrame, since f_code is already cleared at that point:
1669 assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize ==
1670 tstate->datastack_top);
1671 tstate->c_recursion_remaining--;
1672 assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1673 _PyFrame_ClearExceptCode(frame);
1674 Py_DECREF(frame->f_executable);
1675 tstate->c_recursion_remaining++;
1676 _PyThreadState_PopFrame(tstate, frame);
1677 }
1678
1679 static void
clear_gen_frame(PyThreadState * tstate,_PyInterpreterFrame * frame)1680 clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1681 {
1682 assert(frame->owner == FRAME_OWNED_BY_GENERATOR);
1683 PyGenObject *gen = _PyFrame_GetGenerator(frame);
1684 gen->gi_frame_state = FRAME_CLEARED;
1685 assert(tstate->exc_info == &gen->gi_exc_state);
1686 tstate->exc_info = gen->gi_exc_state.previous_item;
1687 gen->gi_exc_state.previous_item = NULL;
1688 tstate->c_recursion_remaining--;
1689 assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1690 _PyFrame_ClearExceptCode(frame);
1691 _PyErr_ClearExcState(&gen->gi_exc_state);
1692 tstate->c_recursion_remaining++;
1693 frame->previous = NULL;
1694 }
1695
1696 void
_PyEval_FrameClearAndPop(PyThreadState * tstate,_PyInterpreterFrame * frame)1697 _PyEval_FrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame)
1698 {
1699 if (frame->owner == FRAME_OWNED_BY_THREAD) {
1700 clear_thread_frame(tstate, frame);
1701 }
1702 else {
1703 clear_gen_frame(tstate, frame);
1704 }
1705 }
1706
1707 /* Consumes references to func, locals and all the args */
1708 _PyInterpreterFrame *
_PyEvalFramePushAndInit(PyThreadState * tstate,PyFunctionObject * func,PyObject * locals,PyObject * const * args,size_t argcount,PyObject * kwnames)1709 _PyEvalFramePushAndInit(PyThreadState *tstate, PyFunctionObject *func,
1710 PyObject *locals, PyObject* const* args,
1711 size_t argcount, PyObject *kwnames)
1712 {
1713 PyCodeObject * code = (PyCodeObject *)func->func_code;
1714 CALL_STAT_INC(frames_pushed);
1715 _PyInterpreterFrame *frame = _PyThreadState_PushFrame(tstate, code->co_framesize);
1716 if (frame == NULL) {
1717 goto fail;
1718 }
1719 _PyFrame_Initialize(frame, func, locals, code, 0);
1720 if (initialize_locals(tstate, func, frame->localsplus, args, argcount, kwnames)) {
1721 assert(frame->owner == FRAME_OWNED_BY_THREAD);
1722 clear_thread_frame(tstate, frame);
1723 return NULL;
1724 }
1725 return frame;
1726 fail:
1727 /* Consume the references */
1728 Py_DECREF(func);
1729 Py_XDECREF(locals);
1730 for (size_t i = 0; i < argcount; i++) {
1731 Py_DECREF(args[i]);
1732 }
1733 if (kwnames) {
1734 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1735 for (Py_ssize_t i = 0; i < kwcount; i++) {
1736 Py_DECREF(args[i+argcount]);
1737 }
1738 }
1739 PyErr_NoMemory();
1740 return NULL;
1741 }
1742
1743 /* Same as _PyEvalFramePushAndInit but takes an args tuple and kwargs dict.
1744 Steals references to func, callargs and kwargs.
1745 */
1746 static _PyInterpreterFrame *
_PyEvalFramePushAndInit_Ex(PyThreadState * tstate,PyFunctionObject * func,PyObject * locals,Py_ssize_t nargs,PyObject * callargs,PyObject * kwargs)1747 _PyEvalFramePushAndInit_Ex(PyThreadState *tstate, PyFunctionObject *func,
1748 PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs)
1749 {
1750 bool has_dict = (kwargs != NULL && PyDict_GET_SIZE(kwargs) > 0);
1751 PyObject *kwnames = NULL;
1752 PyObject *const *newargs;
1753 if (has_dict) {
1754 newargs = _PyStack_UnpackDict(tstate, _PyTuple_ITEMS(callargs), nargs, kwargs, &kwnames);
1755 if (newargs == NULL) {
1756 Py_DECREF(func);
1757 goto error;
1758 }
1759 }
1760 else {
1761 newargs = &PyTuple_GET_ITEM(callargs, 0);
1762 /* We need to incref all our args since the new frame steals the references. */
1763 for (Py_ssize_t i = 0; i < nargs; ++i) {
1764 Py_INCREF(PyTuple_GET_ITEM(callargs, i));
1765 }
1766 }
1767 _PyInterpreterFrame *new_frame = _PyEvalFramePushAndInit(
1768 tstate, (PyFunctionObject *)func, locals,
1769 newargs, nargs, kwnames
1770 );
1771 if (has_dict) {
1772 _PyStack_UnpackDict_FreeNoDecRef(newargs, kwnames);
1773 }
1774 /* No need to decref func here because the reference has been stolen by
1775 _PyEvalFramePushAndInit.
1776 */
1777 Py_DECREF(callargs);
1778 Py_XDECREF(kwargs);
1779 return new_frame;
1780 error:
1781 Py_DECREF(callargs);
1782 Py_XDECREF(kwargs);
1783 return NULL;
1784 }
1785
1786 PyObject *
_PyEval_Vector(PyThreadState * tstate,PyFunctionObject * func,PyObject * locals,PyObject * const * args,size_t argcount,PyObject * kwnames)1787 _PyEval_Vector(PyThreadState *tstate, PyFunctionObject *func,
1788 PyObject *locals,
1789 PyObject* const* args, size_t argcount,
1790 PyObject *kwnames)
1791 {
1792 /* _PyEvalFramePushAndInit consumes the references
1793 * to func, locals and all its arguments */
1794 Py_INCREF(func);
1795 Py_XINCREF(locals);
1796 for (size_t i = 0; i < argcount; i++) {
1797 Py_INCREF(args[i]);
1798 }
1799 if (kwnames) {
1800 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1801 for (Py_ssize_t i = 0; i < kwcount; i++) {
1802 Py_INCREF(args[i+argcount]);
1803 }
1804 }
1805 _PyInterpreterFrame *frame = _PyEvalFramePushAndInit(
1806 tstate, func, locals, args, argcount, kwnames);
1807 if (frame == NULL) {
1808 return NULL;
1809 }
1810 EVAL_CALL_STAT_INC(EVAL_CALL_VECTOR);
1811 return _PyEval_EvalFrame(tstate, frame, 0);
1812 }
1813
1814 /* Legacy API */
1815 PyObject *
PyEval_EvalCodeEx(PyObject * _co,PyObject * globals,PyObject * locals,PyObject * const * args,int argcount,PyObject * const * kws,int kwcount,PyObject * const * defs,int defcount,PyObject * kwdefs,PyObject * closure)1816 PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
1817 PyObject *const *args, int argcount,
1818 PyObject *const *kws, int kwcount,
1819 PyObject *const *defs, int defcount,
1820 PyObject *kwdefs, PyObject *closure)
1821 {
1822 PyThreadState *tstate = _PyThreadState_GET();
1823 PyObject *res = NULL;
1824 PyObject *defaults = _PyTuple_FromArray(defs, defcount);
1825 if (defaults == NULL) {
1826 return NULL;
1827 }
1828 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
1829 if (builtins == NULL) {
1830 Py_DECREF(defaults);
1831 return NULL;
1832 }
1833 if (locals == NULL) {
1834 locals = globals;
1835 }
1836 PyObject *kwnames = NULL;
1837 PyObject *const *allargs;
1838 PyObject **newargs = NULL;
1839 PyFunctionObject *func = NULL;
1840 if (kwcount == 0) {
1841 allargs = args;
1842 }
1843 else {
1844 kwnames = PyTuple_New(kwcount);
1845 if (kwnames == NULL) {
1846 goto fail;
1847 }
1848 newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
1849 if (newargs == NULL) {
1850 goto fail;
1851 }
1852 for (int i = 0; i < argcount; i++) {
1853 newargs[i] = args[i];
1854 }
1855 for (int i = 0; i < kwcount; i++) {
1856 PyTuple_SET_ITEM(kwnames, i, Py_NewRef(kws[2*i]));
1857 newargs[argcount+i] = kws[2*i+1];
1858 }
1859 allargs = newargs;
1860 }
1861 PyFrameConstructor constr = {
1862 .fc_globals = globals,
1863 .fc_builtins = builtins,
1864 .fc_name = ((PyCodeObject *)_co)->co_name,
1865 .fc_qualname = ((PyCodeObject *)_co)->co_name,
1866 .fc_code = _co,
1867 .fc_defaults = defaults,
1868 .fc_kwdefaults = kwdefs,
1869 .fc_closure = closure
1870 };
1871 func = _PyFunction_FromConstructor(&constr);
1872 if (func == NULL) {
1873 goto fail;
1874 }
1875 EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
1876 res = _PyEval_Vector(tstate, func, locals,
1877 allargs, argcount,
1878 kwnames);
1879 fail:
1880 Py_XDECREF(func);
1881 Py_XDECREF(kwnames);
1882 PyMem_Free(newargs);
1883 Py_DECREF(defaults);
1884 return res;
1885 }
1886
1887
1888 /* Logic for the raise statement (too complicated for inlining).
1889 This *consumes* a reference count to each of its arguments. */
1890 static int
do_raise(PyThreadState * tstate,PyObject * exc,PyObject * cause)1891 do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
1892 {
1893 PyObject *type = NULL, *value = NULL;
1894
1895 if (exc == NULL) {
1896 /* Reraise */
1897 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
1898 exc = exc_info->exc_value;
1899 if (Py_IsNone(exc) || exc == NULL) {
1900 _PyErr_SetString(tstate, PyExc_RuntimeError,
1901 "No active exception to reraise");
1902 return 0;
1903 }
1904 Py_INCREF(exc);
1905 assert(PyExceptionInstance_Check(exc));
1906 _PyErr_SetRaisedException(tstate, exc);
1907 return 1;
1908 }
1909
1910 /* We support the following forms of raise:
1911 raise
1912 raise <instance>
1913 raise <type> */
1914
1915 if (PyExceptionClass_Check(exc)) {
1916 type = exc;
1917 value = _PyObject_CallNoArgs(exc);
1918 if (value == NULL)
1919 goto raise_error;
1920 if (!PyExceptionInstance_Check(value)) {
1921 _PyErr_Format(tstate, PyExc_TypeError,
1922 "calling %R should have returned an instance of "
1923 "BaseException, not %R",
1924 type, Py_TYPE(value));
1925 goto raise_error;
1926 }
1927 }
1928 else if (PyExceptionInstance_Check(exc)) {
1929 value = exc;
1930 type = PyExceptionInstance_Class(exc);
1931 Py_INCREF(type);
1932 }
1933 else {
1934 /* Not something you can raise. You get an exception
1935 anyway, just not what you specified :-) */
1936 Py_DECREF(exc);
1937 _PyErr_SetString(tstate, PyExc_TypeError,
1938 "exceptions must derive from BaseException");
1939 goto raise_error;
1940 }
1941
1942 assert(type != NULL);
1943 assert(value != NULL);
1944
1945 if (cause) {
1946 PyObject *fixed_cause;
1947 if (PyExceptionClass_Check(cause)) {
1948 fixed_cause = _PyObject_CallNoArgs(cause);
1949 if (fixed_cause == NULL)
1950 goto raise_error;
1951 if (!PyExceptionInstance_Check(fixed_cause)) {
1952 _PyErr_Format(tstate, PyExc_TypeError,
1953 "calling %R should have returned an instance of "
1954 "BaseException, not %R",
1955 cause, Py_TYPE(fixed_cause));
1956 goto raise_error;
1957 }
1958 Py_DECREF(cause);
1959 }
1960 else if (PyExceptionInstance_Check(cause)) {
1961 fixed_cause = cause;
1962 }
1963 else if (Py_IsNone(cause)) {
1964 Py_DECREF(cause);
1965 fixed_cause = NULL;
1966 }
1967 else {
1968 _PyErr_SetString(tstate, PyExc_TypeError,
1969 "exception causes must derive from "
1970 "BaseException");
1971 goto raise_error;
1972 }
1973 PyException_SetCause(value, fixed_cause);
1974 }
1975
1976 _PyErr_SetObject(tstate, type, value);
1977 /* _PyErr_SetObject incref's its arguments */
1978 Py_DECREF(value);
1979 Py_DECREF(type);
1980 return 0;
1981
1982 raise_error:
1983 Py_XDECREF(value);
1984 Py_XDECREF(type);
1985 Py_XDECREF(cause);
1986 return 0;
1987 }
1988
1989 /* Logic for matching an exception in an except* clause (too
1990 complicated for inlining).
1991 */
1992
1993 int
_PyEval_ExceptionGroupMatch(PyObject * exc_value,PyObject * match_type,PyObject ** match,PyObject ** rest)1994 _PyEval_ExceptionGroupMatch(PyObject* exc_value, PyObject *match_type,
1995 PyObject **match, PyObject **rest)
1996 {
1997 if (Py_IsNone(exc_value)) {
1998 *match = Py_NewRef(Py_None);
1999 *rest = Py_NewRef(Py_None);
2000 return 0;
2001 }
2002 assert(PyExceptionInstance_Check(exc_value));
2003
2004 if (PyErr_GivenExceptionMatches(exc_value, match_type)) {
2005 /* Full match of exc itself */
2006 bool is_eg = _PyBaseExceptionGroup_Check(exc_value);
2007 if (is_eg) {
2008 *match = Py_NewRef(exc_value);
2009 }
2010 else {
2011 /* naked exception - wrap it */
2012 PyObject *excs = PyTuple_Pack(1, exc_value);
2013 if (excs == NULL) {
2014 return -1;
2015 }
2016 PyObject *wrapped = _PyExc_CreateExceptionGroup("", excs);
2017 Py_DECREF(excs);
2018 if (wrapped == NULL) {
2019 return -1;
2020 }
2021 *match = wrapped;
2022 }
2023 *rest = Py_NewRef(Py_None);
2024 return 0;
2025 }
2026
2027 /* exc_value does not match match_type.
2028 * Check for partial match if it's an exception group.
2029 */
2030 if (_PyBaseExceptionGroup_Check(exc_value)) {
2031 PyObject *pair = PyObject_CallMethod(exc_value, "split", "(O)",
2032 match_type);
2033 if (pair == NULL) {
2034 return -1;
2035 }
2036 assert(PyTuple_CheckExact(pair));
2037 assert(PyTuple_GET_SIZE(pair) == 2);
2038 *match = Py_NewRef(PyTuple_GET_ITEM(pair, 0));
2039 *rest = Py_NewRef(PyTuple_GET_ITEM(pair, 1));
2040 Py_DECREF(pair);
2041 return 0;
2042 }
2043 /* no match */
2044 *match = Py_NewRef(Py_None);
2045 *rest = Py_NewRef(exc_value);
2046 return 0;
2047 }
2048
2049 /* Iterate v argcnt times and store the results on the stack (via decreasing
2050 sp). Return 1 for success, 0 if error.
2051
2052 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
2053 with a variable target.
2054 */
2055
2056 int
_PyEval_UnpackIterable(PyThreadState * tstate,PyObject * v,int argcnt,int argcntafter,PyObject ** sp)2057 _PyEval_UnpackIterable(PyThreadState *tstate, PyObject *v,
2058 int argcnt, int argcntafter, PyObject **sp)
2059 {
2060 int i = 0, j = 0;
2061 Py_ssize_t ll = 0;
2062 PyObject *it; /* iter(v) */
2063 PyObject *w;
2064 PyObject *l = NULL; /* variable list */
2065
2066 assert(v != NULL);
2067
2068 it = PyObject_GetIter(v);
2069 if (it == NULL) {
2070 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
2071 Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
2072 {
2073 _PyErr_Format(tstate, PyExc_TypeError,
2074 "cannot unpack non-iterable %.200s object",
2075 Py_TYPE(v)->tp_name);
2076 }
2077 return 0;
2078 }
2079
2080 for (; i < argcnt; i++) {
2081 w = PyIter_Next(it);
2082 if (w == NULL) {
2083 /* Iterator done, via error or exhaustion. */
2084 if (!_PyErr_Occurred(tstate)) {
2085 if (argcntafter == -1) {
2086 _PyErr_Format(tstate, PyExc_ValueError,
2087 "not enough values to unpack "
2088 "(expected %d, got %d)",
2089 argcnt, i);
2090 }
2091 else {
2092 _PyErr_Format(tstate, PyExc_ValueError,
2093 "not enough values to unpack "
2094 "(expected at least %d, got %d)",
2095 argcnt + argcntafter, i);
2096 }
2097 }
2098 goto Error;
2099 }
2100 *--sp = w;
2101 }
2102
2103 if (argcntafter == -1) {
2104 /* We better have exhausted the iterator now. */
2105 w = PyIter_Next(it);
2106 if (w == NULL) {
2107 if (_PyErr_Occurred(tstate))
2108 goto Error;
2109 Py_DECREF(it);
2110 return 1;
2111 }
2112 Py_DECREF(w);
2113 _PyErr_Format(tstate, PyExc_ValueError,
2114 "too many values to unpack (expected %d)",
2115 argcnt);
2116 goto Error;
2117 }
2118
2119 l = PySequence_List(it);
2120 if (l == NULL)
2121 goto Error;
2122 *--sp = l;
2123 i++;
2124
2125 ll = PyList_GET_SIZE(l);
2126 if (ll < argcntafter) {
2127 _PyErr_Format(tstate, PyExc_ValueError,
2128 "not enough values to unpack (expected at least %d, got %zd)",
2129 argcnt + argcntafter, argcnt + ll);
2130 goto Error;
2131 }
2132
2133 /* Pop the "after-variable" args off the list. */
2134 for (j = argcntafter; j > 0; j--, i++) {
2135 *--sp = PyList_GET_ITEM(l, ll - j);
2136 }
2137 /* Resize the list. */
2138 Py_SET_SIZE(l, ll - argcntafter);
2139 Py_DECREF(it);
2140 return 1;
2141
2142 Error:
2143 for (; i > 0; i--, sp++)
2144 Py_DECREF(*sp);
2145 Py_XDECREF(it);
2146 return 0;
2147 }
2148
2149 static int
do_monitor_exc(PyThreadState * tstate,_PyInterpreterFrame * frame,_Py_CODEUNIT * instr,int event)2150 do_monitor_exc(PyThreadState *tstate, _PyInterpreterFrame *frame,
2151 _Py_CODEUNIT *instr, int event)
2152 {
2153 assert(event < _PY_MONITORING_UNGROUPED_EVENTS);
2154 if (_PyFrame_GetCode(frame)->co_flags & CO_NO_MONITORING_EVENTS) {
2155 return 0;
2156 }
2157 PyObject *exc = PyErr_GetRaisedException();
2158 assert(exc != NULL);
2159 int err = _Py_call_instrumentation_arg(tstate, event, frame, instr, exc);
2160 if (err == 0) {
2161 PyErr_SetRaisedException(exc);
2162 }
2163 else {
2164 assert(PyErr_Occurred());
2165 Py_DECREF(exc);
2166 }
2167 return err;
2168 }
2169
2170 static inline bool
no_tools_for_global_event(PyThreadState * tstate,int event)2171 no_tools_for_global_event(PyThreadState *tstate, int event)
2172 {
2173 return tstate->interp->monitors.tools[event] == 0;
2174 }
2175
2176 static inline bool
no_tools_for_local_event(PyThreadState * tstate,_PyInterpreterFrame * frame,int event)2177 no_tools_for_local_event(PyThreadState *tstate, _PyInterpreterFrame *frame, int event)
2178 {
2179 assert(event < _PY_MONITORING_LOCAL_EVENTS);
2180 _PyCoMonitoringData *data = _PyFrame_GetCode(frame)->_co_monitoring;
2181 if (data) {
2182 return data->active_monitors.tools[event] == 0;
2183 }
2184 else {
2185 return no_tools_for_global_event(tstate, event);
2186 }
2187 }
2188
2189 void
_PyEval_MonitorRaise(PyThreadState * tstate,_PyInterpreterFrame * frame,_Py_CODEUNIT * instr)2190 _PyEval_MonitorRaise(PyThreadState *tstate, _PyInterpreterFrame *frame,
2191 _Py_CODEUNIT *instr)
2192 {
2193 if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_RAISE)) {
2194 return;
2195 }
2196 do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RAISE);
2197 }
2198
2199 static void
monitor_reraise(PyThreadState * tstate,_PyInterpreterFrame * frame,_Py_CODEUNIT * instr)2200 monitor_reraise(PyThreadState *tstate, _PyInterpreterFrame *frame,
2201 _Py_CODEUNIT *instr)
2202 {
2203 if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_RERAISE)) {
2204 return;
2205 }
2206 do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RERAISE);
2207 }
2208
2209 static int
monitor_stop_iteration(PyThreadState * tstate,_PyInterpreterFrame * frame,_Py_CODEUNIT * instr,PyObject * value)2210 monitor_stop_iteration(PyThreadState *tstate, _PyInterpreterFrame *frame,
2211 _Py_CODEUNIT *instr, PyObject *value)
2212 {
2213 if (no_tools_for_local_event(tstate, frame, PY_MONITORING_EVENT_STOP_ITERATION)) {
2214 return 0;
2215 }
2216 assert(!PyErr_Occurred());
2217 PyErr_SetObject(PyExc_StopIteration, value);
2218 int res = do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_STOP_ITERATION);
2219 if (res < 0) {
2220 return res;
2221 }
2222 PyErr_SetRaisedException(NULL);
2223 return 0;
2224 }
2225
2226 static void
monitor_unwind(PyThreadState * tstate,_PyInterpreterFrame * frame,_Py_CODEUNIT * instr)2227 monitor_unwind(PyThreadState *tstate,
2228 _PyInterpreterFrame *frame,
2229 _Py_CODEUNIT *instr)
2230 {
2231 if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_UNWIND)) {
2232 return;
2233 }
2234 do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_PY_UNWIND);
2235 }
2236
2237
2238 static int
monitor_handled(PyThreadState * tstate,_PyInterpreterFrame * frame,_Py_CODEUNIT * instr,PyObject * exc)2239 monitor_handled(PyThreadState *tstate,
2240 _PyInterpreterFrame *frame,
2241 _Py_CODEUNIT *instr, PyObject *exc)
2242 {
2243 if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_EXCEPTION_HANDLED)) {
2244 return 0;
2245 }
2246 return _Py_call_instrumentation_arg(tstate, PY_MONITORING_EVENT_EXCEPTION_HANDLED, frame, instr, exc);
2247 }
2248
2249 static void
monitor_throw(PyThreadState * tstate,_PyInterpreterFrame * frame,_Py_CODEUNIT * instr)2250 monitor_throw(PyThreadState *tstate,
2251 _PyInterpreterFrame *frame,
2252 _Py_CODEUNIT *instr)
2253 {
2254 if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_THROW)) {
2255 return;
2256 }
2257 do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_PY_THROW);
2258 }
2259
2260 void
PyThreadState_EnterTracing(PyThreadState * tstate)2261 PyThreadState_EnterTracing(PyThreadState *tstate)
2262 {
2263 assert(tstate->tracing >= 0);
2264 tstate->tracing++;
2265 }
2266
2267 void
PyThreadState_LeaveTracing(PyThreadState * tstate)2268 PyThreadState_LeaveTracing(PyThreadState *tstate)
2269 {
2270 assert(tstate->tracing > 0);
2271 tstate->tracing--;
2272 }
2273
2274
2275 PyObject*
_PyEval_CallTracing(PyObject * func,PyObject * args)2276 _PyEval_CallTracing(PyObject *func, PyObject *args)
2277 {
2278 // Save and disable tracing
2279 PyThreadState *tstate = _PyThreadState_GET();
2280 int save_tracing = tstate->tracing;
2281 tstate->tracing = 0;
2282
2283 // Call the tracing function
2284 PyObject *result = PyObject_Call(func, args, NULL);
2285
2286 // Restore tracing
2287 tstate->tracing = save_tracing;
2288 return result;
2289 }
2290
2291 void
PyEval_SetProfile(Py_tracefunc func,PyObject * arg)2292 PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
2293 {
2294 PyThreadState *tstate = _PyThreadState_GET();
2295 if (_PyEval_SetProfile(tstate, func, arg) < 0) {
2296 /* Log _PySys_Audit() error */
2297 PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfile");
2298 }
2299 }
2300
2301 void
PyEval_SetProfileAllThreads(Py_tracefunc func,PyObject * arg)2302 PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *arg)
2303 {
2304 PyThreadState *this_tstate = _PyThreadState_GET();
2305 PyInterpreterState* interp = this_tstate->interp;
2306
2307 _PyRuntimeState *runtime = &_PyRuntime;
2308 HEAD_LOCK(runtime);
2309 PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
2310 HEAD_UNLOCK(runtime);
2311
2312 while (ts) {
2313 if (_PyEval_SetProfile(ts, func, arg) < 0) {
2314 PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfileAllThreads");
2315 }
2316 HEAD_LOCK(runtime);
2317 ts = PyThreadState_Next(ts);
2318 HEAD_UNLOCK(runtime);
2319 }
2320 }
2321
2322 void
PyEval_SetTrace(Py_tracefunc func,PyObject * arg)2323 PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
2324 {
2325 PyThreadState *tstate = _PyThreadState_GET();
2326 if (_PyEval_SetTrace(tstate, func, arg) < 0) {
2327 /* Log _PySys_Audit() error */
2328 PyErr_FormatUnraisable("Exception ignored in PyEval_SetTrace");
2329 }
2330 }
2331
2332 void
PyEval_SetTraceAllThreads(Py_tracefunc func,PyObject * arg)2333 PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *arg)
2334 {
2335 PyThreadState *this_tstate = _PyThreadState_GET();
2336 PyInterpreterState* interp = this_tstate->interp;
2337
2338 _PyRuntimeState *runtime = &_PyRuntime;
2339 HEAD_LOCK(runtime);
2340 PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
2341 HEAD_UNLOCK(runtime);
2342
2343 while (ts) {
2344 if (_PyEval_SetTrace(ts, func, arg) < 0) {
2345 PyErr_FormatUnraisable("Exception ignored in PyEval_SetTraceAllThreads");
2346 }
2347 HEAD_LOCK(runtime);
2348 ts = PyThreadState_Next(ts);
2349 HEAD_UNLOCK(runtime);
2350 }
2351 }
2352
2353 int
_PyEval_SetCoroutineOriginTrackingDepth(int depth)2354 _PyEval_SetCoroutineOriginTrackingDepth(int depth)
2355 {
2356 PyThreadState *tstate = _PyThreadState_GET();
2357 if (depth < 0) {
2358 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
2359 return -1;
2360 }
2361 tstate->coroutine_origin_tracking_depth = depth;
2362 return 0;
2363 }
2364
2365
2366 int
_PyEval_GetCoroutineOriginTrackingDepth(void)2367 _PyEval_GetCoroutineOriginTrackingDepth(void)
2368 {
2369 PyThreadState *tstate = _PyThreadState_GET();
2370 return tstate->coroutine_origin_tracking_depth;
2371 }
2372
2373 int
_PyEval_SetAsyncGenFirstiter(PyObject * firstiter)2374 _PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
2375 {
2376 PyThreadState *tstate = _PyThreadState_GET();
2377
2378 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
2379 return -1;
2380 }
2381
2382 Py_XSETREF(tstate->async_gen_firstiter, Py_XNewRef(firstiter));
2383 return 0;
2384 }
2385
2386 PyObject *
_PyEval_GetAsyncGenFirstiter(void)2387 _PyEval_GetAsyncGenFirstiter(void)
2388 {
2389 PyThreadState *tstate = _PyThreadState_GET();
2390 return tstate->async_gen_firstiter;
2391 }
2392
2393 int
_PyEval_SetAsyncGenFinalizer(PyObject * finalizer)2394 _PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
2395 {
2396 PyThreadState *tstate = _PyThreadState_GET();
2397
2398 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
2399 return -1;
2400 }
2401
2402 Py_XSETREF(tstate->async_gen_finalizer, Py_XNewRef(finalizer));
2403 return 0;
2404 }
2405
2406 PyObject *
_PyEval_GetAsyncGenFinalizer(void)2407 _PyEval_GetAsyncGenFinalizer(void)
2408 {
2409 PyThreadState *tstate = _PyThreadState_GET();
2410 return tstate->async_gen_finalizer;
2411 }
2412
2413 _PyInterpreterFrame *
_PyEval_GetFrame(void)2414 _PyEval_GetFrame(void)
2415 {
2416 PyThreadState *tstate = _PyThreadState_GET();
2417 return _PyThreadState_GetFrame(tstate);
2418 }
2419
2420 PyFrameObject *
PyEval_GetFrame(void)2421 PyEval_GetFrame(void)
2422 {
2423 _PyInterpreterFrame *frame = _PyEval_GetFrame();
2424 if (frame == NULL) {
2425 return NULL;
2426 }
2427 PyFrameObject *f = _PyFrame_GetFrameObject(frame);
2428 if (f == NULL) {
2429 PyErr_Clear();
2430 }
2431 return f;
2432 }
2433
2434 PyObject *
_PyEval_GetBuiltins(PyThreadState * tstate)2435 _PyEval_GetBuiltins(PyThreadState *tstate)
2436 {
2437 _PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
2438 if (frame != NULL) {
2439 return frame->f_builtins;
2440 }
2441 return tstate->interp->builtins;
2442 }
2443
2444 PyObject *
PyEval_GetBuiltins(void)2445 PyEval_GetBuiltins(void)
2446 {
2447 PyThreadState *tstate = _PyThreadState_GET();
2448 return _PyEval_GetBuiltins(tstate);
2449 }
2450
2451 /* Convenience function to get a builtin from its name */
2452 PyObject *
_PyEval_GetBuiltin(PyObject * name)2453 _PyEval_GetBuiltin(PyObject *name)
2454 {
2455 PyObject *attr;
2456 if (PyMapping_GetOptionalItem(PyEval_GetBuiltins(), name, &attr) == 0) {
2457 PyErr_SetObject(PyExc_AttributeError, name);
2458 }
2459 return attr;
2460 }
2461
2462 PyObject *
_PyEval_GetBuiltinId(_Py_Identifier * name)2463 _PyEval_GetBuiltinId(_Py_Identifier *name)
2464 {
2465 return _PyEval_GetBuiltin(_PyUnicode_FromId(name));
2466 }
2467
2468 PyObject *
PyEval_GetLocals(void)2469 PyEval_GetLocals(void)
2470 {
2471 // We need to return a borrowed reference here, so some tricks are needed
2472 PyThreadState *tstate = _PyThreadState_GET();
2473 _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2474 if (current_frame == NULL) {
2475 _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2476 return NULL;
2477 }
2478
2479 // Be aware that this returns a new reference
2480 PyObject *locals = _PyFrame_GetLocals(current_frame);
2481
2482 if (locals == NULL) {
2483 return NULL;
2484 }
2485
2486 if (PyFrameLocalsProxy_Check(locals)) {
2487 PyFrameObject *f = _PyFrame_GetFrameObject(current_frame);
2488 PyObject *ret = f->f_locals_cache;
2489 if (ret == NULL) {
2490 ret = PyDict_New();
2491 if (ret == NULL) {
2492 Py_DECREF(locals);
2493 return NULL;
2494 }
2495 f->f_locals_cache = ret;
2496 }
2497 if (PyDict_Update(ret, locals) < 0) {
2498 // At this point, if the cache dict is broken, it will stay broken, as
2499 // trying to clean it up or replace it will just cause other problems
2500 ret = NULL;
2501 }
2502 Py_DECREF(locals);
2503 return ret;
2504 }
2505
2506 assert(PyMapping_Check(locals));
2507 assert(Py_REFCNT(locals) > 1);
2508 Py_DECREF(locals);
2509
2510 return locals;
2511 }
2512
2513 PyObject *
_PyEval_GetFrameLocals(void)2514 _PyEval_GetFrameLocals(void)
2515 {
2516 PyThreadState *tstate = _PyThreadState_GET();
2517 _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2518 if (current_frame == NULL) {
2519 _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2520 return NULL;
2521 }
2522
2523 PyObject *locals = _PyFrame_GetLocals(current_frame);
2524 if (locals == NULL) {
2525 return NULL;
2526 }
2527
2528 if (PyFrameLocalsProxy_Check(locals)) {
2529 PyObject* ret = PyDict_New();
2530 if (ret == NULL) {
2531 Py_DECREF(locals);
2532 return NULL;
2533 }
2534 if (PyDict_Update(ret, locals) < 0) {
2535 Py_DECREF(ret);
2536 Py_DECREF(locals);
2537 return NULL;
2538 }
2539 Py_DECREF(locals);
2540 return ret;
2541 }
2542
2543 assert(PyMapping_Check(locals));
2544 return locals;
2545 }
2546
2547 PyObject *
PyEval_GetGlobals(void)2548 PyEval_GetGlobals(void)
2549 {
2550 PyThreadState *tstate = _PyThreadState_GET();
2551 _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2552 if (current_frame == NULL) {
2553 return NULL;
2554 }
2555 return current_frame->f_globals;
2556 }
2557
2558 PyObject*
PyEval_GetFrameLocals(void)2559 PyEval_GetFrameLocals(void)
2560 {
2561 return _PyEval_GetFrameLocals();
2562 }
2563
PyEval_GetFrameGlobals(void)2564 PyObject* PyEval_GetFrameGlobals(void)
2565 {
2566 PyThreadState *tstate = _PyThreadState_GET();
2567 _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2568 if (current_frame == NULL) {
2569 return NULL;
2570 }
2571 return Py_XNewRef(current_frame->f_globals);
2572 }
2573
PyEval_GetFrameBuiltins(void)2574 PyObject* PyEval_GetFrameBuiltins(void)
2575 {
2576 PyThreadState *tstate = _PyThreadState_GET();
2577 return Py_XNewRef(_PyEval_GetBuiltins(tstate));
2578 }
2579
2580 int
PyEval_MergeCompilerFlags(PyCompilerFlags * cf)2581 PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
2582 {
2583 PyThreadState *tstate = _PyThreadState_GET();
2584 _PyInterpreterFrame *current_frame = tstate->current_frame;
2585 int result = cf->cf_flags != 0;
2586
2587 if (current_frame != NULL) {
2588 const int codeflags = _PyFrame_GetCode(current_frame)->co_flags;
2589 const int compilerflags = codeflags & PyCF_MASK;
2590 if (compilerflags) {
2591 result = 1;
2592 cf->cf_flags |= compilerflags;
2593 }
2594 }
2595 return result;
2596 }
2597
2598
2599 const char *
PyEval_GetFuncName(PyObject * func)2600 PyEval_GetFuncName(PyObject *func)
2601 {
2602 if (PyMethod_Check(func))
2603 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
2604 else if (PyFunction_Check(func))
2605 return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
2606 else if (PyCFunction_Check(func))
2607 return ((PyCFunctionObject*)func)->m_ml->ml_name;
2608 else
2609 return Py_TYPE(func)->tp_name;
2610 }
2611
2612 const char *
PyEval_GetFuncDesc(PyObject * func)2613 PyEval_GetFuncDesc(PyObject *func)
2614 {
2615 if (PyMethod_Check(func))
2616 return "()";
2617 else if (PyFunction_Check(func))
2618 return "()";
2619 else if (PyCFunction_Check(func))
2620 return "()";
2621 else
2622 return " object";
2623 }
2624
2625 /* Extract a slice index from a PyLong or an object with the
2626 nb_index slot defined, and store in *pi.
2627 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
2628 and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
2629 Return 0 on error, 1 on success.
2630 */
2631 int
_PyEval_SliceIndex(PyObject * v,Py_ssize_t * pi)2632 _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
2633 {
2634 PyThreadState *tstate = _PyThreadState_GET();
2635 if (!Py_IsNone(v)) {
2636 Py_ssize_t x;
2637 if (_PyIndex_Check(v)) {
2638 x = PyNumber_AsSsize_t(v, NULL);
2639 if (x == -1 && _PyErr_Occurred(tstate))
2640 return 0;
2641 }
2642 else {
2643 _PyErr_SetString(tstate, PyExc_TypeError,
2644 "slice indices must be integers or "
2645 "None or have an __index__ method");
2646 return 0;
2647 }
2648 *pi = x;
2649 }
2650 return 1;
2651 }
2652
2653 int
_PyEval_SliceIndexNotNone(PyObject * v,Py_ssize_t * pi)2654 _PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
2655 {
2656 PyThreadState *tstate = _PyThreadState_GET();
2657 Py_ssize_t x;
2658 if (_PyIndex_Check(v)) {
2659 x = PyNumber_AsSsize_t(v, NULL);
2660 if (x == -1 && _PyErr_Occurred(tstate))
2661 return 0;
2662 }
2663 else {
2664 _PyErr_SetString(tstate, PyExc_TypeError,
2665 "slice indices must be integers or "
2666 "have an __index__ method");
2667 return 0;
2668 }
2669 *pi = x;
2670 return 1;
2671 }
2672
2673 static PyObject *
import_name(PyThreadState * tstate,_PyInterpreterFrame * frame,PyObject * name,PyObject * fromlist,PyObject * level)2674 import_name(PyThreadState *tstate, _PyInterpreterFrame *frame,
2675 PyObject *name, PyObject *fromlist, PyObject *level)
2676 {
2677 PyObject *import_func;
2678 if (PyMapping_GetOptionalItem(frame->f_builtins, &_Py_ID(__import__), &import_func) < 0) {
2679 return NULL;
2680 }
2681 if (import_func == NULL) {
2682 _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
2683 return NULL;
2684 }
2685
2686 PyObject *locals = frame->f_locals;
2687 if (locals == NULL) {
2688 locals = Py_None;
2689 }
2690
2691 /* Fast path for not overloaded __import__. */
2692 if (_PyImport_IsDefaultImportFunc(tstate->interp, import_func)) {
2693 Py_DECREF(import_func);
2694 int ilevel = PyLong_AsInt(level);
2695 if (ilevel == -1 && _PyErr_Occurred(tstate)) {
2696 return NULL;
2697 }
2698 return PyImport_ImportModuleLevelObject(
2699 name,
2700 frame->f_globals,
2701 locals,
2702 fromlist,
2703 ilevel);
2704 }
2705
2706 PyObject* args[5] = {name, frame->f_globals, locals, fromlist, level};
2707 PyObject *res = PyObject_Vectorcall(import_func, args, 5, NULL);
2708 Py_DECREF(import_func);
2709 return res;
2710 }
2711
2712 static PyObject *
import_from(PyThreadState * tstate,PyObject * v,PyObject * name)2713 import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
2714 {
2715 PyObject *x;
2716 PyObject *fullmodname, *mod_name, *origin, *mod_name_or_unknown, *errmsg, *spec;
2717
2718 if (PyObject_GetOptionalAttr(v, name, &x) != 0) {
2719 return x;
2720 }
2721 /* Issue #17636: in case this failed because of a circular relative
2722 import, try to fallback on reading the module directly from
2723 sys.modules. */
2724 if (PyObject_GetOptionalAttr(v, &_Py_ID(__name__), &mod_name) < 0) {
2725 return NULL;
2726 }
2727 if (mod_name == NULL || !PyUnicode_Check(mod_name)) {
2728 Py_CLEAR(mod_name);
2729 goto error;
2730 }
2731 fullmodname = PyUnicode_FromFormat("%U.%U", mod_name, name);
2732 if (fullmodname == NULL) {
2733 Py_DECREF(mod_name);
2734 return NULL;
2735 }
2736 x = PyImport_GetModule(fullmodname);
2737 Py_DECREF(fullmodname);
2738 if (x == NULL && !_PyErr_Occurred(tstate)) {
2739 goto error;
2740 }
2741 Py_DECREF(mod_name);
2742 return x;
2743
2744 error:
2745 if (mod_name == NULL) {
2746 mod_name_or_unknown = PyUnicode_FromString("<unknown module name>");
2747 if (mod_name_or_unknown == NULL) {
2748 return NULL;
2749 }
2750 } else {
2751 mod_name_or_unknown = mod_name;
2752 }
2753 // mod_name is no longer an owned reference
2754 assert(mod_name_or_unknown);
2755 assert(mod_name == NULL || mod_name == mod_name_or_unknown);
2756
2757 origin = NULL;
2758 if (PyObject_GetOptionalAttr(v, &_Py_ID(__spec__), &spec) < 0) {
2759 Py_DECREF(mod_name_or_unknown);
2760 return NULL;
2761 }
2762 if (spec == NULL) {
2763 errmsg = PyUnicode_FromFormat(
2764 "cannot import name %R from %R (unknown location)",
2765 name, mod_name_or_unknown
2766 );
2767 goto done_with_errmsg;
2768 }
2769 if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
2770 goto done;
2771 }
2772
2773 int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
2774 if (is_possibly_shadowing < 0) {
2775 goto done;
2776 }
2777 int is_possibly_shadowing_stdlib = 0;
2778 if (is_possibly_shadowing) {
2779 PyObject *stdlib_modules = PySys_GetObject("stdlib_module_names");
2780 if (stdlib_modules && PyAnySet_Check(stdlib_modules)) {
2781 is_possibly_shadowing_stdlib = PySet_Contains(stdlib_modules, mod_name_or_unknown);
2782 if (is_possibly_shadowing_stdlib < 0) {
2783 goto done;
2784 }
2785 }
2786 }
2787
2788 if (is_possibly_shadowing_stdlib) {
2789 assert(origin);
2790 errmsg = PyUnicode_FromFormat(
2791 "cannot import name %R from %R "
2792 "(consider renaming %R since it has the same "
2793 "name as the standard library module named %R "
2794 "and prevents importing that standard library module)",
2795 name, mod_name_or_unknown, origin, mod_name_or_unknown
2796 );
2797 }
2798 else {
2799 int rc = _PyModuleSpec_IsInitializing(spec);
2800 if (rc < 0) {
2801 goto done;
2802 }
2803 else if (rc > 0) {
2804 if (is_possibly_shadowing) {
2805 assert(origin);
2806 // For non-stdlib modules, only mention the possibility of
2807 // shadowing if the module is being initialized.
2808 errmsg = PyUnicode_FromFormat(
2809 "cannot import name %R from %R "
2810 "(consider renaming %R if it has the same name "
2811 "as a library you intended to import)",
2812 name, mod_name_or_unknown, origin
2813 );
2814 }
2815 else if (origin) {
2816 errmsg = PyUnicode_FromFormat(
2817 "cannot import name %R from partially initialized module %R "
2818 "(most likely due to a circular import) (%S)",
2819 name, mod_name_or_unknown, origin
2820 );
2821 }
2822 else {
2823 errmsg = PyUnicode_FromFormat(
2824 "cannot import name %R from partially initialized module %R "
2825 "(most likely due to a circular import)",
2826 name, mod_name_or_unknown
2827 );
2828 }
2829 }
2830 else {
2831 assert(rc == 0);
2832 if (origin) {
2833 errmsg = PyUnicode_FromFormat(
2834 "cannot import name %R from %R (%S)",
2835 name, mod_name_or_unknown, origin
2836 );
2837 }
2838 else {
2839 errmsg = PyUnicode_FromFormat(
2840 "cannot import name %R from %R (unknown location)",
2841 name, mod_name_or_unknown
2842 );
2843 }
2844 }
2845 }
2846
2847 done_with_errmsg:
2848 /* NULL checks for errmsg, mod_name, origin done by PyErr_SetImportError. */
2849 _PyErr_SetImportErrorWithNameFrom(errmsg, mod_name, origin, name);
2850 Py_DECREF(errmsg);
2851
2852 done:
2853 Py_XDECREF(origin);
2854 Py_XDECREF(spec);
2855 Py_DECREF(mod_name_or_unknown);
2856 return NULL;
2857 }
2858
2859 #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
2860 "BaseException is not allowed"
2861
2862 #define CANNOT_EXCEPT_STAR_EG "catching ExceptionGroup with except* "\
2863 "is not allowed. Use except instead."
2864
2865 int
_PyEval_CheckExceptTypeValid(PyThreadState * tstate,PyObject * right)2866 _PyEval_CheckExceptTypeValid(PyThreadState *tstate, PyObject* right)
2867 {
2868 if (PyTuple_Check(right)) {
2869 Py_ssize_t i, length;
2870 length = PyTuple_GET_SIZE(right);
2871 for (i = 0; i < length; i++) {
2872 PyObject *exc = PyTuple_GET_ITEM(right, i);
2873 if (!PyExceptionClass_Check(exc)) {
2874 _PyErr_SetString(tstate, PyExc_TypeError,
2875 CANNOT_CATCH_MSG);
2876 return -1;
2877 }
2878 }
2879 }
2880 else {
2881 if (!PyExceptionClass_Check(right)) {
2882 _PyErr_SetString(tstate, PyExc_TypeError,
2883 CANNOT_CATCH_MSG);
2884 return -1;
2885 }
2886 }
2887 return 0;
2888 }
2889
2890 int
_PyEval_CheckExceptStarTypeValid(PyThreadState * tstate,PyObject * right)2891 _PyEval_CheckExceptStarTypeValid(PyThreadState *tstate, PyObject* right)
2892 {
2893 if (_PyEval_CheckExceptTypeValid(tstate, right) < 0) {
2894 return -1;
2895 }
2896
2897 /* reject except *ExceptionGroup */
2898
2899 int is_subclass = 0;
2900 if (PyTuple_Check(right)) {
2901 Py_ssize_t length = PyTuple_GET_SIZE(right);
2902 for (Py_ssize_t i = 0; i < length; i++) {
2903 PyObject *exc = PyTuple_GET_ITEM(right, i);
2904 is_subclass = PyObject_IsSubclass(exc, PyExc_BaseExceptionGroup);
2905 if (is_subclass < 0) {
2906 return -1;
2907 }
2908 if (is_subclass) {
2909 break;
2910 }
2911 }
2912 }
2913 else {
2914 is_subclass = PyObject_IsSubclass(right, PyExc_BaseExceptionGroup);
2915 if (is_subclass < 0) {
2916 return -1;
2917 }
2918 }
2919 if (is_subclass) {
2920 _PyErr_SetString(tstate, PyExc_TypeError,
2921 CANNOT_EXCEPT_STAR_EG);
2922 return -1;
2923 }
2924 return 0;
2925 }
2926
2927 static int
check_args_iterable(PyThreadState * tstate,PyObject * func,PyObject * args)2928 check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
2929 {
2930 if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
2931 /* check_args_iterable() may be called with a live exception:
2932 * clear it to prevent calling _PyObject_FunctionStr() with an
2933 * exception set. */
2934 _PyErr_Clear(tstate);
2935 PyObject *funcstr = _PyObject_FunctionStr(func);
2936 if (funcstr != NULL) {
2937 _PyErr_Format(tstate, PyExc_TypeError,
2938 "%U argument after * must be an iterable, not %.200s",
2939 funcstr, Py_TYPE(args)->tp_name);
2940 Py_DECREF(funcstr);
2941 }
2942 return -1;
2943 }
2944 return 0;
2945 }
2946
2947 void
_PyEval_FormatKwargsError(PyThreadState * tstate,PyObject * func,PyObject * kwargs)2948 _PyEval_FormatKwargsError(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
2949 {
2950 /* _PyDict_MergeEx raises attribute
2951 * error (percolated from an attempt
2952 * to get 'keys' attribute) instead of
2953 * a type error if its second argument
2954 * is not a mapping.
2955 */
2956 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
2957 _PyErr_Clear(tstate);
2958 PyObject *funcstr = _PyObject_FunctionStr(func);
2959 if (funcstr != NULL) {
2960 _PyErr_Format(
2961 tstate, PyExc_TypeError,
2962 "%U argument after ** must be a mapping, not %.200s",
2963 funcstr, Py_TYPE(kwargs)->tp_name);
2964 Py_DECREF(funcstr);
2965 }
2966 }
2967 else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2968 PyObject *exc = _PyErr_GetRaisedException(tstate);
2969 PyObject *args = ((PyBaseExceptionObject *)exc)->args;
2970 if (exc && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1) {
2971 _PyErr_Clear(tstate);
2972 PyObject *funcstr = _PyObject_FunctionStr(func);
2973 if (funcstr != NULL) {
2974 PyObject *key = PyTuple_GET_ITEM(args, 0);
2975 _PyErr_Format(
2976 tstate, PyExc_TypeError,
2977 "%U got multiple values for keyword argument '%S'",
2978 funcstr, key);
2979 Py_DECREF(funcstr);
2980 }
2981 Py_XDECREF(exc);
2982 }
2983 else {
2984 _PyErr_SetRaisedException(tstate, exc);
2985 }
2986 }
2987 }
2988
2989 void
_PyEval_FormatExcCheckArg(PyThreadState * tstate,PyObject * exc,const char * format_str,PyObject * obj)2990 _PyEval_FormatExcCheckArg(PyThreadState *tstate, PyObject *exc,
2991 const char *format_str, PyObject *obj)
2992 {
2993 const char *obj_str;
2994
2995 if (!obj)
2996 return;
2997
2998 obj_str = PyUnicode_AsUTF8(obj);
2999 if (!obj_str)
3000 return;
3001
3002 _PyErr_Format(tstate, exc, format_str, obj_str);
3003
3004 if (exc == PyExc_NameError) {
3005 // Include the name in the NameError exceptions to offer suggestions later.
3006 PyObject *exc = PyErr_GetRaisedException();
3007 if (PyErr_GivenExceptionMatches(exc, PyExc_NameError)) {
3008 if (((PyNameErrorObject*)exc)->name == NULL) {
3009 // We do not care if this fails because we are going to restore the
3010 // NameError anyway.
3011 (void)PyObject_SetAttr(exc, &_Py_ID(name), obj);
3012 }
3013 }
3014 PyErr_SetRaisedException(exc);
3015 }
3016 }
3017
3018 void
_PyEval_FormatExcUnbound(PyThreadState * tstate,PyCodeObject * co,int oparg)3019 _PyEval_FormatExcUnbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
3020 {
3021 PyObject *name;
3022 /* Don't stomp existing exception */
3023 if (_PyErr_Occurred(tstate))
3024 return;
3025 name = PyTuple_GET_ITEM(co->co_localsplusnames, oparg);
3026 if (oparg < PyUnstable_Code_GetFirstFree(co)) {
3027 _PyEval_FormatExcCheckArg(tstate, PyExc_UnboundLocalError,
3028 UNBOUNDLOCAL_ERROR_MSG, name);
3029 } else {
3030 _PyEval_FormatExcCheckArg(tstate, PyExc_NameError,
3031 UNBOUNDFREE_ERROR_MSG, name);
3032 }
3033 }
3034
3035 void
_PyEval_FormatAwaitableError(PyThreadState * tstate,PyTypeObject * type,int oparg)3036 _PyEval_FormatAwaitableError(PyThreadState *tstate, PyTypeObject *type, int oparg)
3037 {
3038 if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
3039 if (oparg == 1) {
3040 _PyErr_Format(tstate, PyExc_TypeError,
3041 "'async with' received an object from __aenter__ "
3042 "that does not implement __await__: %.100s",
3043 type->tp_name);
3044 }
3045 else if (oparg == 2) {
3046 _PyErr_Format(tstate, PyExc_TypeError,
3047 "'async with' received an object from __aexit__ "
3048 "that does not implement __await__: %.100s",
3049 type->tp_name);
3050 }
3051 }
3052 }
3053
3054
3055 Py_ssize_t
PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)3056 PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
3057 {
3058 PyInterpreterState *interp = _PyInterpreterState_GET();
3059 Py_ssize_t new_index;
3060
3061 if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
3062 return -1;
3063 }
3064 new_index = interp->co_extra_user_count++;
3065 interp->co_extra_freefuncs[new_index] = free;
3066 return new_index;
3067 }
3068
3069 /* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
3070 for the limited API. */
3071
Py_EnterRecursiveCall(const char * where)3072 int Py_EnterRecursiveCall(const char *where)
3073 {
3074 return _Py_EnterRecursiveCall(where);
3075 }
3076
Py_LeaveRecursiveCall(void)3077 void Py_LeaveRecursiveCall(void)
3078 {
3079 _Py_LeaveRecursiveCall();
3080 }
3081