Coverage Report

Created: 2026-06-21 06:15

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