Coverage Report

Created: 2026-09-06 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Python/ceval.c
Line
Count
Source
1
/* Execute compiled code */
2
3
#include "ceval.h"
4
#include "pycore_long.h"
5
6
int
7
Py_GetRecursionLimit(void)
8
0
{
9
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
10
0
    return interp->ceval.recursion_limit;
11
0
}
12
13
void
14
Py_SetRecursionLimit(int new_limit)
15
0
{
16
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
17
0
    _PyEval_StopTheWorld(interp);
18
0
    interp->ceval.recursion_limit = new_limit;
19
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
20
0
        int depth = p->py_recursion_limit - p->py_recursion_remaining;
21
0
        p->py_recursion_limit = new_limit;
22
0
        p->py_recursion_remaining = new_limit - depth;
23
0
    }
24
0
    _Py_FOR_EACH_TSTATE_END(interp);
25
0
    _PyEval_StartTheWorld(interp);
26
0
}
27
28
int
29
_Py_ReachedRecursionLimitWithMargin(PyThreadState *tstate, int margin_count)
30
176M
{
31
176M
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
32
176M
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
33
176M
#if _Py_STACK_GROWS_DOWN
34
176M
    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
176M
        return 0;
39
176M
    }
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
176M
}
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
21
{
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
21
#  if defined(HAVE_PTHREAD_GETATTR_NP) && !defined(_AIX) && \
147
21
        !defined(__NetBSD__) && (defined(__GLIBC__) || !defined(__linux__))
148
21
    size_t stack_size, guard_size;
149
21
    void *stack_addr;
150
21
    pthread_attr_t attr;
151
21
    int err = pthread_getattr_np(pthread_self(), &attr);
152
21
    if (err == 0) {
153
21
        err = pthread_attr_getguardsize(&attr, &guard_size);
154
21
        err |= pthread_attr_getstack(&attr, &stack_addr, &stack_size);
155
21
        err |= pthread_attr_destroy(&attr);
156
21
    }
157
21
    if (err == 0) {
158
21
        *base = ((uintptr_t)stack_addr) + guard_size;
159
21
        *top = (uintptr_t)stack_addr + stack_size;
160
21
        return;
161
21
    }
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
21
{
183
21
    assert(base < top);
184
21
    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
21
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
196
21
#if _Py_STACK_GROWS_DOWN
197
21
    _tstate->c_stack_top = top;
198
21
    _tstate->c_stack_hard_limit = base + _PyOS_STACK_MARGIN_BYTES;
199
21
    _tstate->c_stack_soft_limit = base + _PyOS_STACK_MARGIN_BYTES * 2;
200
21
#  ifndef NDEBUG
201
    // Sanity checks
202
21
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)tstate;
203
21
    assert(ts->c_stack_hard_limit <= ts->c_stack_soft_limit);
204
21
    assert(ts->c_stack_soft_limit < ts->c_stack_top);
205
21
#  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
21
}
218
219
220
void
221
_Py_InitializeRecursionLimits(PyThreadState *tstate)
222
21
{
223
21
    uintptr_t base, top;
224
21
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
225
21
    hardware_stack_limits(&base, &top, here_addr);
226
21
    assert(top != 0);
227
228
21
    tstate_set_stack(tstate, base, top);
229
21
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)tstate;
230
21
    ts->c_stack_init_base = base;
231
21
    ts->c_stack_init_top = top;
232
21
}
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
9
{
273
9
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
274
9
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
275
9
    assert(_tstate->c_stack_soft_limit != 0);
276
9
    assert(_tstate->c_stack_hard_limit != 0);
277
9
#if _Py_STACK_GROWS_DOWN
278
9
    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
9
    if (tstate->recursion_headroom) {
298
0
        return 0;
299
0
    }
300
9
    else {
301
9
#if _Py_STACK_GROWS_DOWN
302
9
        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
9
        tstate->recursion_headroom++;
307
9
        _PyErr_Format(tstate, PyExc_RecursionError,
308
9
                    "Stack overflow (used %d kB)%s",
309
9
                    kbytes_used,
310
9
                    where);
311
9
        tstate->recursion_headroom--;
312
9
        return -1;
313
9
    }
314
9
}
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
0
{
535
0
    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
0
    assert(PyTuple_CheckExact(kwargs));
541
    // First, an isinstance check:
542
0
    if (PyObject_IsInstance(subject, type) <= 0) {
543
0
        return NULL;
544
0
    }
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
567
{
655
567
    PyThreadState *tstate = _PyThreadState_GET();
656
567
    if (locals == NULL) {
657
0
        locals = globals;
658
0
    }
659
567
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
660
567
    if (builtins == NULL) {
661
0
        return NULL;
662
0
    }
663
567
    PyFrameConstructor desc = {
664
567
        .fc_globals = globals,
665
567
        .fc_builtins = builtins,
666
567
        .fc_name = ((PyCodeObject *)co)->co_name,
667
567
        .fc_qualname = ((PyCodeObject *)co)->co_name,
668
567
        .fc_code = co,
669
567
        .fc_defaults = NULL,
670
567
        .fc_kwdefaults = NULL,
671
567
        .fc_closure = NULL
672
567
    };
673
567
    PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
674
567
    _Py_DECREF_BUILTINS(builtins);
675
567
    if (func == NULL) {
676
0
        return NULL;
677
0
    }
678
567
    EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
679
567
    PyObject *res = _PyEval_Vector(tstate, func, locals, NULL, 0, NULL);
680
567
    Py_DECREF(func);
681
567
    return res;
682
567
}
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
1.68M
{
714
1.68M
    PyObject *res;
715
1.68M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
716
1.68M
    if (CONVERSION_FAILED(args_o)) {
717
0
        res = NULL;
718
0
        goto cleanup;
719
0
    }
720
1.68M
    PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable);
721
1.68M
    PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames);
722
1.68M
    int positional_args = total_args;
723
1.68M
    if (kwnames_o != NULL) {
724
1.24M
        positional_args -= (int)PyTuple_GET_SIZE(kwnames_o);
725
1.24M
    }
726
1.68M
    res = PyObject_Vectorcall(
727
1.68M
        callable_o, args_o,
728
1.68M
        positional_args | PY_VECTORCALL_ARGUMENTS_OFFSET,
729
1.68M
        kwnames_o);
730
1.68M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
731
1.68M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
732
1.68M
cleanup:
733
1.68M
    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
5.61M
    for (int i = total_args-1; i >= 0; i--) {
737
3.93M
        _PyStackRef tmp = arguments[i];
738
3.93M
        arguments[i] = PyStackRef_NULL;
739
3.93M
        PyStackRef_CLOSE(tmp);
740
3.93M
    }
741
1.68M
    PyStackRef_CLOSE(callable);
742
1.68M
    return res;
743
1.68M
}
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
1.48M
{
756
1.48M
    PyObject* res;
757
1.48M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
758
1.48M
    if (CONVERSION_FAILED(args_o)) {
759
0
        res = NULL;
760
0
        goto cleanup;
761
0
    }
762
1.48M
    PyObject* callable_o = PyStackRef_AsPyObjectBorrow(callable);
763
1.48M
    PyObject* kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames);
764
1.48M
    int positional_args = total_args;
765
1.48M
    if (kwnames_o != NULL) {
766
553
        positional_args -= (int)PyTuple_GET_SIZE(kwnames_o);
767
553
    }
768
1.48M
    res = PyObject_Vectorcall(
769
1.48M
        callable_o, args_o,
770
1.48M
        positional_args | PY_VECTORCALL_ARGUMENTS_OFFSET,
771
1.48M
        kwnames_o);
772
1.48M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
773
1.48M
    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
1.48M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
791
1.48M
cleanup:
792
1.48M
    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
3.07M
    for (int i = total_args - 1; i >= 0; i--) {
796
1.58M
        _PyStackRef tmp = arguments[i];
797
1.58M
        arguments[i] = PyStackRef_NULL;
798
1.58M
        PyStackRef_CLOSE(tmp);
799
1.58M
    }
800
1.48M
    PyStackRef_CLOSE(callable);
801
1.48M
    return res;
802
1.48M
}
803
804
PyObject *
805
_Py_BuiltinCallFast_StackRef(
806
    _PyStackRef callable,
807
    _PyStackRef *arguments,
808
    int total_args)
809
550k
{
810
550k
    PyObject *res;
811
550k
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
812
550k
    if (CONVERSION_FAILED(args_o)) {
813
0
        return NULL;
814
0
    }
815
550k
    PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable);
816
550k
    PyCFunction cfunc = PyCFunction_GET_FUNCTION(callable_o);
817
550k
    res = _PyCFunctionFast_CAST(cfunc)(
818
550k
        PyCFunction_GET_SELF(callable_o),
819
550k
        args_o,
820
550k
        total_args
821
550k
    );
822
550k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
823
550k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
824
550k
    return res;
825
550k
}
826
827
PyObject *
828
_Py_BuiltinCallFastWithKeywords_StackRef(
829
    _PyStackRef callable,
830
    _PyStackRef *arguments,
831
    int total_args)
832
15.6M
{
833
15.6M
    PyObject *res;
834
15.6M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
835
15.6M
    if (CONVERSION_FAILED(args_o)) {
836
0
        return NULL;
837
0
    }
838
15.6M
    PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable);
839
15.6M
    PyCFunctionFastWithKeywords cfunc =
840
15.6M
        _PyCFunctionFastWithKeywords_CAST(PyCFunction_GET_FUNCTION(callable_o));
841
15.6M
    res = cfunc(PyCFunction_GET_SELF(callable_o), args_o, total_args, NULL);
842
15.6M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
843
15.6M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
844
15.6M
    return res;
845
15.6M
}
846
847
PyObject *
848
_PyCallMethodDescriptorFast_StackRef(
849
    _PyStackRef callable,
850
    PyCFunctionFast cfunc,
851
    PyObject *self,
852
    _PyStackRef *arguments,
853
    int total_args)
854
3.19M
{
855
3.19M
    PyObject *res;
856
3.19M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
857
3.19M
    if (CONVERSION_FAILED(args_o)) {
858
0
        return NULL;
859
0
    }
860
3.19M
    assert(self == PyStackRef_AsPyObjectBorrow(arguments[0]));
861
862
3.19M
    res = cfunc(self, (args_o + 1), total_args - 1);
863
3.19M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
864
3.19M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
865
3.19M
    return res;
866
3.19M
}
867
868
PyObject *
869
_PyCallMethodDescriptorFastWithKeywords_StackRef(
870
    _PyStackRef callable,
871
    PyCFunctionFastWithKeywords cfunc,
872
    PyObject *self,
873
    _PyStackRef *arguments,
874
    int total_args)
875
143k
{
876
143k
    PyObject *res;
877
143k
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
878
143k
    if (CONVERSION_FAILED(args_o)) {
879
0
        return NULL;
880
0
    }
881
143k
    assert(self == PyStackRef_AsPyObjectBorrow(arguments[0]));
882
883
143k
    res = cfunc(self, (args_o + 1), total_args-1, NULL);
884
143k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
885
143k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
886
143k
    return res;
887
143k
}
888
889
PyObject *
890
_Py_CallBuiltinClass_StackRef(
891
    _PyStackRef callable,
892
    _PyStackRef *arguments,
893
    int total_args)
