Coverage Report

Created: 2025-07-11 06:24

/src/cpython/Python/ceval.c
Line
Count
Source (jump to first uncovered line)
1
#include "python_coverage.h"
2
3
#define _PY_INTERPRETER
4
5
#include "Python.h"
6
#include "pycore_abstract.h"      // _PyIndex_Check()
7
#include "pycore_audit.h"         // _PySys_Audit()
8
#include "pycore_backoff.h"
9
#include "pycore_call.h"          // _PyObject_CallNoArgs()
10
#include "pycore_cell.h"          // PyCell_GetRef()
11
#include "pycore_ceval.h"         // SPECIAL___ENTER__
12
#include "pycore_code.h"
13
#include "pycore_dict.h"
14
#include "pycore_emscripten_signal.h"  // _Py_CHECK_EMSCRIPTEN_SIGNALS
15
#include "pycore_floatobject.h"   // _PyFloat_ExactDealloc()
16
#include "pycore_frame.h"
17
#include "pycore_function.h"
18
#include "pycore_genobject.h"     // _PyCoro_GetAwaitableIter()
19
#include "pycore_import.h"        // _PyImport_IsDefaultImportFunc()
20
#include "pycore_instruments.h"
21
#include "pycore_interpframe.h"   // _PyFrame_SetStackPointer()
22
#include "pycore_interpolation.h" // _PyInterpolation_Build()
23
#include "pycore_intrinsics.h"
24
#include "pycore_jit.h"
25
#include "pycore_list.h"          // _PyList_GetItemRef()
26
#include "pycore_long.h"          // _PyLong_GetZero()
27
#include "pycore_moduleobject.h"  // PyModuleObject
28
#include "pycore_object.h"        // _PyObject_GC_TRACK()
29
#include "pycore_opcode_metadata.h" // EXTRA_CASES
30
#include "pycore_opcode_utils.h"  // MAKE_FUNCTION_*
31
#include "pycore_optimizer.h"     // _PyUOpExecutor_Type
32
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_*
33
#include "pycore_pyerrors.h"      // _PyErr_GetRaisedException()
34
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
35
#include "pycore_range.h"         // _PyRangeIterObject
36
#include "pycore_setobject.h"     // _PySet_Update()
37
#include "pycore_sliceobject.h"   // _PyBuildSlice_ConsumeRefs
38
#include "pycore_sysmodule.h"     // _PySys_GetOptionalAttrString()
39
#include "pycore_template.h"      // _PyTemplate_Build()
40
#include "pycore_traceback.h"     // _PyTraceBack_FromFrame
41
#include "pycore_tuple.h"         // _PyTuple_ITEMS()
42
#include "pycore_uop_ids.h"       // Uops
43
44
#include "dictobject.h"
45
#include "frameobject.h"          // _PyInterpreterFrame_GetLine
46
#include "opcode.h"
47
#include "pydtrace.h"
48
#include "setobject.h"
49
#include "pycore_stackref.h"
50
51
#include <stdbool.h>              // bool
52
53
#if !defined(Py_BUILD_CORE)
54
#  error "ceval.c must be build with Py_BUILD_CORE define for best performance"
55
#endif
56
57
#if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
58
// GH-89279: The MSVC compiler does not inline these static inline functions
59
// in PGO build in _PyEval_EvalFrameDefault(), because this function is over
60
// the limit of PGO, and that limit cannot be configured.
61
// Define them as macros to make sure that they are always inlined by the
62
// preprocessor.
63
64
#undef Py_IS_TYPE
65
#define Py_IS_TYPE(ob, type) \
66
6.01G
    (_PyObject_CAST(ob)->ob_type == (type))
67
68
#undef Py_XDECREF
69
#define Py_XDECREF(arg) \
70
129M
    do { \
71
129M
        PyObject *xop = _PyObject_CAST(arg); \
72
129M
        if (xop != NULL) { \
73
58.8M
            Py_DECREF(xop); \
74
58.8M
        } \
75
129M
    } while (0)
76
77
#ifndef Py_GIL_DISABLED
78
79
#undef Py_DECREF
80
#define Py_DECREF(arg) \
81
157M
    do { \
82
157M
        PyObject *op = _PyObject_CAST(arg); \
83
157M
        if (_Py_IsImmortal(op)) { \
84
38.3M
            _Py_DECREF_IMMORTAL_STAT_INC(); \
85
38.3M
            break; \
86
38.3M
        } \
87
157M
        _Py_DECREF_STAT_INC(); \
88
119M
        if (--op->ob_refcnt == 0) { \
89
81.4M
            _PyReftracerTrack(op, PyRefTracer_DESTROY); \
90
81.4M
            destructor dealloc = Py_TYPE(op)->tp_dealloc; \
91
81.4M
            (*dealloc)(op); \
92
81.4M
        } \
93
119M
    } while (0)
94
95
#undef _Py_DECREF_SPECIALIZED
96
#define _Py_DECREF_SPECIALIZED(arg, dealloc) \
97
    do { \
98
        PyObject *op = _PyObject_CAST(arg); \
99
        if (_Py_IsImmortal(op)) { \
100
            _Py_DECREF_IMMORTAL_STAT_INC(); \
101
            break; \
102
        } \
103
        _Py_DECREF_STAT_INC(); \
104
        if (--op->ob_refcnt == 0) { \
105
            _PyReftracerTrack(op, PyRefTracer_DESTROY); \
106
            destructor d = (destructor)(dealloc); \
107
            d(op); \
108
        } \
109
    } while (0)
110
111
#else // Py_GIL_DISABLED
112
113
#undef Py_DECREF
114
#define Py_DECREF(arg) \
115
    do { \
116
        PyObject *op = _PyObject_CAST(arg); \
117
        uint32_t local = _Py_atomic_load_uint32_relaxed(&op->ob_ref_local); \
118
        if (local == _Py_IMMORTAL_REFCNT_LOCAL) { \
119
            _Py_DECREF_IMMORTAL_STAT_INC(); \
120
            break; \
121
        } \
122
        _Py_DECREF_STAT_INC(); \
123
        if (_Py_IsOwnedByCurrentThread(op)) { \
124
            local--; \
125
            _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, local); \
126
            if (local == 0) { \
127
                _Py_MergeZeroLocalRefcount(op); \
128
            } \
129
        } \
130
        else { \
131
            _Py_DecRefShared(op); \
132
        } \
133
    } while (0)
134
135
#undef _Py_DECREF_SPECIALIZED
136
#define _Py_DECREF_SPECIALIZED(arg, dealloc) Py_DECREF(arg)
137
138
#endif
139
#endif
140
141
142
static void
143
check_invalid_reentrancy(void)
144
198M
{
145
#if defined(Py_DEBUG) && defined(Py_GIL_DISABLED)
146
    // In the free-threaded build, the interpreter must not be re-entered if
147
    // the world-is-stopped.  If so, that's a bug somewhere (quite likely in
148
    // the painfully complex typeobject code).
149
    PyInterpreterState *interp = _PyInterpreterState_GET();
150
    assert(!interp->stoptheworld.world_stopped);
151
#endif
152
198M
}
153
154
155
#ifdef Py_DEBUG
156
static void
157
dump_item(_PyStackRef item)
158
{
159
    if (PyStackRef_IsNull(item)) {
160
        printf("<NULL>");
161
        return;
162
    }
163
    if (PyStackRef_IsTaggedInt(item)) {
164
        printf("%" PRId64, (int64_t)PyStackRef_UntagInt(item));
165
        return;
166
    }
167
    PyObject *obj = PyStackRef_AsPyObjectBorrow(item);
168
    if (obj == NULL) {
169
        printf("<nil>");
170
        return;
171
    }
172
    // Don't call __repr__(), it might recurse into the interpreter.
173
    printf("<%s at %p>", Py_TYPE(obj)->tp_name, (void *)obj);
174
}
175
176
static void
177
dump_stack(_PyInterpreterFrame *frame, _PyStackRef *stack_pointer)
178
{
179
    _PyFrame_SetStackPointer(frame, stack_pointer);
180
    _PyStackRef *locals_base = _PyFrame_GetLocalsArray(frame);
181
    _PyStackRef *stack_base = _PyFrame_Stackbase(frame);
182
    PyObject *exc = PyErr_GetRaisedException();
183
    printf("    locals=[");
184
    for (_PyStackRef *ptr = locals_base; ptr < stack_base; ptr++) {
185
        if (ptr != locals_base) {
186
            printf(", ");
187
        }
188
        dump_item(*ptr);
189
    }
190
    printf("]\n");
191
    if (stack_pointer < stack_base) {
192
        printf("    stack=%d\n", (int)(stack_pointer-stack_base));
193
    }
194
    else {
195
        printf("    stack=[");
196
        for (_PyStackRef *ptr = stack_base; ptr < stack_pointer; ptr++) {
197
            if (ptr != stack_base) {
198
                printf(", ");
199
            }
200
            dump_item(*ptr);
201
        }
202
        printf("]\n");
203
    }
204
    fflush(stdout);
205
    PyErr_SetRaisedException(exc);
206
    _PyFrame_GetStackPointer(frame);
207
}
208
209
static void
210
lltrace_instruction(_PyInterpreterFrame *frame,
211
                    _PyStackRef *stack_pointer,
212
                    _Py_CODEUNIT *next_instr,
213
                    int opcode,
214
                    int oparg)
215
{
216
    int offset = 0;
217
    if (frame->owner < FRAME_OWNED_BY_INTERPRETER) {
218
        dump_stack(frame, stack_pointer);
219
        offset = (int)(next_instr - _PyFrame_GetBytecode(frame));
220
    }
221
    const char *opname = _PyOpcode_OpName[opcode];
222
    assert(opname != NULL);
223
    if (OPCODE_HAS_ARG((int)_PyOpcode_Deopt[opcode])) {
224
        printf("%d: %s %d\n", offset * 2, opname, oparg);
225
    }
226
    else {
227
        printf("%d: %s\n", offset * 2, opname);
228
    }
229
    fflush(stdout);
230
}
231
232
static void
233
lltrace_resume_frame(_PyInterpreterFrame *frame)
234
{
235
    PyObject *fobj = PyStackRef_AsPyObjectBorrow(frame->f_funcobj);
236
    if (!PyStackRef_CodeCheck(frame->f_executable) ||
237
        fobj == NULL ||
238
        !PyFunction_Check(fobj)
239
    ) {
240
        printf("\nResuming frame.\n");
241
        return;
242
    }
243
    PyFunctionObject *f = (PyFunctionObject *)fobj;
244
    PyObject *exc = PyErr_GetRaisedException();
245
    PyObject *name = f->func_qualname;
246
    if (name == NULL) {
247
        name = f->func_name;
248
    }
249
    printf("\nResuming frame");
250
    if (name) {
251
        printf(" for ");
252
        if (PyObject_Print(name, stdout, 0) < 0) {
253
            PyErr_Clear();
254
        }
255
    }
256
    if (f->func_module) {
257
        printf(" in module ");
258
        if (PyObject_Print(f->func_module, stdout, 0) < 0) {
259
            PyErr_Clear();
260
        }
261
    }
262
    printf("\n");
263
    fflush(stdout);
264
    PyErr_SetRaisedException(exc);
265
}
266
267
static int
268
maybe_lltrace_resume_frame(_PyInterpreterFrame *frame, PyObject *globals)
269
{
270
    if (globals == NULL) {
271
        return 0;
272
    }
273
    if (frame->owner >= FRAME_OWNED_BY_INTERPRETER) {
274
        return 0;
275
    }
276
    int r = PyDict_Contains(globals, &_Py_ID(__lltrace__));
277
    if (r < 0) {
278
        return -1;
279
    }
280
    int lltrace = r * 5;  // Levels 1-4 only trace uops
281
    if (!lltrace) {
282
        // Can also be controlled by environment variable
283
        char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
284
        if (python_lltrace != NULL && *python_lltrace >= '0') {
285
            lltrace = *python_lltrace - '0';  // TODO: Parse an int and all that
286
        }
287
    }
288
    if (lltrace >= 5) {
289
        lltrace_resume_frame(frame);
290
    }
291
    return lltrace;
292
}
293
294
#endif
295
296
static void monitor_reraise(PyThreadState *tstate,
297
                 _PyInterpreterFrame *frame,
298
                 _Py_CODEUNIT *instr);
299
static int monitor_stop_iteration(PyThreadState *tstate,
300
                 _PyInterpreterFrame *frame,
301
                 _Py_CODEUNIT *instr,
302
                 PyObject *value);
303
static void monitor_unwind(PyThreadState *tstate,
304
                 _PyInterpreterFrame *frame,
305
                 _Py_CODEUNIT *instr);
306
static int monitor_handled(PyThreadState *tstate,
307
                 _PyInterpreterFrame *frame,
308
                 _Py_CODEUNIT *instr, PyObject *exc);
309
static void monitor_throw(PyThreadState *tstate,
310
                 _PyInterpreterFrame *frame,
311
                 _Py_CODEUNIT *instr);
312
313
static int get_exception_handler(PyCodeObject *, int, int*, int*, int*);
314
static  _PyInterpreterFrame *
315
_PyEvalFramePushAndInit_Ex(PyThreadState *tstate, _PyStackRef func,
316
    PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs, _PyInterpreterFrame *previous);
317
318
#ifdef HAVE_ERRNO_H
319
#include <errno.h>
320
#endif
321
322
int
323
Py_GetRecursionLimit(void)
324
0
{
325
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
326
0
    return interp->ceval.recursion_limit;
327
0
}
328
329
void
330
Py_SetRecursionLimit(int new_limit)
331
0
{
332
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
333
0
    _PyEval_StopTheWorld(interp);
334
0
    interp->ceval.recursion_limit = new_limit;
335
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
336
0
        int depth = p->py_recursion_limit - p->py_recursion_remaining;
337
0
        p->py_recursion_limit = new_limit;
338
0
        p->py_recursion_remaining = new_limit - depth;
339
0
    }
340
0
    _Py_FOR_EACH_TSTATE_END(interp);
341
0
    _PyEval_StartTheWorld(interp);
342
0
}
343
344
int
345
_Py_ReachedRecursionLimitWithMargin(PyThreadState *tstate, int margin_count)
346
84.7M
{
347
84.7M
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
348
84.7M
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
349
84.7M
    if (here_addr > _tstate->c_stack_soft_limit + margin_count * _PyOS_STACK_MARGIN_BYTES) {
350
84.7M
        return 0;
351
84.7M
    }
352
0
    if (_tstate->c_stack_hard_limit == 0) {
353
0
        _Py_InitializeRecursionLimits(tstate);
354
0
    }
355
0
    return here_addr <= _tstate->c_stack_soft_limit + margin_count * _PyOS_STACK_MARGIN_BYTES;
356
84.7M
}
357
358
void
359
_Py_EnterRecursiveCallUnchecked(PyThreadState *tstate)
360
0
{
361
0
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
362
0
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
363
0
    if (here_addr < _tstate->c_stack_hard_limit) {
364
0
        Py_FatalError("Unchecked stack overflow.");
365
0
    }
366
0
}
367
368
#if defined(__s390x__)
369
#  define Py_C_STACK_SIZE 320000
370
#elif defined(_WIN32)
371
   // Don't define Py_C_STACK_SIZE, ask the O/S
372
#elif defined(__ANDROID__)
373
#  define Py_C_STACK_SIZE 1200000
374
#elif defined(__sparc__)
375
#  define Py_C_STACK_SIZE 1600000
376
#elif defined(__hppa__) || defined(__powerpc64__)
377
#  define Py_C_STACK_SIZE 2000000
378
#else
379
0
#  define Py_C_STACK_SIZE 4000000
380
#endif
381
382
#if defined(__EMSCRIPTEN__)
383
384
// Temporary workaround to make `pthread_getattr_np` work on Emscripten.
385
// Emscripten 4.0.6 will contain a fix:
386
// https://github.com/emscripten-core/emscripten/pull/23887
387
388
#include "emscripten/stack.h"
389
390
#define pthread_attr_t workaround_pthread_attr_t
391
#define pthread_getattr_np workaround_pthread_getattr_np
392
#define pthread_attr_getguardsize workaround_pthread_attr_getguardsize
393
#define pthread_attr_getstack workaround_pthread_attr_getstack
394
#define pthread_attr_destroy workaround_pthread_attr_destroy
395
396
typedef struct {
397
    void *_a_stackaddr;
398
    size_t _a_stacksize, _a_guardsize;
399
} pthread_attr_t;
400
401
extern __attribute__((__visibility__("hidden"))) unsigned __default_guardsize;
402
403
// Modified version of pthread_getattr_np from the upstream PR.
404
405
int pthread_getattr_np(pthread_t thread, pthread_attr_t *attr) {
406
  attr->_a_stackaddr = (void*)emscripten_stack_get_base();
407
  attr->_a_stacksize = emscripten_stack_get_base() - emscripten_stack_get_end();
408
  attr->_a_guardsize = __default_guardsize;
409
  return 0;
410
}
411
412
// These three functions copied without any changes from Emscripten libc.
413
414
int pthread_attr_getguardsize(const pthread_attr_t *restrict a, size_t *restrict size)
415
{
416
  *size = a->_a_guardsize;
417
  return 0;
418
}
419
420
int pthread_attr_getstack(const pthread_attr_t *restrict a, void **restrict addr, size_t *restrict size)
421
{
422
/// XXX musl is not standard-conforming? It should not report EINVAL if _a_stackaddr is zero, and it should
423
///     report EINVAL if a is null: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_getstack.html
424
  if (!a) return EINVAL;
425
//  if (!a->_a_stackaddr)
426
//    return EINVAL;
427
428
  *size = a->_a_stacksize;
429
  *addr = (void *)(a->_a_stackaddr - *size);
430
  return 0;
431
}
432
433
int pthread_attr_destroy(pthread_attr_t *a)
434
{
435
  return 0;
436
}
437
438
#endif
439
440
441
void
442
_Py_InitializeRecursionLimits(PyThreadState *tstate)
443
16
{
444
16
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
445
#ifdef WIN32
446
    ULONG_PTR low, high;
447
    GetCurrentThreadStackLimits(&low, &high);
448
    _tstate->c_stack_top = (uintptr_t)high;
449
    ULONG guarantee = 0;
450
    SetThreadStackGuarantee(&guarantee);
451
    _tstate->c_stack_hard_limit = ((uintptr_t)low) + guarantee + _PyOS_STACK_MARGIN_BYTES;
452
    _tstate->c_stack_soft_limit = _tstate->c_stack_hard_limit + _PyOS_STACK_MARGIN_BYTES;
453
#else
454
16
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
455
16
#  if defined(HAVE_PTHREAD_GETATTR_NP) && !defined(_AIX) && !defined(__NetBSD__)
456
16
    size_t stack_size, guard_size;
457
16
    void *stack_addr;
458
16
    pthread_attr_t attr;
459
16
    int err = pthread_getattr_np(pthread_self(), &attr);
460
16
    if (err == 0) {
461
16
        err = pthread_attr_getguardsize(&attr, &guard_size);
462
16
        err |= pthread_attr_getstack(&attr, &stack_addr, &stack_size);
463
16
        err |= pthread_attr_destroy(&attr);
464
16
    }
465
16
    if (err == 0) {
466
16
        uintptr_t base = ((uintptr_t)stack_addr) + guard_size;
467
16
        _tstate->c_stack_top = base + stack_size;
468
#ifdef _Py_THREAD_SANITIZER
469
        // Thread sanitizer crashes if we use a bit more than half the stack.
470
        _tstate->c_stack_soft_limit = base + (stack_size / 2);
471
#else
472
16
        _tstate->c_stack_soft_limit = base + _PyOS_STACK_MARGIN_BYTES * 2;
473
16
#endif
474
16
        _tstate->c_stack_hard_limit = base + _PyOS_STACK_MARGIN_BYTES;
475
16
        assert(_tstate->c_stack_soft_limit < here_addr);
476
16
        assert(here_addr < _tstate->c_stack_top);
477
16
        return;
478
16
    }
479
0
#  endif
480
0
    _tstate->c_stack_top = _Py_SIZE_ROUND_UP(here_addr, 4096);
481
0
    _tstate->c_stack_soft_limit = _tstate->c_stack_top - Py_C_STACK_SIZE;
482
0
    _tstate->c_stack_hard_limit = _tstate->c_stack_top - (Py_C_STACK_SIZE + _PyOS_STACK_MARGIN_BYTES);
483
0
#endif
484
0
}
485
486
/* The function _Py_EnterRecursiveCallTstate() only calls _Py_CheckRecursiveCall()
487
   if the recursion_depth reaches recursion_limit. */
