Coverage Report

Created: 2025-12-07 07:03

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