Coverage Report

Created: 2025-11-11 06:44

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