Coverage Report

Created: 2026-06-09 06:53

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