488
int
489
_Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
490
32
{
491
32
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
492
32
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
493
32
    assert(_tstate->c_stack_soft_limit != 0);
494
32
    assert(_tstate->c_stack_hard_limit != 0);
495
32
    if (here_addr < _tstate->c_stack_hard_limit) {
496
        /* Overflowing while handling an overflow. Give up. */
497
0
        int kbytes_used = (int)(_tstate->c_stack_top - here_addr)/1024;
498
0
        char buffer[80];
499
0
        snprintf(buffer, 80, "Unrecoverable stack overflow (used %d kB)%s", kbytes_used, where);
500
0
        Py_FatalError(buffer);
501
0
    }
502
32
    if (tstate->recursion_headroom) {
503
0
        return 0;
504
0
    }
505
32
    else {
506
32
        int kbytes_used = (int)(_tstate->c_stack_top - here_addr)/1024;
507
32
        tstate->recursion_headroom++;
508
32
        _PyErr_Format(tstate, PyExc_RecursionError,
509
32
                    "Stack overflow (used %d kB)%s",
510
32
                    kbytes_used,
511
32
                    where);
512
32
        tstate->recursion_headroom--;
513
32
        return -1;
514
32
    }
515
32
}
516
517
518
const binaryfunc _PyEval_BinaryOps[] = {
519
    [NB_ADD] = PyNumber_Add,
520
    [NB_AND] = PyNumber_And,
521
    [NB_FLOOR_DIVIDE] = PyNumber_FloorDivide,
522
    [NB_LSHIFT] = PyNumber_Lshift,
523
    [NB_MATRIX_MULTIPLY] = PyNumber_MatrixMultiply,
524
    [NB_MULTIPLY] = PyNumber_Multiply,
525
    [NB_REMAINDER] = PyNumber_Remainder,
526
    [NB_OR] = PyNumber_Or,
527
    [NB_POWER] = _PyNumber_PowerNoMod,
528
    [NB_RSHIFT] = PyNumber_Rshift,
529
    [NB_SUBTRACT] = PyNumber_Subtract,
530
    [NB_TRUE_DIVIDE] = PyNumber_TrueDivide,
531
    [NB_XOR] = PyNumber_Xor,
532
    [NB_INPLACE_ADD] = PyNumber_InPlaceAdd,
533
    [NB_INPLACE_AND] = PyNumber_InPlaceAnd,
534
    [NB_INPLACE_FLOOR_DIVIDE] = PyNumber_InPlaceFloorDivide,
535
    [NB_INPLACE_LSHIFT] = PyNumber_InPlaceLshift,
536
    [NB_INPLACE_MATRIX_MULTIPLY] = PyNumber_InPlaceMatrixMultiply,
537
    [NB_INPLACE_MULTIPLY] = PyNumber_InPlaceMultiply,
538
    [NB_INPLACE_REMAINDER] = PyNumber_InPlaceRemainder,
539
    [NB_INPLACE_OR] = PyNumber_InPlaceOr,
540
    [NB_INPLACE_POWER] = _PyNumber_InPlacePowerNoMod,
541
    [NB_INPLACE_RSHIFT] = PyNumber_InPlaceRshift,
542
    [NB_INPLACE_SUBTRACT] = PyNumber_InPlaceSubtract,
543
    [NB_INPLACE_TRUE_DIVIDE] = PyNumber_InPlaceTrueDivide,
544
    [NB_INPLACE_XOR] = PyNumber_InPlaceXor,
545
    [NB_SUBSCR] = PyObject_GetItem,
546
};
547
548
const conversion_func _PyEval_ConversionFuncs[4] = {
549
    [FVC_STR] = PyObject_Str,
550
    [FVC_REPR] = PyObject_Repr,
551
    [FVC_ASCII] = PyObject_ASCII
552
};
553
554
const _Py_SpecialMethod _Py_SpecialMethods[] = {
555
    [SPECIAL___ENTER__] = {
556
        .name = &_Py_ID(__enter__),
557
        .error = (
558
            "'%T' object does not support the context manager protocol "
559
            "(missed __enter__ method)"
560
        ),
561
        .error_suggestion = (
562
            "'%T' object does not support the context manager protocol "
563
            "(missed __enter__ method) but it supports the asynchronous "
564
            "context manager protocol. Did you mean to use 'async with'?"
565
        )
566
    },
567
    [SPECIAL___EXIT__] = {
568
        .name = &_Py_ID(__exit__),
569
        .error = (
570
            "'%T' object does not support the context manager protocol "
571
            "(missed __exit__ method)"
572
        ),
573
        .error_suggestion = (
574
            "'%T' object does not support the context manager protocol "
575
            "(missed __exit__ method) but it supports the asynchronous "
576
            "context manager protocol. Did you mean to use 'async with'?"
577
        )
578
    },
579
    [SPECIAL___AENTER__] = {
580
        .name = &_Py_ID(__aenter__),
581
        .error = (
582
            "'%T' object does not support the asynchronous "
583
            "context manager protocol (missed __aenter__ method)"
584
        ),
585
        .error_suggestion = (
586
            "'%T' object does not support the asynchronous context manager "
587
            "protocol (missed __aenter__ method) but it supports the context "
588
            "manager protocol. Did you mean to use 'with'?"
589
        )
590
    },
591
    [SPECIAL___AEXIT__] = {
592
        .name = &_Py_ID(__aexit__),
593
        .error = (
594
            "'%T' object does not support the asynchronous "
595
            "context manager protocol (missed __aexit__ method)"
596
        ),
597
        .error_suggestion = (
598
            "'%T' object does not support the asynchronous context manager "
599
            "protocol (missed __aexit__ method) but it supports the context "
600
            "manager protocol. Did you mean to use 'with'?"
601
        )
602
    }
603
};
604
605
const size_t _Py_FunctionAttributeOffsets[] = {
606
    [MAKE_FUNCTION_CLOSURE] = offsetof(PyFunctionObject, func_closure),
607
    [MAKE_FUNCTION_ANNOTATIONS] = offsetof(PyFunctionObject, func_annotations),
608
    [MAKE_FUNCTION_KWDEFAULTS] = offsetof(PyFunctionObject, func_kwdefaults),
609
    [MAKE_FUNCTION_DEFAULTS] = offsetof(PyFunctionObject, func_defaults),
610
    [MAKE_FUNCTION_ANNOTATE] = offsetof(PyFunctionObject, func_annotate),
611
};
612
613
// PEP 634: Structural Pattern Matching
614
615
616
// Return a tuple of values corresponding to keys, with error checks for
617
// duplicate/missing keys.
618
PyObject *
619
_PyEval_MatchKeys(PyThreadState *tstate, PyObject *map, PyObject *keys)
620
0
{
621
0
    assert(PyTuple_CheckExact(keys));
622
0
    Py_ssize_t nkeys = PyTuple_GET_SIZE(keys);
623
0
    if (!nkeys) {
624
        // No keys means no items.
625
0
        return PyTuple_New(0);
626
0
    }
627
0
    PyObject *seen = NULL;
628
0
    PyObject *dummy = NULL;
629
0
    PyObject *values = NULL;
630
    // We use the two argument form of map.get(key, default) for two reasons:
631
    // - Atomically check for a key and get its value without error handling.
632
    // - Don't cause key creation or resizing in dict subclasses like
633
    //   collections.defaultdict that define __missing__ (or similar).
634
0
    _PyCStackRef cref;
635
0
    _PyThreadState_PushCStackRef(tstate, &cref);
636
0
    int meth_found = _PyObject_GetMethodStackRef(tstate, map, &_Py_ID(get), &cref.ref);
637
0
    PyObject *get = PyStackRef_AsPyObjectBorrow(cref.ref);
638
0
    if (get == NULL) {
639
0
        goto fail;
640
0
    }
641
0
    seen = PySet_New(NULL);
642
0
    if (seen == NULL) {
643
0
        goto fail;
644
0
    }
645
    // dummy = object()
646
0
    dummy = _PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
647
0
    if (dummy == NULL) {
648
0
        goto fail;
649
0
    }
650
0
    values = PyTuple_New(nkeys);
651
0
    if (values == NULL) {
652
0
        goto fail;
653
0
    }
654
0
    for (Py_ssize_t i = 0; i < nkeys; i++) {
655
0
        PyObject *key = PyTuple_GET_ITEM(keys, i);
656
0
        if (PySet_Contains(seen, key) || PySet_Add(seen, key)) {
657
0
            if (!_PyErr_Occurred(tstate)) {
658
                // Seen it before!
659
0
                _PyErr_Format(tstate, PyExc_ValueError,
660
0
                              "mapping pattern checks duplicate key (%R)", key);
661
0
            }
662
0
            goto fail;
663
0
        }
664
0
        PyObject *args[] = { map, key, dummy };
665
0
        PyObject *value = NULL;
666
0
        if (meth_found) {
667
0
            value = PyObject_Vectorcall(get, args, 3, NULL);
668
0
        }
669
0
        else {
670
0
            value = PyObject_Vectorcall(get, &args[1], 2, NULL);
671
0
        }
672
0
        if (value == NULL) {
673
0
            goto fail;
674
0
        }
675
0
        if (value == dummy) {
676
            // key not in map!
677
0
            Py_DECREF(value);
678
0
            Py_DECREF(values);
679
            // Return None:
680
0
            values = Py_NewRef(Py_None);
681
0
            goto done;
682
0
        }
683
0
        PyTuple_SET_ITEM(values, i, value);
684
0
    }
685
    // Success:
686
0
done:
687
0
    _PyThreadState_PopCStackRef(tstate, &cref);
688
0
    Py_DECREF(seen);
689
0
    Py_DECREF(dummy);
690
0
    return values;
691
0
fail:
692
0
    _PyThreadState_PopCStackRef(tstate, &cref);
693
0
    Py_XDECREF(seen);
694
0
    Py_XDECREF(dummy);
695
0
    Py_XDECREF(values);
696
0
    return NULL;
697
0
}
698
699
// Extract a named attribute from the subject, with additional bookkeeping to
700
// raise TypeErrors for repeated lookups. On failure, return NULL (with no
701
// error set). Use _PyErr_Occurred(tstate) to disambiguate.
702
static PyObject *
703
match_class_attr(PyThreadState *tstate, PyObject *subject, PyObject *type,
704
                 PyObject *name, PyObject *seen)
705
0
{
706
0
    assert(PyUnicode_CheckExact(name));
707
0
    assert(PySet_CheckExact(seen));
708
0
    if (PySet_Contains(seen, name) || PySet_Add(seen, name)) {
709
0
        if (!_PyErr_Occurred(tstate)) {
710
            // Seen it before!
711
0
            _PyErr_Format(tstate, PyExc_TypeError,
712
0
                          "%s() got multiple sub-patterns for attribute %R",
713
0
                          ((PyTypeObject*)type)->tp_name, name);
714
0
        }
715
0
        return NULL;
716
0
    }
717
0
    PyObject *attr;
718
0
    (void)PyObject_GetOptionalAttr(subject, name, &attr);
719
0
    return attr;
720
0
}
721
722
// On success (match), return a tuple of extracted attributes. On failure (no
723
// match), return NULL. Use _PyErr_Occurred(tstate) to disambiguate.
724
PyObject*
725
_PyEval_MatchClass(PyThreadState *tstate, PyObject *subject, PyObject *type,
726
                   Py_ssize_t nargs, PyObject *kwargs)
727
0
{
728
0
    if (!PyType_Check(type)) {
729
0
        const char *e = "called match pattern must be a class";
730
0
        _PyErr_Format(tstate, PyExc_TypeError, e);
731
0
        return NULL;
732
0
    }
733
0
    assert(PyTuple_CheckExact(kwargs));
734
    // First, an isinstance check:
735
0
    if (PyObject_IsInstance(subject, type) <= 0) {
736
0
        return NULL;
737
0
    }
738
    // So far so good:
739
0
    PyObject *seen = PySet_New(NULL);
740
0
    if (seen == NULL) {
741
0
        return NULL;
742
0
    }
743
0
    PyObject *attrs = PyList_New(0);
744
0
    if (attrs == NULL) {
745
0
        Py_DECREF(seen);
746
0
        return NULL;
747
0
    }
748
    // NOTE: From this point on, goto fail on failure:
749
0
    PyObject *match_args = NULL;
750
    // First, the positional subpatterns:
751
0
    if (nargs) {
752
0
        int match_self = 0;
753
0
        if (PyObject_GetOptionalAttr(type, &_Py_ID(__match_args__), &match_args) < 0) {
754
0
            goto fail;
755
0
        }
756
0
        if (match_args) {
757
0
            if (!PyTuple_CheckExact(match_args)) {
758
0
                const char *e = "%s.__match_args__ must be a tuple (got %s)";
759
0
                _PyErr_Format(tstate, PyExc_TypeError, e,
760
0
                              ((PyTypeObject *)type)->tp_name,
761
0
                              Py_TYPE(match_args)->tp_name);
762
0
                goto fail;
763
0
            }
764
0
        }
765
0
        else {
766
            // _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
767
            // define __match_args__. This is natural behavior for subclasses:
768
            // it's as if __match_args__ is some "magic" value that is lost as
769
            // soon as they redefine it.
770
0
            match_args = PyTuple_New(0);
771
0
            match_self = PyType_HasFeature((PyTypeObject*)type,
772
0
                                            _Py_TPFLAGS_MATCH_SELF);
773
0
        }
774
0
        assert(PyTuple_CheckExact(match_args));
775
0
        Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
776
0
        if (allowed < nargs) {
777
0
            const char *plural = (allowed == 1) ? "" : "s";
778
0
            _PyErr_Format(tstate, PyExc_TypeError,
779
0
                          "%s() accepts %d positional sub-pattern%s (%d given)",
780
0
                          ((PyTypeObject*)type)->tp_name,
781
0
                          allowed, plural, nargs);
782
0
            goto fail;
783
0
        }
784
0
        if (match_self) {
785
            // Easy. Copy the subject itself, and move on to kwargs.
786
0
            if (PyList_Append(attrs, subject) < 0) {
787
0
                goto fail;
788
0
            }
789
0
        }
790
0
        else {
791
0
            for (Py_ssize_t i = 0; i < nargs; i++) {
792
0
                PyObject *name = PyTuple_GET_ITEM(match_args, i);
793
0
                if (!PyUnicode_CheckExact(name)) {
794
0
                    _PyErr_Format(tstate, PyExc_TypeError,
795
0
                                  "__match_args__ elements must be strings "
796
0
                                  "(got %s)", Py_TYPE(name)->tp_name);
797
0
                    goto fail;
798
0
                }
799
0
                PyObject *attr = match_class_attr(tstate, subject, type, name,
800
0
                                                  seen);
801
0
                if (attr == NULL) {
802
0
                    goto fail;
803
0
                }
804
0
                if (PyList_Append(attrs, attr) < 0) {
805
0
                    Py_DECREF(attr);
806
0
                    goto fail;
807
0
                }
808
0
                Py_DECREF(attr);
809
0
            }
810
0
        }
811
0
        Py_CLEAR(match_args);
812
0
    }
813
    // Finally, the keyword subpatterns:
814
0
    for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
815
0
        PyObject *name = PyTuple_GET_ITEM(kwargs, i);
816
0
        PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
817
0
        if (attr == NULL) {
818
0
            goto fail;
819
0
        }
820
0
        if (PyList_Append(attrs, attr) < 0) {
821
0
            Py_DECREF(attr);
822
0
            goto fail;
823
0
        }
824
0
        Py_DECREF(attr);
825
0
    }
826
0
    Py_SETREF(attrs, PyList_AsTuple(attrs));
827
0
    Py_DECREF(seen);
828
0
    return attrs;
829
0
fail:
830
    // We really don't care whether an error was raised or not... that's our
831
    // caller's problem. All we know is that the match failed.
832
0
    Py_XDECREF(match_args);
833
0
    Py_DECREF(seen);
834
0
    Py_DECREF(attrs);
835
0
    return NULL;
836
0
}
837
838
839
static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
840
841
PyObject *
842
PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
843
1.03k
{
844
1.03k
    PyThreadState *tstate = _PyThreadState_GET();
845
1.03k
    if (locals == NULL) {
846
0
        locals = globals;
847
0
    }
848
1.03k
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
849
1.03k
    if (builtins == NULL) {
850
0
        return NULL;
851
0
    }
852
1.03k
    PyFrameConstructor desc = {
853
1.03k
        .fc_globals = globals,
854
1.03k
        .fc_builtins = builtins,
855
1.03k
        .fc_name = ((PyCodeObject *)co)->co_name,
856
1.03k
        .fc_qualname = ((PyCodeObject *)co)->co_name,
857
1.03k
        .fc_code = co,
858
1.03k
        .fc_defaults = NULL,
859
1.03k
        .fc_kwdefaults = NULL,
860
1.03k
        .fc_closure = NULL
861
1.03k
    };
862
1.03k
    PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
863
1.03k
    _Py_DECREF_BUILTINS(builtins);
864
1.03k
    if (func == NULL) {
865
0
        return NULL;
866
0
    }
867
1.03k
    EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
868
1.03k
    PyObject *res = _PyEval_Vector(tstate, func, locals, NULL, 0, NULL);
869
1.03k
    Py_DECREF(func);
870
0
    return res;
871
1.03k
}
872
873
874
/* Interpreter main loop */
875
876
PyObject *
877
PyEval_EvalFrame(PyFrameObject *f)
878
0
{
879
    /* Function kept for backward compatibility */
880
0
    PyThreadState *tstate = _PyThreadState_GET();
881
0
    return _PyEval_EvalFrame(tstate, f->f_frame, 0);
882
0
}
883
884
PyObject *
885
PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
886
0
{
887
0
    PyThreadState *tstate = _PyThreadState_GET();
888
0
    return _PyEval_EvalFrame(tstate, f->f_frame, throwflag);
889
0
}
890
891
#include "ceval_macros.h"
892
893
int _Py_CheckRecursiveCallPy(
894
    PyThreadState *tstate)
