Coverage Report

Created: 2026-12-01 06:09

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