Coverage Report

Created: 2025-08-26 06:26

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