895
304
{
896
304
    if (tstate->recursion_headroom) {
897
0
        if (tstate->py_recursion_remaining < -50) {
898
            /* Overflowing while handling an overflow. Give up. */
899
0
            Py_FatalError("Cannot recover from Python stack overflow.");
900
0
        }
901
0
    }
902
304
    else {
903
304
        if (tstate->py_recursion_remaining <= 0) {
904
304
            tstate->recursion_headroom++;
905
304
            _PyErr_Format(tstate, PyExc_RecursionError,
906
304
                        "maximum recursion depth exceeded");
907
304
            tstate->recursion_headroom--;
908
304
            return -1;
909
304
        }
910
304
    }
911
0
    return 0;
912
304
}
913
914
static const _Py_CODEUNIT _Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS[] = {
915
    /* Put a NOP at the start, so that the IP points into
916
    * the code, rather than before it */
917
    { .op.code = NOP, .op.arg = 0 },
918
    { .op.code = INTERPRETER_EXIT, .op.arg = 0 },  /* reached on return */
919
    { .op.code = NOP, .op.arg = 0 },
920
    { .op.code = INTERPRETER_EXIT, .op.arg = 0 },  /* reached on yield */
921
    { .op.code = RESUME, .op.arg = RESUME_OPARG_DEPTH1_MASK | RESUME_AT_FUNC_START }
922
};
923
924
#ifdef Py_DEBUG
925
extern void _PyUOpPrint(const _PyUOpInstruction *uop);
926
#endif
927
928
929
/* Disable unused label warnings.  They are handy for debugging, even
930
   if computed gotos aren't used. */
931
932
/* TBD - what about other compilers? */
933
#if defined(__GNUC__) || defined(__clang__)
934
#  pragma GCC diagnostic push
935
#  pragma GCC diagnostic ignored "-Wunused-label"
936
#elif defined(_MSC_VER) /* MS_WINDOWS */
937
#  pragma warning(push)
938
#  pragma warning(disable:4102)
939
#endif
940
941
942
PyObject **
943
_PyObjectArray_FromStackRefArray(_PyStackRef *input, Py_ssize_t nargs, PyObject **scratch)
944
1.38G
{
945
1.38G
    PyObject **result;
946
1.38G
    if (nargs > MAX_STACKREF_SCRATCH) {
947
        // +1 in case PY_VECTORCALL_ARGUMENTS_OFFSET is set.
948
243
        result = PyMem_Malloc((nargs + 1) * sizeof(PyObject *));
949
243
        if (result == NULL) {
950
0
            return NULL;
951
0
        }
952
243
        result++;
953
243
    }
954
1.38G
    else {
955
1.38G
        result = scratch;
956
1.38G
    }
957
4.02G
    for (int i = 0; i < nargs; i++) {
958
2.64G
        result[i] = PyStackRef_AsPyObjectBorrow(input[i]);
959
2.64G
    }
960
1.38G
    return result;
961
1.38G
}
962
963
void
964
_PyObjectArray_Free(PyObject **array, PyObject **scratch)
965
1.38G
{
966
1.38G
    if (array != scratch) {
967
243
        PyMem_Free(array);
968
243
    }
969
1.38G
}
970
971
972
/* _PyEval_EvalFrameDefault is too large to optimize for speed with PGO on MSVC.
973
 */
974
#if (defined(_MSC_VER) && \
975
     (_MSC_VER < 1943) && \
976
     defined(_Py_USING_PGO))
977
#define DO_NOT_OPTIMIZE_INTERP_LOOP
978
#endif
979
980
#ifdef DO_NOT_OPTIMIZE_INTERP_LOOP
981
#  pragma optimize("t", off)
982
/* This setting is reversed below following _PyEval_EvalFrameDefault */
983
#endif
984
985
#if Py_TAIL_CALL_INTERP
986
#include "opcode_targets.h"
987
#include "generated_cases.c.h"
988
#endif
989
990
#if (defined(__GNUC__) && __GNUC__ >= 10 && !defined(__clang__)) && defined(__x86_64__)
991
/*
992
 * gh-129987: The SLP autovectorizer can cause poor code generation for
993
 * opcode dispatch in some GCC versions (observed in GCCs 12 through 15,
994
 * probably caused by https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115777),
995
 * negating any benefit we get from vectorization elsewhere in the
996
 * interpreter loop. Disabling it significantly affected older GCC versions
997
 * (prior to GCC 9, 40% performance drop), so we have to selectively disable
998
 * it.
999
 */
1000
#define DONT_SLP_VECTORIZE __attribute__((optimize ("no-tree-slp-vectorize")))
1001
#else
1002
#define DONT_SLP_VECTORIZE
1003
#endif
1004
1005
typedef struct {
1006
    _PyInterpreterFrame frame;
1007
    _PyStackRef stack[1];
1008
} _PyEntryFrame;
1009
1010
PyObject* _Py_HOT_FUNCTION DONT_SLP_VECTORIZE
1011
_PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
1012
198M
{
1013
198M
    _Py_EnsureTstateNotNULL(tstate);
1014
198M
    check_invalid_reentrancy();
1015
198M
    CALL_STAT_INC(pyeval_calls);
1016
1017
198M
#if USE_COMPUTED_GOTOS && !Py_TAIL_CALL_INTERP
1018
/* Import the static jump table */
1019
198M
#include "opcode_targets.h"
1020
198M
#endif
1021
1022
#ifdef Py_STATS
1023
    int lastopcode = 0;
1024
#endif
1025
198M
#if !Py_TAIL_CALL_INTERP
1026
198M
    uint8_t opcode;    /* Current opcode */
1027
198M
    int oparg;         /* Current opcode argument, if any */
1028
198M
    assert(tstate->current_frame == NULL || tstate->current_frame->stackpointer != NULL);
1029
198M
#endif
1030
198M
    _PyEntryFrame entry;
1031
1032
198M
    if (_Py_EnterRecursiveCallTstate(tstate, "")) {
1033
0
        assert(frame->owner != FRAME_OWNED_BY_INTERPRETER);
1034
0
        _PyEval_FrameClearAndPop(tstate, frame);
1035
0
        return NULL;
1036
0
    }
1037
1038
    /* Local "register" variables.
1039
     * These are cached values from the frame and code object.  */
1040
198M
    _Py_CODEUNIT *next_instr;
1041
198M
    _PyStackRef *stack_pointer;
1042
198M
    entry.stack[0] = PyStackRef_NULL;
1043
#ifdef Py_STACKREF_DEBUG
1044
    entry.frame.f_funcobj = PyStackRef_None;
1045
#elif defined(Py_DEBUG)
1046
    /* Set these to invalid but identifiable values for debugging. */
1047
    entry.frame.f_funcobj = (_PyStackRef){.bits = 0xaaa0};
1048
    entry.frame.f_locals = (PyObject*)0xaaa1;
1049
    entry.frame.frame_obj = (PyFrameObject*)0xaaa2;
1050
    entry.frame.f_globals = (PyObject*)0xaaa3;
1051
    entry.frame.f_builtins = (PyObject*)0xaaa4;
1052
#endif
1053
198M
    entry.frame.f_executable = PyStackRef_None;
1054
198M
    entry.frame.instr_ptr = (_Py_CODEUNIT *)_Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS + 1;
1055
198M
    entry.frame.stackpointer = entry.stack;
1056
198M
    entry.frame.owner = FRAME_OWNED_BY_INTERPRETER;
1057
198M
    entry.frame.visited = 0;
1058
198M
    entry.frame.return_offset = 0;
1059
#ifdef Py_DEBUG
1060
    entry.frame.lltrace = 0;
1061
#endif
1062
    /* Push frame */
1063
198M
    entry.frame.previous = tstate->current_frame;
1064
198M
    frame->previous = &entry.frame;
1065
198M
    tstate->current_frame = frame;
1066
198M
    entry.frame.localsplus[0] = PyStackRef_NULL;
1067
#ifdef _Py_TIER2
1068
    if (tstate->current_executor != NULL) {
1069
        entry.frame.localsplus[0] = PyStackRef_FromPyObjectNew(tstate->current_executor);
1070
        tstate->current_executor = NULL;
1071
    }
1072
#endif
1073
1074
    /* support for generator.throw() */
1075
198M
    if (throwflag) {
1076
2.50k
        if (_Py_EnterRecursivePy(tstate)) {
1077
0
            goto early_exit;
1078
0
        }
1079
#ifdef Py_GIL_DISABLED
1080
        /* Load thread-local bytecode */
1081
        if (frame->tlbc_index != ((_PyThreadStateImpl *)tstate)->tlbc_index) {
1082
            _Py_CODEUNIT *bytecode =
1083
                _PyEval_GetExecutableCode(tstate, _PyFrame_GetCode(frame));
1084
            if (bytecode == NULL) {
1085
                goto early_exit;
1086
            }
1087
            ptrdiff_t off = frame->instr_ptr - _PyFrame_GetBytecode(frame);
1088
            frame->tlbc_index = ((_PyThreadStateImpl *)tstate)->tlbc_index;
1089
            frame->instr_ptr = bytecode + off;
1090
        }
1091
#endif
1092
        /* Because this avoids the RESUME, we need to update instrumentation */
1093
2.50k
        _Py_Instrument(_PyFrame_GetCode(frame), tstate->interp);
1094
2.50k
        next_instr = frame->instr_ptr;
1095
2.50k
        monitor_throw(tstate, frame, next_instr);
1096
2.50k
        stack_pointer = _PyFrame_GetStackPointer(frame);
1097
#if Py_TAIL_CALL_INTERP
1098
#   if Py_STATS
1099
        return _TAIL_CALL_error(frame, stack_pointer, tstate, next_instr, 0, lastopcode);
1100
#   else
1101
        return _TAIL_CALL_error(frame, stack_pointer, tstate, next_instr, 0);
1102
#   endif
1103
#else
1104
2.50k
        goto error;
1105
2.50k
#endif
1106
2.50k
    }
1107
1108
#if defined(_Py_TIER2) && !defined(_Py_JIT)
1109
    /* Tier 2 interpreter state */
1110
    _PyExecutorObject *current_executor = NULL;
1111
    const _PyUOpInstruction *next_uop = NULL;
1112
#endif
1113
#if Py_TAIL_CALL_INTERP
1114
#   if Py_STATS
1115
        return _TAIL_CALL_start_frame(frame, NULL, tstate, NULL, 0, lastopcode);
1116
#   else
1117
        return _TAIL_CALL_start_frame(frame, NULL, tstate, NULL, 0);
1118
#   endif
1119
#else
1120
198M
    goto start_frame;
1121
198M
#   include "generated_cases.c.h"
1122
0
#endif
1123
1124
1125
#ifdef _Py_TIER2
1126
1127
// Tier 2 is also here!
1128
enter_tier_two:
1129
1130
#ifdef _Py_JIT
1131
    assert(0);
1132
#else
1133
1134
#undef LOAD_IP
1135
#define LOAD_IP(UNUSED) (void)0
1136
1137
#ifdef Py_STATS
1138
// Disable these macros that apply to Tier 1 stats when we are in Tier 2
1139
#undef STAT_INC
1140
#define STAT_INC(opname, name) ((void)0)
1141
#undef STAT_DEC
1142
#define STAT_DEC(opname, name) ((void)0)
1143
#endif
1144
1145
#undef ENABLE_SPECIALIZATION
1146
#define ENABLE_SPECIALIZATION 0
1147
#undef ENABLE_SPECIALIZATION_FT
1148
#define ENABLE_SPECIALIZATION_FT 0
1149
1150
    ; // dummy statement after a label, before a declaration
1151
    uint16_t uopcode;
1152
#ifdef Py_STATS
1153
    int lastuop = 0;
1154
    uint64_t trace_uop_execution_counter = 0;
1155
#endif
1156
1157
    assert(next_uop->opcode == _START_EXECUTOR);
1158
tier2_dispatch:
1159
    for (;;) {
1160
        uopcode = next_uop->opcode;
1161
#ifdef Py_DEBUG
1162
        if (frame->lltrace >= 3) {
1163
            dump_stack(frame, stack_pointer);
1164
            if (next_uop->opcode == _START_EXECUTOR) {
1165
                printf("%4d uop: ", 0);
1166
            }
1167
            else {
1168
                printf("%4d uop: ", (int)(next_uop - current_executor->trace));
1169
            }
1170
            _PyUOpPrint(next_uop);
1171
            printf("\n");
1172
        }
1173
#endif
1174
        next_uop++;
1175
        OPT_STAT_INC(uops_executed);
1176
        UOP_STAT_INC(uopcode, execution_count);
1177
        UOP_PAIR_INC(uopcode, lastuop);
1178
#ifdef Py_STATS
1179
        trace_uop_execution_counter++;
1180
        ((_PyUOpInstruction  *)next_uop)[-1].execution_count++;
1181
#endif
1182
1183
        switch (uopcode) {
1184
1185
#include "executor_cases.c.h"
1186
1187
            default:
1188
#ifdef Py_DEBUG
1189
            {
1190
                printf("Unknown uop: ");
1191
                _PyUOpPrint(&next_uop[-1]);
1192
                printf(" @ %d\n", (int)(next_uop - current_executor->trace - 1));
1193
                Py_FatalError("Unknown uop");
1194
            }
1195
#else
1196
            Py_UNREACHABLE();
1197
#endif
1198
1199
        }
1200
    }
1201
1202
jump_to_error_target:
1203
#ifdef Py_DEBUG
1204
    if (frame->lltrace >= 2) {
1205
        printf("Error: [UOp ");
1206
        _PyUOpPrint(&next_uop[-1]);
1207
        printf(" @ %d -> %s]\n",
1208
               (int)(next_uop - current_executor->trace - 1),
1209
               _PyOpcode_OpName[frame->instr_ptr->op.code]);
1210
    }
1211
#endif
1212
    assert(next_uop[-1].format == UOP_FORMAT_JUMP);
1213
    uint16_t target = uop_get_error_target(&next_uop[-1]);
1214
    next_uop = current_executor->trace + target;
1215
    goto tier2_dispatch;
1216
1217
jump_to_jump_target:
1218
    assert(next_uop[-1].format == UOP_FORMAT_JUMP);
1219
    target = uop_get_jump_target(&next_uop[-1]);
1220
    next_uop = current_executor->trace + target;
1221
    goto tier2_dispatch;
1222
1223
#endif  // _Py_JIT
1224
1225
#endif // _Py_TIER2
1226
1227
0
early_exit:
1228
0
    assert(_PyErr_Occurred(tstate));
1229
0
    _Py_LeaveRecursiveCallPy(tstate);
1230
0
    assert(frame->owner != FRAME_OWNED_BY_INTERPRETER);
1231
    // GH-99729: We need to unlink the frame *before* clearing it:
1232
0
    _PyInterpreterFrame *dying = frame;
1233
0
    frame = tstate->current_frame = dying->previous;
1234
0
    _PyEval_FrameClearAndPop(tstate, dying);
1235
0
    frame->return_offset = 0;
1236
0
    assert(frame->owner == FRAME_OWNED_BY_INTERPRETER);
1237
    /* Restore previous frame and exit */
1238
0
    tstate->current_frame = frame->previous;
1239
0
    return NULL;
1240
61.5G
}
1241
1242
#ifdef DO_NOT_OPTIMIZE_INTERP_LOOP
1243
#  pragma optimize("", on)
1244
#endif
1245
1246
#if defined(__GNUC__) || defined(__clang__)
1247
#  pragma GCC diagnostic pop
1248
#elif defined(_MSC_VER) /* MS_WINDOWS */
1249
#  pragma warning(pop)
1250
#endif
1251
1252
static void
1253
format_missing(PyThreadState *tstate, const char *kind,
1254
               PyCodeObject *co, PyObject *names, PyObject *qualname)
1255
0
{
1256
0
    int err;
1257
0
    Py_ssize_t len = PyList_GET_SIZE(names);
1258
0
    PyObject *name_str, *comma, *tail, *tmp;
1259
1260
0
    assert(PyList_CheckExact(names));
1261
0
    assert(len >= 1);
1262
    /* Deal with the joys of natural language. */
1263
0
    switch (len) {
1264
0
    case 1:
1265
0
        name_str = PyList_GET_ITEM(names, 0);
1266
0
        Py_INCREF(name_str);
1267
0
        break;
1268
0
    case 2:
1269
0
        name_str = PyUnicode_FromFormat("%U and %U",
1270
0
                                        PyList_GET_ITEM(names, len - 2),
1271
0
                                        PyList_GET_ITEM(names, len - 1));
1272
0
        break;
1273
0
    default:
1274
0
        tail = PyUnicode_FromFormat(", %U, and %U",
1275
0
                                    PyList_GET_ITEM(names, len - 2),
1276
0
                                    PyList_GET_ITEM(names, len - 1));
1277
0
        if (tail == NULL)
1278
0
            return;
1279
        /* Chop off the last two objects in the list. This shouldn't actually
1280
           fail, but we can't be too careful. */
1281
0
        err = PyList_SetSlice(names, len - 2, len, NULL);
1282
0
        if (err == -1) {
1283
0
            Py_DECREF(tail);
1284
0
            return;
1285
0
        }
1286
        /* Stitch everything up into a nice comma-separated list. */
1287
0
        comma = PyUnicode_FromString(", ");
1288
0
        if (comma == NULL) {
1289
0
            Py_DECREF(tail);
1290
0
            return;
1291
0
        }
1292
0
        tmp = PyUnicode_Join(comma, names);
1293
0
        Py_DECREF(comma);
1294
0
        if (tmp == NULL) {
1295
0
            Py_DECREF(tail);
1296
0
            return;
1297
0
        }
1298
0
        name_str = PyUnicode_Concat(tmp, tail);
1299
0
        Py_DECREF(tmp);
1300
0
        Py_DECREF(tail);
1301
0
        break;
1302
0
    }
1303
0
    if (name_str == NULL)
1304
0
        return;
1305
0
    _PyErr_Format(tstate, PyExc_TypeError,
1306
0
                  "%U() missing %i required %s argument%s: %U",
1307
0
                  qualname,
1308
0
                  len,
1309
0
                  kind,
1310
0
                  len == 1 ? "" : "s",
1311
0
                  name_str);
1312
0
    Py_DECREF(name_str);
1313
0
}
1314
1315
static void
1316
missing_arguments(PyThreadState *tstate, PyCodeObject *co,
1317
                  Py_ssize_t missing, Py_ssize_t defcount,
1318
                  _PyStackRef *localsplus, PyObject *qualname)
