Coverage Report

Created: 2026-03-23 06:45

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