Coverage Report

Created: 2026-07-14 06:16

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