894
8.46M
{
895
8.46M
    PyObject *res;
896
8.46M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
897
8.46M
    if (CONVERSION_FAILED(args_o)) {
898
0
        return NULL;
899
0
    }
900
8.46M
    PyTypeObject *tp = (PyTypeObject *)PyStackRef_AsPyObjectBorrow(callable);
901
8.46M
    res = tp->tp_vectorcall((PyObject *)tp, args_o, total_args | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
902
8.46M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
903
8.46M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
904
8.46M
    return res;
905
8.46M
}
906
907
PyObject *
908
_Py_BuildString_StackRefSteal(
909
    _PyStackRef *arguments,
910
    int total_args)
911
136k
{
912
136k
    PyObject *res;
913
136k
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
914
136k
    if (CONVERSION_FAILED(args_o)) {
915
0
        res = NULL;
916
0
        goto cleanup;
917
0
    }
918
136k
    res = _PyUnicode_JoinArray(&_Py_STR(empty), args_o, total_args);
919
136k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
920
136k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
921
136k
cleanup:
922
    // arguments is a pointer into the GC visible stack,
923
    // so we must NULL out values as we clear them.
924
1.22M
    for (int i = total_args-1; i >= 0; i--) {
925
1.08M
        _PyStackRef tmp = arguments[i];
926
1.08M
        arguments[i] = PyStackRef_NULL;
927
1.08M
        PyStackRef_CLOSE(tmp);
928
1.08M
    }
929
136k
    return res;
930
136k
}
931
932
PyObject *
933
_Py_BuildMap_StackRefSteal(
934
    _PyStackRef *arguments,
935
    int half_args)
936
20.4k
{
937
20.4k
    PyObject *res;
938
20.4k
    STACKREFS_TO_PYOBJECTS(arguments, half_args*2, args_o);
939
20.4k
    if (CONVERSION_FAILED(args_o)) {
940
0
        res = NULL;
941
0
        goto cleanup;
942
0
    }
943
20.4k
    res = _PyDict_FromItems(
944
20.4k
        args_o, 2,
945
20.4k
        args_o+1, 2,
946
20.4k
        half_args
947
20.4k
    );
948
20.4k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
949
20.4k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
950
20.4k
cleanup:
951
    // arguments is a pointer into the GC visible stack,
952
    // so we must NULL out values as we clear them.
953
26.6k
    for (int i = half_args*2-1; i >= 0; i--) {
954
6.21k
        _PyStackRef tmp = arguments[i];
955
6.21k
        arguments[i] = PyStackRef_NULL;
956
6.21k
        PyStackRef_CLOSE(tmp);
957
6.21k
    }
958
20.4k
    return res;
959
20.4k
}
960
961
_PyStackRef
962
_Py_LoadAttr_StackRefSteal(
963
    PyThreadState *tstate, _PyStackRef owner,
964
    PyObject *name, _PyStackRef *self_or_null)
965
1.44M
{
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
1.44M
    _PyCStackRef method, self;
970
1.44M
    _PyThreadState_PushCStackRef(tstate, &method);
971
1.44M
    _PyThreadState_PushCStackRef(tstate, &self);
972
1.44M
    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
1.44M
    _PyObject_GetMethodStackRef(tstate, &self.ref, name, &method.ref);
976
1.44M
    *self_or_null = _PyThreadState_PopCStackRefSteal(tstate, &self);
977
1.44M
    return _PyThreadState_PopCStackRefSteal(tstate, &method);
978
1.44M
}
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
20.0k
{
1015
20.0k
    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
20.0k
    else {
1022
20.0k
        if (tstate->py_recursion_remaining <= 0) {
1023
20.0k
            tstate->recursion_headroom++;
1024
20.0k
            _PyErr_Format(tstate, PyExc_RecursionError,
1025
20.0k
                        "maximum recursion depth exceeded");
1026
20.0k
            tstate->recursion_headroom--;
1027
20.0k
            return -1;
1028
20.0k
        }
1029
20.0k
    }
1030
0
    return 0;
1031
20.0k
}
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
31.2M
{
1054
31.2M
    PyObject **result;
1055
31.2M
    if (nargs > MAX_STACKREF_SCRATCH) {
1056
        // +1 in case PY_VECTORCALL_ARGUMENTS_OFFSET is set.
1057
120
        result = PyMem_Malloc((nargs + 1) * sizeof(PyObject *));
1058
120
        if (result == NULL) {
1059
0
            PyErr_NoMemory();
1060
0
            return NULL;
1061
0
        }
1062
120
    }
1063
31.2M
    else {
1064
31.2M
        result = scratch;
1065
31.2M
    }
1066
31.2M
    result++;
1067
31.2M
    result[0] = NULL; /* Keep GCC happy */
1068
87.2M
    for (int i = 0; i < nargs; i++) {
1069
55.9M
        result[i] = PyStackRef_AsPyObjectBorrow(input[i]);
1070
55.9M
    }
1071
31.2M
    return result;
1072
31.2M
}
1073
1074
void
1075
_PyObjectArray_Free(PyObject **array, PyObject **scratch)
1076
31.2M
{
1077
31.2M
    if (array != scratch) {
1078
120
        PyMem_Free(array);
1079
120
    }
1080
31.2M
}
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
5.92M
{
1119
5.92M
    PyTypeObject *tp = PyStackRef_TYPE(iterable);
1120
5.92M
    if (tp->_tp_iteritem != NULL) {
1121
        /* Leave iterable on stack and pushed tagged 0 */
1122
3.11k
        *index_or_null = PyStackRef_TagInt(0);
1123
3.11k
        return iterable;
1124
3.11k
    }
1125
5.92M
    *index_or_null = PyStackRef_NULL;
1126
5.92M
    if (tp->tp_iter == PyObject_SelfIter) {
1127
72
        return iterable;
1128
72
    }
1129
5.92M
    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
5.92M
    PyObject *iter_o = PyObject_GetIter(PyStackRef_AsPyObjectBorrow(iterable));
1144
5.92M
    PyStackRef_CLOSE(iterable);
1145
5.92M
    if (iter_o == NULL) {
1146
0
        return PyStackRef_ERROR;
1147
0
    }
1148
5.92M
    return PyStackRef_FromPyObjectSteal(iter_o);
1149
5.92M
}
1150
1151
int _PyEval_StoreName(PyThreadState *tstate, _PyStackRef v, PyObject *name, PyObject* ns)
1152
49.0k
{
1153
49.0k
    int deletion = PyStackRef_IsNull(v);
1154
1155
49.0k
    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
49.0k
    if (deletion) {
1164
326
        int error = PyObject_DelItem(ns, name);
1165
326
        if (error) {
1166
0
            _PyEval_FormatExcCheckArg(tstate, PyExc_NameError,
1167
0
                                    NAME_ERROR_MSG,
1168
0
                                    name);
1169
0
        }
1170
326
        return error;
1171
326
    }
1172
1173
48.7k
    PyObject *v_o = PyStackRef_AsPyObjectBorrow(v);
1174
48.7k
    if (PyDict_CheckExact(ns)) {
1175
48.2k
        return PyDict_SetItem(ns, name, v_o);
1176
48.2k
    }
1177
1178
474
    return PyObject_SetItem(ns, name, v_o);
1179
48.7k
}
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
22.2M
{
1231
22.2M
    _Py_EnsureTstateNotNULL(tstate);
1232
22.2M
    check_invalid_reentrancy();
1233
22.2M
    CALL_STAT_INC(pyeval_calls);
1234
1235
22.2M
#if USE_COMPUTED_GOTOS && !_Py_TAIL_CALL_INTERP
1236
/* Import the static jump table */
1237
22.2M
#include "opcode_targets.h"
1238
22.2M
    void **opcode_targets = opcode_targets_table;
1239
22.2M
#endif
1240
1241
#ifdef Py_STATS
1242
    int lastopcode = 0;
1243
#endif
1244
22.2M
#if !_Py_TAIL_CALL_INTERP
1245
22.2M
    uint8_t opcode;    /* Current opcode */
1246
22.2M
    int oparg;         /* Current opcode argument, if any */
1247
22.2M
    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
22.2M
#endif
1253
22.2M
    _PyEntryFrame entry;
1254
1255
22.2M
    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
22.2M
    _Py_CODEUNIT *next_instr;
1264
22.2M
    _PyStackRef *stack_pointer;
1265
22.2M
    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
22.2M
    entry.frame.f_executable = PyStackRef_None;
1277
22.2M
    entry.frame.instr_ptr = (_Py_CODEUNIT *)_Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS + 1;
1278
22.2M
    entry.frame.stackpointer = entry.stack;
1279
22.2M
    entry.frame.owner = FRAME_OWNED_BY_INTERPRETER;
1280
22.2M
    entry.frame.visited = 0;
1281
22.2M
    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
22.2M
    entry.frame.previous = tstate->current_frame;
1288
22.2M
    frame->previous = &entry.frame;
1289
22.2M
    tstate->current_frame = frame;
1290
22.2M
    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
22.2M
    if (throwflag) {
1301
25.8k
        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
25.8k
        _Py_Instrument(_PyFrame_GetCode(frame), tstate->interp);
1319
25.8k
        next_instr = frame->instr_ptr;
1320
25.8k
        monitor_throw(tstate, frame, next_instr);
1321
25.8k
        stack_pointer = _PyFrame_GetStackPointer(frame);
1322
25.8k
        _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
25.8k
        goto error;
1331
25.8k
#endif
1332
25.8k
    }
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
22.2M
    goto start_frame;
1342
22.2M
#   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
0
}
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
32.6M
{
1732
32.6M
    PyCodeObject *co = (PyCodeObject*)func->func_code;
1733
32.6M
    const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
1734
    /* Create a dictionary for keyword parameters (**kwags) */
1735
32.6M
    PyObject *kwdict;
1736
32.6M
    Py_ssize_t i;
1737
32.6M
    if (co->co_flags & CO_VARKEYWORDS) {
1738
5.36k
        kwdict = PyDict_New();
1739
5.36k
        if (kwdict == NULL) {
1740
0
            goto fail_pre_positional;
1741
0
        }
1742
5.36k
        i = total_args;
1743
5.36k
        if (co->co_flags & CO_VARARGS) {
1744
4.47k
            i++;
1745
4.47k
        }
1746
5.36k
        assert(PyStackRef_IsNull(localsplus[i]));
1747
5.36k
        localsplus[i] = PyStackRef_FromPyObjectSteal(kwdict);
1748
5.36k
    }
1749
32.6M
    else {
1750
32.6M
        kwdict = NULL;
1751
32.6M
    }
1752
1753
    /* Copy all positional arguments into local variables */
1754
32.6M
    Py_ssize_t j, n;
1755
32.6M
    if (argcount > co->co_argcount) {
1756
16.0k
        n = co->co_argcount;
1757
16.0k
    }
1758
32.6M
    else {
1759
32.6M
        n = argcount;
1760
32.6M
    }
1761
92.5M
    for (j = 0; j < n; j++) {
1762
59.8M
        assert(PyStackRef_IsNull(localsplus[j]));
1763
59.8M
        localsplus[j] = args[j];
1764
59.8M
    }
1765
1766
    /* Pack other positional arguments into the *args argument */
1767
32.6M
    if (co->co_flags & CO_VARARGS) {
1768
18.7k
        PyObject *u = NULL;
1769
18.7k
        if (argcount == n) {
1770
2.69k
            u = (PyObject *)&_Py_SINGLETON(tuple_empty);
1771
2.69k
        }
1772
16.0k
        else {
1773
16.0k
            u = _PyTuple_FromStackRefStealOnSuccess(args + n, argcount - n);
1774
16.0k
            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
16.0k
        }
1780
18.7k
        if (u == NULL) {
1781
0
            goto fail_post_positional;
1782
0
        }
1783
18.7k
        assert(PyStackRef_AsPyObjectBorrow(localsplus[total_args]) == NULL);
1784
18.7k
        localsplus[total_args] = PyStackRef_FromPyObjectSteal(u);
1785
18.7k
    }
1786
32.6M
    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
32.6M
    if (kwnames != NULL) {
1795
11.5k
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1796
25.9k
        for (i = 0; i < kwcount; i++) {
1797
14.3k
            PyObject **co_varnames;
1798
14.3k
            PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
1799
0
            _PyStackRef value_stackref = args[i+argcount];
1800
14.3k
            Py_ssize_t j;
1801
1802
14.3k
            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
14.3k
            co_varnames = ((PyTupleObject *)(co->co_localsplusnames))->ob_item;
1812
52.4k
            for (j = co->co_posonlyargcount; j < total_args; j++) {
1813
52.4k
                PyObject *varname = co_varnames[j];
1814
52.4k
                if (varname == keyword) {
1815
14.3k
                    goto kw_found;
1816
14.3k
                }
1817
52.4k
            }
1818
1819
            /* Slow fallback, just in case */
1820
48
            for (j = co->co_posonlyargcount; j < total_args; j++) {
1821
36
                PyObject *varname = co_varnames[j];
1822
36
                int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
1823
36
                if (cmp > 0) {
1824
0
                    goto kw_found;
1825
0
                }
1826
36
                else if (cmp < 0) {
1827
0
                    goto kw_fail;
1828
0
                }
1829
36
            }
1830
1831
12
            assert(j >= total_args);
1832
12
            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
12
            if (PyDict_SetItem(kwdict, keyword, PyStackRef_AsPyObjectBorrow(value_stackref)) == -1) {
1873
0
                goto kw_fail;
1874
0
            }
1875
12
            PyStackRef_CLOSE(value_stackref);
1876
12
            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
14.3k
        kw_found:
1885
14.3k
            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
14.3k
            localsplus[j] = value_stackref;
1892
14.3k
        }
1893
11.5k
    }
1894
1895
    /* Check the number of positional arguments */
1896
32.6M
    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
32.6M
    if (argcount < co->co_argcount) {
1904
6.31M
        Py_ssize_t defcount = func->func_defaults == NULL ? 0 : PyTuple_GET_SIZE(func->func_defaults);
1905
6.31M
        Py_ssize_t m = co->co_argcount - defcount;
1906
6.31M
        Py_ssize_t missing = 0;
1907
6.31M
        for (i = argcount; i < m; i++) {
1908
350
            if (PyStackRef_IsNull(localsplus[i])) {
1909
0
                missing++;
1910
0
            }
1911
350
        }
1912
6.31M
        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
6.31M
        if (n > m)
1918
194k
            i = n - m;
1919
6.12M
        else
1920
6.12M
            i = 0;
1921
6.31M
        if (defcount) {
1922
6.31M
            PyObject **defs = &PyTuple_GET_ITEM(func->func_defaults, 0);
1923
12.7M
            for (; i < defcount; i++) {
1924
6.38M
                if (PyStackRef_AsPyObjectBorrow(localsplus[m+i]) == NULL) {
1925
6.37M
                    PyObject *def = defs[i];
1926
6.37M
                    localsplus[m+i] = PyStackRef_FromPyObjectNew(def);
1927
6.37M
                }
1928
6.38M
            }
1929
6.31M
        }
1930
6.31M
    }
1931
1932
    /* Add missing keyword arguments (copy default values from kwdefs) */
1933
32.6M
    if (co->co_kwonlyargcount > 0) {
1934
18.2k
        Py_ssize_t missing = 0;
1935
54.3k
        for (i = co->co_argcount; i < total_args; i++) {
1936
36.0k
            if (PyStackRef_AsPyObjectBorrow(localsplus[i]) != NULL)
1937
8.40k
                continue;
1938
27.6k
            PyObject *varname = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1939
27.6k
            if (func->func_kwdefaults != NULL) {
1940
27.6k
                PyObject *def;
1941
27.6k
                if (PyDict_GetItemRef(func->func_kwdefaults, varname, &def) < 0) {
1942
0
                    goto fail_post_args;
1943
0
                }
1944
27.6k
                if (def) {
1945
27.6k
                    localsplus[i] = PyStackRef_FromPyObjectSteal(def);
1946
27.6k
                    continue;
1947
27.6k
                }
1948
27.6k
            }
1949
0
            missing++;
1950
0
        }
1951
18.2k
        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
18.2k
    }
1957
32.6M
    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
160M
{
1979
160M
    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
160M
    assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize ==
1983
160M
        tstate->datastack_top);
1984
160M
    assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1985
160M
    _PyFrame_ClearExceptCode(frame);
1986
160M
    PyStackRef_CLEAR(frame->f_executable);
1987
160M
    _PyThreadState_PopFrame(tstate, frame);
1988
160M
}
1989
1990
static void
1991
clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1992
5.38M
{
1993
5.38M
    assert(frame->owner == FRAME_OWNED_BY_GENERATOR);
1994
5.38M
    PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame);
1995
5.38M
    FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_CLEARED);
