Coverage Report

Created: 2025-07-04 06:49

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