Coverage Report

Created: 2026-03-08 06:40

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