1996
5.38M
    assert(tstate->exc_info == &gen->gi_exc_state);
1997
5.38M
    tstate->exc_info = gen->gi_exc_state.previous_item;
1998
5.38M
    gen->gi_exc_state.previous_item = NULL;
1999
5.38M
    frame->previous = NULL;
2000
5.38M
    Py_BEGIN_CRITICAL_SECTION(gen);
2001
5.38M
    assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
2002
5.38M
    _PyFrame_ClearExceptCode(frame);
2003
5.38M
    Py_END_CRITICAL_SECTION();
2004
5.38M
    _PyErr_ClearExcState(&gen->gi_exc_state);
2005
    // gh-143939: There must not be any escaping calls between setting
2006
    // the generator return kind and returning from _PyEval_EvalFrame.
2007
5.38M
    ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_RETURN;
2008
5.38M
}
2009
2010
void
2011
_PyEval_FrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame)
2012
165M
{
2013
    // By this point, tstate->current_frame is already set to the parent frame.
2014
165M
    _PyThreadState_UpdateLastProfiledFrame(tstate, frame, tstate->current_frame);
2015
2016
165M
    if (frame->owner == FRAME_OWNED_BY_THREAD) {
2017
160M
        clear_thread_frame(tstate, frame);
2018
160M
    }
2019
5.38M
    else {
2020
5.38M
        clear_gen_frame(tstate, frame);
2021
5.38M
    }
2022
165M
}
2023
2024
/* Consumes references to func, locals and all the args */
2025
_PyInterpreterFrame *
2026
_PyEvalFramePushAndInit(PyThreadState *tstate, _PyStackRef func,
2027
                        PyObject *locals, _PyStackRef const* args,
2028
                        size_t argcount, PyObject *kwnames, _PyInterpreterFrame *previous)
2029
32.6M
{
2030
32.6M
    PyFunctionObject *func_obj = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(func);
2031
32.6M
    PyCodeObject * code = (PyCodeObject *)func_obj->func_code;
2032
32.6M
    CALL_STAT_INC(frames_pushed);
2033
32.6M
    _PyInterpreterFrame *frame = _PyThreadState_PushFrame(tstate, code->co_framesize);
2034
32.6M
    if (frame == NULL) {
2035
0
        goto fail;
2036
0
    }
2037
32.6M
    _PyFrame_Initialize(tstate, frame, func, locals, code, 0, previous);
2038
32.6M
    if (initialize_locals(tstate, func_obj, frame->localsplus, args, argcount, kwnames)) {
2039
0
        assert(frame->owner == FRAME_OWNED_BY_THREAD);
2040
0
        _PyThreadState_UpdateLastProfiledFrame(tstate, frame, tstate->current_frame);
2041
0
        clear_thread_frame(tstate, frame);
2042
0
        return NULL;
2043
0
    }
2044
32.6M
    return frame;
2045
0
fail:
2046
    /* Consume the references */
2047
0
    PyStackRef_CLOSE(func);
2048
0
    Py_XDECREF(locals);
2049
0
    for (size_t i = 0; i < argcount; i++) {
2050
0
        PyStackRef_CLOSE(args[i]);
2051
0
    }
2052
0
    if (kwnames) {
2053
0
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
2054
0
        for (Py_ssize_t i = 0; i < kwcount; i++) {
2055
0
            PyStackRef_CLOSE(args[i+argcount]);
2056
0
        }
2057
0
    }
2058
0
    PyErr_NoMemory();
2059
0
    return NULL;
2060
32.6M
}
2061
2062
/* Same as _PyEvalFramePushAndInit but takes an args tuple and kwargs dict.
2063
   Steals references to func, callargs and kwargs.
2064
*/
2065
_PyInterpreterFrame *
2066
_PyEvalFramePushAndInit_Ex(PyThreadState *tstate, _PyStackRef func,
2067
    PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs, _PyInterpreterFrame *previous)
2068
472
{
2069
472
    bool has_dict = (kwargs != NULL && PyDict_GET_SIZE(kwargs) > 0);
2070
472
    PyObject *kwnames = NULL;
2071
472
    _PyStackRef *newargs;
2072
472
    PyObject *const *object_array = NULL;
2073
472
    _PyStackRef stack_array[8] = {0};
2074
472
    if (has_dict) {
2075
0
        object_array = _PyStack_UnpackDict(tstate, _PyTuple_ITEMS(callargs), nargs, kwargs, &kwnames);
2076
0
        if (object_array == NULL) {
2077
0
            PyStackRef_CLOSE(func);
2078
0
            goto error;
2079
0
        }
2080
0
        size_t nkwargs = PyDict_GET_SIZE(kwargs);
2081
0
        assert(sizeof(PyObject *) == sizeof(_PyStackRef));
2082
0
        newargs = (_PyStackRef *)object_array;
2083
        /* Positional args are borrowed from callargs tuple, need new reference */
2084
0
        for (Py_ssize_t i = 0; i < nargs; i++) {
2085
0
            newargs[i] = PyStackRef_FromPyObjectNew(object_array[i]);
2086
0
        }
2087
        /* Keyword args are owned by _PyStack_UnpackDict, steal them */
2088
0
        for (size_t i = 0; i < nkwargs; i++) {
2089
0
            newargs[nargs + i] = PyStackRef_FromPyObjectSteal(object_array[nargs + i]);
2090
0
        }
2091
0
    }
2092
472
    else {
2093
472
        if (nargs <= 8) {
2094
454
            newargs = stack_array;
2095
454
        }
2096
18
        else {
2097
18
            newargs = PyMem_Malloc(sizeof(_PyStackRef) *nargs);
2098
18
            if (newargs == NULL) {
2099
0
                PyErr_NoMemory();
2100
0
                PyStackRef_CLOSE(func);
2101
0
                goto error;
2102
0
            }
2103
18
        }
2104
        /* We need to create a new reference for all our args since the new frame steals them. */
2105
2.27k
        for (Py_ssize_t i = 0; i < nargs; i++) {
2106
1.80k
            newargs[i] = PyStackRef_FromPyObjectNew(PyTuple_GET_ITEM(callargs, i));
2107
1.80k
        }
2108
472
    }
2109
472
    _PyInterpreterFrame *new_frame = _PyEvalFramePushAndInit(
2110
472
        tstate, func, locals,
2111
472
        newargs, nargs, kwnames, previous
2112
472
    );
2113
472
    if (has_dict) {
2114
0
        _PyStack_UnpackDict_FreeNoDecRef(object_array, kwnames);
2115
0
    }
2116
472
    else if (nargs > 8) {
2117
18
       PyMem_Free((void *)newargs);
2118
18
    }
2119
    /* No need to decref func here because the reference has been stolen by
2120
       _PyEvalFramePushAndInit.
2121
    */
2122
472
    Py_DECREF(callargs);
2123
472
    Py_XDECREF(kwargs);
2124
472
    return new_frame;
2125
0
error:
2126
0
    Py_DECREF(callargs);
2127
0
    Py_XDECREF(kwargs);
2128
0
    return NULL;
2129
472
}
2130
2131
PyObject *
2132
_PyEval_Vector(PyThreadState *tstate, PyFunctionObject *func,
2133
               PyObject *locals,
2134
               PyObject* const* args, size_t argcount,
2135
               PyObject *kwnames)
2136
22.1M
{
2137
22.1M
    size_t total_args = argcount;
2138
22.1M
    if (kwnames) {
2139
1.12k
        total_args += PyTuple_GET_SIZE(kwnames);
2140
1.12k
    }
2141
22.1M
    _PyStackRef stack_array[8] = {0};
2142
22.1M
    _PyStackRef *arguments;
2143
22.1M
    if (total_args <= 8) {
2144
22.0M
        arguments = stack_array;
2145
22.0M
    }
2146
86.1k
    else {
2147
86.1k
        arguments = PyMem_Malloc(sizeof(_PyStackRef) * total_args);
2148
86.1k
        if (arguments == NULL) {
2149
0
            return PyErr_NoMemory();
2150
0
        }
2151
86.1k
    }
2152
    /* _PyEvalFramePushAndInit consumes the references
2153
     * to func, locals and all its arguments */
2154
22.1M
    Py_XINCREF(locals);
2155
59.4M
    for (size_t i = 0; i < argcount; i++) {
2156
37.2M
        arguments[i] = PyStackRef_FromPyObjectNew(args[i]);
2157
37.2M
    }
2158
22.1M
    if (kwnames) {
2159
1.12k
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
2160
3.96k
        for (Py_ssize_t i = 0; i < kwcount; i++) {
2161
2.84k
            arguments[i+argcount] = PyStackRef_FromPyObjectNew(args[i+argcount]);
2162
2.84k
        }
2163
1.12k
    }
2164
22.1M
    _PyInterpreterFrame *frame = _PyEvalFramePushAndInit(
2165
22.1M
        tstate, PyStackRef_FromPyObjectNew(func), locals,
2166
22.1M
        arguments, argcount, kwnames, NULL);
2167
22.1M
    if (total_args > 8) {
2168
86.1k
        PyMem_Free(arguments);
2169
86.1k
    }
2170
22.1M
    if (frame == NULL) {
2171
0
        return NULL;
2172
0
    }
2173
22.1M
    EVAL_CALL_STAT_INC(EVAL_CALL_VECTOR);
2174
22.1M
    return _PyEval_EvalFrame(tstate, frame, 0);
2175
22.1M
}
2176
2177
/* Legacy API */
2178
PyObject *
2179
PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
2180
                  PyObject *const *args, int argcount,
2181
                  PyObject *const *kws, int kwcount,
2182
                  PyObject *const *defs, int defcount,
2183
                  PyObject *kwdefs, PyObject *closure)
2184
0
{
2185
0
    PyThreadState *tstate = _PyThreadState_GET();
2186
0
    PyObject *res = NULL;
2187
0
    PyObject *defaults = PyTuple_FromArray(defs, defcount);
2188
0
    if (defaults == NULL) {
2189
0
        return NULL;
2190
0
    }
2191
0
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
2192
0
    if (builtins == NULL) {
2193
0
        Py_DECREF(defaults);
2194
0
        return NULL;
2195
0
    }
2196
0
    if (locals == NULL) {
2197
0
        locals = globals;
2198
0
    }
2199
0
    PyObject *kwnames = NULL;
2200
0
    PyObject *const *allargs;
2201
0
    PyObject **newargs = NULL;
2202
0
    PyFunctionObject *func = NULL;
2203
0
    if (kwcount == 0) {
2204
0
        allargs = args;
2205
0
    }
2206
0
    else {
2207
0
        kwnames = PyTuple_New(kwcount);
2208
0
        if (kwnames == NULL) {
2209
0
            goto fail;
2210
0
        }
2211
0
        newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
2212
0
        if (newargs == NULL) {
2213
0
            goto fail;
2214
0
        }
2215
0
        for (int i = 0; i < argcount; i++) {
2216
0
            newargs[i] = args[i];
2217
0
        }
2218
0
        for (int i = 0; i < kwcount; i++) {
2219
0
            PyTuple_SET_ITEM(kwnames, i, Py_NewRef(kws[2*i]));
2220
0
            newargs[argcount+i] = kws[2*i+1];
2221
0
        }
2222
0
        allargs = newargs;
2223
0
    }
2224
0
    PyFrameConstructor constr = {
2225
0
        .fc_globals = globals,
2226
0
        .fc_builtins = builtins,
2227
0
        .fc_name = ((PyCodeObject *)_co)->co_name,
2228
0
        .fc_qualname = ((PyCodeObject *)_co)->co_name,
2229
0
        .fc_code = _co,
2230
0
        .fc_defaults = defaults,
2231
0
        .fc_kwdefaults = kwdefs,
2232
0
        .fc_closure = closure
2233
0
    };
2234
0
    func = _PyFunction_FromConstructor(&constr);
2235
0
    if (func == NULL) {
2236
0
        goto fail;
2237
0
    }
2238
0
    EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
2239
0
    res = _PyEval_Vector(tstate, func, locals,
2240
0
                         allargs, argcount,
2241
0
                         kwnames);
2242
0
fail:
2243
0
    Py_XDECREF(func);
2244
0
    Py_XDECREF(kwnames);
2245
0
    PyMem_Free(newargs);
2246
0
    _Py_DECREF_BUILTINS(builtins);
2247
0
    Py_DECREF(defaults);
2248
0
    return res;
2249
0
}
2250
2251
/* Logic for matching an exception in an except* clause (too
2252
   complicated for inlining).
2253
*/
2254
2255
int
2256
_PyEval_ExceptionGroupMatch(_PyInterpreterFrame *frame, PyObject* exc_value,
2257
                            PyObject *match_type, PyObject **match, PyObject **rest)