1319
0
{
1320
0
    Py_ssize_t i, j = 0;
1321
0
    Py_ssize_t start, end;
1322
0
    int positional = (defcount != -1);
1323
0
    const char *kind = positional ? "positional" : "keyword-only";
1324
0
    PyObject *missing_names;
1325
1326
    /* Compute the names of the arguments that are missing. */
1327
0
    missing_names = PyList_New(missing);
1328
0
    if (missing_names == NULL)
1329
0
        return;
1330
0
    if (positional) {
1331
0
        start = 0;
1332
0
        end = co->co_argcount - defcount;
1333
0
    }
1334
0
    else {
1335
0
        start = co->co_argcount;
1336
0
        end = start + co->co_kwonlyargcount;
1337
0
    }
1338
0
    for (i = start; i < end; i++) {
1339
0
        if (PyStackRef_IsNull(localsplus[i])) {
1340
0
            PyObject *raw = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1341
0
            PyObject *name = PyObject_Repr(raw);
1342
0
            if (name == NULL) {
1343
0
                Py_DECREF(missing_names);
1344
0
                return;
1345
0
            }
1346
0
            PyList_SET_ITEM(missing_names, j++, name);
1347
0
        }
1348
0
    }
1349
0
    assert(j == missing);
1350
0
    format_missing(tstate, kind, co, missing_names, qualname);
1351
0
    Py_DECREF(missing_names);
1352
0
}
1353
1354
static void
1355
too_many_positional(PyThreadState *tstate, PyCodeObject *co,
1356
                    Py_ssize_t given, PyObject *defaults,
1357
                    _PyStackRef *localsplus, PyObject *qualname)
1358
0
{
1359
0
    int plural;
1360
0
    Py_ssize_t kwonly_given = 0;
1361
0
    Py_ssize_t i;
1362
0
    PyObject *sig, *kwonly_sig;
1363
0
    Py_ssize_t co_argcount = co->co_argcount;
1364
1365
0
    assert((co->co_flags & CO_VARARGS) == 0);
1366
    /* Count missing keyword-only args. */
1367
0
    for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
1368
0
        if (PyStackRef_AsPyObjectBorrow(localsplus[i]) != NULL) {
1369
0
            kwonly_given++;
1370
0
        }
1371
0
    }
1372
0
    Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
1373
0
    if (defcount) {
1374
0
        Py_ssize_t atleast = co_argcount - defcount;
1375
0
        plural = 1;
1376
0
        sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
1377
0
    }
1378
0
    else {
1379
0
        plural = (co_argcount != 1);
1380
0
        sig = PyUnicode_FromFormat("%zd", co_argcount);
1381
0
    }
1382
0
    if (sig == NULL)
1383
0
        return;
1384
0
    if (kwonly_given) {
1385
0
        const char *format = " positional argument%s (and %zd keyword-only argument%s)";
1386
0
        kwonly_sig = PyUnicode_FromFormat(format,
1387
0
                                          given != 1 ? "s" : "",
1388
0
                                          kwonly_given,
1389
0
                                          kwonly_given != 1 ? "s" : "");
1390
0
        if (kwonly_sig == NULL) {
1391
0
            Py_DECREF(sig);
1392
0
            return;
1393
0
        }
1394
0
    }
1395
0
    else {
1396
        /* This will not fail. */
1397
0
        kwonly_sig = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
1398
0
        assert(kwonly_sig != NULL);
1399
0
    }
1400
0
    _PyErr_Format(tstate, PyExc_TypeError,
1401
0
                  "%U() takes %U positional argument%s but %zd%U %s given",
1402
0
                  qualname,
1403
0
                  sig,
1404
0
                  plural ? "s" : "",
1405
0
                  given,
1406
0
                  kwonly_sig,
1407
0
                  given == 1 && !kwonly_given ? "was" : "were");
1408
0
    Py_DECREF(sig);
1409
0
    Py_DECREF(kwonly_sig);
1410
0
}
1411
1412
static int
1413
positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
1414
                                  Py_ssize_t kwcount, PyObject* kwnames,
1415
                                  PyObject *qualname)
1416
0
{
1417
0
    int posonly_conflicts = 0;
1418
0
    PyObject* posonly_names = PyList_New(0);
1419
0
    if (posonly_names == NULL) {
1420
0
        goto fail;
1421
0
    }
1422
0
    for(int k=0; k < co->co_posonlyargcount; k++){
1423
0
        PyObject* posonly_name = PyTuple_GET_ITEM(co->co_localsplusnames, k);
1424
1425
0
        for (int k2=0; k2<kwcount; k2++){
1426
            /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
1427
0
            PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
1428
0
            if (kwname == posonly_name){
1429
0
                if(PyList_Append(posonly_names, kwname) != 0) {
1430
0
                    goto fail;
1431
0
                }
1432
0
                posonly_conflicts++;
1433
0
                continue;
1434
0
            }
1435
1436
0
            int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
1437
1438
0
            if ( cmp > 0) {
1439
0
                if(PyList_Append(posonly_names, kwname) != 0) {
1440
0
                    goto fail;
1441
0
                }
1442
0
                posonly_conflicts++;
1443
0
            } else if (cmp < 0) {
1444
0
                goto fail;
1445
0
            }
1446
1447
0
        }
1448
0
    }
1449
0
    if (posonly_conflicts) {
1450
0
        PyObject* comma = PyUnicode_FromString(", ");
1451
0
        if (comma == NULL) {
1452
0
            goto fail;
1453
0
        }
1454
0
        PyObject* error_names = PyUnicode_Join(comma, posonly_names);
1455
0
        Py_DECREF(comma);
1456
0
        if (error_names == NULL) {
1457
0
            goto fail;
1458
0
        }
1459
0
        _PyErr_Format(tstate, PyExc_TypeError,
1460
0
                      "%U() got some positional-only arguments passed"
1461
0
                      " as keyword arguments: '%U'",
1462
0
                      qualname, error_names);
1463
0
        Py_DECREF(error_names);
1464
0
        goto fail;
1465
0
    }
1466
1467
0
    Py_DECREF(posonly_names);
1468
0
    return 0;
1469
1470
0
fail:
1471
0
    Py_XDECREF(posonly_names);
1472
0
    return 1;
1473
1474
0
}
1475
1476
1477
static inline unsigned char *
1478
400k
scan_back_to_entry_start(unsigned char *p) {
1479
1.43M
    for (; (p[0]&128) == 0; p--);
1480
400k
    return p;
1481
400k
}
1482
1483
static inline unsigned char *
1484
4.92M
skip_to_next_entry(unsigned char *p, unsigned char *end) {
1485
19.6M
    while (p < end && ((p[0] & 128) == 0)) {
1486
14.7M
        p++;
1487
14.7M
    }
1488
4.92M
    return p;
1489
4.92M
}
1490
1491
1492
28.5M
#define MAX_LINEAR_SEARCH 40
1493
1494
static Py_NO_INLINE int
1495
get_exception_handler(PyCodeObject *code, int index, int *level, int *handler, int *lasti)
1496
28.1M
{
1497
28.1M
    unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code->co_exceptiontable);
1498
28.1M
    unsigned char *end = start + PyBytes_GET_SIZE(code->co_exceptiontable);
1499
    /* Invariants:
1500
     * start_table == end_table OR
1501
     * start_table points to a legal entry and end_table points
1502
     * beyond the table or to a legal entry that is after index.
1503
     */
1504
28.1M
    if (end - start > MAX_LINEAR_SEARCH) {
1505
258k
        int offset;
1506
258k
        parse_varint(start, &offset);
1507
258k
        if (offset > index) {
1508
59
            return 0;
1509
59
        }
1510
400k
        do {
1511
400k
            unsigned char * mid = start + ((end-start)>>1);
1512
400k
            mid = scan_back_to_entry_start(mid);
1513
400k
            parse_varint(mid, &offset);
1514
400k
            if (offset > index) {
1515
353k
                end = mid;
1516
353k
            }
1517
47.5k
            else {
1518
47.5k
                start = mid;
1519
47.5k
            }
1520
1521
400k
        } while (end - start > MAX_LINEAR_SEARCH);
1522
258k
    }
1523
28.1M
    unsigned char *scan = start;
1524
33.1M
    while (scan < end) {
1525
22.5M
        int start_offset, size;
1526
22.5M
        scan = parse_varint(scan, &start_offset);
1527
22.5M
        if (start_offset > index) {
1528
412k
            break;
1529
412k
        }
1530
22.1M
        scan = parse_varint(scan, &size);
1531
22.1M
        if (start_offset + size > index) {
1532
17.2M
            scan = parse_varint(scan, handler);
1533
17.2M
            int depth_and_lasti;
1534
17.2M
            parse_varint(scan, &depth_and_lasti);
1535
17.2M
            *level = depth_and_lasti >> 1;
1536
17.2M
            *lasti = depth_and_lasti & 1;
1537
17.2M
            return 1;
1538
17.2M
        }
1539
4.92M
        scan = skip_to_next_entry(scan, end);
1540
4.92M
    }
1541
10.9M
    return 0;
1542
28.1M
}
1543
1544
static int
1545
initialize_locals(PyThreadState *tstate, PyFunctionObject *func,
1546
    _PyStackRef *localsplus, _PyStackRef const *args,
1547
    Py_ssize_t argcount, PyObject *kwnames)
1548
142M
{
1549
142M
    PyCodeObject *co = (PyCodeObject*)func->func_code;
1550
142M
    const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
1551
    /* Create a dictionary for keyword parameters (**kwags) */
1552
142M
    PyObject *kwdict;
1553
142M
    Py_ssize_t i;
1554
142M
    if (co->co_flags & CO_VARKEYWORDS) {
1555
17.4M
        kwdict = PyDict_New();
1556
17.4M
        if (kwdict == NULL) {
1557
0
            goto fail_pre_positional;
1558
0
        }
1559
17.4M
        i = total_args;
1560
17.4M
        if (co->co_flags & CO_VARARGS) {
1561
17.4M
            i++;
1562
17.4M
        }
1563
17.4M
        assert(PyStackRef_IsNull(localsplus[i]));
1564
17.4M
        localsplus[i] = PyStackRef_FromPyObjectSteal(kwdict);
1565
17.4M
    }
1566
125M
    else {
1567
125M
        kwdict = NULL;
1568
125M
    }
1569
1570
    /* Copy all positional arguments into local variables */
1571
142M
    Py_ssize_t j, n;
1572
142M
    if (argcount > co->co_argcount) {
1573
7.62M
        n = co->co_argcount;
1574
7.62M
    }
1575
134M
    else {
1576
134M
        n = argcount;
1577
134M
    }
1578
383M
    for (j = 0; j < n; j++) {
1579
241M
        assert(PyStackRef_IsNull(localsplus[j]));
1580
241M
        localsplus[j] = args[j];
1581
241M
    }
1582
1583
    /* Pack other positional arguments into the *args argument */
1584
142M
    if (co->co_flags & CO_VARARGS) {
1585
18.9M
        PyObject *u = NULL;
1586
18.9M
        if (argcount == n) {
1587
11.2M
            u = (PyObject *)&_Py_SINGLETON(tuple_empty);
1588
11.2M
        }
1589
7.62M
        else {
1590
7.62M
            u = _PyTuple_FromStackRefStealOnSuccess(args + n, argcount - n);
1591
7.62M
            if (u == NULL) {
1592
0
                for (Py_ssize_t i = n; i < argcount; i++) {
1593
0
                    PyStackRef_CLOSE(args[i]);
1594
0
                }
1595
0
            }
1596
7.62M
        }
1597
18.9M
        if (u == NULL) {
1598
0
            goto fail_post_positional;
1599
0
        }
1600
18.9M
        assert(PyStackRef_AsPyObjectBorrow(localsplus[total_args]) == NULL);
1601
18.9M
        localsplus[total_args] = PyStackRef_FromPyObjectSteal(u);
1602
18.9M
    }
1603
123M
    else if (argcount > n) {
1604
        /* Too many positional args. Error is reported later */
1605
0
        for (j = n; j < argcount; j++) {
1606
0
            PyStackRef_CLOSE(args[j]);
1607
0
        }
1608
0
    }
1609
1610
    /* Handle keyword arguments */
1611
142M
    if (kwnames != NULL) {
1612
6.68M
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1613
14.5M
        for (i = 0; i < kwcount; i++) {
1614
7.89M
            PyObject **co_varnames;
1615
7.89M
            PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
1616
7.89M
            _PyStackRef value_stackref = args[i+argcount];
1617
7.89M
            Py_ssize_t j;
1618
1619
7.89M
            if (keyword == NULL || !PyUnicode_Check(keyword)) {
1620
0
                _PyErr_Format(tstate, PyExc_TypeError,
1621
0
                            "%U() keywords must be strings",
1622
0
                          func->func_qualname);
1623
0
                goto kw_fail;
1624
0
            }
1625
1626
            /* Speed hack: do raw pointer compares. As names are
1627
            normally interned this should almost always hit. */
1628
7.89M
            co_varnames = ((PyTupleObject *)(co->co_localsplusnames))->ob_item;
1629
16.7M
            for (j = co->co_posonlyargcount; j < total_args; j++) {
1630
15.3M
                PyObject *varname = co_varnames[j];
1631
15.3M
                if (varname == keyword) {
1632
6.47M
                    goto kw_found;
1633
6.47M
                }
1634
15.3M
            }
1635
1636
            /* Slow fallback, just in case */
1637
2.84M
            for (j = co->co_posonlyargcount; j < total_args; j++) {
1638
1.42M
                PyObject *varname = co_varnames[j];
1639
1.42M
                int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
1640
1.42M
                if (cmp > 0) {
1641
0
                    goto kw_found;
1642
0
                }
1643
1.42M
                else if (cmp < 0) {
1644
0
                    goto kw_fail;
1645
0
                }
1646
1.42M
            }
1647
1648
1.42M
            assert(j >= total_args);
1649
1.42M
            if (kwdict == NULL) {
1650
1651
0
                if (co->co_posonlyargcount
1652
0
                    && positional_only_passed_as_keyword(tstate, co,
1653
0
                                                        kwcount, kwnames,
1654
0
                                                        func->func_qualname))
1655
0
                {
1656
0
                    goto kw_fail;
1657
0
                }
1658
1659
0
                PyObject* suggestion_keyword = NULL;
1660
0
                if (total_args > co->co_posonlyargcount) {
1661
0
                    PyObject* possible_keywords = PyList_New(total_args - co->co_posonlyargcount);
1662
1663
0
                    if (!possible_keywords) {
1664
0
                        PyErr_Clear();
1665
0
                    } else {
1666
0
                        for (Py_ssize_t k = co->co_posonlyargcount; k < total_args; k++) {
1667
0
                            PyList_SET_ITEM(possible_keywords, k - co->co_posonlyargcount, co_varnames[k]);
1668
0
                        }
1669
1670
0
                        suggestion_keyword = _Py_CalculateSuggestions(possible_keywords, keyword);
1671
0
                        Py_DECREF(possible_keywords);
1672
0
                    }
1673
0
                }
1674
1675
0
                if (suggestion_keyword) {
1676
0
                    _PyErr_Format(tstate, PyExc_TypeError,
1677
0
                                "%U() got an unexpected keyword argument '%S'. Did you mean '%S'?",
1678
0
                                func->func_qualname, keyword, suggestion_keyword);
1679
0
                    Py_DECREF(suggestion_keyword);
1680
0
                } else {
1681
0
                    _PyErr_Format(tstate, PyExc_TypeError,
1682
0
                                "%U() got an unexpected keyword argument '%S'",
1683
0
                                func->func_qualname, keyword);
1684
0
                }
1685
1686
0
                goto kw_fail;
1687
0
            }
1688
1689
1.42M
            if (PyDict_SetItem(kwdict, keyword, PyStackRef_AsPyObjectBorrow(value_stackref)) == -1) {
1690
0
                goto kw_fail;
1691
0
            }
1692
1.42M
            PyStackRef_CLOSE(value_stackref);
1693
1.42M
            continue;
1694
1695
0
        kw_fail:
1696
0
            for (;i < kwcount; i++) {
1697
0
                PyStackRef_CLOSE(args[i+argcount]);
1698
0
            }
1699
0
            goto fail_post_args;
1700
1701
6.47M
        kw_found:
1702
6.47M
            if (PyStackRef_AsPyObjectBorrow(localsplus[j]) != NULL) {
1703
0
                _PyErr_Format(tstate, PyExc_TypeError,
1704
0
                            "%U() got multiple values for argument '%S'",
1705
0
                          func->func_qualname, keyword);
1706
0
                goto kw_fail;
1707
0
            }
1708
6.47M
            localsplus[j] = value_stackref;
1709
6.47M
        }
1710
6.68M
    }
1711
1712
    /* Check the number of positional arguments */
1713
142M
    if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
1714
0
        too_many_positional(tstate, co, argcount, func->func_defaults, localsplus,
1715
0
                            func->func_qualname);
1716
0
        goto fail_post_args;
1717
0
    }
1718
1719
    /* Add missing positional arguments (copy default values from defs) */
1720
142M
    if (argcount < co->co_argcount) {
1721
22.7M
        Py_ssize_t defcount = func->func_defaults == NULL ? 0 : PyTuple_GET_SIZE(func->func_defaults);
1722
22.7M
        Py_ssize_t m = co->co_argcount - defcount;
1723
22.7M
        Py_ssize_t missing = 0;
1724
22.7M
        for (i = argcount; i < m; i++) {
1725
1.86k
            if (PyStackRef_IsNull(localsplus[i])) {
1726
0
                missing++;
1727
0
            }
1728
1.86k
        }
1729
22.7M
        if (missing) {
1730
0
            missing_arguments(tstate, co, missing, defcount, localsplus,
1731
0
                              func->func_qualname);
1732
0
            goto fail_post_args;
1733
0
        }
1734
22.7M
        if (n > m)
1735
222k
            i = n - m;
1736
22.4M
        else
1737
22.4M
            i = 0;
1738
22.7M
        if (defcount) {
1739
22.7M
            PyObject **defs = &PyTuple_GET_ITEM(func->func_defaults, 0);
1740
46.3M
            for (; i < defcount; i++) {
1741
23.6M
                if (PyStackRef_AsPyObjectBorrow(localsplus[m+i]) == NULL) {
1742
17.7M
                    PyObject *def = defs[i];
1743
17.7M
                    localsplus[m+i] = PyStackRef_FromPyObjectNew(def);
1744
17.7M
                }
1745
23.6M
            }
1746
22.7M
        }
1747
22.7M
    }
1748
1749
    /* Add missing keyword arguments (copy default values from kwdefs) */
1750
142M
    if (co->co_kwonlyargcount > 0) {
1751
831k
        Py_ssize_t missing = 0;
1752
3.69M
        for (i = co->co_argcount; i < total_args; i++) {
1753
2.86M
            if (PyStackRef_AsPyObjectBorrow(localsplus[i]) != NULL)
1754
557k
                continue;
1755
2.31M
            PyObject *varname = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1756
2.31M
            if (func->func_kwdefaults != NULL) {
1757
2.31M
                PyObject *def;
1758
2.31M
                if (PyDict_GetItemRef(func->func_kwdefaults, varname, &def) < 0) {
1759
0
                    goto fail_post_args;
1760
0
                }
1761
2.31M
                if (def) {
1762
2.31M
                    localsplus[i] = PyStackRef_FromPyObjectSteal(def);
1763
2.31M
                    continue;
1764
2.31M
                }
1765
2.31M
            }
1766
0
            missing++;
1767
0
        }
1768
831k
        if (missing) {
1769
0
            missing_arguments(tstate, co, missing, -1, localsplus,
1770
0
                              func->func_qualname);
1771
0
            goto fail_post_args;
1772
0
        }
1773
831k
    }
1774
142M
    return 0;
