Coverage Report

Created: 2026-10-31 06:21

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