2258
0
{
2259
0
    if (Py_IsNone(exc_value)) {
2260
0
        *match = Py_NewRef(Py_None);
2261
0
        *rest = Py_NewRef(Py_None);
2262
0
        return 0;
2263
0
    }
2264
0
    assert(PyExceptionInstance_Check(exc_value));
2265
2266
0
    if (PyErr_GivenExceptionMatches(exc_value, match_type)) {
2267
        /* Full match of exc itself */
2268
0
        bool is_eg = _PyBaseExceptionGroup_Check(exc_value);
2269
0
        if (is_eg) {
2270
0
            *match = Py_NewRef(exc_value);
2271
0
        }
2272
0
        else {
2273
            /* naked exception - wrap it */
2274
0
            PyObject *excs = PyTuple_Pack(1, exc_value);
2275
0
            if (excs == NULL) {
2276
0
                return -1;
2277
0
            }
2278
0
            PyObject *wrapped = _PyExc_CreateExceptionGroup("", excs);
2279
0
            Py_DECREF(excs);
2280
0
            if (wrapped == NULL) {
2281
0
                return -1;
2282
0
            }
2283
0
            PyFrameObject *f = _PyFrame_GetFrameObject(frame);
2284
0
            if (f == NULL) {
2285
0
                Py_DECREF(wrapped);
2286
0
                return -1;
2287
0
            }
2288
2289
0
            PyObject *tb = _PyTraceBack_FromFrame(NULL, f);
2290
0
            if (tb == NULL) {
2291
0
                Py_DECREF(wrapped);
2292
0
                return -1;
2293
0
            }
2294
0
            PyException_SetTraceback(wrapped, tb);
2295
0
            Py_DECREF(tb);
2296
2297
0
            *match = wrapped;
2298
0
        }
2299
0
        *rest = Py_NewRef(Py_None);
2300
0
        return 0;
2301
0
    }
2302
2303
    /* exc_value does not match match_type.
2304
     * Check for partial match if it's an exception group.
2305
     */
2306
0
    if (_PyBaseExceptionGroup_Check(exc_value)) {
2307
0
        PyObject *pair = PyObject_CallMethod(exc_value, "split", "(O)",
2308
0
                                             match_type);
2309
0
        if (pair == NULL) {
2310
0
            return -1;
2311
0
        }
2312
2313
0
        if (!PyTuple_CheckExact(pair)) {
2314
0
            PyErr_Format(PyExc_TypeError,
2315
0
                         "%.200s.split must return a tuple, not %.200s",
2316
0
                         Py_TYPE(exc_value)->tp_name, Py_TYPE(pair)->tp_name);
2317
0
            Py_DECREF(pair);
2318
0
            return -1;
2319
0
        }
2320
2321
        // allow tuples of length > 2 for backwards compatibility
2322
0
        if (PyTuple_GET_SIZE(pair) < 2) {
2323
0
            PyErr_Format(PyExc_TypeError,
2324
0
                         "%.200s.split must return a 2-tuple, "
2325
0
                         "got tuple of size %zd",
2326
0
                         Py_TYPE(exc_value)->tp_name, PyTuple_GET_SIZE(pair));
2327
0
            Py_DECREF(pair);
2328
0
            return -1;
2329
0
        }
2330
2331
0
        *match = Py_NewRef(PyTuple_GET_ITEM(pair, 0));
2332
0
        *rest = Py_NewRef(PyTuple_GET_ITEM(pair, 1));
2333
0
        Py_DECREF(pair);
2334
0
        return 0;
2335
0
    }
2336
    /* no match */
2337
0
    *match = Py_NewRef(Py_None);
2338
0
    *rest = Py_NewRef(exc_value);
2339
0
    return 0;
2340
0
}
2341
2342
/* Iterate v argcnt times and store the results on the stack (via decreasing
2343
   sp).  Return 1 for success, 0 if error.
2344
2345
   If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
2346
   with a variable target.
2347
*/
2348
2349
int
2350
_PyEval_UnpackIterableStackRef(PyThreadState *tstate, PyObject *v,
2351
                       int argcnt, int argcntafter, _PyStackRef *sp)
2352
591
{
2353
591
    int i = 0, j = 0;
2354
591
    Py_ssize_t ll = 0;
2355
591
    PyObject *it;  /* iter(v) */
2356
591
    PyObject *w;
2357
591
    PyObject *l = NULL; /* variable list */
2358
591
    assert(v != NULL);
2359
2360
591
    it = PyObject_GetIter(v);
2361
591
    if (it == NULL) {
2362
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
2363
0
            Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
2364
0
        {
2365
0
            _PyErr_Format(tstate, PyExc_TypeError,
2366
0
                          "cannot unpack non-iterable %.200s object",
2367
0
                          Py_TYPE(v)->tp_name);
2368
0
        }
2369
0
        return 0;
2370
0
    }
2371
2372
1.90k
    for (; i < argcnt; i++) {
2373
1.31k
        w = PyIter_Next(it);
2374
1.31k
        if (w == NULL) {
2375
            /* Iterator done, via error or exhaustion. */
2376
0
            if (!_PyErr_Occurred(tstate)) {
2377
0
                if (argcntafter == -1) {
2378
0
                    _PyErr_Format(tstate, PyExc_ValueError,
2379
0
                                  "not enough values to unpack "
2380
0
                                  "(expected %d, got %d)",
2381
0
                                  argcnt, i);
2382
0
                }
2383
0
                else {
2384
0
                    _PyErr_Format(tstate, PyExc_ValueError,
2385
0
                                  "not enough values to unpack "
2386
0
                                  "(expected at least %d, got %d)",
2387
0
                                  argcnt + argcntafter, i);
2388
0
                }
2389
0
            }
2390
0
            goto Error;
2391
0
        }
2392
1.31k
        *--sp = PyStackRef_FromPyObjectSteal(w);
2393
1.31k
    }
2394
2395
591
    if (argcntafter == -1) {
2396
        /* We better have exhausted the iterator now. */
2397
591
        w = PyIter_Next(it);
2398
591
        if (w == NULL) {
2399
591
            if (_PyErr_Occurred(tstate))
2400
0
                goto Error;
2401
591
            Py_DECREF(it);
2402
591
            return 1;
2403
591
        }
2404
0
        Py_DECREF(w);
2405
2406
0
        if (PyList_CheckExact(v) || PyTuple_CheckExact(v)
2407
0
              || PyDict_CheckExact(v)) {
2408
0
            ll = PyDict_CheckExact(v) ? PyDict_Size(v) : Py_SIZE(v);
2409
0
            if (ll > argcnt) {
2410
0
                _PyErr_Format(tstate, PyExc_ValueError,
2411
0
                              "too many values to unpack (expected %d, got %zd)",
2412
0
                              argcnt, ll);
2413
0
                goto Error;
2414
0
            }
2415
0
        }
2416
0
        _PyErr_Format(tstate, PyExc_ValueError,
2417
0
                      "too many values to unpack (expected %d)",
2418
0
                      argcnt);
2419
0
        goto Error;
2420
0
    }
2421
2422
0
    l = PySequence_List(it);
2423
0
    if (l == NULL)
2424
0
        goto Error;
2425
0
    *--sp = PyStackRef_FromPyObjectSteal(l);
2426
0
    i++;
2427
2428
0
    ll = PyList_GET_SIZE(l);
2429
0
    if (ll < argcntafter) {
2430
0
        _PyErr_Format(tstate, PyExc_ValueError,
2431
0
            "not enough values to unpack (expected at least %d, got %zd)",
2432
0
            argcnt + argcntafter, argcnt + ll);
2433
0
        goto Error;
2434
0
    }
2435
2436
    /* Pop the "after-variable" args off the list. */
2437
0
    for (j = argcntafter; j > 0; j--, i++) {
2438
0
        *--sp = PyStackRef_FromPyObjectSteal(PyList_GET_ITEM(l, ll - j));
2439
0
    }
2440
    /* Resize the list. */
2441
0
    Py_SET_SIZE(l, ll - argcntafter);
2442
0
    Py_DECREF(it);
2443
0
    return 1;
2444
2445
0
Error:
2446
0
    for (; i > 0; i--, sp++) {
2447
0
        PyStackRef_CLOSE(*sp);
2448
0
    }
2449
0
    Py_XDECREF(it);
2450
0
    return 0;
2451
0
}
2452
2453
2454
2455
void
2456
_PyEval_MonitorRaise(PyThreadState *tstate, _PyInterpreterFrame *frame,
2457
              _Py_CODEUNIT *instr)
2458
3.41M
{
2459
3.41M
    if (no_tools_for_local_event(tstate, frame, PY_MONITORING_EVENT_RAISE)) {
2460
3.41M
        return;
2461
3.41M
    }
2462
0
    do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RAISE);
2463
0
}
2464
2465
bool
2466
_PyEval_NoToolsForUnwind(PyThreadState *tstate, _PyInterpreterFrame *frame)
2467
41.8k
{
2468
41.8k
    return no_tools_for_local_event(tstate, frame, PY_MONITORING_EVENT_PY_UNWIND);
2469
41.8k
}
2470
2471
2472
void
2473
PyThreadState_EnterTracing(PyThreadState *tstate)
2474
0
{
2475
0
    assert(tstate->tracing >= 0);
2476
0
    tstate->tracing++;
2477
0
}
2478
2479
void
2480
PyThreadState_LeaveTracing(PyThreadState *tstate)
2481
0
{
2482
0
    assert(tstate->tracing > 0);
2483
0
    tstate->tracing--;
2484
0
}
2485
2486
2487
PyObject*
2488
_PyEval_CallTracing(PyObject *func, PyObject *args)
2489
0
{
2490
    // Save and disable tracing
2491
0
    PyThreadState *tstate = _PyThreadState_GET();
2492
0
    int save_tracing = tstate->tracing;
2493
0
    tstate->tracing = 0;
2494
2495
    // Call the tracing function
2496
0
    PyObject *result = PyObject_Call(func, args, NULL);
2497
2498
    // Restore tracing
2499
0
    tstate->tracing = save_tracing;
2500
0
    return result;
2501
0
}
2502
2503
void
2504
PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
2505
0
{
2506
0
    PyThreadState *tstate = _PyThreadState_GET();
2507
0
    if (_PyEval_SetProfile(tstate, func, arg) < 0) {
2508
        /* Log _PySys_Audit() error */
2509
0
        PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfile");
2510
0
    }
2511
0
}
2512
2513
void
2514
PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *arg)
2515
0
{
2516
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2517
0
    if (_PyEval_SetProfileAllThreads(interp, func, arg) < 0) {
2518
        /* Log _PySys_Audit() error */
2519
0
        PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfileAllThreads");
2520
0
    }
2521
0
}
2522
2523
void
2524
PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
2525
0
{
2526
0
    PyThreadState *tstate = _PyThreadState_GET();
2527
0
    if (_PyEval_SetTrace(tstate, func, arg) < 0) {
2528
        /* Log _PySys_Audit() error */
2529
0
        PyErr_FormatUnraisable("Exception ignored in PyEval_SetTrace");
2530
0
    }
2531
0
}
2532
2533
void
2534
PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *arg)
2535
0
{
2536
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2537
0
    if (_PyEval_SetTraceAllThreads(interp, func, arg) < 0) {
2538
        /* Log _PySys_Audit() error */
2539
0
        PyErr_FormatUnraisable("Exception ignored in PyEval_SetTraceAllThreads");
2540
0
    }
2541
0
}
2542
2543
int
2544
_PyEval_SetCoroutineOriginTrackingDepth(int depth)
2545
0
{
2546
0
    PyThreadState *tstate = _PyThreadState_GET();
2547
0
    if (depth < 0) {
2548
0
        _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
2549
0
        return -1;
2550
0
    }
2551
0
    tstate->coroutine_origin_tracking_depth = depth;
2552
0
    return 0;
2553
0
}
2554
2555
2556
int
2557
_PyEval_GetCoroutineOriginTrackingDepth(void)
2558
0
{
2559
0
    PyThreadState *tstate = _PyThreadState_GET();
2560
0
    return tstate->coroutine_origin_tracking_depth;
2561
0
}
2562
2563
int
2564
_PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
2565
0
{
2566
0
    PyThreadState *tstate = _PyThreadState_GET();
2567
2568
0
    if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
2569
0
        return -1;
2570
0
    }
