Coverage Report

Created: 2025-10-10 06:33

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