Coverage Report

Created: 2026-10-17 06:15

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