2571
2572
0
    Py_XSETREF(tstate->async_gen_firstiter, Py_XNewRef(firstiter));
2573
0
    return 0;
2574
0
}
2575
2576
PyObject *
2577
_PyEval_GetAsyncGenFirstiter(void)
2578
0
{
2579
0
    PyThreadState *tstate = _PyThreadState_GET();
2580
0
    return tstate->async_gen_firstiter;
2581
0
}
2582
2583
int
2584
_PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
2585
0
{
2586
0
    PyThreadState *tstate = _PyThreadState_GET();
2587
2588
0
    if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
2589
0
        return -1;
2590
0
    }
2591
2592
0
    Py_XSETREF(tstate->async_gen_finalizer, Py_XNewRef(finalizer));
2593
0
    return 0;
2594
0
}
2595
2596
PyObject *
2597
_PyEval_GetAsyncGenFinalizer(void)
2598
0
{
2599
0
    PyThreadState *tstate = _PyThreadState_GET();
2600
0
    return tstate->async_gen_finalizer;
2601
0
}
2602
2603
_PyInterpreterFrame *
2604
_PyEval_GetFrame(void)
2605
1.96k
{
2606
1.96k
    PyThreadState *tstate = _PyThreadState_GET();
2607
1.96k
    return _PyThreadState_GetFrame(tstate);
2608
1.96k
}
2609
2610
PyFrameObject *
2611
PyEval_GetFrame(void)
2612
0
{
2613
0
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
2614
0
    if (frame == NULL) {
2615
0
        return NULL;
2616
0
    }
2617
0
    PyFrameObject *f = _PyFrame_GetFrameObject(frame);
2618
0
    if (f == NULL) {
2619
0
        PyErr_Clear();
2620
0
    }
2621
0
    return f;
2622
0
}
2623
2624
PyObject *
2625
_PyEval_GetBuiltins(PyThreadState *tstate)
2626
554
{
2627
554
    _PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
2628
554
    if (frame != NULL) {
2629
512
        return frame->f_builtins;
2630
512
    }
2631
42
    return tstate->interp->builtins;
2632
554
}
2633
2634
PyObject *
2635
PyEval_GetBuiltins(void)
2636
554
{
2637
554
    PyThreadState *tstate = _PyThreadState_GET();
2638
554
    return _PyEval_GetBuiltins(tstate);
2639
554
}
2640
2641
/* Convenience function to get a builtin from its name */
2642
PyObject *
2643
_PyEval_GetBuiltin(PyObject *name)
2644
0
{
2645
0
    PyObject *attr;
2646
0
    if (PyMapping_GetOptionalItem(PyEval_GetBuiltins(), name, &attr) == 0) {
2647
0
        PyErr_SetObject(PyExc_AttributeError, name);
2648
0
    }
2649
0
    return attr;
2650
0
}
2651
2652
PyObject *
2653
PyEval_GetLocals(void)
2654
0
{
2655
    // We need to return a borrowed reference here, so some tricks are needed
2656
0
    PyThreadState *tstate = _PyThreadState_GET();
2657
0
     _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2658
0
    if (current_frame == NULL) {
2659
0
        _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2660
0
        return NULL;
2661
0
    }
2662
2663
    // Be aware that this returns a new reference
2664
0
    PyObject *locals = _PyFrame_GetLocals(current_frame);
2665
2666
0
    if (locals == NULL) {
2667
0
        return NULL;
2668
0
    }
2669
2670
0
    if (PyFrameLocalsProxy_Check(locals)) {
2671
0
        PyFrameObject *f = _PyFrame_GetFrameObject(current_frame);
2672
0
        if (f == NULL) {
2673
0
            Py_DECREF(locals);
2674
0
            return NULL;
2675
0
        }
2676
2677
0
        PyObject *ret = f->f_locals_cache;
2678
0
        if (ret == NULL) {
2679
0
            ret = PyDict_New();
2680
0
            if (ret == NULL) {
2681
0
                Py_DECREF(locals);
2682
0
                return NULL;
2683
0
            }
2684
0
            f->f_locals_cache = ret;
2685
0
        }
2686
0
        if (PyDict_Update(ret, locals) < 0) {
2687
            // At this point, if the cache dict is broken, it will stay broken, as
2688
            // trying to clean it up or replace it will just cause other problems
2689
0
            ret = NULL;
2690
0
        }
2691
0
        Py_DECREF(locals);
2692
0
        return ret;
2693
0
    }
2694
2695
0
    assert(PyMapping_Check(locals));
2696
0
    assert(Py_REFCNT(locals) > 1);
2697
0
    Py_DECREF(locals);
2698
2699
0
    return locals;
2700
0
}
2701
2702
PyObject *
2703
_PyEval_GetFrameLocals(void)
2704
4
{
2705
4
    PyThreadState *tstate = _PyThreadState_GET();
2706
4
     _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2707
4
    if (current_frame == NULL) {
2708
0
        _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2709
0
        return NULL;
2710
0
    }
2711
2712
4
    PyObject *locals = _PyFrame_GetLocals(current_frame);
2713
4
    if (locals == NULL) {
2714
0
        return NULL;
2715
0
    }
2716
2717
4
    if (PyFrameLocalsProxy_Check(locals)) {
2718
0
        PyObject* ret = PyDict_New();
2719
0
        if (ret == NULL) {
2720
0
            Py_DECREF(locals);
2721
0
            return NULL;
2722
0
        }
2723
0
        if (PyDict_Update(ret, locals) < 0) {
2724
0
            Py_DECREF(ret);
2725
0
            Py_DECREF(locals);
2726
0
            return NULL;
2727
0
        }
2728
0
        Py_DECREF(locals);
2729
0
        return ret;
2730
0
    }
2731
2732
4
    assert(PyMapping_Check(locals));
2733
4
    return locals;
2734
4
}
2735
2736
static PyObject *
2737
_PyEval_GetGlobals(PyThreadState *tstate)
2738
143k
{
2739
143k
    _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2740
143k
    if (current_frame == NULL) {
2741
52.4k
        return NULL;
2742
52.4k
    }
2743
90.6k
    return current_frame->f_globals;
2744
143k
}
2745
2746
PyObject *
2747
PyEval_GetGlobals(void)
2748
143k
{
2749
143k
    PyThreadState *tstate = _PyThreadState_GET();
2750
143k
    return _PyEval_GetGlobals(tstate);
2751
143k
}
2752
2753
PyObject *
2754
_PyEval_GetGlobalsFromRunningMain(PyThreadState *tstate)
2755
0
{
2756
0
    if (!_PyInterpreterState_IsRunningMain(tstate->interp)) {
2757
0
        return NULL;
2758
0
    }
2759
0
    PyObject *mod = _Py_GetMainModule(tstate);
2760
0
    if (_Py_CheckMainModule(mod) < 0) {
2761
0
        Py_XDECREF(mod);
2762
0
        return NULL;
2763
0
    }
2764
0
    PyObject *globals = PyModule_GetDict(mod);  // borrowed
2765
0
    Py_DECREF(mod);
2766
0
    return globals;
2767
0
}
2768
2769
static PyObject *
2770
get_globals_builtins(PyObject *globals)
2771
52.9k
{
2772
52.9k
    PyObject *builtins = NULL;
2773
52.9k
    if (PyAnyDict_Check(globals)) {
2774
52.9k
        if (PyDict_GetItemRef(globals, &_Py_ID(__builtins__), &builtins) < 0) {
2775
0
            return NULL;
2776
0
        }
2777
52.9k
    }
2778
0
    else {
2779
0
        if (PyMapping_GetOptionalItem(
2780
0
                        globals, &_Py_ID(__builtins__), &builtins) < 0)
2781
0
        {
2782
0
            return NULL;
2783
0
        }
2784
0
    }
2785
52.9k
    return builtins;
2786
52.9k
}
2787
2788
static int
2789
set_globals_builtins(PyObject *globals, PyObject *builtins)
2790
52.9k
{
2791
52.9k
    if (PyDict_Check(globals)) {
2792
52.9k
        if (PyDict_SetItem(globals, &_Py_ID(__builtins__), builtins) < 0) {
2793
0
            return -1;
2794
0
        }
2795
52.9k
    }
2796
0
    else {
2797
0
        if (PyObject_SetItem(globals, &_Py_ID(__builtins__), builtins) < 0) {
2798
0
            if (PyFrozenDict_Check(globals)) {
2799
0
                PyErr_SetString(PyExc_TypeError,
2800
0
                                "cannot assign __builtins__ to frozendict globals");
2801
0
            }
2802
0
            return -1;
2803
0
        }
2804
0
    }
2805
52.9k
    return 0;
2806
52.9k
}
2807
2808
int
2809
_PyEval_EnsureBuiltins(PyThreadState *tstate, PyObject *globals,
2810
                       PyObject **p_builtins)
2811
525
{
2812
525
    PyObject *builtins = get_globals_builtins(globals);
2813
525
    if (builtins == NULL) {
2814
512
        if (_PyErr_Occurred(tstate)) {
2815
0
            return -1;
2816
0
        }
2817
512
        builtins = PyEval_GetBuiltins();  // borrowed
2818
512
        if (builtins == NULL) {
2819
0
            assert(_PyErr_Occurred(tstate));
2820
0
            return -1;
2821
0
        }
2822
512
        Py_INCREF(builtins);
2823
512
        if (set_globals_builtins(globals, builtins) < 0) {
2824
0
            Py_DECREF(builtins);
2825
0
            return -1;
2826
0
        }
2827
512
    }
2828
525
    if (p_builtins != NULL) {
2829
0
        *p_builtins = builtins;
2830
0
    }
2831
525
    else {
2832
525
        Py_DECREF(builtins);
2833
525
    }
2834
525
    return 0;
2835
525
}
2836
2837
int
2838
_PyEval_EnsureBuiltinsWithModule(PyThreadState *tstate, PyObject *globals,
2839
                                 PyObject **p_builtins)
2840
52.4k
{
2841
52.4k
    PyObject *builtins = get_globals_builtins(globals);
2842
52.4k
    if (builtins == NULL) {
2843
52.4k
        if (_PyErr_Occurred(tstate)) {
2844
0
            return -1;
2845
0
        }
2846
52.4k
        builtins = PyImport_ImportModuleLevel("builtins", NULL, NULL, NULL, 0);
2847
52.4k
        if (builtins == NULL) {
2848
0
            return -1;
2849
0
        }
2850
52.4k
        if (set_globals_builtins(globals, builtins) < 0) {
2851
0
            Py_DECREF(builtins);
2852
0
            return -1;
2853
0
        }
2854
52.4k
    }
2855
52.4k
    if (p_builtins != NULL) {
2856
52.4k
        *p_builtins = builtins;
2857
52.4k
    }
2858
0
    else {
2859
0
        Py_DECREF(builtins);
2860
0
    }
2861
52.4k
    return 0;
2862
52.4k
}
2863
2864
PyObject*
2865
PyEval_GetFrameLocals(void)
2866
0
{
2867
0
    return _PyEval_GetFrameLocals();
2868
0
}
2869
2870
PyObject* PyEval_GetFrameGlobals(void)
2871
0
{
2872
0
    PyThreadState *tstate = _PyThreadState_GET();
2873
0
    _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2874
0
    if (current_frame == NULL) {
2875
0
        return NULL;
2876
0
    }
2877
0
    return Py_XNewRef(current_frame->f_globals);
2878
0
}
2879
2880
PyObject* PyEval_GetFrameBuiltins(void)
2881
0
{
2882
0
    PyThreadState *tstate = _PyThreadState_GET();
2883
0
    return Py_XNewRef(_PyEval_GetBuiltins(tstate));
2884
0
}
2885
2886
int
2887
PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
2888
50
{
2889
50
    PyThreadState *tstate = _PyThreadState_GET();
2890
50
    _PyInterpreterFrame *current_frame = tstate->current_frame;
2891
50
    if (current_frame == tstate->base_frame) {
2892
0
        current_frame = NULL;
2893
0
    }
2894
50
    int result = cf->cf_flags != 0;
2895
2896
50
    if (current_frame != NULL) {
2897
50
        const int codeflags = _PyFrame_GetCode(current_frame)->co_flags;
2898
50
        const int compilerflags = codeflags & PyCF_MASK;
2899
50
        if (compilerflags) {
2900
0
            result = 1;
2901
0
            cf->cf_flags |= compilerflags;
2902
0
        }
2903
50
    }
2904
50
    return result;
2905
50
}
2906
2907
2908
const char *
2909
PyEval_GetFuncName(PyObject *func)
2910
0
{
2911
0
    if (PyMethod_Check(func))
2912
0
        return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
2913
0
    else if (PyFunction_Check(func))
2914
0
        return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
2915
0
    else if (PyCFunction_Check(func))
2916
0
        return ((PyCFunctionObject*)func)->m_ml->ml_name;
2917
0
    else
2918
0
        return Py_TYPE(func)->tp_name;
2919
0
}
2920
2921
const char *
2922
PyEval_GetFuncDesc(PyObject *func)
2923
0
{
2924
0
    if (PyMethod_Check(func))
2925
0
        return "()";
2926
0
    else if (PyFunction_Check(func))
2927
0
        return "()";
2928
0
    else if (PyCFunction_Check(func))
2929
0
        return "()";
2930
0
    else
2931
0
        return " object";
2932
0
}
2933
2934
/* Extract a slice index from a PyLong or an object with the
2935
   nb_index slot defined, and store in *pi.
2936
   Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
2937
   and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
2938
   Return 0 on error, 1 on success.
2939
*/
2940
int
2941
_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
2942
4.76M
{
2943
4.76M
    if (Py_IsNone(v)) {
2944
426k
        return 1;
2945
426k
    }
2946
4.33M
    return _PyEval_SliceIndexNotNone(v, pi);
2947
4.76M
}
2948
2949
int
2950
_PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
2951
4.33M
{
2952
4.33M
    PyThreadState *tstate = _PyThreadState_GET();
2953
4.33M
    Py_ssize_t x;
2954
4.33M
    if (PyLong_CheckExact(v) && _PyLong_IsCompact((PyLongObject *)v)) {
2955
4.33M
        *pi = _PyLong_CompactValue((PyLongObject *)v);
2956
4.33M
        return 1;
2957
4.33M
    }
2958
1.81k
    if (_PyIndex_Check(v)) {
2959
772
        x = PyNumber_AsSsize_t(v, NULL);
2960
772
        if (x == -1 && _PyErr_Occurred(tstate))
2961
0
            return 0;
2962
772
    }
2963
1.04k
    else {
2964
1.04k
        _PyErr_SetString(tstate, PyExc_TypeError,
2965
1.04k
                         "slice indices must be integers or "
2966
1.04k
                         "have an __index__ method");
2967
1.04k
        return 0;
2968
1.04k
    }
2969
772
    *pi = x;
2970
772
    return 1;
2971
1.81k
}
2972
2973
int
2974
_PyEval_UnpackIndices(PyObject *start, PyObject *stop,
2975
                      Py_ssize_t len,
2976
                      Py_ssize_t *istart, Py_ssize_t *istop)