1775
1776
0
fail_pre_positional:
1777
0
    for (j = 0; j < argcount; j++) {
1778
0
        PyStackRef_CLOSE(args[j]);
1779
0
    }
1780
    /* fall through */
1781
0
fail_post_positional:
1782
0
    if (kwnames) {
1783
0
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1784
0
        for (j = argcount; j < argcount+kwcount; j++) {
1785
0
            PyStackRef_CLOSE(args[j]);
1786
0
        }
1787
0
    }
1788
    /* fall through */
1789
0
fail_post_args:
1790
0
    return -1;
1791
0
}
1792
1793
static void
1794
clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1795
430M
{
1796
430M
    assert(frame->owner == FRAME_OWNED_BY_THREAD);
1797
    // Make sure that this is, indeed, the top frame. We can't check this in
1798
    // _PyThreadState_PopFrame, since f_code is already cleared at that point:
1799
430M
    assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize ==
1800
430M
        tstate->datastack_top);
1801
430M
    assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1802
430M
    _PyFrame_ClearExceptCode(frame);
1803
430M
    PyStackRef_CLEAR(frame->f_executable);
1804
430M
    _PyThreadState_PopFrame(tstate, frame);
1805
430M
}
1806
1807
static void
1808
clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1809
18.4M
{
1810
18.4M
    assert(frame->owner == FRAME_OWNED_BY_GENERATOR);
1811
18.4M
    PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame);
1812
18.4M
    gen->gi_frame_state = FRAME_CLEARED;
1813
18.4M
    assert(tstate->exc_info == &gen->gi_exc_state);
1814
18.4M
    tstate->exc_info = gen->gi_exc_state.previous_item;
1815
18.4M
    gen->gi_exc_state.previous_item = NULL;
1816
18.4M
    assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1817
18.4M
    _PyFrame_ClearExceptCode(frame);
1818
18.4M
    _PyErr_ClearExcState(&gen->gi_exc_state);
1819
18.4M
    frame->previous = NULL;
1820
18.4M
}
1821
1822
void
1823
_PyEval_FrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame)
1824
448M
{
1825
448M
    if (frame->owner == FRAME_OWNED_BY_THREAD) {
1826
430M
        clear_thread_frame(tstate, frame);
1827
430M
    }
1828
18.4M
    else {
1829
18.4M
        clear_gen_frame(tstate, frame);
1830
18.4M
    }
1831
448M
}
1832
1833
/* Consumes references to func, locals and all the args */
1834
_PyInterpreterFrame *
1835
_PyEvalFramePushAndInit(PyThreadState *tstate, _PyStackRef func,
1836
                        PyObject *locals, _PyStackRef const* args,
1837
                        size_t argcount, PyObject *kwnames, _PyInterpreterFrame *previous)
1838
142M
{
1839
142M
    PyFunctionObject *func_obj = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(func);
1840
142M
    PyCodeObject * code = (PyCodeObject *)func_obj->func_code;
1841
142M
    CALL_STAT_INC(frames_pushed);
1842
142M
    _PyInterpreterFrame *frame = _PyThreadState_PushFrame(tstate, code->co_framesize);
1843
142M
    if (frame == NULL) {
1844
0
        goto fail;
1845
0
    }
1846
142M
    _PyFrame_Initialize(tstate, frame, func, locals, code, 0, previous);
1847
142M
    if (initialize_locals(tstate, func_obj, frame->localsplus, args, argcount, kwnames)) {
1848
0
        assert(frame->owner == FRAME_OWNED_BY_THREAD);
1849
0
        clear_thread_frame(tstate, frame);
1850
0
        return NULL;
1851
0
    }
1852
142M
    return frame;
1853
0
fail:
1854
    /* Consume the references */
1855
0
    PyStackRef_CLOSE(func);
1856
0
    Py_XDECREF(locals);
1857
0
    for (size_t i = 0; i < argcount; i++) {
1858
0
        PyStackRef_CLOSE(args[i]);
1859
0
    }
1860
0
    if (kwnames) {
1861
0
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1862
0
        for (Py_ssize_t i = 0; i < kwcount; i++) {
1863
0
            PyStackRef_CLOSE(args[i+argcount]);
1864
0
        }
1865
0
    }
1866
0
    PyErr_NoMemory();
1867
0
    return NULL;
1868
142M
}
1869
1870
/* Same as _PyEvalFramePushAndInit but takes an args tuple and kwargs dict.
1871
   Steals references to func, callargs and kwargs.
1872
*/
1873
static _PyInterpreterFrame *
1874
_PyEvalFramePushAndInit_Ex(PyThreadState *tstate, _PyStackRef func,
1875
    PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs, _PyInterpreterFrame *previous)
1876
83.3k
{
1877
83.3k
    bool has_dict = (kwargs != NULL && PyDict_GET_SIZE(kwargs) > 0);
1878
83.3k
    PyObject *kwnames = NULL;
1879
83.3k
    _PyStackRef *newargs;
1880
83.3k
    PyObject *const *object_array = NULL;
1881
83.3k
    _PyStackRef stack_array[8];
1882
83.3k
    if (has_dict) {
1883
3.13k
        object_array = _PyStack_UnpackDict(tstate, _PyTuple_ITEMS(callargs), nargs, kwargs, &kwnames);
1884
3.13k
        if (object_array == NULL) {
1885
0
            PyStackRef_CLOSE(func);
1886
0
            goto error;
1887
0
        }
1888
3.13k
        size_t total_args = nargs + PyDict_GET_SIZE(kwargs);
1889
3.13k
        assert(sizeof(PyObject *) == sizeof(_PyStackRef));
1890
3.13k
        newargs = (_PyStackRef *)object_array;
1891
9.40k
        for (size_t i = 0; i < total_args; i++) {
1892
6.26k
            newargs[i] = PyStackRef_FromPyObjectSteal(object_array[i]);
1893
6.26k
        }
1894
3.13k
    }
1895
80.2k
    else {
1896
80.2k
        if (nargs <= 8) {
1897
80.2k
            newargs = stack_array;
1898
80.2k
        }
1899
11
        else {
1900
11
            newargs = PyMem_Malloc(sizeof(_PyStackRef) *nargs);
1901
11
            if (newargs == NULL) {
1902
0
                PyErr_NoMemory();
1903
0
                PyStackRef_CLOSE(func);
1904
0
                goto error;
1905
0
            }
1906
11
        }
1907
        /* We need to create a new reference for all our args since the new frame steals them. */
1908
248k
        for (Py_ssize_t i = 0; i < nargs; i++) {
1909
168k
            newargs[i] = PyStackRef_FromPyObjectNew(PyTuple_GET_ITEM(callargs, i));
1910
168k
        }
1911
80.2k
    }
1912
83.3k
    _PyInterpreterFrame *new_frame = _PyEvalFramePushAndInit(
1913
83.3k
        tstate, func, locals,
1914
83.3k
        newargs, nargs, kwnames, previous
1915
83.3k
    );
1916
83.3k
    if (has_dict) {
1917
3.13k
        _PyStack_UnpackDict_FreeNoDecRef(object_array, kwnames);
1918
3.13k
    }
1919
80.2k
    else if (nargs > 8) {
1920
11
       PyMem_Free((void *)newargs);
1921
11
    }
1922
    /* No need to decref func here because the reference has been stolen by
1923
       _PyEvalFramePushAndInit.
1924
    */
1925
83.3k
    Py_DECREF(callargs);
1926
83.3k
    Py_XDECREF(kwargs);
1927
0
    return new_frame;
1928
0
error:
1929
0
    Py_DECREF(callargs);
1930
0
    Py_XDECREF(kwargs);
1931
0
    return NULL;
1932
83.3k
}
1933
1934
PyObject *
1935
_PyEval_Vector(PyThreadState *tstate, PyFunctionObject *func,
1936
               PyObject *locals,
1937
               PyObject* const* args, size_t argcount,
1938
               PyObject *kwnames)
1939
124M
{
1940
124M
    size_t total_args = argcount;
1941
124M
    if (kwnames) {
1942
6.15M
        total_args += PyTuple_GET_SIZE(kwnames);
1943
6.15M
    }
1944
124M
    _PyStackRef stack_array[8];
1945
124M
    _PyStackRef *arguments;
1946
124M
    if (total_args <= 8) {
1947
124M
        arguments = stack_array;
1948
124M
    }
1949
963
    else {
1950
963
        arguments = PyMem_Malloc(sizeof(_PyStackRef) * total_args);
1951
963
        if (arguments == NULL) {
1952
0
            return PyErr_NoMemory();
1953
0
        }
1954
963
    }
1955
    /* _PyEvalFramePushAndInit consumes the references
1956
     * to func, locals and all its arguments */
1957
124M
    Py_XINCREF(locals);
1958
334M
    for (size_t i = 0; i < argcount; i++) {
1959
209M
        arguments[i] = PyStackRef_FromPyObjectNew(args[i]);
1960
209M
    }
1961
124M
    if (kwnames) {
1962
6.15M
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1963
13.5M
        for (Py_ssize_t i = 0; i < kwcount; i++) {
1964
7.34M
            arguments[i+argcount] = PyStackRef_FromPyObjectNew(args[i+argcount]);
1965
7.34M
        }
1966
6.15M
    }
1967
124M
    _PyInterpreterFrame *frame = _PyEvalFramePushAndInit(
1968
124M
        tstate, PyStackRef_FromPyObjectNew(func), locals,
1969
124M
        arguments, argcount, kwnames, NULL);
1970
124M
    if (total_args > 8) {
1971
963
        PyMem_Free(arguments);
1972
963
    }
1973
124M
    if (frame == NULL) {
1974
0
        return NULL;
1975
0
    }
1976
124M
    EVAL_CALL_STAT_INC(EVAL_CALL_VECTOR);
1977
124M
    return _PyEval_EvalFrame(tstate, frame, 0);
1978
124M
}
1979
1980
/* Legacy API */
1981
PyObject *
1982
PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
1983
                  PyObject *const *args, int argcount,
1984
                  PyObject *const *kws, int kwcount,
1985
                  PyObject *const *defs, int defcount,
1986
                  PyObject *kwdefs, PyObject *closure)
1987
0
{
1988
0
    PyThreadState *tstate = _PyThreadState_GET();
1989
0
    PyObject *res = NULL;
1990
0
    PyObject *defaults = _PyTuple_FromArray(defs, defcount);
1991
0
    if (defaults == NULL) {
1992
0
        return NULL;
1993
0
    }
1994
0
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
1995
0
    if (builtins == NULL) {
1996
0
        Py_DECREF(defaults);
1997
0
        return NULL;
1998
0
    }
1999
0
    if (locals == NULL) {
2000
0
        locals = globals;
2001
0
    }
2002
0
    PyObject *kwnames = NULL;
2003
0
    PyObject *const *allargs;
2004
0
    PyObject **newargs = NULL;
2005
0
    PyFunctionObject *func = NULL;
2006
0
    if (kwcount == 0) {
2007
0
        allargs = args;
2008
0
    }
2009
0
    else {
2010
0
        kwnames = PyTuple_New(kwcount);
2011
0
        if (kwnames == NULL) {
2012
0
            goto fail;
2013
0
        }
2014
0
        newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
2015
0
        if (newargs == NULL) {
2016
0
            goto fail;
2017
0
        }
2018
0
        for (int i = 0; i < argcount; i++) {
2019
0
            newargs[i] = args[i];
2020
0
        }
2021
0
        for (int i = 0; i < kwcount; i++) {
2022
0
            PyTuple_SET_ITEM(kwnames, i, Py_NewRef(kws[2*i]));
2023
0
            newargs[argcount+i] = kws[2*i+1];
2024
0
        }
2025
0
        allargs = newargs;
2026
0
    }
2027
0
    PyFrameConstructor constr = {
2028
0
        .fc_globals = globals,
2029
0
        .fc_builtins = builtins,
2030
0
        .fc_name = ((PyCodeObject *)_co)->co_name,
2031
0
        .fc_qualname = ((PyCodeObject *)_co)->co_name,
2032
0
        .fc_code = _co,
2033
0
        .fc_defaults = defaults,
2034
0
        .fc_kwdefaults = kwdefs,
2035
0
        .fc_closure = closure
2036
0
    };
2037
0
    func = _PyFunction_FromConstructor(&constr);
2038
0
    if (func == NULL) {
2039
0
        goto fail;
2040
0
    }
2041
0
    EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
2042
0
    res = _PyEval_Vector(tstate, func, locals,
2043
0
                         allargs, argcount,
2044
0
                         kwnames);
2045
0
fail:
2046
0
    Py_XDECREF(func);
2047
0
    Py_XDECREF(kwnames);
2048
0
    PyMem_Free(newargs);
2049
0
    _Py_DECREF_BUILTINS(builtins);
2050
0
    Py_DECREF(defaults);
2051
0
    return res;
2052
0
}
2053
2054
2055
/* Logic for the raise statement (too complicated for inlining).
2056
   This *consumes* a reference count to each of its arguments. */
2057
static int
2058
do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
2059
10.2M
{
2060
10.2M
    PyObject *type = NULL, *value = NULL;
2061
2062
10.2M
    if (exc == NULL) {
2063
        /* Reraise */
2064
10
        _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
2065
10
        exc = exc_info->exc_value;
2066
10
        if (Py_IsNone(exc) || exc == NULL) {
2067
0
            _PyErr_SetString(tstate, PyExc_RuntimeError,
2068
0
                             "No active exception to reraise");
2069
0
            return 0;
2070
0
        }
2071
10
        Py_INCREF(exc);
2072
10
        assert(PyExceptionInstance_Check(exc));
2073
10
        _PyErr_SetRaisedException(tstate, exc);
2074
10
        return 1;
2075
10
    }
2076
2077
    /* We support the following forms of raise:
2078
       raise
2079
       raise <instance>
2080
       raise <type> */
2081
2082
10.2M
    if (PyExceptionClass_Check(exc)) {
2083
9.66M
        type = exc;
2084
9.66M
        value = _PyObject_CallNoArgs(exc);
2085
9.66M
        if (value == NULL)
2086
0
            goto raise_error;
2087
9.66M
        if (!PyExceptionInstance_Check(value)) {
2088
0
            _PyErr_Format(tstate, PyExc_TypeError,
2089
0
                          "calling %R should have returned an instance of "
2090
0
                          "BaseException, not %R",
2091
0
                          type, Py_TYPE(value));
2092
0
             goto raise_error;
2093
0
        }
2094
9.66M
    }
2095
541k
    else if (PyExceptionInstance_Check(exc)) {
2096
541k
        value = exc;
2097
541k
        type = PyExceptionInstance_Class(exc);
2098
541k
        Py_INCREF(type);
2099
541k
    }
2100
0
    else {
2101
        /* Not something you can raise.  You get an exception
2102
           anyway, just not what you specified :-) */
2103
0
        Py_DECREF(exc);
2104
0
        _PyErr_SetString(tstate, PyExc_TypeError,
2105
0
                         "exceptions must derive from BaseException");
2106
0
        goto raise_error;
2107
0
    }
2108
2109
10.2M
    assert(type != NULL);
2110
10.2M
    assert(value != NULL);
2111
2112
10.2M
    if (cause) {
2113
2.53k
        PyObject *fixed_cause;
2114
2.53k
        if (PyExceptionClass_Check(cause)) {
2115
0
            fixed_cause = _PyObject_CallNoArgs(cause);
2116
0
            if (fixed_cause == NULL)
2117
0
                goto raise_error;
2118
0
            if (!PyExceptionInstance_Check(fixed_cause)) {
2119
0
                _PyErr_Format(tstate, PyExc_TypeError,
2120
0
                              "calling %R should have returned an instance of "
2121
0
                              "BaseException, not %R",
2122
0
                              cause, Py_TYPE(fixed_cause));
2123
0
                goto raise_error;
2124
0
            }
2125
0
            Py_DECREF(cause);
2126
0
        }
2127
2.53k
        else if (PyExceptionInstance_Check(cause)) {
2128
0
            fixed_cause = cause;
2129
0
        }
2130
2.53k
        else if (Py_IsNone(cause)) {
2131
2.53k
            Py_DECREF(cause);
2132
0
            fixed_cause = NULL;
2133
2.53k
        }
2134
0
        else {
2135
0
            _PyErr_SetString(tstate, PyExc_TypeError,
2136
0
                             "exception causes must derive from "
2137
0
                             "BaseException");
2138
0
            goto raise_error;
2139
0
        }
2140
2.53k
        PyException_SetCause(value, fixed_cause);
2141
2.53k
    }
2142
2143
10.2M
    _PyErr_SetObject(tstate, type, value);
2144
    /* _PyErr_SetObject incref's its arguments */
2145
10.2M
    Py_DECREF(value);
2146
10.2M
    Py_DECREF(type);
2147
0
    return 0;
2148
2149
0
raise_error:
2150
0
    Py_XDECREF(value);
2151
0
    Py_XDECREF(type);
2152
0
    Py_XDECREF(cause);
2153
0
    return 0;
2154
10.2M
}
2155
2156
/* Logic for matching an exception in an except* clause (too
2157
   complicated for inlining).
2158
*/
2159
2160
int
2161
_PyEval_ExceptionGroupMatch(_PyInterpreterFrame *frame, PyObject* exc_value,
2162
                            PyObject *match_type, PyObject **match, PyObject **rest)
2163
0
{
2164
0
    if (Py_IsNone(exc_value)) {
2165
0
        *match = Py_NewRef(Py_None);
2166
0
        *rest = Py_NewRef(Py_None);
2167
0
        return 0;
2168
0
    }
2169
0
    assert(PyExceptionInstance_Check(exc_value));
2170
2171
0
    if (PyErr_GivenExceptionMatches(exc_value, match_type)) {
2172
        /* Full match of exc itself */
2173
0
        bool is_eg = _PyBaseExceptionGroup_Check(exc_value);
2174
0
        if (is_eg) {
2175
0
            *match = Py_NewRef(exc_value);
2176
0
        }
2177
0
        else {
2178
            /* naked exception - wrap it */
2179
0
            PyObject *excs = PyTuple_Pack(1, exc_value);
2180
0
            if (excs == NULL) {
2181
0
                return -1;
2182
0
            }
2183
0
            PyObject *wrapped = _PyExc_CreateExceptionGroup("", excs);
2184
0
            Py_DECREF(excs);
2185
0
            if (wrapped == NULL) {
2186
0
                return -1;
2187
0
            }
2188
0
            PyFrameObject *f = _PyFrame_GetFrameObject(frame);
2189
0
            if (f != NULL) {
2190
0
                PyObject *tb = _PyTraceBack_FromFrame(NULL, f);
2191
0
                if (tb == NULL) {
2192
0
                    return -1;
2193
0
                }
2194
0
                PyException_SetTraceback(wrapped, tb);
2195
0
                Py_DECREF(tb);
2196
0
            }
2197
0
            *match = wrapped;
2198
0
        }
2199
0
        *rest = Py_NewRef(Py_None);
2200
0
        return 0;
2201
0
    }
2202
2203
    /* exc_value does not match match_type.
2204
     * Check for partial match if it's an exception group.
2205
     */
2206
0
    if (_PyBaseExceptionGroup_Check(exc_value)) {
2207
0
        PyObject *pair = PyObject_CallMethod(exc_value, "split", "(O)",
2208
0
                                             match_type);
2209
0
        if (pair == NULL) {
2210
0
            return -1;
2211
0
        }
2212
2213
0
        if (!PyTuple_CheckExact(pair)) {
2214
0
            PyErr_Format(PyExc_TypeError,
2215
0
                         "%.200s.split must return a tuple, not %.200s",
2216
0
                         Py_TYPE(exc_value)->tp_name, Py_TYPE(pair)->tp_name);
2217
0
            Py_DECREF(pair);
2218
0
            return -1;
2219
0
        }
2220
2221
        // allow tuples of length > 2 for backwards compatibility
2222
0
        if (PyTuple_GET_SIZE(pair) < 2) {
2223
0
            PyErr_Format(PyExc_TypeError,
2224
0
                         "%.200s.split must return a 2-tuple, "
2225
0
                         "got tuple of size %zd",
2226
0
                         Py_TYPE(exc_value)->tp_name, PyTuple_GET_SIZE(pair));
2227
0
            Py_DECREF(pair);
2228
0
            return -1;
2229
0
        }
2230
2231
0
        *match = Py_NewRef(PyTuple_GET_ITEM(pair, 0));
2232
0
        *rest = Py_NewRef(PyTuple_GET_ITEM(pair, 1));
2233
0
        Py_DECREF(pair);
2234
0
        return 0;
2235
0
    }
2236
    /* no match */
2237
0
    *match = Py_NewRef(Py_None);
2238
0
    *rest = Py_NewRef(exc_value);
2239
0
    return 0;
2240
0
}
2241
2242
/* Iterate v argcnt times and store the results on the stack (via decreasing
2243
   sp).  Return 1 for success, 0 if error.
2244
2245
   If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
2246
   with a variable target.
2247
*/
2248
2249
int
2250
_PyEval_UnpackIterableStackRef(PyThreadState *tstate, PyObject *v,
2251
                       int argcnt, int argcntafter, _PyStackRef *sp)
