Coverage Report

Created: 2025-12-14 07:06

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