2977
442k
{
2978
442k
    if (len < 0) {
2979
0
        return 0;
2980
0
    }
2981
442k
    *istart = 0;
2982
442k
    *istop = PY_SSIZE_T_MAX;
2983
442k
    if (!_PyEval_SliceIndex(start, istart)) {
2984
0
        return 0;
2985
0
    }
2986
442k
    if (!_PyEval_SliceIndex(stop, istop)) {
2987
0
        return 0;
2988
0
    }
2989
442k
    PySlice_AdjustIndices(len, istart, istop, 1);
2990
442k
    return 1;
2991
442k
}
2992
2993
PyObject *
2994
_PyEval_ImportName(PyThreadState *tstate, PyObject *builtins,
2995
            PyObject *globals, PyObject *locals, PyObject *name,
2996
            PyObject *fromlist, PyObject *level)
2997
1.73M
{
2998
1.73M
    PyObject *import_func;
2999
1.73M
    if (PyMapping_GetOptionalItem(builtins, &_Py_ID(__import__),
3000
1.73M
                                  &import_func) < 0) {
3001
0
        return NULL;
3002
0
    }
3003
1.73M
    if (import_func == NULL) {
3004
0
        _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
3005
0
        return NULL;
3006
0
    }
3007
3008
1.73M
    PyObject *res = _PyEval_ImportNameWithImport(
3009
1.73M
        tstate, import_func, globals, locals, name, fromlist, level);
3010
1.73M
    Py_DECREF(import_func);
3011
1.73M
    return res;
3012
1.73M
}
3013
3014
PyObject *
3015
_PyEval_ImportNameWithImport(PyThreadState *tstate, PyObject *import_func,
3016
                             PyObject *globals, PyObject *locals,
3017
                             PyObject *name, PyObject *fromlist, PyObject *level)
3018
1.73M
{
3019
1.73M
    if (locals == NULL) {
3020
1.73M
        locals = Py_None;
3021
1.73M
    }
3022
3023
    /* Fast path for not overloaded __import__. */
3024
1.73M
    if (_PyImport_IsDefaultImportFunc(tstate->interp, import_func)) {
3025
1.73M
        int ilevel = PyLong_AsInt(level);
3026
1.73M
        if (ilevel == -1 && _PyErr_Occurred(tstate)) {
3027
0
            return NULL;
3028
0
        }
3029
1.73M
        return PyImport_ImportModuleLevelObject(
3030
1.73M
                        name,
3031
1.73M
                        globals,
3032
1.73M
                        locals,
3033
1.73M
                        fromlist,
3034
1.73M
                        ilevel);
3035
1.73M
    }
3036
3037
0
    PyObject *args[5] = {name, globals, locals, fromlist, level};
3038
0
    PyObject *res = PyObject_Vectorcall(import_func, args, 5, NULL);
3039
0
    return res;
3040
1.73M
}
3041
3042
static int
3043
check_lazy_import_compatibility(PyThreadState *tstate, PyObject *globals,
3044
                               PyObject *name, PyObject *level)
3045
1.44k
{
3046
     // Check if this module should be imported lazily due to
3047
     // the compatibility mode support via __lazy_modules__.
3048
1.44k
    PyObject *lazy_modules = NULL;
3049
1.44k
    PyObject *abs_name = NULL;
3050
1.44k
    int res = -1;
3051
3052
1.44k
    if (globals != NULL &&
3053
1.44k
        PyMapping_GetOptionalItem(globals, &_Py_ID(__lazy_modules__),
3054
1.44k
                                  &lazy_modules) < 0)
3055
0
    {
3056
0
        return -1;
3057
0
    }
3058
1.44k
    if (lazy_modules == NULL) {
3059
1.44k
        assert(!PyErr_Occurred());
3060
1.44k
        return 0;
3061
1.44k
    }
3062
3063
0
    int ilevel = PyLong_AsInt(level);
3064
0
    if (ilevel == -1 && _PyErr_Occurred(tstate)) {
3065
0
        goto error;
3066
0
    }
3067
3068
0
    abs_name = _PyImport_GetAbsName(tstate, name, globals, ilevel);
3069
0
    if (abs_name == NULL) {
3070
0
        goto error;
3071
0
    }
3072
3073
0
    res = PySequence_Contains(lazy_modules, abs_name);
3074
0
error:
3075
0
    Py_XDECREF(abs_name);
3076
0
    Py_XDECREF(lazy_modules);
3077
0
    return res;
3078
0
}
3079
3080
static int
3081
is_lazy_import_module_level(void)
3082
1.44k
{
3083
1.44k
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
3084
1.44k
    return frame != NULL && frame->f_globals == frame->f_locals;
3085
1.44k
}
3086
3087
PyObject *
3088
_PyEval_LazyImportName(PyThreadState *tstate, PyObject *builtins,
3089
                       PyObject *globals, PyObject *locals, PyObject *name,
3090
                       PyObject *fromlist, PyObject *level, int lazy)
3091
1.54k
{
3092
1.54k
    PyObject *res = NULL;
3093
    // Check if global policy overrides the local syntax
3094
1.54k
    switch (PyImport_GetLazyImportsMode()) {
3095
0
        case PyImport_LAZY_ALL:
3096
0
            if (!lazy) {
3097
0
                lazy = is_lazy_import_module_level();
3098
0
            }
3099
0
            break;
3100
1.54k
        case PyImport_LAZY_NORMAL:
3101
1.54k
            break;
3102
1.54k
    }
3103
3104
1.54k
    if (!lazy) {
3105
        // See if __lazy_modules__ forces this to be lazy.
3106
        // __lazy_modules__ only applies at module level; exec() inside
3107
        // functions or classes should remain eager.
3108
1.44k
        if (is_lazy_import_module_level()) {
3109
1.44k
            lazy = check_lazy_import_compatibility(tstate, globals, name, level);
3110
1.44k
            if (lazy < 0) {
3111
0
                return NULL;
3112
0
            }
3113
1.44k
        }
3114
1.44k
    }
3115
3116
1.54k
    if (!lazy) {
3117
        // Not a lazy import or lazy imports are disabled, fallback to the
3118
        // regular import.
3119
1.44k
        return _PyEval_ImportName(tstate, builtins, globals, locals,
3120
1.44k
                                  name, fromlist, level);
3121
1.44k
    }
3122
3123
100
    PyObject *lazy_import_func;
3124
100
    if (PyMapping_GetOptionalItem(builtins, &_Py_ID(__lazy_import__),
3125
100
                                  &lazy_import_func) < 0) {
3126
0
        goto error;
3127
0
    }
3128
100
    if (lazy_import_func == NULL) {
3129
0
        assert(!PyErr_Occurred());
3130
0
        _PyErr_SetString(tstate, PyExc_ImportError,
3131
0
                         "__lazy_import__ not found");
3132
0
        goto error;
3133
0
    }
3134
3135
100
    if (locals == NULL) {
3136
0
        locals = Py_None;
3137
0
    }
3138
3139
100
    if (_PyImport_IsDefaultLazyImportFunc(tstate->interp, lazy_import_func)) {
3140
100
        int ilevel = PyLong_AsInt(level);
3141
100
        if (ilevel == -1 && PyErr_Occurred()) {
3142
0
            goto error;
3143
0
        }
3144
3145
100
        res = _PyImport_LazyImportModuleLevelObject(
3146
100
            tstate, name, builtins, globals, locals, fromlist, ilevel
3147
100
        );
3148
100
        goto error;
3149
100
    }
3150
3151
0
    PyObject *args[6] = {name, globals, locals, fromlist, level, builtins};
3152
0
    res = PyObject_Vectorcall(lazy_import_func, args, 6, NULL);
3153
100
error:
3154
100
    Py_XDECREF(lazy_import_func);
3155
100
    return res;
3156
0
}
3157
3158
PyObject *
3159
_PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
3160
1.37k
{
3161
1.37k
    PyObject *x;
3162
1.37k
    PyObject *fullmodname, *mod_name, *origin, *mod_name_or_unknown, *errmsg, *spec;
3163
3164
1.37k
    if (PyObject_GetOptionalAttr(v, name, &x) != 0) {
3165
1.37k
        return x;
3166
1.37k
    }
3167
    /* Issue #17636: in case this failed because of a circular relative
3168
       import, try to fallback on reading the module directly from
3169
       sys.modules. */
3170
4
    if (PyObject_GetOptionalAttr(v, &_Py_ID(__name__), &mod_name) < 0) {
3171
0
        return NULL;
3172
0
    }
3173
4
    if (mod_name == NULL || !PyUnicode_Check(mod_name)) {
3174
0
        Py_CLEAR(mod_name);
3175
0
        goto error;
3176
0
    }
3177
4
    fullmodname = PyUnicode_FromFormat("%U.%U", mod_name, name);
3178
4
    if (fullmodname == NULL) {
3179
0
        Py_DECREF(mod_name);
3180
0
        return NULL;
3181
0
    }
3182
4
    x = PyImport_GetModule(fullmodname);
3183
4
    Py_DECREF(fullmodname);
3184
4
    if (x == NULL && !_PyErr_Occurred(tstate)) {
3185
4
        goto error;
3186
4
    }
3187
0
    Py_DECREF(mod_name);
3188
0
    return x;
3189
3190
4
 error:
3191
4
    if (mod_name == NULL) {
3192
0
        mod_name_or_unknown = PyUnicode_FromString("<unknown module name>");
3193
0
        if (mod_name_or_unknown == NULL) {
3194
0
            return NULL;
3195
0
        }
3196
4
    } else {
3197
4
        mod_name_or_unknown = mod_name;
3198
4
    }
3199
    // mod_name is no longer an owned reference
3200
4
    assert(mod_name_or_unknown);
3201
4
    assert(mod_name == NULL || mod_name == mod_name_or_unknown);
3202
3203
4
    origin = NULL;
3204
4
    if (PyObject_GetOptionalAttr(v, &_Py_ID(__spec__), &spec) < 0) {
3205
0
        Py_DECREF(mod_name_or_unknown);
3206
0
        return NULL;
3207
0
    }
3208
4
    if (spec == NULL) {
3209
0
        errmsg = PyUnicode_FromFormat(
3210
0
            "cannot import name %R from %R (unknown location)",
3211
0
            name, mod_name_or_unknown
3212
0
        );
3213
0
        goto done_with_errmsg;
3214
0
    }
3215
4
    if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
3216
0
        goto done;
3217
0
    }
3218
3219
4
    int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
3220
4
    if (is_possibly_shadowing < 0) {
3221
0
        goto done;
3222
0
    }
3223
4
    int is_possibly_shadowing_stdlib = 0;