2252
11.5M
{
2253
11.5M
    int i = 0, j = 0;
2254
11.5M
    Py_ssize_t ll = 0;
2255
11.5M
    PyObject *it;  /* iter(v) */
2256
11.5M
    PyObject *w;
2257
11.5M
    PyObject *l = NULL; /* variable list */
2258
11.5M
    assert(v != NULL);
2259
2260
11.5M
    it = PyObject_GetIter(v);
2261
11.5M
    if (it == NULL) {
2262
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
2263
0
            Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
2264
0
        {
2265
0
            _PyErr_Format(tstate, PyExc_TypeError,
2266
0
                          "cannot unpack non-iterable %.200s object",
2267
0
                          Py_TYPE(v)->tp_name);
2268
0
        }
2269
0
        return 0;
2270
0
    }
2271
2272
28.0M
    for (; i < argcnt; i++) {
2273
24.1M
        w = PyIter_Next(it);
2274
24.1M
        if (w == NULL) {
2275
            /* Iterator done, via error or exhaustion. */
2276
7.63M
            if (!_PyErr_Occurred(tstate)) {
2277
7.63M
                if (argcntafter == -1) {
2278
7.63M
                    _PyErr_Format(tstate, PyExc_ValueError,
2279
7.63M
                                  "not enough values to unpack "
2280
7.63M
                                  "(expected %d, got %d)",
2281
7.63M
                                  argcnt, i);
2282
7.63M
                }
2283
0
                else {
2284
0
                    _PyErr_Format(tstate, PyExc_ValueError,
2285
0
                                  "not enough values to unpack "
2286
0
                                  "(expected at least %d, got %d)",
2287
0
                                  argcnt + argcntafter, i);
2288
0
                }
2289
7.63M
            }
2290
7.63M
            goto Error;
2291
7.63M
        }
2292
16.4M
        *--sp = PyStackRef_FromPyObjectSteal(w);
2293
16.4M
    }
2294
2295
3.93M
    if (argcntafter == -1) {
2296
        /* We better have exhausted the iterator now. */
2297
2.48M
        w = PyIter_Next(it);
2298
2.48M
        if (w == NULL) {
2299
2.44M
            if (_PyErr_Occurred(tstate))
2300
0
                goto Error;
2301
2.44M
            Py_DECREF(it);
2302
0
            return 1;
2303
2.44M
        }
2304
39.5k
        Py_DECREF(w);
2305
2306
39.5k
        if (PyList_CheckExact(v) || PyTuple_CheckExact(v)
2307
39.5k
              || PyDict_CheckExact(v)) {
2308
39.5k
            ll = PyDict_CheckExact(v) ? PyDict_Size(v) : Py_SIZE(v);
2309
39.5k
            if (ll > argcnt) {
2310
39.5k
                _PyErr_Format(tstate, PyExc_ValueError,
2311
39.5k
                              "too many values to unpack (expected %d, got %zd)",
2312
39.5k
                              argcnt, ll);
2313
39.5k
                goto Error;
2314
39.5k
            }
2315
39.5k
        }
2316
0
        _PyErr_Format(tstate, PyExc_ValueError,
2317
0
                      "too many values to unpack (expected %d)",
2318
0
                      argcnt);
2319
0
        goto Error;
2320
39.5k
    }
2321
2322
1.44M
    l = PySequence_List(it);
2323
1.44M
    if (l == NULL)
2324
0
        goto Error;
2325
1.44M
    *--sp = PyStackRef_FromPyObjectSteal(l);
2326
1.44M
    i++;
2327
2328
1.44M
    ll = PyList_GET_SIZE(l);
2329
1.44M
    if (ll < argcntafter) {
2330
0
        _PyErr_Format(tstate, PyExc_ValueError,
2331
0
            "not enough values to unpack (expected at least %d, got %zd)",
2332
0
            argcnt + argcntafter, argcnt + ll);
2333
0
        goto Error;
2334
0
    }
2335
2336
    /* Pop the "after-variable" args off the list. */
2337
1.44M
    for (j = argcntafter; j > 0; j--, i++) {
2338
0
        *--sp = PyStackRef_FromPyObjectSteal(PyList_GET_ITEM(l, ll - j));
2339
0
    }
2340
    /* Resize the list. */
2341
1.44M
    Py_SET_SIZE(l, ll - argcntafter);
2342
1.44M
    Py_DECREF(it);
2343
0
    return 1;
2344
2345
7.67M
Error:
2346
15.5M
    for (; i > 0; i--, sp++) {
2347
7.90M
        PyStackRef_CLOSE(*sp);
2348
7.90M
    }
2349
7.67M
    Py_XDECREF(it);
2350
0
    return 0;
2351
1.44M
}
2352
2353
static int
2354
do_monitor_exc(PyThreadState *tstate, _PyInterpreterFrame *frame,
2355
               _Py_CODEUNIT *instr, int event)
2356
0
{
2357
0
    assert(event < _PY_MONITORING_UNGROUPED_EVENTS);
2358
0
    if (_PyFrame_GetCode(frame)->co_flags & CO_NO_MONITORING_EVENTS) {
2359
0
        return 0;
2360
0
    }
2361
0
    PyObject *exc = PyErr_GetRaisedException();
2362
0
    assert(exc != NULL);
2363
0
    int err = _Py_call_instrumentation_arg(tstate, event, frame, instr, exc);
2364
0
    if (err == 0) {
2365
0
        PyErr_SetRaisedException(exc);
2366
0
    }
2367
0
    else {
2368
0
        assert(PyErr_Occurred());
2369
0
        Py_DECREF(exc);
2370
0
    }
2371
0
    return err;
2372
0
}
2373
2374
static inline bool
2375
no_tools_for_global_event(PyThreadState *tstate, int event)
2376
66.0M
{
2377
66.0M
    return tstate->interp->monitors.tools[event] == 0;
2378
66.0M
}
2379
2380
static inline bool
2381
no_tools_for_local_event(PyThreadState *tstate, _PyInterpreterFrame *frame, int event)
2382
0
{
2383
0
    assert(event < _PY_MONITORING_LOCAL_EVENTS);
2384
0
    _PyCoMonitoringData *data = _PyFrame_GetCode(frame)->_co_monitoring;
2385
0
    if (data) {
2386
0
        return data->active_monitors.tools[event] == 0;
2387
0
    }
2388
0
    else {
2389
0
        return no_tools_for_global_event(tstate, event);
2390
0
    }
2391
0
}
2392
2393
void
2394
_PyEval_MonitorRaise(PyThreadState *tstate, _PyInterpreterFrame *frame,
2395
              _Py_CODEUNIT *instr)
2396
37.5M
{
2397
37.5M
    if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_RAISE)) {
2398
37.5M
        return;
2399
37.5M
    }
2400
0
    do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RAISE);
2401
0
}
2402
2403
static void
2404
monitor_reraise(PyThreadState *tstate, _PyInterpreterFrame *frame,
2405
              _Py_CODEUNIT *instr)
2406
336k
{
2407
336k
    if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_RERAISE)) {
2408
336k
        return;
2409
336k
    }
2410
0
    do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RERAISE);
2411
0
}
2412
2413
static int
2414
monitor_stop_iteration(PyThreadState *tstate, _PyInterpreterFrame *frame,
2415
                       _Py_CODEUNIT *instr, PyObject *value)
2416
0
{
2417
0
    if (no_tools_for_local_event(tstate, frame, PY_MONITORING_EVENT_STOP_ITERATION)) {
2418
0
        return 0;
2419
0
    }
2420
0
    assert(!PyErr_Occurred());
2421
0
    PyErr_SetObject(PyExc_StopIteration, value);
2422
0
    int res = do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_STOP_ITERATION);
2423
0
    if (res < 0) {
2424
0
        return res;
2425
0
    }
2426
0
    PyErr_SetRaisedException(NULL);
2427
0
    return 0;
2428
0
}
2429
2430
static void
2431
monitor_unwind(PyThreadState *tstate,
2432
               _PyInterpreterFrame *frame,
2433
               _Py_CODEUNIT *instr)
2434
10.9M
{
2435
10.9M
    if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_UNWIND)) {
2436
10.9M
        return;
2437
10.9M
    }
2438
0
    do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_PY_UNWIND);
2439
0
}
2440
2441
2442
static int
2443
monitor_handled(PyThreadState *tstate,
2444
                _PyInterpreterFrame *frame,
2445
                _Py_CODEUNIT *instr, PyObject *exc)
2446
17.2M
{
2447
17.2M
    if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_EXCEPTION_HANDLED)) {
2448
17.2M
        return 0;
2449
17.2M
    }
2450
0
    return _Py_call_instrumentation_arg(tstate, PY_MONITORING_EVENT_EXCEPTION_HANDLED, frame, instr, exc);
2451
17.2M
}
2452
2453
static void
2454
monitor_throw(PyThreadState *tstate,
2455
              _PyInterpreterFrame *frame,
2456
              _Py_CODEUNIT *instr)
2457
2.50k
{
2458
2.50k
    if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_THROW)) {
2459
2.50k
        return;
2460
2.50k
    }
2461
0
    do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_PY_THROW);
2462
0
}
2463
2464
void
2465
PyThreadState_EnterTracing(PyThreadState *tstate)
2466
0
{
2467
0
    assert(tstate->tracing >= 0);
2468
0
    tstate->tracing++;
2469
0
}
2470
2471
void
2472
PyThreadState_LeaveTracing(PyThreadState *tstate)
2473
0
{
2474
0
    assert(tstate->tracing > 0);
2475
0
    tstate->tracing--;
2476
0
}
2477
2478
2479
PyObject*
2480
_PyEval_CallTracing(PyObject *func, PyObject *args)
2481
0
{
2482
    // Save and disable tracing
2483
0
    PyThreadState *tstate = _PyThreadState_GET();
2484
0
    int save_tracing = tstate->tracing;
2485
0
    tstate->tracing = 0;
2486
2487
    // Call the tracing function
2488
0
    PyObject *result = PyObject_Call(func, args, NULL);
2489
2490
    // Restore tracing
2491
0
    tstate->tracing = save_tracing;
2492
0
    return result;
2493
0
}
2494
2495
void
2496
PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
2497
0
{
2498
0
    PyThreadState *tstate = _PyThreadState_GET();
2499
0
    if (_PyEval_SetProfile(tstate, func, arg) < 0) {
2500
        /* Log _PySys_Audit() error */
2501
0
        PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfile");
2502
0
    }
2503
0
}
2504
2505
void
2506
PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *arg)
2507
0
{
2508
0
    PyThreadState *this_tstate = _PyThreadState_GET();
2509
0
    PyInterpreterState* interp = this_tstate->interp;
2510
2511
0
    _PyRuntimeState *runtime = &_PyRuntime;
2512
0
    HEAD_LOCK(runtime);
2513
0
    PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
2514
0
    HEAD_UNLOCK(runtime);
2515
2516
0
    while (ts) {
2517
0
        if (_PyEval_SetProfile(ts, func, arg) < 0) {
2518
0
            PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfileAllThreads");
2519
0
        }
2520
0
        HEAD_LOCK(runtime);
2521
0
        ts = PyThreadState_Next(ts);
2522
0
        HEAD_UNLOCK(runtime);
2523
0
    }
2524
0
}
2525
2526
void
2527
PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
2528
0
{
2529
0
    PyThreadState *tstate = _PyThreadState_GET();
2530
0
    if (_PyEval_SetTrace(tstate, func, arg) < 0) {
2531
        /* Log _PySys_Audit() error */
2532
0
        PyErr_FormatUnraisable("Exception ignored in PyEval_SetTrace");
2533
0
    }
2534
0
}
2535
2536
void
2537
PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *arg)
2538
0
{
2539
0
    PyThreadState *this_tstate = _PyThreadState_GET();
2540
0
    PyInterpreterState* interp = this_tstate->interp;
2541
2542
0
    _PyRuntimeState *runtime = &_PyRuntime;
2543
0
    HEAD_LOCK(runtime);
2544
0
    PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
2545
0
    HEAD_UNLOCK(runtime);
2546
2547
0
    while (ts) {
2548
0
        if (_PyEval_SetTrace(ts, func, arg) < 0) {
2549
0
            PyErr_FormatUnraisable("Exception ignored in PyEval_SetTraceAllThreads");
2550
0
        }
2551
0
        HEAD_LOCK(runtime);
2552
0
        ts = PyThreadState_Next(ts);
2553
0
        HEAD_UNLOCK(runtime);
2554
0
    }
2555
0
}
2556
2557
int
2558
_PyEval_SetCoroutineOriginTrackingDepth(int depth)
2559
0
{
2560
0
    PyThreadState *tstate = _PyThreadState_GET();
2561
0
    if (depth < 0) {
2562
0
        _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
2563
0
        return -1;
2564
0
    }
2565
0
    tstate->coroutine_origin_tracking_depth = depth;
2566
0
    return 0;
2567
0
}
2568
2569
2570
int
2571
_PyEval_GetCoroutineOriginTrackingDepth(void)
2572
0
{
2573
0
    PyThreadState *tstate = _PyThreadState_GET();
2574
0
    return tstate->coroutine_origin_tracking_depth;
2575
0
}
2576
2577
int
2578
_PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
2579
0
{
2580
0
    PyThreadState *tstate = _PyThreadState_GET();
2581
2582
0
    if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
2583
0
        return -1;
2584
0
    }
2585
2586
0
    Py_XSETREF(tstate->async_gen_firstiter, Py_XNewRef(firstiter));
2587
0
    return 0;
2588
0
}
2589
2590
PyObject *
2591
_PyEval_GetAsyncGenFirstiter(void)
2592
0
{
2593
0
    PyThreadState *tstate = _PyThreadState_GET();
2594
0
    return tstate->async_gen_firstiter;
2595
0
}
2596
2597
int
2598
_PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
2599
0
{
2600
0
    PyThreadState *tstate = _PyThreadState_GET();
2601
2602
0
    if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
2603
0
        return -1;
2604
0
    }
2605
2606
0
    Py_XSETREF(tstate->async_gen_finalizer, Py_XNewRef(finalizer));
2607
0
    return 0;
