Coverage Report

Created: 2026-01-17 06:16

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