Coverage Report

Created: 2026-05-16 06:46

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