3224
4
    if (is_possibly_shadowing) {
3225
0
        PyObject *stdlib_modules;
3226
0
        if (PySys_GetOptionalAttrString("stdlib_module_names", &stdlib_modules) < 0) {
3227
0
            goto done;
3228
0
        }
3229
0
        if (stdlib_modules && PyAnySet_Check(stdlib_modules)) {
3230
0
            is_possibly_shadowing_stdlib = PySet_Contains(stdlib_modules, mod_name_or_unknown);
3231
0
            if (is_possibly_shadowing_stdlib < 0) {
3232
0
                Py_DECREF(stdlib_modules);
3233
0
                goto done;
3234
0
            }
3235
0
        }
3236
0
        Py_XDECREF(stdlib_modules);
3237
0
    }
3238
3239
4
    if (origin == NULL && PyModule_Check(v)) {
3240
        // Fall back to __file__ for diagnostics if we don't have
3241
        // an origin that is a location
3242
4
        origin = PyModule_GetFilenameObject(v);
3243
4
        if (origin == NULL) {
3244
4
            if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
3245
0
                goto done;
3246
0
            }
3247
            // PyModule_GetFilenameObject raised "module filename missing"
3248
4
            _PyErr_Clear(tstate);
3249
4
        }
3250
4
        assert(origin == NULL || PyUnicode_Check(origin));
3251
4
    }
3252
3253
4
    if (is_possibly_shadowing_stdlib) {
3254
0
        assert(origin);
3255
0
        errmsg = PyUnicode_FromFormat(
3256
0
            "cannot import name %R from %R "
3257
0
            "(consider renaming %R since it has the same "
3258
0
            "name as the standard library module named %R "
3259
0
            "and prevents importing that standard library module)",
3260
0
            name, mod_name_or_unknown, origin, mod_name_or_unknown
3261
0
        );
3262
0
    }
3263
4
    else {
3264
4
        int rc = _PyModuleSpec_IsInitializing(spec);
3265
4
        if (rc < 0) {
3266
0
            goto done;
3267
0
        }
3268
4
        else if (rc > 0) {
3269
0
            if (is_possibly_shadowing) {
3270
0
                assert(origin);
3271
                // For non-stdlib modules, only mention the possibility of
3272
                // shadowing if the module is being initialized.
3273
0
                errmsg = PyUnicode_FromFormat(
3274
0
                    "cannot import name %R from %R "
3275
0
                    "(consider renaming %R if it has the same name "
3276
0
                    "as a library you intended to import)",
3277
0
                    name, mod_name_or_unknown, origin
3278
0
                );
3279
0
            }
3280
0
            else if (origin) {
3281
0
                errmsg = PyUnicode_FromFormat(
3282
0
                    "cannot import name %R from partially initialized module %R "
3283
0
                    "(most likely due to a circular import) (%S)",
3284
0
                    name, mod_name_or_unknown, origin
3285
0
                );
3286
0
            }
3287
0
            else {
3288
0
                errmsg = PyUnicode_FromFormat(
3289
0
                    "cannot import name %R from partially initialized module %R "
3290
0
                    "(most likely due to a circular import)",
3291
0
                    name, mod_name_or_unknown
3292
0
                );
3293
0
            }
3294
0
        }
3295
4
        else {
3296
4
            assert(rc == 0);
3297
4
            if (origin) {
3298
0
                errmsg = PyUnicode_FromFormat(
3299
0
                    "cannot import name %R from %R (%S)",
3300
0
                    name, mod_name_or_unknown, origin
3301
0
                );
3302
0
            }
3303
4
            else {
3304
4
                errmsg = PyUnicode_FromFormat(
3305
4
                    "cannot import name %R from %R (unknown location)",
3306
4
                    name, mod_name_or_unknown
3307
4
                );
3308
4
            }
3309
4
        }
3310
4
    }
3311
3312
4
done_with_errmsg:
3313
4
    if (errmsg != NULL) {
3314
        /* NULL checks for mod_name and origin done by _PyErr_SetImportErrorWithNameFrom */
3315
4
        _PyErr_SetImportErrorWithNameFrom(errmsg, mod_name, origin, name);
3316
4
        Py_DECREF(errmsg);
3317
4
    }
3318
3319
4
done:
3320
4
    Py_XDECREF(origin);
3321
4
    Py_XDECREF(spec);
3322
4
    Py_DECREF(mod_name_or_unknown);
3323
4
    return NULL;
3324
4
}
3325
3326
PyObject *
3327
_PyEval_LazyImportFrom(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *v, PyObject *name)
3328
12
{
3329
12
    assert(PyLazyImport_CheckExact(v));
3330
12
    assert(name);
3331
12
    assert(PyUnicode_Check(name));
3332
12
    PyObject *ret;
3333
12
    PyLazyImportObject *d = (PyLazyImportObject *)v;
3334
12
    PyObject *mod = PyImport_GetModule(d->lz_from);
3335
12
    if (mod != NULL) {
3336
        // Check if the module already has the attribute, if so, resolve it
3337
        // eagerly.
3338
0
        if (PyModule_Check(mod)) {
3339
0
            PyObject *mod_dict = PyModule_GetDict(mod);
3340
0
            if (mod_dict != NULL) {
3341
0
                if (PyDict_GetItemRef(mod_dict, name, &ret) < 0) {
3342
0
                    Py_DECREF(mod);
3343
0
                    return NULL;
3344
0
                }
3345
0
                if (ret != NULL) {
3346
0
                    Py_DECREF(mod);
3347
0
                    return ret;
3348
0
                }
3349
0
            }
3350
0
        }
3351
0
        Py_DECREF(mod);
3352
0
    }
3353
3354
12
    if (d->lz_attr != NULL) {
3355
12
        if (PyUnicode_Check(d->lz_attr)) {
3356
0
            PyObject *from = PyUnicode_FromFormat(
3357
0
                "%U.%U", d->lz_from, d->lz_attr);
3358
0
            if (from == NULL) {
3359
0
                return NULL;
3360
0
            }
3361
0
            ret = _PyLazyImport_New(frame, d->lz_builtins, from, name);
3362
0
            Py_DECREF(from);
3363
0
            return ret;
3364
0
        }
3365
12
    }
3366
0
    else {
3367
0
        Py_ssize_t dot = PyUnicode_FindChar(
3368
0
            d->lz_from, '.', 0, PyUnicode_GET_LENGTH(d->lz_from), 1
3369
0
        );
3370
0
        if (dot >= 0) {
3371
0
            PyObject *from = PyUnicode_Substring(d->lz_from, 0, dot);
3372
0
            if (from == NULL) {
3373
0
                return NULL;
3374
0
            }
3375
0
            ret = _PyLazyImport_New(frame, d->lz_builtins, from, name);
3376
0
            Py_DECREF(from);
3377
0
            return ret;
3378
0
        }
3379
0
    }
3380
12
    ret = _PyLazyImport_New(frame, d->lz_builtins, d->lz_from, name);
3381
12
    return ret;
3382
12
}
3383
3384
0
#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
3385
0
                         "BaseException is not allowed"
3386
3387
0
#define CANNOT_EXCEPT_STAR_EG "catching ExceptionGroup with except* "\
3388
0
                              "is not allowed. Use except instead."
3389
3390
int
3391
_PyEval_CheckExceptTypeValid(PyThreadState *tstate, PyObject* right)
3392
74.8k
{
3393
74.8k
    if (PyTuple_Check(right)) {
3394
1.36k
        Py_ssize_t i, length;
3395
1.36k
        length = PyTuple_GET_SIZE(right);
3396
4.09k
        for (i = 0; i < length; i++) {
3397
2.72k
            PyObject *exc = PyTuple_GET_ITEM(right, i);
3398
2.72k
            if (!PyExceptionClass_Check(exc)) {
3399
0
                _PyErr_SetString(tstate, PyExc_TypeError,
3400
0
                    CANNOT_CATCH_MSG);
3401
0
                return -1;
3402
0
            }
3403
2.72k
        }
3404
1.36k
    }
3405
73.4k
    else {
3406
73.4k
        if (!PyExceptionClass_Check(right)) {
3407
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3408
0
                CANNOT_CATCH_MSG);
3409
0
            return -1;
3410
0
        }
3411
73.4k
    }
3412
74.8k
    return 0;
3413
74.8k
}
3414
3415
int
3416
_PyEval_CheckExceptStarTypeValid(PyThreadState *tstate, PyObject* right)
3417
0
{
3418
0
    if (_PyEval_CheckExceptTypeValid(tstate, right) < 0) {
3419
0
        return -1;
3420
0
    }
3421
3422
    /* reject except *ExceptionGroup */
3423
3424
0
    int is_subclass = 0;
3425
0
    if (PyTuple_Check(right)) {
3426
0
        Py_ssize_t length = PyTuple_GET_SIZE(right);
3427
0
        for (Py_ssize_t i = 0; i < length; i++) {
3428
0
            PyObject *exc = PyTuple_GET_ITEM(right, i);
3429
0
            is_subclass = PyObject_IsSubclass(exc, PyExc_BaseExceptionGroup);
3430
0
            if (is_subclass < 0) {
3431
0
                return -1;
3432
0
            }
3433
0
            if (is_subclass) {
3434
0
                break;
3435
0
            }
3436
0
        }
3437
0
    }
3438
0
    else {
3439
0
        is_subclass = PyObject_IsSubclass(right, PyExc_BaseExceptionGroup);
3440
0
        if (is_subclass < 0) {
3441
0
            return -1;
3442
0
        }
3443
0
    }
3444
0
    if (is_subclass) {
3445
0
        _PyErr_SetString(tstate, PyExc_TypeError,
3446
0
            CANNOT_EXCEPT_STAR_EG);
3447
0
            return -1;
3448
0
    }
3449
0
    return 0;
3450
0
}
3451
3452
int
3453
_Py_Check_ArgsIterable(PyThreadState *tstate, PyObject *func, PyObject *args)
3454
126
{
3455
126
    if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
3456
0
        _PyErr_Format(tstate, PyExc_TypeError,
3457
0
                      "Value after * must be an iterable, not %.200s",
3458
0
                      Py_TYPE(args)->tp_name);
3459
0
        return -1;
3460
0
    }
3461
126
    return 0;
3462
126
}
3463
3464
void
3465
_PyEval_FormatKwargsError(PyThreadState *tstate, PyObject *func, PyObject *kwargs, PyObject *dupkey)
3466
0
{
3467
0
    if (dupkey != NULL) {
3468
0
        PyObject *funcstr = _PyObject_FunctionStr(func);
3469
0
        _PyErr_Format(
3470
0
            tstate, PyExc_TypeError,
3471
0
            "%V got multiple values for keyword argument '%S'",
3472
0
            funcstr, "function", dupkey);
3473
0
        Py_XDECREF(funcstr);
3474
0
        return;
3475
0
    }
3476
    /* _PyDict_MergeUniq raises attribute
3477
     * error (percolated from an attempt
3478
     * to get 'keys' attribute) instead of
3479
     * a type error if its second argument
3480
     * is not a mapping.
3481
     */
3482
0
    if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
3483
0
        PyObject *exc = _PyErr_GetRaisedException(tstate);
3484
0
        int has_keys = PyObject_HasAttrWithError(kwargs, &_Py_ID(keys));
3485
0
        if (has_keys == 0) {
3486
0
            _PyErr_Format(
3487
0
                tstate, PyExc_TypeError,
3488
0
                "Value after ** must be a mapping, not %T",
3489
0
                kwargs);
3490
0
            Py_DECREF(exc);
3491
0
        }
3492
0
        else {
3493
0
            _PyErr_ChainExceptions1Tstate(tstate, exc);
3494
0
        }
3495
0
    }
3496
0
}
3497
3498
void
3499
_PyEval_FormatExcCheckArg(PyThreadState *tstate, PyObject *exc,
3500
                          const char *format_str, PyObject *obj)
3501
4
{
3502
4
    const char *obj_str;
3503
3504
4
    if (!obj)
3505
0
        return;
3506
3507
4
    obj_str = PyUnicode_AsUTF8(obj);
3508
4
    if (!obj_str)
3509
0
        return;
3510
3511
4
    _PyErr_Format(tstate, exc, format_str, obj_str);
3512
3513
4
    if (exc == PyExc_NameError) {
3514
        // Include the name in the NameError exceptions to offer suggestions later.
3515
4
        PyObject *exc = PyErr_GetRaisedException();
3516
4
        if (PyErr_GivenExceptionMatches(exc, PyExc_NameError)) {
3517
4
            if (((PyNameErrorObject*)exc)->name == NULL) {
3518
                // We do not care if this fails because we are going to restore the
3519
                // NameError anyway.
3520
4
                (void)PyObject_SetAttr(exc, &_Py_ID(name), obj);
3521
4
            }
3522
4
        }
3523
4
        PyErr_SetRaisedException(exc);
3524
4
    }
3525
4
}
3526
3527
void
3528
_PyEval_FormatExcUnbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
3529
0
{
3530
0
    PyObject *name;
3531
    /* Don't stomp existing exception */
3532
0
    if (_PyErr_Occurred(tstate))
3533
0
        return;
3534
0
    name = PyTuple_GET_ITEM(co->co_localsplusnames, oparg);
3535
0
    if (oparg < PyUnstable_Code_GetFirstFree(co)) {
3536
0
        _PyEval_FormatExcCheckArg(tstate, PyExc_UnboundLocalError,
3537
0
                                  UNBOUNDLOCAL_ERROR_MSG, name);
3538
0
    } else {
3539
0
        _PyEval_FormatExcCheckArg(tstate, PyExc_NameError,
3540
0
                                  UNBOUNDFREE_ERROR_MSG, name);
3541
0
    }
3542
0
}
3543
3544
void
3545
_PyEval_FormatAwaitableError(PyThreadState *tstate, PyTypeObject *type, int oparg)
3546
0
{
3547
0
    if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
3548
0
        if (oparg == 1) {
3549
0
            _PyErr_Format(tstate, PyExc_TypeError,
3550
0
                          "'async with' received an object from __aenter__ "
3551
0
                          "that does not implement __await__: %.100s",
3552
0
                          type->tp_name);
3553
0
        }
3554
0
        else if (oparg == 2) {
3555
0
            _PyErr_Format(tstate, PyExc_TypeError,
3556
0
                          "'async with' received an object from __aexit__ "
3557
0
                          "that does not implement __await__: %.100s",
3558
0
                          type->tp_name);
3559
0
        }
3560
0
    }