2608
0
}
2609
2610
PyObject *
2611
_PyEval_GetAsyncGenFinalizer(void)
2612
0
{
2613
0
    PyThreadState *tstate = _PyThreadState_GET();
2614
0
    return tstate->async_gen_finalizer;
2615
0
}
2616
2617
_PyInterpreterFrame *
2618
_PyEval_GetFrame(void)
2619
287
{
2620
287
    PyThreadState *tstate = _PyThreadState_GET();
2621
287
    return _PyThreadState_GetFrame(tstate);
2622
287
}
2623
2624
PyFrameObject *
2625
PyEval_GetFrame(void)
2626
0
{
2627
0
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
2628
0
    if (frame == NULL) {
2629
0
        return NULL;
2630
0
    }
2631
0
    PyFrameObject *f = _PyFrame_GetFrameObject(frame);
2632
0
    if (f == NULL) {
2633
0
        PyErr_Clear();
2634
0
    }
2635
0
    return f;
2636
0
}
2637
2638
PyObject *
2639
_PyEval_GetBuiltins(PyThreadState *tstate)
2640
945
{
2641
945
    _PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
2642
945
    if (frame != NULL) {
2643
913
        return frame->f_builtins;
2644
913
    }
2645
32
    return tstate->interp->builtins;
2646
945
}
2647
2648
PyObject *
2649
PyEval_GetBuiltins(void)
2650
945
{
2651
945
    PyThreadState *tstate = _PyThreadState_GET();
2652
945
    return _PyEval_GetBuiltins(tstate);
2653
945
}
2654
2655
/* Convenience function to get a builtin from its name */
2656
PyObject *
2657
_PyEval_GetBuiltin(PyObject *name)
2658
0
{
2659
0
    PyObject *attr;
2660
0
    if (PyMapping_GetOptionalItem(PyEval_GetBuiltins(), name, &attr) == 0) {
2661
0
        PyErr_SetObject(PyExc_AttributeError, name);
2662
0
    }
2663
0
    return attr;
2664
0
}
2665
2666
PyObject *
2667
_PyEval_GetBuiltinId(_Py_Identifier *name)
2668
0
{
2669
0
    return _PyEval_GetBuiltin(_PyUnicode_FromId(name));
2670
0
}
2671
2672
PyObject *
2673
PyEval_GetLocals(void)
2674
0
{
2675
    // We need to return a borrowed reference here, so some tricks are needed
2676
0
    PyThreadState *tstate = _PyThreadState_GET();
2677
0
     _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2678
0
    if (current_frame == NULL) {
2679
0
        _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2680
0
        return NULL;
2681
0
    }
2682
2683
    // Be aware that this returns a new reference
2684
0
    PyObject *locals = _PyFrame_GetLocals(current_frame);
2685
2686
0
    if (locals == NULL) {
2687
0
        return NULL;
2688
0
    }
2689
2690
0
    if (PyFrameLocalsProxy_Check(locals)) {
2691
0
        PyFrameObject *f = _PyFrame_GetFrameObject(current_frame);
2692
0
        PyObject *ret = f->f_locals_cache;
2693
0
        if (ret == NULL) {
2694
0
            ret = PyDict_New();
2695
0
            if (ret == NULL) {
2696
0
                Py_DECREF(locals);
2697
0
                return NULL;
2698
0
            }
2699
0
            f->f_locals_cache = ret;
2700
0
        }
2701
0
        if (PyDict_Update(ret, locals) < 0) {
2702
            // At this point, if the cache dict is broken, it will stay broken, as
2703
            // trying to clean it up or replace it will just cause other problems
2704
0
            ret = NULL;
2705
0
        }
2706
0
        Py_DECREF(locals);
2707
0
        return ret;
2708
0
    }
2709
2710
0
    assert(PyMapping_Check(locals));
2711
0
    assert(Py_REFCNT(locals) > 1);
2712
0
    Py_DECREF(locals);
2713
2714
0
    return locals;
2715
0
}
2716
2717
PyObject *
2718
_PyEval_GetFrameLocals(void)
2719
0
{
2720
0
    PyThreadState *tstate = _PyThreadState_GET();
2721
0
     _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2722
0
    if (current_frame == NULL) {
2723
0
        _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2724
0
        return NULL;
2725
0
    }
2726
2727
0
    PyObject *locals = _PyFrame_GetLocals(current_frame);
2728
0
    if (locals == NULL) {
2729
0
        return NULL;
2730
0
    }
2731
2732
0
    if (PyFrameLocalsProxy_Check(locals)) {
2733
0
        PyObject* ret = PyDict_New();
2734
0
        if (ret == NULL) {
2735
0
            Py_DECREF(locals);
2736
0
            return NULL;
2737
0
        }
2738
0
        if (PyDict_Update(ret, locals) < 0) {
2739
0
            Py_DECREF(ret);
2740
0
            Py_DECREF(locals);
2741
0
            return NULL;
2742
0
        }
2743
0
        Py_DECREF(locals);
2744
0
        return ret;
2745
0
    }
2746
2747
0
    assert(PyMapping_Check(locals));
2748
0
    return locals;
2749
0
}
2750
2751
static PyObject *
2752
_PyEval_GetGlobals(PyThreadState *tstate)
2753
243k
{
2754
243k
    _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2755
243k
    if (current_frame == NULL) {
2756
128
        return NULL;
2757
128
    }
2758
243k
    return current_frame->f_globals;
2759
243k
}
2760
2761
PyObject *
2762
PyEval_GetGlobals(void)
2763
243k
{
2764
243k
    PyThreadState *tstate = _PyThreadState_GET();
2765
243k
    return _PyEval_GetGlobals(tstate);
2766
243k
}
2767
2768
PyObject *
2769
_PyEval_GetGlobalsFromRunningMain(PyThreadState *tstate)
2770
0
{
2771
0
    if (!_PyInterpreterState_IsRunningMain(tstate->interp)) {
2772
0
        return NULL;
2773
0
    }
2774
0
    PyObject *mod = _Py_GetMainModule(tstate);
2775
0
    if (_Py_CheckMainModule(mod) < 0) {
2776
0
        Py_XDECREF(mod);
2777
0
        return NULL;
2778
0
    }
2779
0
    PyObject *globals = PyModule_GetDict(mod);  // borrowed
2780
0
    Py_DECREF(mod);
2781
0
    return globals;
2782
0
}
2783
2784
static PyObject *
2785
get_globals_builtins(PyObject *globals)
2786
1.08k
{
2787
1.08k
    PyObject *builtins = NULL;
2788
1.08k
    if (PyDict_Check(globals)) {
2789
1.08k
        if (PyDict_GetItemRef(globals, &_Py_ID(__builtins__), &builtins) < 0) {
2790
0
            return NULL;
2791
0
        }
2792
1.08k
    }
2793
0
    else {
2794
0
        if (PyMapping_GetOptionalItem(
2795
0
                        globals, &_Py_ID(__builtins__), &builtins) < 0)
2796
0
        {
2797
0
            return NULL;
2798
0
        }
2799
0
    }
2800
1.08k
    return builtins;
2801
1.08k
}
2802
2803
static int
2804
set_globals_builtins(PyObject *globals, PyObject *builtins)
2805
1.04k
{
2806
1.04k
    if (PyDict_Check(globals)) {
2807
1.04k
        if (PyDict_SetItem(globals, &_Py_ID(__builtins__), builtins) < 0) {
2808
0
            return -1;
2809
0
        }
2810
1.04k
    }
2811
0
    else {
2812
0
        if (PyObject_SetItem(globals, &_Py_ID(__builtins__), builtins) < 0) {
2813
0
            return -1;
2814
0
        }
2815
0
    }
2816
1.04k
    return 0;
2817
1.04k
}
2818
2819
int
2820
_PyEval_EnsureBuiltins(PyThreadState *tstate, PyObject *globals,
2821
                       PyObject **p_builtins)
2822
956
{
2823
956
    PyObject *builtins = get_globals_builtins(globals);
2824
956
    if (builtins == NULL) {
2825
913
        if (_PyErr_Occurred(tstate)) {
2826
0
            return -1;
2827
0
        }
2828
913
        builtins = PyEval_GetBuiltins();  // borrowed
2829
913
        if (builtins == NULL) {
2830
0
            assert(_PyErr_Occurred(tstate));
2831
0
            return -1;
2832
0
        }
2833
913
        Py_INCREF(builtins);
2834
913
        if (set_globals_builtins(globals, builtins) < 0) {
2835
0
            Py_DECREF(builtins);
2836
0
            return -1;
2837
0
        }
2838
913
    }
2839
956
    if (p_builtins != NULL) {
2840
0
        *p_builtins = builtins;
2841
0
    }
2842
956
    else {
2843
956
        Py_DECREF(builtins);
2844
956
    }
2845
0
    return 0;
2846
956
}
2847
2848
int
2849
_PyEval_EnsureBuiltinsWithModule(PyThreadState *tstate, PyObject *globals,
2850
                                 PyObject **p_builtins)
2851
128
{
2852
128
    PyObject *builtins = get_globals_builtins(globals);
2853
128
    if (builtins == NULL) {
2854
128
        if (_PyErr_Occurred(tstate)) {
2855
0
            return -1;
2856
0
        }
2857
128
        builtins = PyImport_ImportModuleLevel("builtins", NULL, NULL, NULL, 0);
2858
128
        if (builtins == NULL) {
2859
0
            return -1;
2860
0
        }
2861
128
        if (set_globals_builtins(globals, builtins) < 0) {
2862
0
            Py_DECREF(builtins);
2863
0
            return -1;
2864
0
        }
2865
128
    }
2866
128
    if (p_builtins != NULL) {
2867
128
        *p_builtins = builtins;
2868
128
    }
2869
0
    else {
2870
0
        Py_DECREF(builtins);
2871
0
    }
2872
0
    return 0;
2873
128
}
2874
2875
PyObject*
2876
PyEval_GetFrameLocals(void)
2877
0
{
2878
0
    return _PyEval_GetFrameLocals();
2879
0
}
2880
2881
PyObject* PyEval_GetFrameGlobals(void)
2882
0
{
2883
0
    PyThreadState *tstate = _PyThreadState_GET();
2884
0
    _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2885
0
    if (current_frame == NULL) {
2886
0
        return NULL;
2887
0
    }
2888
0
    return Py_XNewRef(current_frame->f_globals);
2889
0
}
2890
2891
PyObject* PyEval_GetFrameBuiltins(void)
2892
0
{
2893
0
    PyThreadState *tstate = _PyThreadState_GET();
2894
0
    return Py_XNewRef(_PyEval_GetBuiltins(tstate));
2895
0
}
2896
2897
int
2898
PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
2899
22.5k
{
2900
22.5k
    PyThreadState *tstate = _PyThreadState_GET();
2901
22.5k
    _PyInterpreterFrame *current_frame = tstate->current_frame;
2902
22.5k
    int result = cf->cf_flags != 0;
2903
2904
22.5k
    if (current_frame != NULL) {
2905
22.5k
        const int codeflags = _PyFrame_GetCode(current_frame)->co_flags;
2906
22.5k
        const int compilerflags = codeflags & PyCF_MASK;
2907
22.5k
        if (compilerflags) {
2908
0
            result = 1;
2909
0
            cf->cf_flags |= compilerflags;
2910
0
        }
2911
22.5k
    }
2912
22.5k
    return result;
2913
22.5k
}
2914
2915
2916
const char *
2917
PyEval_GetFuncName(PyObject *func)
2918
0
{
2919
0
    if (PyMethod_Check(func))
2920
0
        return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
2921
0
    else if (PyFunction_Check(func))
2922
0
        return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
2923
0
    else if (PyCFunction_Check(func))
2924
0
        return ((PyCFunctionObject*)func)->m_ml->ml_name;
2925
0
    else
2926
0
        return Py_TYPE(func)->tp_name;
2927
0
}
2928
2929
const char *
2930
PyEval_GetFuncDesc(PyObject *func)
2931
0
{
2932
0
    if (PyMethod_Check(func))
2933
0
        return "()";
2934
0
    else if (PyFunction_Check(func))
2935
0
        return "()";
2936
0
    else if (PyCFunction_Check(func))
2937
0
        return "()";
2938
0
    else
2939
0
        return " object";
2940
0
}
2941
2942
/* Extract a slice index from a PyLong or an object with the
2943
   nb_index slot defined, and store in *pi.
2944
   Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
2945
   and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
2946
   Return 0 on error, 1 on success.
2947
*/
2948
int
2949
_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
2950
120M
{
2951
120M
    PyThreadState *tstate = _PyThreadState_GET();
2952
120M
    if (!Py_IsNone(v)) {
2953
120M
        Py_ssize_t x;
2954
120M
        if (_PyIndex_Check(v)) {
2955
120M
            x = PyNumber_AsSsize_t(v, NULL);
2956
120M
            if (x == -1 && _PyErr_Occurred(tstate))
2957
0
                return 0;
2958
120M
        }
2959
0
        else {
2960
0
            _PyErr_SetString(tstate, PyExc_TypeError,
2961
0
                             "slice indices must be integers or "
2962
0
                             "None or have an __index__ method");
2963
0
            return 0;
2964
0
        }
2965
120M
        *pi = x;
2966
120M
    }
2967
120M
    return 1;
2968
120M
}
2969
2970
int
2971
_PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
2972
0
{
2973
0
    PyThreadState *tstate = _PyThreadState_GET();
2974
0
    Py_ssize_t x;
2975
0
    if (_PyIndex_Check(v)) {
2976
0
        x = PyNumber_AsSsize_t(v, NULL);
2977
0
        if (x == -1 && _PyErr_Occurred(tstate))
2978
0
            return 0;
2979
0
    }
2980
0
    else {
2981
0
        _PyErr_SetString(tstate, PyExc_TypeError,
2982
0
                         "slice indices must be integers or "
2983
0
                         "have an __index__ method");
2984
0
        return 0;
2985
0
    }
2986
0
    *pi = x;
2987
0
    return 1;
2988
0
}
2989
2990
PyObject *
2991
_PyEval_ImportName(PyThreadState *tstate, _PyInterpreterFrame *frame,
2992
            PyObject *name, PyObject *fromlist, PyObject *level)
2993
8.30k
{
2994
8.30k
    PyObject *import_func;
2995
8.30k
    if (PyMapping_GetOptionalItem(frame->f_builtins, &_Py_ID(__import__), &import_func) < 0) {
2996
0
        return NULL;
2997
0
    }
2998
8.30k
    if (import_func == NULL) {
2999
0
        _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
3000
0
        return NULL;
3001
0
    }
3002
3003
8.30k
    PyObject *locals = frame->f_locals;
3004
8.30k
    if (locals == NULL) {
3005
5.39k
        locals = Py_None;
3006
5.39k
    }
3007
3008
    /* Fast path for not overloaded __import__. */
3009
8.30k
    if (_PyImport_IsDefaultImportFunc(tstate->interp, import_func)) {
3010
8.30k
        Py_DECREF(import_func);
3011
0
        int ilevel = PyLong_AsInt(level);
3012
8.30k
        if (ilevel == -1 && _PyErr_Occurred(tstate)) {
3013
0
            return NULL;
3014
0
        }
3015
8.30k
        return PyImport_ImportModuleLevelObject(
3016
8.30k
                        name,
3017
8.30k
                        frame->f_globals,
3018
8.30k
                        locals,
3019
8.30k
                        fromlist,
3020
8.30k
                        ilevel);
3021
8.30k
    }
3022
3023
0
    PyObject* args[5] = {name, frame->f_globals, locals, fromlist, level};
3024
0
    PyObject *res = PyObject_Vectorcall(import_func, args, 5, NULL);
3025
0
    Py_DECREF(import_func);
3026
0
    return res;
3027
8.30k
}
3028
3029
PyObject *
3030
_PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
3031
2.31k
{
3032
2.31k
    PyObject *x;
3033
2.31k
    PyObject *fullmodname, *mod_name, *origin, *mod_name_or_unknown, *errmsg, *spec;
3034
3035
2.31k
    if (PyObject_GetOptionalAttr(v, name, &x) != 0) {
3036
2.29k
        return x;
3037
2.29k
    }
3038
    /* Issue #17636: in case this failed because of a circular relative
3039
       import, try to fallback on reading the module directly from
3040
       sys.modules. */
3041
18
    if (PyObject_GetOptionalAttr(v, &_Py_ID(__name__), &mod_name) < 0) {
3042
0
        return NULL;
3043
0
    }
3044
18
    if (mod_name == NULL || !PyUnicode_Check(mod_name)) {
3045
0
        Py_CLEAR(mod_name);
3046
0
        goto error;
3047
0
    }
3048
18
    fullmodname = PyUnicode_FromFormat("%U.%U", mod_name, name);
3049
18
    if (fullmodname == NULL) {
3050
0
        Py_DECREF(mod_name);
3051
0
        return NULL;
3052
0
    }
3053
18
    x = PyImport_GetModule(fullmodname);
3054
18
    Py_DECREF(fullmodname);
3055
18
    if (x == NULL && !_PyErr_Occurred(tstate)) {
3056
18
        goto error;
3057
18
    }
3058
0
    Py_DECREF(mod_name);
3059
0
    return x;
3060
3061
18
 error:
3062
18
    if (mod_name == NULL) {
3063
0
        mod_name_or_unknown = PyUnicode_FromString("<unknown module name>");
3064
0
        if (mod_name_or_unknown == NULL) {
3065
0
            return NULL;
3066
0
        }
3067
18
    } else {
3068
18
        mod_name_or_unknown = mod_name;
3069
18
    }
3070
    // mod_name is no longer an owned reference
3071
18
    assert(mod_name_or_unknown);
3072
18
    assert(mod_name == NULL || mod_name == mod_name_or_unknown);
3073
3074
18
    origin = NULL;
3075
18
    if (PyObject_GetOptionalAttr(v, &_Py_ID(__spec__), &spec) < 0) {
3076
0
        Py_DECREF(mod_name_or_unknown);
3077
0
        return NULL;
3078
0
    }
3079
18
    if (spec == NULL) {
3080
0
        errmsg = PyUnicode_FromFormat(
3081
0
            "cannot import name %R from %R (unknown location)",
3082
0
            name, mod_name_or_unknown
3083
0
        );
3084
0
        goto done_with_errmsg;
3085
0
    }
3086
18
    if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
3087
0
        goto done;
3088
0
    }
3089
3090
18
    int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
3091
18
    if (is_possibly_shadowing < 0) {
3092
0
        goto done;
3093
0
    }
3094
18
    int is_possibly_shadowing_stdlib = 0;
3095
18
    if (is_possibly_shadowing) {
3096
0
        PyObject *stdlib_modules;
3097
0
        if (PySys_GetOptionalAttrString("stdlib_module_names", &stdlib_modules) < 0) {
3098
0
            goto done;
3099
0
        }
3100
0
        if (stdlib_modules && PyAnySet_Check(stdlib_modules)) {
3101
0
            is_possibly_shadowing_stdlib = PySet_Contains(stdlib_modules, mod_name_or_unknown);
3102
0
            if (is_possibly_shadowing_stdlib < 0) {
3103
0
                Py_DECREF(stdlib_modules);
3104
0
                goto done;
3105
0
            }
3106
0
        }
3107
0
        Py_XDECREF(stdlib_modules);
3108
0
    }
3109
3110
18
    if (origin == NULL && PyModule_Check(v)) {
3111
        // Fall back to __file__ for diagnostics if we don't have
3112
        // an origin that is a location
3113
14
        origin = PyModule_GetFilenameObject(v);
3114
14
        if (origin == NULL) {
3115
10
            if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
3116
0
                goto done;
3117
0
            }
3118
            // PyModule_GetFilenameObject raised "module filename missing"
3119
10
            _PyErr_Clear(tstate);
3120
10
        }
3121
14
        assert(origin == NULL || PyUnicode_Check(origin));
3122
14
    }
3123
3124
18
    if (is_possibly_shadowing_stdlib) {
3125
0
        assert(origin);
3126
0
        errmsg = PyUnicode_FromFormat(
3127
0
            "cannot import name %R from %R "
3128
0
            "(consider renaming %R since it has the same "
3129
0
            "name as the standard library module named %R "
3130
0
            "and prevents importing that standard library module)",
3131
0
            name, mod_name_or_unknown, origin, mod_name_or_unknown
3132
0
        );
3133
0
    }
3134
18
    else {
3135
18
        int rc = _PyModuleSpec_IsInitializing(spec);
3136
18
        if (rc < 0) {
3137
0
            goto done;
3138
0
        }
3139
18
        else if (rc > 0) {
3140
0
            if (is_possibly_shadowing) {
3141
0
                assert(origin);
3142
                // For non-stdlib modules, only mention the possibility of
3143
                // shadowing if the module is being initialized.
3144
0
                errmsg = PyUnicode_FromFormat(
3145
0
                    "cannot import name %R from %R "
3146
0
                    "(consider renaming %R if it has the same name "
3147
0
                    "as a library you intended to import)",
3148
0
                    name, mod_name_or_unknown, origin
3149
0
                );
3150
0
            }
3151
0
            else if (origin) {
3152
0
                errmsg = PyUnicode_FromFormat(
3153
0
                    "cannot import name %R from partially initialized module %R "
3154
0
                    "(most likely due to a circular import) (%S)",
3155
0
                    name, mod_name_or_unknown, origin
3156
0
                );
3157
0
            }
3158
0
            else {
3159
0
                errmsg = PyUnicode_FromFormat(
3160
0
                    "cannot import name %R from partially initialized module %R "
3161
0
                    "(most likely due to a circular import)",
3162
0
                    name, mod_name_or_unknown
3163
0
                );
3164
0
            }
3165
0
        }
3166
18
        else {
3167
18
            assert(rc == 0);
3168
18
            if (origin) {
3169
8
                errmsg = PyUnicode_FromFormat(
3170
8
                    "cannot import name %R from %R (%S)",
3171
8
                    name, mod_name_or_unknown, origin
3172
8
                );
3173
8
            }
3174
10
            else {
3175
10
                errmsg = PyUnicode_FromFormat(
3176
10
                    "cannot import name %R from %R (unknown location)",
3177
10
                    name, mod_name_or_unknown
3178
10
                );
3179
10
            }
3180
18
        }
3181
18
    }
3182
3183
18
done_with_errmsg:
3184
18
    if (errmsg != NULL) {
3185
        /* NULL checks for mod_name and origin done by _PyErr_SetImportErrorWithNameFrom */
3186
18
        _PyErr_SetImportErrorWithNameFrom(errmsg, mod_name, origin, name);
3187
18
        Py_DECREF(errmsg);
3188
18
    }