3561
0
}
3562
3563
3564
Py_ssize_t
3565
PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
3566
0
{
3567
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
3568
0
    Py_ssize_t new_index;
3569
3570
#ifdef Py_GIL_DISABLED
3571
    struct _py_code_state *state = &interp->code_state;
3572
    FT_MUTEX_LOCK(&state->mutex);
3573
#endif
3574
3575
0
    if (interp->co_extra_user_count >= MAX_CO_EXTRA_USERS - 1) {
3576
#ifdef Py_GIL_DISABLED
3577
        FT_MUTEX_UNLOCK(&state->mutex);
3578
#endif
3579
0
        return -1;
3580
0
    }
3581
3582
0
    new_index = interp->co_extra_user_count;
3583
0
    interp->co_extra_freefuncs[new_index] = free;
3584
3585
    // Publish freefuncs[new_index] before making the index visible.
3586
0
    FT_ATOMIC_STORE_SSIZE_RELEASE(interp->co_extra_user_count, new_index + 1);
3587
3588
#ifdef Py_GIL_DISABLED
3589
    FT_MUTEX_UNLOCK(&state->mutex);
3590
#endif
3591
0
    return new_index;
3592
0
}
3593
3594
/* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
3595
   for the limited API. */
3596
3597
int Py_EnterRecursiveCall(const char *where)
3598
8.45M
{
3599
8.45M
    return _Py_EnterRecursiveCall(where);
3600
8.45M
}
3601
3602
void Py_LeaveRecursiveCall(void)
3603
5.93M
{
3604
5.93M
    _Py_LeaveRecursiveCall();
3605
5.93M
}
3606
3607
PyObject *
3608
_PyEval_GetANext(PyObject *aiter)
3609
0
{
3610
0
    unaryfunc getter = NULL;
3611
0
    PyObject *next_iter = NULL;
3612
0
    PyTypeObject *type = Py_TYPE(aiter);
3613
0
    if (PyAsyncGen_CheckExact(aiter)) {
3614
0
        return type->tp_as_async->am_anext(aiter);
3615
0
    }
3616
0
    if (type->tp_as_async != NULL){
3617
0
        getter = type->tp_as_async->am_anext;
3618
0
    }
3619
3620
0
    if (getter != NULL) {
3621
0
        next_iter = (*getter)(aiter);
3622
0
        if (next_iter == NULL) {
3623
0
            return NULL;
3624
0
        }
3625
0
    }
3626
0
    else {
3627
0
        PyErr_Format(PyExc_TypeError,
3628
0
                        "'async for' requires an iterator with "
3629
0
                        "__anext__ method, got %.100s",
3630
0
                        type->tp_name);
3631
0
        return NULL;
3632
0
    }
3633
3634
0
    PyObject *awaitable = _PyCoro_GetAwaitableIter(next_iter);
3635
0
    if (awaitable == NULL) {
3636
0
        _PyErr_FormatFromCause(
3637
0
            PyExc_TypeError,
3638
0
            "'async for' received an invalid object "
3639
0
            "from __anext__: %.100s",
3640
0
            Py_TYPE(next_iter)->tp_name);
3641
0
    }
3642
0
    Py_DECREF(next_iter);
3643
0
    return awaitable;
3644
0
}
3645
3646
void
3647
_PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name, _PyStackRef *writeto)
3648
47.6k
{
3649
47.6k
    if (PyAnyDict_CheckExact(globals) && PyAnyDict_CheckExact(builtins)) {
3650
47.6k
        _PyDict_LoadGlobalStackRef((PyDictObject *)globals,
3651
47.6k
                                    (PyDictObject *)builtins,
3652
47.6k
                                    name, writeto);
3653
47.6k
        if (PyStackRef_IsNull(*writeto) && !PyErr_Occurred()) {
3654
            /* _PyDict_LoadGlobal() returns NULL without raising
3655
                * an exception if the key doesn't exist */
3656
4
            _PyEval_FormatExcCheckArg(PyThreadState_GET(), PyExc_NameError,
3657
4
                                        NAME_ERROR_MSG, name);
3658
4
        }
3659
47.6k
    }
3660
0
    else {
3661
        /* Slow-path if globals or builtins is not a dict */
3662
        /* namespace 1: globals */
3663
0
        PyObject *res;
3664
0
        if (PyMapping_GetOptionalItem(globals, name, &res) < 0) {
3665
0
            *writeto = PyStackRef_NULL;
3666
0
            return;
3667
0
        }
3668
0
        if (res == NULL) {
3669
            /* namespace 2: builtins */
3670
0
            if (PyMapping_GetOptionalItem(builtins, name, &res) < 0) {
3671
0
                *writeto = PyStackRef_NULL;
3672
0
                return;
3673
0
            }
3674
0
            if (res == NULL) {
3675
0
                _PyEval_FormatExcCheckArg(
3676
0
                            PyThreadState_GET(), PyExc_NameError,
3677
0
                            NAME_ERROR_MSG, name);
3678
0
                *writeto = PyStackRef_NULL;
3679
0
                return;
3680
0
            }
3681
0
        }
3682
0
        *writeto = PyStackRef_FromPyObjectSteal(res);
3683
0
    }
3684
3685
47.6k
    PyObject *res_o = PyStackRef_AsPyObjectBorrow(*writeto);
3686
47.6k
    if (res_o != NULL && PyLazyImport_CheckExact(res_o)) {
3687
0
        PyObject *l_v = _PyImport_LoadLazyImportTstate(PyThreadState_GET(), res_o);
3688
0
        PyStackRef_CLOSE(writeto[0]);
3689
0
        if (l_v == NULL) {
3690
0
            assert(PyErr_Occurred());
3691
0
            *writeto = PyStackRef_NULL;
3692
0
            return;
3693
0
        }
3694
0
        int err = PyDict_SetItem(globals, name, l_v);
3695
0
        if (err < 0) {
3696
0
            Py_DECREF(l_v);
3697
0
            *writeto = PyStackRef_NULL;
3698
0
            return;
3699
0
        }
3700
0
        *writeto = PyStackRef_FromPyObjectSteal(l_v);
3701
0
    }
3702
47.6k
}
3703
3704
PyObject *
3705
_PyEval_GetAwaitable(PyObject *iterable, int oparg)
3706
0
{
3707
0
    PyObject *iter = _PyCoro_GetAwaitableIter(iterable);
3708
3709
0
    if (iter == NULL) {
3710
0
        _PyEval_FormatAwaitableError(PyThreadState_GET(),
3711
0
            Py_TYPE(iterable), oparg);
3712
0
    }
3713
0
    else if (PyCoro_CheckExact(iter)) {
3714
0
        PyCoroObject *coro = (PyCoroObject *)iter;
3715
0
        int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(coro->cr_frame_state);
3716
0
        if (frame_state == FRAME_SUSPENDED_YIELD_FROM ||
3717
0
            frame_state == FRAME_SUSPENDED_YIELD_FROM_LOCKED)
3718
0
        {
3719
            /* `iter` is a coroutine object that is being awaited. */
3720
0
            Py_CLEAR(iter);
3721
0
            _PyErr_SetString(PyThreadState_GET(), PyExc_RuntimeError,
3722
0
                             "coroutine is being awaited already");
3723
0
        }
3724
0
    }
3725
0
    return iter;
3726
0
}
3727
3728
PyObject *
3729
_PyEval_LoadName(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *name)
3730
29.3k
{
3731
3732
29.3k
    PyObject *value;
3733
29.3k
    if (frame->f_locals == NULL) {
3734
0
        _PyErr_SetString(tstate, PyExc_SystemError,
3735
0
                            "no locals found");
3736
0
        return NULL;
3737
0
    }
3738
29.3k
    if (PyMapping_GetOptionalItem(frame->f_locals, name, &value) < 0) {
3739
0
        return NULL;
3740
0
    }
3741
29.3k
    if (value != NULL) {
3742
20.2k
        return value;
3743
20.2k
    }
3744
9.11k
    if (PyDict_GetItemRef(frame->f_globals, name, &value) < 0) {
3745
0
        return NULL;
3746
0
    }
3747
9.11k
    if (value != NULL) {
3748
4.15k
        return value;
3749
4.15k
    }
3750
4.96k
    if (PyMapping_GetOptionalItem(frame->f_builtins, name, &value) < 0) {
3751
0
        return NULL;
3752
0
    }
3753
4.96k
    if (value == NULL) {
3754
0
        _PyEval_FormatExcCheckArg(
3755
0
                    tstate, PyExc_NameError,
3756
0
                    NAME_ERROR_MSG, name);
3757
0
    }
3758
4.96k
    return value;
3759
4.96k
}
3760
3761
_PyStackRef _PyForIter_VirtualIteratorNext(PyThreadState* tstate, _PyInterpreterFrame* frame, _PyStackRef iter, _PyStackRef* index_ptr)
3762
24.8M
{
3763
24.8M
    PyObject *iter_o = PyStackRef_AsPyObjectBorrow(iter);
3764
24.8M
    _PyStackRef index = *index_ptr;
3765
24.8M
    if (PyStackRef_IsTaggedInt(index)) {
3766
684k
        intptr_t i = PyStackRef_UntagInt(index);
3767
684k
        assert(i >= 0);
3768
684k
        _PyObjectIndexPair next_index = Py_TYPE(iter_o)->_tp_iteritem(iter_o, i);
3769
684k
        i = next_index.index;
3770
684k
        PyObject *next = next_index.object;
3771
684k
        if (next == NULL) {
3772
1.86k
            return i < 0 ? PyStackRef_ERROR : PyStackRef_NULL;
3773
1.86k
        }
3774
682k
        *index_ptr = PyStackRef_TagInt(i);
3775
682k
        return PyStackRef_FromPyObjectSteal(next);
3776
684k
    }
3777
24.1M
    PyObject *next = (*Py_TYPE(iter_o)->tp_iternext)(iter_o);
3778
24.1M
    if (next == NULL) {
3779
6.16M
        if (_PyErr_Occurred(tstate)) {
3780
0
            if (_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
3781
0
                _PyEval_MonitorRaise(tstate, frame, frame->instr_ptr);
3782
0
                _PyErr_Clear(tstate);
3783
0
            }
3784
0
            else {
3785
0
                return PyStackRef_ERROR;
3786
0
            }
3787
0
        }
3788
6.16M
        return PyStackRef_NULL;
3789
6.16M
    }
3790
18.0M
    return PyStackRef_FromPyObjectSteal(next);
3791
24.1M
}
3792
3793
/* Check if a 'cls' provides the given special method. */
3794
static inline int
3795
type_has_special_method(PyTypeObject *cls, PyObject *name)
3796
0
{
3797
    // _PyType_Lookup() does not set an exception and returns a borrowed ref
3798
0
    assert(!PyErr_Occurred());
3799
0
    PyObject *r = _PyType_Lookup(cls, name);
3800
0
    return r != NULL && Py_TYPE(r)->tp_descr_get != NULL;
3801
0
}
3802
3803
int
3804
_PyEval_SpecialMethodCanSuggest(PyObject *self, int oparg)
3805
0
{
3806
0
    PyTypeObject *type = Py_TYPE(self);
3807
0
    switch (oparg) {
3808
0
        case SPECIAL___ENTER__:
3809
0
        case SPECIAL___EXIT__: {
3810
0
            return type_has_special_method(type, &_Py_ID(__aenter__))
3811
0
                   && type_has_special_method(type, &_Py_ID(__aexit__));
3812
0
        }
3813
0
        case SPECIAL___AENTER__:
3814
0
        case SPECIAL___AEXIT__: {
3815
0
            return type_has_special_method(type, &_Py_ID(__enter__))
3816
0
                   && type_has_special_method(type, &_Py_ID(__exit__));
3817
0
        }
3818
0
        default:
3819
0
            Py_FatalError("unsupported special method");
3820
0
    }
3821
0
}