3189
3190
18
done:
3191
18
    Py_XDECREF(origin);
3192
18
    Py_XDECREF(spec);
3193
18
    Py_DECREF(mod_name_or_unknown);
3194
0
    return NULL;
3195
18
}
3196
3197
0
#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
3198
0
                         "BaseException is not allowed"
3199
3200
0
#define CANNOT_EXCEPT_STAR_EG "catching ExceptionGroup with except* "\
3201
0
                              "is not allowed. Use except instead."
3202
3203
int
3204
_PyEval_CheckExceptTypeValid(PyThreadState *tstate, PyObject* right)
3205
16.8M
{
3206
16.8M
    if (PyTuple_Check(right)) {
3207
173k
        Py_ssize_t i, length;
3208
173k
        length = PyTuple_GET_SIZE(right);
3209
520k
        for (i = 0; i < length; i++) {
3210
347k
            PyObject *exc = PyTuple_GET_ITEM(right, i);
3211
347k
            if (!PyExceptionClass_Check(exc)) {
3212
0
                _PyErr_SetString(tstate, PyExc_TypeError,
3213
0
                    CANNOT_CATCH_MSG);
3214
0
                return -1;
3215
0
            }
3216
347k
        }
3217
173k
    }
3218
16.7M
    else {
3219
16.7M
        if (!PyExceptionClass_Check(right)) {
3220
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3221
0
                CANNOT_CATCH_MSG);
3222
0
            return -1;
3223
0
        }
3224
16.7M
    }
3225
16.8M
    return 0;
3226
16.8M
}
3227
3228
int
3229
_PyEval_CheckExceptStarTypeValid(PyThreadState *tstate, PyObject* right)
3230
0
{
3231
0
    if (_PyEval_CheckExceptTypeValid(tstate, right) < 0) {
3232
0
        return -1;
3233
0
    }
3234
3235
    /* reject except *ExceptionGroup */
3236
3237
0
    int is_subclass = 0;
3238
0
    if (PyTuple_Check(right)) {
3239
0
        Py_ssize_t length = PyTuple_GET_SIZE(right);
3240
0
        for (Py_ssize_t i = 0; i < length; i++) {
3241
0
            PyObject *exc = PyTuple_GET_ITEM(right, i);
3242
0
            is_subclass = PyObject_IsSubclass(exc, PyExc_BaseExceptionGroup);
3243
0
            if (is_subclass < 0) {
3244
0
                return -1;
3245
0
            }
3246
0
            if (is_subclass) {
3247
0
                break;
3248
0
            }
3249
0
        }
3250
0
    }
3251
0
    else {
3252
0
        is_subclass = PyObject_IsSubclass(right, PyExc_BaseExceptionGroup);
3253
0
        if (is_subclass < 0) {
3254
0
            return -1;
3255
0
        }
3256
0
    }
3257
0
    if (is_subclass) {
3258
0
        _PyErr_SetString(tstate, PyExc_TypeError,
3259
0
            CANNOT_EXCEPT_STAR_EG);
3260
0
            return -1;
3261
0
    }
3262
0
    return 0;
3263
0
}
3264
3265
int
3266
_Py_Check_ArgsIterable(PyThreadState *tstate, PyObject *func, PyObject *args)
3267
16
{
3268
16
    if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
3269
        /* _Py_Check_ArgsIterable() may be called with a live exception:
3270
         * clear it to prevent calling _PyObject_FunctionStr() with an
3271
         * exception set. */
3272
0
        _PyErr_Clear(tstate);
3273
0
        PyObject *funcstr = _PyObject_FunctionStr(func);
3274
0
        if (funcstr != NULL) {
3275
0
            _PyErr_Format(tstate, PyExc_TypeError,
3276
0
                          "%U argument after * must be an iterable, not %.200s",
3277
0
                          funcstr, Py_TYPE(args)->tp_name);
3278
0
            Py_DECREF(funcstr);
3279
0
        }
3280
0
        return -1;
3281
0
    }
3282
16
    return 0;
3283
16
}
3284
3285
void
3286
_PyEval_FormatKwargsError(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
3287
0
{
3288
    /* _PyDict_MergeEx raises attribute
3289
     * error (percolated from an attempt
3290
     * to get 'keys' attribute) instead of
3291
     * a type error if its second argument
3292
     * is not a mapping.
3293
     */
3294
0
    if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
3295
0
        _PyErr_Clear(tstate);
3296
0
        PyObject *funcstr = _PyObject_FunctionStr(func);
3297
0
        if (funcstr != NULL) {
3298
0
            _PyErr_Format(
3299
0
                tstate, PyExc_TypeError,
3300
0
                "%U argument after ** must be a mapping, not %.200s",
3301
0
                funcstr, Py_TYPE(kwargs)->tp_name);
3302
0
            Py_DECREF(funcstr);
3303
0
        }
3304
0
    }
3305
0
    else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
3306
0
        PyObject *exc = _PyErr_GetRaisedException(tstate);
3307
0
        PyObject *args = PyException_GetArgs(exc);
3308
0
        if (PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1) {
3309
0
            _PyErr_Clear(tstate);
3310
0
            PyObject *funcstr = _PyObject_FunctionStr(func);
3311
0
            if (funcstr != NULL) {
3312
0
                PyObject *key = PyTuple_GET_ITEM(args, 0);
3313
0
                _PyErr_Format(
3314
0
                    tstate, PyExc_TypeError,
3315
0
                    "%U got multiple values for keyword argument '%S'",
3316
0
                    funcstr, key);
3317
0
                Py_DECREF(funcstr);
3318
0
            }
3319
0
            Py_XDECREF(exc);
3320
0
        }
3321
0
        else {
3322
0
            _PyErr_SetRaisedException(tstate, exc);
3323
0
        }
3324
0
        Py_DECREF(args);
3325
0
    }
3326
0
}
3327
3328
void
3329
_PyEval_FormatExcCheckArg(PyThreadState *tstate, PyObject *exc,
3330
                          const char *format_str, PyObject *obj)
3331
1
{
3332
1
    const char *obj_str;
3333
3334
1
    if (!obj)
3335
0
        return;
3336
3337
1
    obj_str = PyUnicode_AsUTF8(obj);
3338
1
    if (!obj_str)
3339
0
        return;
3340
3341
1
    _PyErr_Format(tstate, exc, format_str, obj_str);
3342
3343
1
    if (exc == PyExc_NameError) {
3344
        // Include the name in the NameError exceptions to offer suggestions later.
3345
1
        PyObject *exc = PyErr_GetRaisedException();
3346
1
        if (PyErr_GivenExceptionMatches(exc, PyExc_NameError)) {
3347
1
            if (((PyNameErrorObject*)exc)->name == NULL) {
3348
                // We do not care if this fails because we are going to restore the
3349
                // NameError anyway.
3350
1
                (void)PyObject_SetAttr(exc, &_Py_ID(name), obj);
3351
1
            }
3352
1
        }
3353
1
        PyErr_SetRaisedException(exc);
3354
1
    }
3355
1
}
3356
3357
void
3358
_PyEval_FormatExcUnbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
3359
0
{
3360
0
    PyObject *name;
3361
    /* Don't stomp existing exception */
3362
0
    if (_PyErr_Occurred(tstate))
3363
0
        return;
3364
0
    name = PyTuple_GET_ITEM(co->co_localsplusnames, oparg);
3365
0
    if (oparg < PyUnstable_Code_GetFirstFree(co)) {
3366
0
        _PyEval_FormatExcCheckArg(tstate, PyExc_UnboundLocalError,
3367
0
                                  UNBOUNDLOCAL_ERROR_MSG, name);
3368
0
    } else {
3369
0
        _PyEval_FormatExcCheckArg(tstate, PyExc_NameError,
3370
0
                                  UNBOUNDFREE_ERROR_MSG, name);
3371
0
    }
3372
0
}
3373
3374
void
3375
_PyEval_FormatAwaitableError(PyThreadState *tstate, PyTypeObject *type, int oparg)
3376
0
{
3377
0
    if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
3378
0
        if (oparg == 1) {
3379
0
            _PyErr_Format(tstate, PyExc_TypeError,
3380
0
                          "'async with' received an object from __aenter__ "
3381
0
                          "that does not implement __await__: %.100s",
3382
0
                          type->tp_name);
3383
0
        }
3384
0
        else if (oparg == 2) {
3385
0
            _PyErr_Format(tstate, PyExc_TypeError,
3386
0
                          "'async with' received an object from __aexit__ "
3387
0
                          "that does not implement __await__: %.100s",
3388
0
                          type->tp_name);
3389
0
        }
3390
0
    }
3391
0
}
3392
3393
3394
Py_ssize_t
3395
PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
3396
0
{
3397
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
3398
0
    Py_ssize_t new_index;
3399
3400
0
    if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
3401
0
        return -1;
3402
0
    }
3403
0
    new_index = interp->co_extra_user_count++;
3404
0
    interp->co_extra_freefuncs[new_index] = free;
3405
0
    return new_index;
3406
0
}
3407
3408
/* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
3409
   for the limited API. */
3410
3411
int Py_EnterRecursiveCall(const char *where)
3412
1.52M
{
3413
1.52M
    return _Py_EnterRecursiveCall(where);
3414
1.52M
}
3415
3416
void Py_LeaveRecursiveCall(void)
3417
1.36M
{
3418
1.36M
    _Py_LeaveRecursiveCall();
3419
1.36M
}
3420
3421
PyObject *
3422
_PyEval_GetANext(PyObject *aiter)
3423
0
{
3424
0
    unaryfunc getter = NULL;
3425
0
    PyObject *next_iter = NULL;
3426
0
    PyTypeObject *type = Py_TYPE(aiter);
3427
0
    if (PyAsyncGen_CheckExact(aiter)) {
3428
0
        return type->tp_as_async->am_anext(aiter);
3429
0
    }
3430
0
    if (type->tp_as_async != NULL){
3431
0
        getter = type->tp_as_async->am_anext;
3432
0
    }
3433
3434
0
    if (getter != NULL) {
3435
0
        next_iter = (*getter)(aiter);
3436
0
        if (next_iter == NULL) {
3437
0
            return NULL;
3438
0
        }
3439
0
    }
3440
0
    else {
3441
0
        PyErr_Format(PyExc_TypeError,
3442
0
                        "'async for' requires an iterator with "
3443
0
                        "__anext__ method, got %.100s",
3444
0
                        type->tp_name);
3445
0
        return NULL;
3446
0
    }
3447
3448
0
    PyObject *awaitable = _PyCoro_GetAwaitableIter(next_iter);
3449
0
    if (awaitable == NULL) {
3450
0
        _PyErr_FormatFromCause(
3451
0
            PyExc_TypeError,
3452
0
            "'async for' received an invalid object "
3453
0
            "from __anext__: %.100s",
3454
0
            Py_TYPE(next_iter)->tp_name);
3455
0
    }
3456
0
    Py_DECREF(next_iter);
3457
0
    return awaitable;
3458
0
}
3459
3460
void
3461
_PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name, _PyStackRef *writeto)
3462
76.5k
{
3463
76.5k
    if (PyDict_CheckExact(globals) && PyDict_CheckExact(builtins)) {
3464
76.5k
        _PyDict_LoadGlobalStackRef((PyDictObject *)globals,
3465
76.5k
                                    (PyDictObject *)builtins,
3466
76.5k
                                    name, writeto);
3467
76.5k
        if (PyStackRef_IsNull(*writeto) && !PyErr_Occurred()) {
3468
            /* _PyDict_LoadGlobal() returns NULL without raising
3469
                * an exception if the key doesn't exist */
3470
1
            _PyEval_FormatExcCheckArg(PyThreadState_GET(), PyExc_NameError,
3471
1
                                        NAME_ERROR_MSG, name);
3472
1
        }
3473
76.5k
    }
3474
0
    else {
3475
        /* Slow-path if globals or builtins is not a dict */
3476
        /* namespace 1: globals */
3477
0
        PyObject *res;
3478
0
        if (PyMapping_GetOptionalItem(globals, name, &res) < 0) {
3479
0
            *writeto = PyStackRef_NULL;
3480
0
            return;
3481
0
        }
3482
0
        if (res == NULL) {
3483
            /* namespace 2: builtins */
3484
0
            if (PyMapping_GetOptionalItem(builtins, name, &res) < 0) {
3485
0
                *writeto = PyStackRef_NULL;
3486
0
                return;
3487
0
            }
3488
0
            if (res == NULL) {
3489
0
                _PyEval_FormatExcCheckArg(
3490
0
                            PyThreadState_GET(), PyExc_NameError,
3491
0
                            NAME_ERROR_MSG, name);
3492
0
                *writeto = PyStackRef_NULL;
3493
0
                return;
3494
0
            }
3495
0
        }
3496
0
        *writeto = PyStackRef_FromPyObjectSteal(res);
3497
0
    }
3498
76.5k
}
3499
3500
PyObject *
3501
_PyEval_GetAwaitable(PyObject *iterable, int oparg)
3502
0
{
3503
0
    PyObject *iter = _PyCoro_GetAwaitableIter(iterable);
3504
3505
0
    if (iter == NULL) {
3506
0
        _PyEval_FormatAwaitableError(PyThreadState_GET(),
3507
0
            Py_TYPE(iterable), oparg);
3508
0
    }
3509
0
    else if (PyCoro_CheckExact(iter)) {
3510
0
        PyObject *yf = _PyGen_yf((PyGenObject*)iter);
3511
0
        if (yf != NULL) {
3512
            /* `iter` is a coroutine object that is being
3513
                awaited, `yf` is a pointer to the current awaitable
3514
                being awaited on. */
3515
0
            Py_DECREF(yf);
3516
0
            Py_CLEAR(iter);
3517
0
            _PyErr_SetString(PyThreadState_GET(), PyExc_RuntimeError,
3518
0
                                "coroutine is being awaited already");
3519
0
        }
3520
0
    }
3521
0
    return iter;
3522
0
}
3523
3524
PyObject *
3525
_PyEval_LoadName(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *name)
3526
37.3k
{
3527
3528
37.3k
    PyObject *value;
3529
37.3k
    if (frame->f_locals == NULL) {
3530
0
        _PyErr_SetString(tstate, PyExc_SystemError,
3531
0
                            "no locals found");
3532
0
        return NULL;
3533
0
    }
3534
37.3k
    if (PyMapping_GetOptionalItem(frame->f_locals, name, &value) < 0) {
3535
0
        return NULL;
3536
0
    }
3537
37.3k
    if (value != NULL) {
3538
23.6k
        return value;
3539
23.6k
    }
3540
13.7k
    if (PyDict_GetItemRef(frame->f_globals, name, &value) < 0) {
3541
0
        return NULL;
3542
0
    }
3543
13.7k
    if (value != NULL) {
3544
6.78k
        return value;
3545
6.78k
    }
3546
6.97k
    if (PyMapping_GetOptionalItem(frame->f_builtins, name, &value) < 0) {
3547
0
        return NULL;
3548
0
    }
3549
6.97k
    if (value == NULL) {
3550
0
        _PyEval_FormatExcCheckArg(
3551
0
                    tstate, PyExc_NameError,
3552
0
                    NAME_ERROR_MSG, name);
3553
0
    }
3554
6.97k
    return value;
3555
6.97k
}
3556
3557
static _PyStackRef
3558
foriter_next(PyObject *seq, _PyStackRef index)
3559
3.38k
{
3560
3.38k
    assert(PyStackRef_IsTaggedInt(index));
3561
3.38k
    assert(PyTuple_CheckExact(seq) || PyList_CheckExact(seq));
3562
3.38k
    intptr_t i = PyStackRef_UntagInt(index);
3563
3.38k
    if (PyTuple_CheckExact(seq)) {
3564
1.50k
        size_t size = PyTuple_GET_SIZE(seq);
3565
1.50k
        if ((size_t)i >= size) {
3566
394
            return PyStackRef_NULL;
3567
394
        }
3568
1.10k
        return PyStackRef_FromPyObjectNew(PyTuple_GET_ITEM(seq, i));
3569
1.50k
    }
3570
1.88k
    PyObject *item = _PyList_GetItemRef((PyListObject *)seq, i);
3571
1.88k
    if (item == NULL) {
3572
372
        return PyStackRef_NULL;
3573
372
    }
3574
1.51k
    return PyStackRef_FromPyObjectSteal(item);
3575
1.88k
}
3576
3577
_PyStackRef _PyForIter_VirtualIteratorNext(PyThreadState* tstate, _PyInterpreterFrame* frame, _PyStackRef iter, _PyStackRef* index_ptr)
3578
346M
{
3579
346M
    PyObject *iter_o = PyStackRef_AsPyObjectBorrow(iter);
3580
346M
    _PyStackRef index = *index_ptr;
3581
346M
    if (PyStackRef_IsTaggedInt(index)) {
3582
3.38k
        *index_ptr = PyStackRef_IncrementTaggedIntNoOverflow(index);
3583
3.38k
        return foriter_next(iter_o, index);
3584
3.38k
    }
3585
346M
    PyObject *next_o = (*Py_TYPE(iter_o)->tp_iternext)(iter_o);
3586
346M
    if (next_o == NULL) {
3587
54.9M
        if (_PyErr_Occurred(tstate)) {
3588
9.66M
            if (_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
3589
9.66M
                _PyEval_MonitorRaise(tstate, frame, frame->instr_ptr);
3590
9.66M
                _PyErr_Clear(tstate);
3591
9.66M
            }
3592
73
            else {
3593
73
                return PyStackRef_ERROR;
3594
73
            }
3595
9.66M
        }
3596
54.9M
        return PyStackRef_NULL;
3597
54.9M
    }
3598
291M
    return PyStackRef_FromPyObjectSteal(next_o);
3599
346M
}
3600
3601
/* Check if a 'cls' provides the given special method. */
3602
static inline int
3603
type_has_special_method(PyTypeObject *cls, PyObject *name)
3604
0
{
3605
    // _PyType_Lookup() does not set an exception and returns a borrowed ref
3606
0
    assert(!PyErr_Occurred());
3607
0
    PyObject *r = _PyType_Lookup(cls, name);
3608
0
    return r != NULL && Py_TYPE(r)->tp_descr_get != NULL;
3609
0
}
3610
3611
int
3612
_PyEval_SpecialMethodCanSuggest(PyObject *self, int oparg)
3613
0
{
3614
0
    PyTypeObject *type = Py_TYPE(self);
3615
0
    switch (oparg) {
3616
0
        case SPECIAL___ENTER__:
3617
0
        case SPECIAL___EXIT__: {
3618
0
            return type_has_special_method(type, &_Py_ID(__aenter__))
3619
0
                   && type_has_special_method(type, &_Py_ID(__aexit__));
3620
0
        }
3621
0
        case SPECIAL___AENTER__:
3622
0
        case SPECIAL___AEXIT__: {
3623
0
            return type_has_special_method(type, &_Py_ID(__enter__))
3624
0
                   && type_has_special_method(type, &_Py_ID(__exit__));
3625
0
        }
3626
0
        default:
3627
0
            Py_FatalError("unsupported special method");
3628
0
    }
3629
0
}