Coverage Report

Created: 2026-03-07 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Python/ceval.c
Line
Count
Source
1
/* Execute compiled code */
2
3
#include "ceval.h"
4
#include "pycore_long.h"
5
6
int
7
Py_GetRecursionLimit(void)
8
0
{
9
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
10
0
    return interp->ceval.recursion_limit;
11
0
}
12
13
void
14
Py_SetRecursionLimit(int new_limit)
15
0
{
16
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
17
0
    _PyEval_StopTheWorld(interp);
18
0
    interp->ceval.recursion_limit = new_limit;
19
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
20
0
        int depth = p->py_recursion_limit - p->py_recursion_remaining;
21
0
        p->py_recursion_limit = new_limit;
22
0
        p->py_recursion_remaining = new_limit - depth;
23
0
    }
24
0
    _Py_FOR_EACH_TSTATE_END(interp);
25
0
    _PyEval_StartTheWorld(interp);
26
0
}
27
28
int
29
_Py_ReachedRecursionLimitWithMargin(PyThreadState *tstate, int margin_count)
30
131M
{
31
131M
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
32
131M
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
33
131M
#if _Py_STACK_GROWS_DOWN
34
131M
    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
131M
        return 0;
39
131M
    }
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
131M
}
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
22
{
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
22
#  if defined(HAVE_PTHREAD_GETATTR_NP) && !defined(_AIX) && \
159
22
        !defined(__NetBSD__) && (defined(__GLIBC__) || !defined(__linux__))
160
22
    size_t stack_size, guard_size;
161
22
    void *stack_addr;
162
22
    pthread_attr_t attr;
163
22
    int err = pthread_getattr_np(pthread_self(), &attr);
164
22
    if (err == 0) {
165
22
        err = pthread_attr_getguardsize(&attr, &guard_size);
166
22
        err |= pthread_attr_getstack(&attr, &stack_addr, &stack_size);
167
22
        err |= pthread_attr_destroy(&attr);
168
22
    }
169
22
    if (err == 0) {
170
22
        *base = ((uintptr_t)stack_addr) + guard_size;
171
22
        *top = (uintptr_t)stack_addr + stack_size;
172
22
        return;
173
22
    }
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
22
{
195
22
    assert(base < top);
196
22
    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
22
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
208
22
#if _Py_STACK_GROWS_DOWN
209
22
    _tstate->c_stack_top = top;
210
22
    _tstate->c_stack_hard_limit = base + _PyOS_STACK_MARGIN_BYTES;
211
22
    _tstate->c_stack_soft_limit = base + _PyOS_STACK_MARGIN_BYTES * 2;
212
22
#  ifndef NDEBUG
213
    // Sanity checks
214
22
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)tstate;
215
22
    assert(ts->c_stack_hard_limit <= ts->c_stack_soft_limit);
216
22
    assert(ts->c_stack_soft_limit < ts->c_stack_top);
217
22
#  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
22
}
230
231
232
void
233
_Py_InitializeRecursionLimits(PyThreadState *tstate)
234
22
{
235
22
    uintptr_t base, top;
236
22
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
237
22
    hardware_stack_limits(&base, &top, here_addr);
238
22
    assert(top != 0);
239
240
22
    tstate_set_stack(tstate, base, top);
241
22
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)tstate;
242
22
    ts->c_stack_init_base = base;
243
22
    ts->c_stack_init_top = top;
244
22
}
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
176
{
285
176
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
286
176
    uintptr_t here_addr = _Py_get_machine_stack_pointer();
287
176
    assert(_tstate->c_stack_soft_limit != 0);
288
176
    assert(_tstate->c_stack_hard_limit != 0);
289
176
#if _Py_STACK_GROWS_DOWN
290
176
    assert(here_addr >= _tstate->c_stack_hard_limit - _PyOS_STACK_MARGIN_BYTES);
291
176
    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
176
    if (tstate->recursion_headroom) {
305
0
        return 0;
306
0
    }
307
176
    else {
308
176
#if _Py_STACK_GROWS_DOWN
309
176
        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
176
        tstate->recursion_headroom++;
314
176
        _PyErr_Format(tstate, PyExc_RecursionError,
315
176
                    "Stack overflow (used %d kB)%s",
316
176
                    kbytes_used,
317
176
                    where);
318
176
        tstate->recursion_headroom--;
319
176
        return -1;
320
176
    }
321
176
}
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
0
{
537
0
    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
0
    assert(PyTuple_CheckExact(kwargs));
543
    // First, an isinstance check:
544
0
    if (PyObject_IsInstance(subject, type) <= 0) {
545
0
        return NULL;
546
0
    }
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
644
{
657
644
    PyThreadState *tstate = _PyThreadState_GET();
658
644
    if (locals == NULL) {
659
0
        locals = globals;
660
0
    }
661
644
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
662
644
    if (builtins == NULL) {
663
0
        return NULL;
664
0
    }
665
644
    PyFrameConstructor desc = {
666
644
        .fc_globals = globals,
667
644
        .fc_builtins = builtins,
668
644
        .fc_name = ((PyCodeObject *)co)->co_name,
669
644
        .fc_qualname = ((PyCodeObject *)co)->co_name,
670
644
        .fc_code = co,
671
644
        .fc_defaults = NULL,
672
644
        .fc_kwdefaults = NULL,
673
644
        .fc_closure = NULL
674
644
    };
675
644
    PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
676
644
    _Py_DECREF_BUILTINS(builtins);
677
644
    if (func == NULL) {
678
0
        return NULL;
679
0
    }
680
644
    EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
681
644
    PyObject *res = _PyEval_Vector(tstate, func, locals, NULL, 0, NULL);
682
644
    Py_DECREF(func);
683
644
    return res;
684
644
}
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
1.04M
{
716
1.04M
    PyObject *res;
717
1.04M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
718
1.04M
    if (CONVERSION_FAILED(args_o)) {
719
0
        res = NULL;
720
0
        goto cleanup;
721
0
    }
722
1.04M
    PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable);
723
1.04M
    PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames);
724
1.04M
    int positional_args = total_args;
725
1.04M
    if (kwnames_o != NULL) {
726
760k
        positional_args -= (int)PyTuple_GET_SIZE(kwnames_o);
727
760k
    }
728
1.04M
    res = PyObject_Vectorcall(
729
1.04M
        callable_o, args_o,
730
1.04M
        positional_args | PY_VECTORCALL_ARGUMENTS_OFFSET,
731
1.04M
        kwnames_o);
732
1.04M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
733
1.04M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
734
1.04M
cleanup:
735
1.04M
    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
3.57M
    for (int i = total_args-1; i >= 0; i--) {
739
2.52M
        _PyStackRef tmp = arguments[i];
740
2.52M
        arguments[i] = PyStackRef_NULL;
741
2.52M
        PyStackRef_CLOSE(tmp);
742
2.52M
    }
743
1.04M
    PyStackRef_CLOSE(callable);
744
1.04M
    return res;
745
1.04M
}
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
424k
{
758
424k
    PyObject* res;
759
424k
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
760
424k
    if (CONVERSION_FAILED(args_o)) {
761
0
        res = NULL;
762
0
        goto cleanup;
763
0
    }
764
424k
    PyObject* callable_o = PyStackRef_AsPyObjectBorrow(callable);
765
424k
    PyObject* kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames);
766
424k
    int positional_args = total_args;
767
424k
    if (kwnames_o != NULL) {
768
651
        positional_args -= (int)PyTuple_GET_SIZE(kwnames_o);
769
651
    }
770
424k
    res = PyObject_Vectorcall(
771
424k
        callable_o, args_o,
772
424k
        positional_args | PY_VECTORCALL_ARGUMENTS_OFFSET,
773
424k
        kwnames_o);
774
424k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
775
424k
    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
424k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
793
424k
cleanup:
794
424k
    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
982k
    for (int i = total_args - 1; i >= 0; i--) {
798
557k
        _PyStackRef tmp = arguments[i];
799
557k
        arguments[i] = PyStackRef_NULL;
800
557k
        PyStackRef_CLOSE(tmp);
801
557k
    }
802
424k
    PyStackRef_CLOSE(callable);
803
424k
    return res;
804
424k
}
805
806
PyObject *
807
_Py_BuiltinCallFast_StackRefSteal(
808
    _PyStackRef callable,
809
    _PyStackRef *arguments,
810
    int total_args)
811
204k
{
812
204k
    PyObject *res;
813
204k
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
814
204k
    if (CONVERSION_FAILED(args_o)) {
815
0
        res = NULL;
816
0
        goto cleanup;
817
0
    }
818
204k
    PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable);
819
204k
    PyCFunction cfunc = PyCFunction_GET_FUNCTION(callable_o);
820
204k
    res = _PyCFunctionFast_CAST(cfunc)(
821
204k
        PyCFunction_GET_SELF(callable_o),
822
204k
        args_o,
823
204k
        total_args
824
204k
    );
825
204k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
826
204k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
827
204k
cleanup:
828
    // arguments is a pointer into the GC visible stack,
829
    // so we must NULL out values as we clear them.
830
600k
    for (int i = total_args-1; i >= 0; i--) {
831
395k
        _PyStackRef tmp = arguments[i];
832
395k
        arguments[i] = PyStackRef_NULL;
833
395k
        PyStackRef_CLOSE(tmp);
834
395k
    }
835
204k
    PyStackRef_CLOSE(callable);
836
204k
    return res;
837
204k
}
838
839
PyObject *
840
_Py_BuiltinCallFastWithKeywords_StackRefSteal(
841
    _PyStackRef callable,
842
    _PyStackRef *arguments,
843
    int total_args)
844
13.2M
{
845
13.2M
    PyObject *res;
846
13.2M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
847
13.2M
    if (CONVERSION_FAILED(args_o)) {
848
0
        res = NULL;
849
0
        goto cleanup;
850
0
    }
851
13.2M
    PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable);
852
13.2M
    PyCFunctionFastWithKeywords cfunc =
853
13.2M
        _PyCFunctionFastWithKeywords_CAST(PyCFunction_GET_FUNCTION(callable_o));
854
13.2M
    res = cfunc(PyCFunction_GET_SELF(callable_o), args_o, total_args, NULL);
855
13.2M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
856
13.2M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
857
13.2M
cleanup:
858
    // arguments is a pointer into the GC visible stack,
859
    // so we must NULL out values as we clear them.
860
39.5M
    for (int i = total_args-1; i >= 0; i--) {
861
26.3M
        _PyStackRef tmp = arguments[i];
862
26.3M
        arguments[i] = PyStackRef_NULL;
863
26.3M
        PyStackRef_CLOSE(tmp);
864
26.3M
    }
865
13.2M
    PyStackRef_CLOSE(callable);
866
13.2M
    return res;
867
13.2M
}
868
869
PyObject *
870
_PyCallMethodDescriptorFast_StackRefSteal(
871
    _PyStackRef callable,
872
    PyMethodDef *meth,
873
    PyObject *self,
874
    _PyStackRef *arguments,
875
    int total_args)
876
2.25M
{
877
2.25M
    PyObject *res;
878
2.25M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
879
2.25M
    if (CONVERSION_FAILED(args_o)) {
880
0
        res = NULL;
881
0
        goto cleanup;
882
0
    }
883
2.25M
    assert(((PyMethodDescrObject *)PyStackRef_AsPyObjectBorrow(callable))->d_method == meth);
884
2.25M
    assert(self == PyStackRef_AsPyObjectBorrow(arguments[0]));
885
886
2.25M
    PyCFunctionFast cfunc = _PyCFunctionFast_CAST(meth->ml_meth);
887
2.25M
    res = cfunc(self, (args_o + 1), total_args - 1);
888
2.25M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
889
2.25M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
890
2.25M
cleanup:
891
    // arguments is a pointer into the GC visible stack,
892
    // so we must NULL out values as we clear them.
893
7.70M
    for (int i = total_args-1; i >= 0; i--) {
894
5.44M
        _PyStackRef tmp = arguments[i];
895
5.44M
        arguments[i] = PyStackRef_NULL;
896
5.44M
        PyStackRef_CLOSE(tmp);
897
5.44M
    }
898
2.25M
    PyStackRef_CLOSE(callable);
899
2.25M
    return res;
900
2.25M
}
901
902
PyObject *
903
_PyCallMethodDescriptorFastWithKeywords_StackRefSteal(
904
    _PyStackRef callable,
905
    PyMethodDef *meth,
906
    PyObject *self,
907
    _PyStackRef *arguments,
908
    int total_args)
909
109k
{
910
109k
    PyObject *res;
911
109k
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
912
109k
    if (CONVERSION_FAILED(args_o)) {
913
0
        res = NULL;
914
0
        goto cleanup;
915
0
    }
916
109k
    assert(((PyMethodDescrObject *)PyStackRef_AsPyObjectBorrow(callable))->d_method == meth);
917
109k
    assert(self == PyStackRef_AsPyObjectBorrow(arguments[0]));
918
919
109k
    PyCFunctionFastWithKeywords cfunc =
920
109k
        _PyCFunctionFastWithKeywords_CAST(meth->ml_meth);
921
109k
    res = cfunc(self, (args_o + 1), total_args-1, NULL);
922
109k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
923
109k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
924
109k
cleanup:
925
    // arguments is a pointer into the GC visible stack,
926
    // so we must NULL out values as we clear them.
927
359k
    for (int i = total_args-1; i >= 0; i--) {
928
250k
        _PyStackRef tmp = arguments[i];
929
250k
        arguments[i] = PyStackRef_NULL;
930
250k
        PyStackRef_CLOSE(tmp);
931
250k
    }
932
109k
    PyStackRef_CLOSE(callable);
933
109k
    return res;
934
109k
}
935
936
PyObject *
937
_Py_CallBuiltinClass_StackRefSteal(
938
    _PyStackRef callable,
939
    _PyStackRef *arguments,
940
    int total_args)
941
3.78M
{
942
3.78M
    PyObject *res;
943
3.78M
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
944
3.78M
    if (CONVERSION_FAILED(args_o)) {
945
0
        res = NULL;
946
0
        goto cleanup;
947
0
    }
948
3.78M
    PyTypeObject *tp = (PyTypeObject *)PyStackRef_AsPyObjectBorrow(callable);
949
3.78M
    res = tp->tp_vectorcall((PyObject *)tp, args_o, total_args | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
950
3.78M
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
951
3.78M
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
952
3.78M
cleanup:
953
    // arguments is a pointer into the GC visible stack,
954
    // so we must NULL out values as we clear them.
955
8.08M
    for (int i = total_args-1; i >= 0; i--) {
956
4.29M
        _PyStackRef tmp = arguments[i];
957
4.29M
        arguments[i] = PyStackRef_NULL;
958
4.29M
        PyStackRef_CLOSE(tmp);
959
4.29M
    }
960
3.78M
    PyStackRef_CLOSE(callable);
961
3.78M
    return res;
962
3.78M
}
963
964
PyObject *
965
_Py_BuildString_StackRefSteal(
966
    _PyStackRef *arguments,
967
    int total_args)
968
174k
{
969
174k
    PyObject *res;
970
174k
    STACKREFS_TO_PYOBJECTS(arguments, total_args, args_o);
971
174k
    if (CONVERSION_FAILED(args_o)) {
972
0
        res = NULL;
973
0
        goto cleanup;
974
0
    }
975
174k
    res = _PyUnicode_JoinArray(&_Py_STR(empty), args_o, total_args);
976
174k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
977
174k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
978
174k
cleanup:
979
    // arguments is a pointer into the GC visible stack,
980
    // so we must NULL out values as we clear them.
981
1.56M
    for (int i = total_args-1; i >= 0; i--) {
982
1.38M
        _PyStackRef tmp = arguments[i];
983
1.38M
        arguments[i] = PyStackRef_NULL;
984
1.38M
        PyStackRef_CLOSE(tmp);
985
1.38M
    }
986
174k
    return res;
987
174k
}
988
989
PyObject *
990
_Py_BuildMap_StackRefSteal(
991
    _PyStackRef *arguments,
992
    int half_args)
993
36.5k
{
994
36.5k
    PyObject *res;
995
36.5k
    STACKREFS_TO_PYOBJECTS(arguments, half_args*2, args_o);
996
36.5k
    if (CONVERSION_FAILED(args_o)) {
997
0
        res = NULL;
998
0
        goto cleanup;
999
0
    }
1000
36.5k
    res = _PyDict_FromItems(
1001
36.5k
        args_o, 2,
1002
36.5k
        args_o+1, 2,
1003
36.5k
        half_args
1004
36.5k
    );
1005
36.5k
    STACKREFS_TO_PYOBJECTS_CLEANUP(args_o);
1006
36.5k
    assert((res != NULL) ^ (PyErr_Occurred() != NULL));
1007
36.5k
cleanup:
1008
    // arguments is a pointer into the GC visible stack,
1009
    // so we must NULL out values as we clear them.
1010
43.3k
    for (int i = half_args*2-1; i >= 0; i--) {
1011
6.78k
        _PyStackRef tmp = arguments[i];
1012
6.78k
        arguments[i] = PyStackRef_NULL;
1013
6.78k
        PyStackRef_CLOSE(tmp);
1014
6.78k
    }
1015
36.5k
    return res;
1016
36.5k
}
1017
1018
_PyStackRef
1019
_Py_LoadAttr_StackRefSteal(
1020
    PyThreadState *tstate, _PyStackRef owner,
1021
    PyObject *name, _PyStackRef *self_or_null)
1022
478k
{
1023
478k
    _PyCStackRef method;
1024
478k
    _PyThreadState_PushCStackRef(tstate, &method);
1025
478k
    int is_meth = _PyObject_GetMethodStackRef(tstate, PyStackRef_AsPyObjectBorrow(owner), name, &method.ref);
1026
478k
    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
183k
        assert(!PyStackRef_IsNull(method.ref)); // No errors on this branch
1032
183k
        self_or_null[0] = owner;  // Transfer ownership
1033
183k
        return _PyThreadState_PopCStackRefSteal(tstate, &method);
1034
183k
    }
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
295k
    PyStackRef_CLOSE(owner);
1042
295k
    self_or_null[0] = PyStackRef_NULL;
1043
295k
    return _PyThreadState_PopCStackRefSteal(tstate, &method);
1044
478k
}
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
35.6k
{
1073
35.6k
    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
35.6k
    else {
1080
35.6k
        if (tstate->py_recursion_remaining <= 0) {
1081
35.6k
            tstate->recursion_headroom++;
1082
35.6k
            _PyErr_Format(tstate, PyExc_RecursionError,
1083
35.6k
                        "maximum recursion depth exceeded");
1084
35.6k
            tstate->recursion_headroom--;
1085
35.6k
            return -1;
1086
35.6k
        }
1087
35.6k
    }
1088
0
    return 0;
1089
35.6k
}
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
21.2M
{
1111
21.2M
    PyObject **result;
1112
21.2M
    if (nargs > MAX_STACKREF_SCRATCH) {
1113
        // +1 in case PY_VECTORCALL_ARGUMENTS_OFFSET is set.
1114
117
        result = PyMem_Malloc((nargs + 1) * sizeof(PyObject *));
1115
117
        if (result == NULL) {
1116
0
            return NULL;
1117
0
        }
1118
117
    }
1119
21.2M
    else {
1120
21.2M
        result = scratch;
1121
21.2M
    }
1122
21.2M
    result++;
1123
21.2M
    result[0] = NULL; /* Keep GCC happy */
1124
62.4M
    for (int i = 0; i < nargs; i++) {
1125
41.2M
        result[i] = PyStackRef_AsPyObjectBorrow(input[i]);
1126
41.2M
    }
1127
21.2M
    return result;
1128
21.2M
}
1129
1130
void
1131
_PyObjectArray_Free(PyObject **array, PyObject **scratch)
1132
21.2M
{
1133
21.2M
    if (array != scratch) {
1134
117
        PyMem_Free(array);
1135
117
    }
1136
21.2M
}
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
19.9M
{
1189
19.9M
    _Py_EnsureTstateNotNULL(tstate);
1190
19.9M
    check_invalid_reentrancy();
1191
19.9M
    CALL_STAT_INC(pyeval_calls);
1192
1193
19.9M
#if USE_COMPUTED_GOTOS && !_Py_TAIL_CALL_INTERP
1194
/* Import the static jump table */
1195
19.9M
#include "opcode_targets.h"
1196
19.9M
    void **opcode_targets = opcode_targets_table;
1197
19.9M
#endif
1198
1199
#ifdef Py_STATS
1200
    int lastopcode = 0;
1201
#endif
1202
19.9M
#if !_Py_TAIL_CALL_INTERP
1203
19.9M
    uint8_t opcode;    /* Current opcode */
1204
19.9M
    int oparg;         /* Current opcode argument, if any */
1205
19.9M
    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
19.9M
#endif
1211
19.9M
    _PyEntryFrame entry;
1212
1213
19.9M
    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
19.9M
    _Py_CODEUNIT *next_instr;
1222
19.9M
    _PyStackRef *stack_pointer;
1223
19.9M
    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
19.9M
    entry.frame.f_executable = PyStackRef_None;
1235
19.9M
    entry.frame.instr_ptr = (_Py_CODEUNIT *)_Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS + 1;
1236
19.9M
    entry.frame.stackpointer = entry.stack;
1237
19.9M
    entry.frame.owner = FRAME_OWNED_BY_INTERPRETER;
1238
19.9M
    entry.frame.visited = 0;
1239
19.9M
    entry.frame.return_offset = 0;
1240
#ifdef Py_DEBUG
1241
    entry.frame.lltrace = 0;
1242
#endif
1243
    /* Push frame */
1244
19.9M
    entry.frame.previous = tstate->current_frame;
1245
19.9M
    frame->previous = &entry.frame;
1246
19.9M
    tstate->current_frame = frame;
1247
19.9M
    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
19.9M
    if (throwflag) {
1257
0
        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
0
        _Py_Instrument(_PyFrame_GetCode(frame), tstate->interp);
1275
0
        next_instr = frame->instr_ptr;
1276
0
        monitor_throw(tstate, frame, next_instr);
1277
0
        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
0
        goto error;
1286
0
#endif
1287
0
    }
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
19.9M
    goto start_frame;
1297
19.9M
#   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
0
}
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
26.3M
{
1687
26.3M
    PyCodeObject *co = (PyCodeObject*)func->func_code;
1688
26.3M
    const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
1689
    /* Create a dictionary for keyword parameters (**kwags) */
1690
26.3M
    PyObject *kwdict;
1691
26.3M
    Py_ssize_t i;
1692
26.3M
    if (co->co_flags & CO_VARKEYWORDS) {
1693
14.8k
        kwdict = PyDict_New();
1694
14.8k
        if (kwdict == NULL) {
1695
0
            goto fail_pre_positional;
1696
0
        }
1697
14.8k
        i = total_args;
1698
14.8k
        if (co->co_flags & CO_VARARGS) {
1699
5.37k
            i++;
1700
5.37k
        }
1701
14.8k
        assert(PyStackRef_IsNull(localsplus[i]));
1702
14.8k
        localsplus[i] = PyStackRef_FromPyObjectSteal(kwdict);
1703
14.8k
    }
1704
26.3M
    else {
1705
26.3M
        kwdict = NULL;
1706
26.3M
    }
1707
1708
    /* Copy all positional arguments into local variables */
1709
26.3M
    Py_ssize_t j, n;
1710
26.3M
    if (argcount > co->co_argcount) {
1711
16.0k
        n = co->co_argcount;
1712
16.0k
    }
1713
26.3M
    else {
1714
26.3M
        n = argcount;
1715
26.3M
    }
1716
74.4M
    for (j = 0; j < n; j++) {
1717
48.1M
        assert(PyStackRef_IsNull(localsplus[j]));
1718
48.1M
        localsplus[j] = args[j];
1719
48.1M
    }
1720
1721
    /* Pack other positional arguments into the *args argument */
1722
26.3M
    if (co->co_flags & CO_VARARGS) {
1723
18.7k
        PyObject *u = NULL;
1724
18.7k
        if (argcount == n) {
1725
2.62k
            u = (PyObject *)&_Py_SINGLETON(tuple_empty);
1726
2.62k
        }
1727
16.0k
        else {
1728
16.0k
            u = _PyTuple_FromStackRefStealOnSuccess(args + n, argcount - n);
1729
16.0k
            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.0k
        }
1735
18.7k
        if (u == NULL) {
1736
0
            goto fail_post_positional;
1737
0
        }
1738
18.7k
        assert(PyStackRef_AsPyObjectBorrow(localsplus[total_args]) == NULL);
1739
18.7k
        localsplus[total_args] = PyStackRef_FromPyObjectSteal(u);
1740
18.7k
    }
1741
26.3M
    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
26.3M
    if (kwnames != NULL) {
1750
14.3k
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1751
32.3k
        for (i = 0; i < kwcount; i++) {
1752
17.9k
            PyObject **co_varnames;
1753
17.9k
            PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
1754
0
            _PyStackRef value_stackref = args[i+argcount];
1755
17.9k
            Py_ssize_t j;
1756
1757
17.9k
            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
17.9k
            co_varnames = ((PyTupleObject *)(co->co_localsplusnames))->ob_item;
1767
57.5k
            for (j = co->co_posonlyargcount; j < total_args; j++) {
1768
57.4k
                PyObject *varname = co_varnames[j];
1769
57.4k
                if (varname == keyword) {
1770
17.9k
                    goto kw_found;
1771
17.9k
                }
1772
57.4k
            }
1773
1774
            /* Slow fallback, just in case */
1775
56
            for (j = co->co_posonlyargcount; j < total_args; j++) {
1776
42
                PyObject *varname = co_varnames[j];
1777
42
                int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
1778
42
                if (cmp > 0) {
1779
0
                    goto kw_found;
1780
0
                }
1781
42
                else if (cmp < 0) {
1782
0
                    goto kw_fail;
1783
0
                }
1784
42
            }
1785
1786
14
            assert(j >= total_args);
1787
14
            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
14
            if (PyDict_SetItem(kwdict, keyword, PyStackRef_AsPyObjectBorrow(value_stackref)) == -1) {
1828
0
                goto kw_fail;
1829
0
            }
1830
14
            PyStackRef_CLOSE(value_stackref);
1831
14
            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
17.9k
        kw_found:
1840
17.9k
            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
17.9k
            localsplus[j] = value_stackref;
1847
17.9k
        }
1848
14.3k
    }
1849
1850
    /* Check the number of positional arguments */
1851
26.3M
    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
26.3M
    if (argcount < co->co_argcount) {
1859
4.60M
        Py_ssize_t defcount = func->func_defaults == NULL ? 0 : PyTuple_GET_SIZE(func->func_defaults);
1860
4.60M
        Py_ssize_t m = co->co_argcount - defcount;
1861
4.60M
        Py_ssize_t missing = 0;
1862
4.60M
        for (i = argcount; i < m; i++) {
1863
571
            if (PyStackRef_IsNull(localsplus[i])) {
1864
0
                missing++;
1865
0
            }
1866
571
        }
1867
4.60M
        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
4.60M
        if (n > m)
1873
177k
            i = n - m;
1874
4.43M
        else
1875
4.43M
            i = 0;
1876
4.60M
        if (defcount) {
1877
4.60M
            PyObject **defs = &PyTuple_GET_ITEM(func->func_defaults, 0);
1878
9.26M
            for (; i < defcount; i++) {
1879
4.65M
                if (PyStackRef_AsPyObjectBorrow(localsplus[m+i]) == NULL) {
1880
4.64M
                    PyObject *def = defs[i];
1881
4.64M
                    localsplus[m+i] = PyStackRef_FromPyObjectNew(def);
1882
4.64M
                }
1883
4.65M
            }
1884
4.60M
        }
1885
4.60M
    }
1886
1887
    /* Add missing keyword arguments (copy default values from kwdefs) */
1888
26.3M
    if (co->co_kwonlyargcount > 0) {
1889
40.5k
        Py_ssize_t missing = 0;
1890
156k
        for (i = co->co_argcount; i < total_args; i++) {
1891
116k
            if (PyStackRef_AsPyObjectBorrow(localsplus[i]) != NULL)
1892
7.08k
                continue;
1893
109k
            PyObject *varname = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1894
109k
            if (func->func_kwdefaults != NULL) {
1895
109k
                PyObject *def;
1896
109k
                if (PyDict_GetItemRef(func->func_kwdefaults, varname, &def) < 0) {
1897
0
                    goto fail_post_args;
1898
0
                }
1899
109k
                if (def) {
1900
109k
                    localsplus[i] = PyStackRef_FromPyObjectSteal(def);
1901
109k
                    continue;
1902
109k
                }
1903
109k
            }
1904
0
            missing++;
1905
0
        }
1906
40.5k
        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
40.5k
    }
1912
26.3M
    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
124M
{
1934
124M
    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
124M
    assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize ==
1938
124M
        tstate->datastack_top);
1939
124M
    assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1940
124M
    _PyFrame_ClearExceptCode(frame);
1941
124M
    PyStackRef_CLEAR(frame->f_executable);
1942
124M
    _PyThreadState_PopFrame(tstate, frame);
1943
124M
}
1944
1945
static void
1946
clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1947
1.49k
{
1948
1.49k
    assert(frame->owner == FRAME_OWNED_BY_GENERATOR);
1949
1.49k
    PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame);
1950
1.49k
    FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_CLEARED);
1951
1.49k
    assert(tstate->exc_info == &gen->gi_exc_state);
1952
1.49k
    tstate->exc_info = gen->gi_exc_state.previous_item;
1953
1.49k
    gen->gi_exc_state.previous_item = NULL;
1954
1.49k
    assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1955
1.49k
    frame->previous = NULL;
1956
1.49k
    _PyFrame_ClearExceptCode(frame);
1957
1.49k
    _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
1.49k
    ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_RETURN;
1961
1.49k
}
1962
1963
void
1964
_PyEval_FrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame)
1965
124M
{
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
124M
    if (tstate->last_profiled_frame != NULL && tstate->last_profiled_frame == frame) {
1973
0
        tstate->last_profiled_frame = tstate->current_frame;
1974
0
    }
1975
1976
124M
    if (frame->owner == FRAME_OWNED_BY_THREAD) {
1977
124M
        clear_thread_frame(tstate, frame);
1978
124M
    }
1979
1.49k
    else {
1980
1.49k
        clear_gen_frame(tstate, frame);
1981
1.49k
    }
1982
124M
}
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
26.3M
{
1990
26.3M
    PyFunctionObject *func_obj = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(func);
1991
26.3M
    PyCodeObject * code = (PyCodeObject *)func_obj->func_code;
1992
26.3M
    CALL_STAT_INC(frames_pushed);
1993
26.3M
    _PyInterpreterFrame *frame = _PyThreadState_PushFrame(tstate, code->co_framesize);
1994
26.3M
    if (frame == NULL) {
1995
0
        goto fail;
1996
0
    }
1997
26.3M
    _PyFrame_Initialize(tstate, frame, func, locals, code, 0, previous);
1998
26.3M
    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
26.3M
    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
26.3M
}
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
543
{
2028
543
    bool has_dict = (kwargs != NULL && PyDict_GET_SIZE(kwargs) > 0);
2029
543
    PyObject *kwnames = NULL;
2030
543
    _PyStackRef *newargs;
2031
543
    PyObject *const *object_array = NULL;
2032
543
    _PyStackRef stack_array[8] = {0};
2033
543
    if (has_dict) {
2034
0
        object_array = _PyStack_UnpackDict(tstate, _PyTuple_ITEMS(callargs), nargs, kwargs, &kwnames);
2035
0
        if (object_array == NULL) {
2036
0
            PyStackRef_CLOSE(func);
2037
0
            goto error;
2038
0
        }
2039
0
        size_t nkwargs = PyDict_GET_SIZE(kwargs);
2040
0
        assert(sizeof(PyObject *) == sizeof(_PyStackRef));
2041
0
        newargs = (_PyStackRef *)object_array;
2042
        /* Positional args are borrowed from callargs tuple, need new reference */
2043
0
        for (Py_ssize_t i = 0; i < nargs; i++) {
2044
0
            newargs[i] = PyStackRef_FromPyObjectNew(object_array[i]);
2045
0
        }
2046
        /* Keyword args are owned by _PyStack_UnpackDict, steal them */
2047
0
        for (size_t i = 0; i < nkwargs; i++) {
2048
0
            newargs[nargs + i] = PyStackRef_FromPyObjectSteal(object_array[nargs + i]);
2049
0
        }
2050
0
    }
2051
543
    else {
2052
543
        if (nargs <= 8) {
2053
530
            newargs = stack_array;
2054
530
        }
2055
13
        else {
2056
13
            newargs = PyMem_Malloc(sizeof(_PyStackRef) *nargs);
2057
13
            if (newargs == NULL) {
2058
0
                PyErr_NoMemory();
2059
0
                PyStackRef_CLOSE(func);
2060
0
                goto error;
2061
0
            }
2062
13
        }
2063
        /* We need to create a new reference for all our args since the new frame steals them. */
2064
2.13k
        for (Py_ssize_t i = 0; i < nargs; i++) {
2065
1.59k
            newargs[i] = PyStackRef_FromPyObjectNew(PyTuple_GET_ITEM(callargs, i));
2066
1.59k
        }
2067
543
    }
2068
543
    _PyInterpreterFrame *new_frame = _PyEvalFramePushAndInit(
2069
543
        tstate, func, locals,
2070
543
        newargs, nargs, kwnames, previous
2071
543
    );
2072
543
    if (has_dict) {
2073
0
        _PyStack_UnpackDict_FreeNoDecRef(object_array, kwnames);
2074
0
    }
2075
543
    else if (nargs > 8) {
2076
13
       PyMem_Free((void *)newargs);
2077
13
    }
2078
    /* No need to decref func here because the reference has been stolen by
2079
       _PyEvalFramePushAndInit.
2080
    */
2081
543
    Py_DECREF(callargs);
2082
543
    Py_XDECREF(kwargs);
2083
543
    return new_frame;
2084
0
error:
2085
0
    Py_DECREF(callargs);
2086
0
    Py_XDECREF(kwargs);
2087
0
    return NULL;
2088
543
}
2089
2090
PyObject *
2091
_PyEval_Vector(PyThreadState *tstate, PyFunctionObject *func,
2092
               PyObject *locals,
2093
               PyObject* const* args, size_t argcount,
2094
               PyObject *kwnames)
2095
19.9M
{
2096
19.9M
    size_t total_args = argcount;
2097
19.9M
    if (kwnames) {
2098
1.34k
        total_args += PyTuple_GET_SIZE(kwnames);
2099
1.34k
    }
2100
19.9M
    _PyStackRef stack_array[8] = {0};
2101
19.9M
    _PyStackRef *arguments;
2102
19.9M
    if (total_args <= 8) {
2103
19.9M
        arguments = stack_array;
2104
19.9M
    }
2105
14
    else {
2106
14
        arguments = PyMem_Malloc(sizeof(_PyStackRef) * total_args);
2107
14
        if (arguments == NULL) {
2108
0
            return PyErr_NoMemory();
2109
0
        }
2110
14
    }
2111
    /* _PyEvalFramePushAndInit consumes the references
2112
     * to func, locals and all its arguments */
2113
19.9M
    Py_XINCREF(locals);
2114
53.2M
    for (size_t i = 0; i < argcount; i++) {
2115
33.3M
        arguments[i] = PyStackRef_FromPyObjectNew(args[i]);
2116
33.3M
    }
2117
19.9M
    if (kwnames) {
2118
1.34k
        Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
2119
5.02k
        for (Py_ssize_t i = 0; i < kwcount; i++) {
2120
3.67k
            arguments[i+argcount] = PyStackRef_FromPyObjectNew(args[i+argcount]);
2121
3.67k
        }
2122
1.34k
    }
2123
19.9M
    _PyInterpreterFrame *frame = _PyEvalFramePushAndInit(
2124
19.9M
        tstate, PyStackRef_FromPyObjectNew(func), locals,
2125
19.9M
        arguments, argcount, kwnames, NULL);
2126
19.9M
    if (total_args > 8) {
2127
14
        PyMem_Free(arguments);
2128
14
    }
2129
19.9M
    if (frame == NULL) {
2130
0
        return NULL;
2131
0
    }
2132
19.9M
    EVAL_CALL_STAT_INC(EVAL_CALL_VECTOR);
2133
19.9M
    return _PyEval_EvalFrame(tstate, frame, 0);
2134
19.9M
}
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
541
{
2307
541
    int i = 0, j = 0;
2308
541
    Py_ssize_t ll = 0;
2309
541
    PyObject *it;  /* iter(v) */
2310
541
    PyObject *w;
2311
541
    PyObject *l = NULL; /* variable list */
2312
541
    assert(v != NULL);
2313
2314
541
    it = PyObject_GetIter(v);
2315
541
    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
1.77k
    for (; i < argcnt; i++) {
2327
1.23k
        w = PyIter_Next(it);
2328
1.23k
        if (w == NULL) {
2329
            /* Iterator done, via error or exhaustion. */
2330
0
            if (!_PyErr_Occurred(tstate)) {
2331
0
                if (argcntafter == -1) {
2332
0
                    _PyErr_Format(tstate, PyExc_ValueError,
2333
0
                                  "not enough values to unpack "
2334
0
                                  "(expected %d, got %d)",
2335
0
                                  argcnt, i);
2336
0
                }
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
0
            }
2344
0
            goto Error;
2345
0
        }
2346
1.23k
        *--sp = PyStackRef_FromPyObjectSteal(w);
2347
1.23k
    }
2348
2349
541
    if (argcntafter == -1) {
2350
        /* We better have exhausted the iterator now. */
2351
541
        w = PyIter_Next(it);
2352
541
        if (w == NULL) {
2353
541
            if (_PyErr_Occurred(tstate))
2354
0
                goto Error;
2355
541
            Py_DECREF(it);
2356
541
            return 1;
2357
541
        }
2358
0
        Py_DECREF(w);
2359
2360
0
        if (PyList_CheckExact(v) || PyTuple_CheckExact(v)
2361
0
              || PyDict_CheckExact(v)) {
2362
0
            ll = PyDict_CheckExact(v) ? PyDict_Size(v) : Py_SIZE(v);
2363
0
            if (ll > argcnt) {
2364
0
                _PyErr_Format(tstate, PyExc_ValueError,
2365
0
                              "too many values to unpack (expected %d, got %zd)",
2366
0
                              argcnt, ll);
2367
0
                goto Error;
2368
0
            }
2369
0
        }
2370
0
        _PyErr_Format(tstate, PyExc_ValueError,
2371
0
                      "too many values to unpack (expected %d)",
2372
0
                      argcnt);
2373
0
        goto Error;
2374
0
    }
2375
2376
0
    l = PySequence_List(it);
2377
0
    if (l == NULL)
2378
0
        goto Error;
2379
0
    *--sp = PyStackRef_FromPyObjectSteal(l);
2380
0
    i++;
2381
2382
0
    ll = PyList_GET_SIZE(l);
2383
0
    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
0
    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
0
    Py_SET_SIZE(l, ll - argcntafter);
2396
0
    Py_DECREF(it);
2397
0
    return 1;
2398
2399
0
Error:
2400
0
    for (; i > 0; i--, sp++) {
2401
0
        PyStackRef_CLOSE(*sp);
2402
0
    }
2403
0
    Py_XDECREF(it);
2404
0
    return 0;
2405
0
}
2406
2407
2408
2409
void
2410
_PyEval_MonitorRaise(PyThreadState *tstate, _PyInterpreterFrame *frame,
2411
              _Py_CODEUNIT *instr)
2412
2.63M
{
2413
2.63M
    if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_RAISE)) {
2414
2.63M
        return;
2415
2.63M
    }
2416
0
    do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RAISE);
2417
0
}
2418
2419
bool
2420
50
_PyEval_NoToolsForUnwind(PyThreadState *tstate) {
2421
50
    return no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_UNWIND);
2422
50
}
2423
2424
2425
void
2426
PyThreadState_EnterTracing(PyThreadState *tstate)
2427
0
{
2428
0
    assert(tstate->tracing >= 0);
2429
0
    tstate->tracing++;
2430
0
}
2431
2432
void
2433
PyThreadState_LeaveTracing(PyThreadState *tstate)
2434
0
{
2435
0
    assert(tstate->tracing > 0);
2436
0
    tstate->tracing--;
2437
0
}
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
450
{
2559
450
    PyThreadState *tstate = _PyThreadState_GET();
2560
450
    return _PyThreadState_GetFrame(tstate);
2561
450
}
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
630
{
2580
630
    _PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
2581
630
    if (frame != NULL) {
2582
586
        return frame->f_builtins;
2583
586
    }
2584
44
    return tstate->interp->builtins;
2585
630
}
2586
2587
PyObject *
2588
PyEval_GetBuiltins(void)
2589
630
{
2590
630
    PyThreadState *tstate = _PyThreadState_GET();
2591
630
    return _PyEval_GetBuiltins(tstate);
2592
630
}
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
0
{
2653
0
    PyThreadState *tstate = _PyThreadState_GET();
2654
0
     _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2655
0
    if (current_frame == NULL) {
2656
0
        _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2657
0
        return NULL;
2658
0
    }
2659
2660
0
    PyObject *locals = _PyFrame_GetLocals(current_frame);
2661
0
    if (locals == NULL) {
2662
0
        return NULL;
2663
0
    }
2664
2665
0
    if (PyFrameLocalsProxy_Check(locals)) {
2666
0
        PyObject* ret = PyDict_New();
2667
0
        if (ret == NULL) {
2668
0
            Py_DECREF(locals);
2669
0
            return NULL;
2670
0
        }
2671
0
        if (PyDict_Update(ret, locals) < 0) {
2672
0
            Py_DECREF(ret);
2673
0
            Py_DECREF(locals);
2674
0
            return NULL;
2675
0
        }
2676
0
        Py_DECREF(locals);
2677
0
        return ret;
2678
0
    }
2679
2680
0
    assert(PyMapping_Check(locals));
2681
0
    return locals;
2682
0
}
2683
2684
static PyObject *
2685
_PyEval_GetGlobals(PyThreadState *tstate)
2686
200k
{
2687
200k
    _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2688
200k
    if (current_frame == NULL) {
2689
50.0k
        return NULL;
2690
50.0k
    }
2691
150k
    return current_frame->f_globals;
2692
200k
}
2693
2694
PyObject *
2695
PyEval_GetGlobals(void)
2696
200k
{
2697
200k
    PyThreadState *tstate = _PyThreadState_GET();
2698
200k
    return _PyEval_GetGlobals(tstate);
2699
200k
}
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
50.6k
{
2720
50.6k
    PyObject *builtins = NULL;
2721
50.6k
    if (PyAnyDict_Check(globals)) {
2722
50.6k
        if (PyDict_GetItemRef(globals, &_Py_ID(__builtins__), &builtins) < 0) {
2723
0
            return NULL;
2724
0
        }
2725
50.6k
    }
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
50.6k
    return builtins;
2734
50.6k
}
2735
2736
static int
2737
set_globals_builtins(PyObject *globals, PyObject *builtins)
2738
50.6k
{
2739
50.6k
    if (PyDict_Check(globals)) {
2740
50.6k
        if (PyDict_SetItem(globals, &_Py_ID(__builtins__), builtins) < 0) {
2741
0
            return -1;
2742
0
        }
2743
50.6k
    }
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
50.6k
    return 0;
2754
50.6k
}
2755
2756
int
2757
_PyEval_EnsureBuiltins(PyThreadState *tstate, PyObject *globals,
2758
                       PyObject **p_builtins)
2759
600
{
2760
600
    PyObject *builtins = get_globals_builtins(globals);
2761
600
    if (builtins == NULL) {
2762
586
        if (_PyErr_Occurred(tstate)) {
2763
0
            return -1;
2764
0
        }
2765
586
        builtins = PyEval_GetBuiltins();  // borrowed
2766
586
        if (builtins == NULL) {
2767
0
            assert(_PyErr_Occurred(tstate));
2768
0
            return -1;
2769
0
        }
2770
586
        Py_INCREF(builtins);
2771
586
        if (set_globals_builtins(globals, builtins) < 0) {
2772
0
            Py_DECREF(builtins);
2773
0
            return -1;
2774
0
        }
2775
586
    }
2776
600
    if (p_builtins != NULL) {
2777
0
        *p_builtins = builtins;
2778
0
    }
2779
600
    else {
2780
600
        Py_DECREF(builtins);
2781
600
    }
2782
600
    return 0;
2783
600
}
2784
2785
int
2786
_PyEval_EnsureBuiltinsWithModule(PyThreadState *tstate, PyObject *globals,
2787
                                 PyObject **p_builtins)
2788
50.0k
{
2789
50.0k
    PyObject *builtins = get_globals_builtins(globals);
2790
50.0k
    if (builtins == NULL) {
2791
50.0k
        if (_PyErr_Occurred(tstate)) {
2792
0
            return -1;
2793
0
        }
2794
50.0k
        builtins = PyImport_ImportModuleLevel("builtins", NULL, NULL, NULL, 0);
2795
50.0k
        if (builtins == NULL) {
2796
0
            return -1;
2797
0
        }
2798
50.0k
        if (set_globals_builtins(globals, builtins) < 0) {
2799
0
            Py_DECREF(builtins);
2800
0
            return -1;
2801
0
        }
2802
50.0k
    }
2803
50.0k
    if (p_builtins != NULL) {
2804
50.0k
        *p_builtins = builtins;
2805
50.0k
    }
2806
0
    else {
2807
0
        Py_DECREF(builtins);
2808
0
    }
2809
50.0k
    return 0;
2810
50.0k
}
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
29
{
2837
29
    PyThreadState *tstate = _PyThreadState_GET();
2838
29
    _PyInterpreterFrame *current_frame = tstate->current_frame;
2839
29
    if (current_frame == tstate->base_frame) {
2840
0
        current_frame = NULL;
2841
0
    }
2842
29
    int result = cf->cf_flags != 0;
2843
2844
29
    if (current_frame != NULL) {
2845
29
        const int codeflags = _PyFrame_GetCode(current_frame)->co_flags;
2846
29
        const int compilerflags = codeflags & PyCF_MASK;
2847
29
        if (compilerflags) {
2848
0
            result = 1;
2849
0
            cf->cf_flags |= compilerflags;
2850
0
        }
2851
29
    }
2852
29
    return result;
2853
29
}
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
3.63M
{
2891
3.63M
    if (Py_IsNone(v)) {
2892
100k
        return 1;
2893
100k
    }
2894
3.53M
    return _PyEval_SliceIndexNotNone(v, pi);
2895
3.63M
}
2896
2897
int
2898
_PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
2899
3.53M
{
2900
3.53M
    PyThreadState *tstate = _PyThreadState_GET();
2901
3.53M
    Py_ssize_t x;
2902
3.53M
    if (PyLong_CheckExact(v) && _PyLong_IsCompact((PyLongObject *)v)) {
2903
3.52M
        *pi = _PyLong_CompactValue((PyLongObject *)v);
2904
3.52M
        return 1;
2905
3.52M
    }
2906
1.08k
    if (_PyIndex_Check(v)) {
2907
704
        x = PyNumber_AsSsize_t(v, NULL);
2908
704
        if (x == -1 && _PyErr_Occurred(tstate))
2909
0
            return 0;
2910
704
    }
2911
381
    else {
2912
381
        _PyErr_SetString(tstate, PyExc_TypeError,
2913
381
                         "slice indices must be integers or "
2914
381
                         "have an __index__ method");
2915
381
        return 0;
2916
381
    }
2917
704
    *pi = x;
2918
704
    return 1;
2919
1.08k
}
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
178k
{
2926
178k
    if (len < 0) {
2927
0
        return 0;
2928
0
    }
2929
178k
    *istart = 0;
2930
178k
    *istop = PY_SSIZE_T_MAX;
2931
178k
    if (!_PyEval_SliceIndex(start, istart)) {
2932
0
        return 0;
2933
0
    }
2934
178k
    if (!_PyEval_SliceIndex(stop, istop)) {
2935
0
        return 0;
2936
0
    }
2937
178k
    PySlice_AdjustIndices(len, istart, istop, 1);
2938
178k
    return 1;
2939
178k
}
2940
2941
PyObject *
2942
_PyEval_ImportName(PyThreadState *tstate, PyObject *builtins,
2943
            PyObject *globals, PyObject *locals, PyObject *name,
2944
            PyObject *fromlist, PyObject *level)
2945
1.34M
{
2946
1.34M
    PyObject *import_func;
2947
1.34M
    if (PyMapping_GetOptionalItem(builtins, &_Py_ID(__import__),
2948
1.34M
                                  &import_func) < 0) {
2949
0
        return NULL;
2950
0
    }
2951
1.34M
    if (import_func == NULL) {
2952
0
        _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
2953
0
        return NULL;
2954
0
    }
2955
2956
1.34M
    PyObject *res = _PyEval_ImportNameWithImport(
2957
1.34M
        tstate, import_func, globals, locals, name, fromlist, level);
2958
1.34M
    Py_DECREF(import_func);
2959
1.34M
    return res;
2960
1.34M
}
2961
2962
PyObject *
2963
_PyEval_ImportNameWithImport(PyThreadState *tstate, PyObject *import_func,
2964
                             PyObject *globals, PyObject *locals,
2965
                             PyObject *name, PyObject *fromlist, PyObject *level)
2966
1.34M
{
2967
1.34M
    if (locals == NULL) {
2968
1.34M
        locals = Py_None;
2969
1.34M
    }
2970
2971
    /* Fast path for not overloaded __import__. */
2972
1.34M
    if (_PyImport_IsDefaultImportFunc(tstate->interp, import_func)) {
2973
1.34M
        int ilevel = PyLong_AsInt(level);
2974
1.34M
        if (ilevel == -1 && _PyErr_Occurred(tstate)) {
2975
0
            return NULL;
2976
0
        }
2977
1.34M
        return PyImport_ImportModuleLevelObject(
2978
1.34M
                        name,
2979
1.34M
                        globals,
2980
1.34M
                        locals,
2981
1.34M
                        fromlist,
2982
1.34M
                        ilevel);
2983
1.34M
    }
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
1.34M
}
2989
2990
static int
2991
check_lazy_import_compatibility(PyThreadState *tstate, PyObject *globals,
2992
                               PyObject *name, PyObject *level)
2993
1.56k
{
2994
     // Check if this module should be imported lazily due to
2995
     // the compatibility mode support via __lazy_modules__.
2996
1.56k
    PyObject *lazy_modules = NULL;
2997
1.56k
    PyObject *abs_name = NULL;
2998
1.56k
    int res = -1;
2999
3000
1.56k
    if (globals != NULL &&
3001
1.56k
        PyMapping_GetOptionalItem(globals, &_Py_ID(__lazy_modules__),
3002
1.56k
                                  &lazy_modules) < 0)
3003
0
    {
3004
0
        return -1;
3005
0
    }
3006
1.56k
    if (lazy_modules == NULL) {
3007
1.56k
        assert(!PyErr_Occurred());
3008
1.56k
        return 0;
3009
1.56k
    }
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
1.57k
{
3033
1.57k
    PyObject *res = NULL;
3034
    // Check if global policy overrides the local syntax
3035
1.57k
    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
1.57k
        case PyImport_LAZY_NORMAL:
3043
1.57k
            break;
3044
1.57k
    }
3045
3046
1.57k
    if (!lazy) {
3047
        // See if __lazy_modules__ forces this to be lazy.
3048
1.56k
        lazy = check_lazy_import_compatibility(tstate, globals, name, level);
3049
1.56k
        if (lazy < 0) {
3050
0
            return NULL;
3051
0
        }
3052
1.56k
    }
3053
3054
1.57k
    if (!lazy) {
3055
        // Not a lazy import or lazy imports are disabled, fallback to the
3056
        // regular import.
3057
1.56k
        return _PyEval_ImportName(tstate, builtins, globals, locals,
3058
1.56k
                                  name, fromlist, level);
3059
1.56k
    }
3060
3061
14
    PyObject *lazy_import_func;
3062
14
    if (PyMapping_GetOptionalItem(builtins, &_Py_ID(__lazy_import__),
3063
14
                                  &lazy_import_func) < 0) {
3064
0
        goto error;
3065
0
    }
3066
14
    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
14
    if (locals == NULL) {
3074
0
        locals = Py_None;
3075
0
    }
3076
3077
14
    if (_PyImport_IsDefaultLazyImportFunc(tstate->interp, lazy_import_func)) {
3078
14
        int ilevel = PyLong_AsInt(level);
3079
14
        if (ilevel == -1 && PyErr_Occurred()) {
3080
0
            goto error;
3081
0
        }
3082
3083
14
        res = _PyImport_LazyImportModuleLevelObject(
3084
14
            tstate, name, builtins, globals, locals, fromlist, ilevel
3085
14
        );
3086
14
        goto error;
3087
14
    }
3088
3089
0
    PyObject *args[6] = {name, globals, locals, fromlist, level, builtins};
3090
0
    res = PyObject_Vectorcall(lazy_import_func, args, 6, NULL);
3091
14
error:
3092
14
    Py_XDECREF(lazy_import_func);
3093
14
    return res;
3094
0
}
3095
3096
PyObject *
3097
_PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
3098
1.34k
{
3099
1.34k
    PyObject *x;
3100
1.34k
    PyObject *fullmodname, *mod_name, *origin, *mod_name_or_unknown, *errmsg, *spec;
3101
3102
1.34k
    if (PyObject_GetOptionalAttr(v, name, &x) != 0) {
3103
1.33k
        return x;
3104
1.33k
    }
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
5
    if (PyObject_GetOptionalAttr(v, &_Py_ID(__name__), &mod_name) < 0) {
3109
0
        return NULL;
3110
0
    }
3111
5
    if (mod_name == NULL || !PyUnicode_Check(mod_name)) {
3112
0
        Py_CLEAR(mod_name);
3113
0
        goto error;
3114
0
    }
3115
5
    fullmodname = PyUnicode_FromFormat("%U.%U", mod_name, name);
3116
5
    if (fullmodname == NULL) {
3117
0
        Py_DECREF(mod_name);
3118
0
        return NULL;
3119
0
    }
3120
5
    x = PyImport_GetModule(fullmodname);
3121
5
    Py_DECREF(fullmodname);
3122
5
    if (x == NULL && !_PyErr_Occurred(tstate)) {
3123
5
        goto error;
3124
5
    }
3125
0
    Py_DECREF(mod_name);
3126
0
    return x;
3127
3128
5
 error:
3129
5
    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
5
    } else {
3135
5
        mod_name_or_unknown = mod_name;
3136
5
    }
3137
    // mod_name is no longer an owned reference
3138
5
    assert(mod_name_or_unknown);
3139
5
    assert(mod_name == NULL || mod_name == mod_name_or_unknown);
3140
3141
5
    origin = NULL;
3142
5
    if (PyObject_GetOptionalAttr(v, &_Py_ID(__spec__), &spec) < 0) {
3143
0
        Py_DECREF(mod_name_or_unknown);
3144
0
        return NULL;
3145
0
    }
3146
5
    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
5
    if (_PyModuleSpec_GetFileOrigin(spec, &origin) < 0) {
3154
0
        goto done;
3155
0
    }
3156
3157
5
    int is_possibly_shadowing = _PyModule_IsPossiblyShadowing(origin);
3158
5
    if (is_possibly_shadowing < 0) {
3159
0
        goto done;
3160
0
    }
3161
5
    int is_possibly_shadowing_stdlib = 0;
3162
5
    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
5
    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
5
        origin = PyModule_GetFilenameObject(v);
3181
5
        if (origin == NULL) {
3182
5
            if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
3183
0
                goto done;
3184
0
            }
3185
            // PyModule_GetFilenameObject raised "module filename missing"
3186
5
            _PyErr_Clear(tstate);
3187
5
        }
3188
5
        assert(origin == NULL || PyUnicode_Check(origin));
3189
5
    }
3190
3191
5
    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
5
    else {
3202
5
        int rc = _PyModuleSpec_IsInitializing(spec);
3203
5
        if (rc < 0) {
3204
0
            goto done;
3205
0
        }
3206
5
        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
5
        else {
3234
5
            assert(rc == 0);
3235
5
            if (origin) {
3236
0
                errmsg = PyUnicode_FromFormat(
3237
0
                    "cannot import name %R from %R (%S)",
3238
0
                    name, mod_name_or_unknown, origin
3239
0
                );
3240
0
            }
3241
5
            else {
3242
5
                errmsg = PyUnicode_FromFormat(
3243
5
                    "cannot import name %R from %R (unknown location)",
3244
5
                    name, mod_name_or_unknown
3245
5
                );
3246
5
            }
3247
5
        }
3248
5
    }
3249
3250
5
done_with_errmsg:
3251
5
    if (errmsg != NULL) {
3252
        /* NULL checks for mod_name and origin done by _PyErr_SetImportErrorWithNameFrom */
3253
5
        _PyErr_SetImportErrorWithNameFrom(errmsg, mod_name, origin, name);
3254
5
        Py_DECREF(errmsg);
3255
5
    }
3256
3257
5
done:
3258
5
    Py_XDECREF(origin);
3259
5
    Py_XDECREF(spec);
3260
5
    Py_DECREF(mod_name_or_unknown);
3261
5
    return NULL;
3262
5
}
3263
3264
PyObject *
3265
_PyEval_LazyImportFrom(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *v, PyObject *name)
3266
14
{
3267
14
    assert(PyLazyImport_CheckExact(v));
3268
14
    assert(name);
3269
14
    assert(PyUnicode_Check(name));
3270
14
    PyObject *ret;
3271
14
    PyLazyImportObject *d = (PyLazyImportObject *)v;
3272
14
    PyObject *mod = PyImport_GetModule(d->lz_from);
3273
14
    if (mod != NULL) {
3274
        // Check if the module already has the attribute, if so, resolve it
3275
        // eagerly.
3276
1
        if (PyModule_Check(mod)) {
3277
1
            PyObject *mod_dict = PyModule_GetDict(mod);
3278
1
            if (mod_dict != NULL) {
3279
1
                if (PyDict_GetItemRef(mod_dict, name, &ret) < 0) {
3280
0
                    Py_DECREF(mod);
3281
0
                    return NULL;
3282
0
                }
3283
1
                if (ret != NULL) {
3284
1
                    Py_DECREF(mod);
3285
1
                    return ret;
3286
1
                }
3287
1
            }
3288
1
        }
3289
0
        Py_DECREF(mod);
3290
0
    }
3291
3292
13
    if (d->lz_attr != NULL) {
3293
13
        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
13
    }
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
13
    ret = _PyLazyImport_New(frame, d->lz_builtins, d->lz_from, name);
3319
13
    return ret;
3320
13
}
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
82.3k
{
3331
82.3k
    if (PyTuple_Check(right)) {
3332
817
        Py_ssize_t i, length;
3333
817
        length = PyTuple_GET_SIZE(right);
3334
2.45k
        for (i = 0; i < length; i++) {
3335
1.63k
            PyObject *exc = PyTuple_GET_ITEM(right, i);
3336
1.63k
            if (!PyExceptionClass_Check(exc)) {
3337
0
                _PyErr_SetString(tstate, PyExc_TypeError,
3338
0
                    CANNOT_CATCH_MSG);
3339
0
                return -1;
3340
0
            }
3341
1.63k
        }
3342
817
    }
3343
81.5k
    else {
3344
81.5k
        if (!PyExceptionClass_Check(right)) {
3345
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3346
0
                CANNOT_CATCH_MSG);
3347
0
            return -1;
3348
0
        }
3349
81.5k
    }
3350
82.3k
    return 0;
3351
82.3k
}
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
127
{
3393
127
    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
127
    return 0;
3400
127
}
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
4
{
3444
4
    const char *obj_str;
3445
3446
4
    if (!obj)
3447
0
        return;
3448
3449
4
    obj_str = PyUnicode_AsUTF8(obj);
3450
4
    if (!obj_str)
3451
0
        return;
3452
3453
4
    _PyErr_Format(tstate, exc, format_str, obj_str);
3454
3455
4
    if (exc == PyExc_NameError) {
3456
        // Include the name in the NameError exceptions to offer suggestions later.
3457
4
        PyObject *exc = PyErr_GetRaisedException();
3458
4
        if (PyErr_GivenExceptionMatches(exc, PyExc_NameError)) {
3459
4
            if (((PyNameErrorObject*)exc)->name == NULL) {
3460
                // We do not care if this fails because we are going to restore the
3461
                // NameError anyway.
3462
4
                (void)PyObject_SetAttr(exc, &_Py_ID(name), obj);
3463
4
            }
3464
4
        }
3465
4
        PyErr_SetRaisedException(exc);
3466
4
    }
3467
4
}
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
5.30M
{
3541
5.30M
    return _Py_EnterRecursiveCall(where);
3542
5.30M
}
3543
3544
void Py_LeaveRecursiveCall(void)
3545
3.54M
{
3546
3.54M
    _Py_LeaveRecursiveCall();
3547
3.54M
}
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
52.4k
{
3591
52.4k
    if (PyAnyDict_CheckExact(globals) && PyAnyDict_CheckExact(builtins)) {
3592
52.4k
        _PyDict_LoadGlobalStackRef((PyDictObject *)globals,
3593
52.4k
                                    (PyDictObject *)builtins,
3594
52.4k
                                    name, writeto);
3595
52.4k
        if (PyStackRef_IsNull(*writeto) && !PyErr_Occurred()) {
3596
            /* _PyDict_LoadGlobal() returns NULL without raising
3597
                * an exception if the key doesn't exist */
3598
4
            _PyEval_FormatExcCheckArg(PyThreadState_GET(), PyExc_NameError,
3599
4
                                        NAME_ERROR_MSG, name);
3600
4
        }
3601
52.4k
    }
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
52.4k
    PyObject *res_o = PyStackRef_AsPyObjectBorrow(*writeto);
3628
52.4k
    if (res_o != NULL && PyLazyImport_CheckExact(res_o)) {
3629
0
        PyObject *l_v = _PyImport_LoadLazyImportTstate(PyThreadState_GET(), res_o);
3630
0
        PyStackRef_CLOSE(writeto[0]);
3631
0
        if (l_v == NULL) {
3632
0
            assert(PyErr_Occurred());
3633
0
            *writeto = PyStackRef_NULL;
3634
0
            return;
3635
0
        }
3636
0
        int err = PyDict_SetItem(globals, name, l_v);
3637
0
        if (err < 0) {
3638
0
            Py_DECREF(l_v);
3639
0
            *writeto = PyStackRef_NULL;
3640
0
            return;
3641
0
        }
3642
0
        *writeto = PyStackRef_FromPyObjectSteal(l_v);
3643
0
    }
3644
52.4k
}
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
29.6k
{
3673
3674
29.6k
    PyObject *value;
3675
29.6k
    if (frame->f_locals == NULL) {
3676
0
        _PyErr_SetString(tstate, PyExc_SystemError,
3677
0
                            "no locals found");
3678
0
        return NULL;
3679
0
    }
3680
29.6k
    if (PyMapping_GetOptionalItem(frame->f_locals, name, &value) < 0) {
3681
0
        return NULL;
3682
0
    }
3683
29.6k
    if (value != NULL) {
3684
19.6k
        return value;
3685
19.6k
    }
3686
9.97k
    if (PyDict_GetItemRef(frame->f_globals, name, &value) < 0) {
3687
0
        return NULL;
3688
0
    }
3689
9.97k
    if (value != NULL) {
3690
4.68k
        return value;
3691
4.68k
    }
3692
5.28k
    if (PyMapping_GetOptionalItem(frame->f_builtins, name, &value) < 0) {
3693
0
        return NULL;
3694
0
    }
3695
5.28k
    if (value == NULL) {
3696
0
        _PyEval_FormatExcCheckArg(
3697
0
                    tstate, PyExc_NameError,
3698
0
                    NAME_ERROR_MSG, name);
3699
0
    }
3700
5.28k
    return value;
3701
5.28k
}
3702
3703
static _PyStackRef
3704
foriter_next(PyObject *seq, _PyStackRef index)
3705
778k
{
3706
778k
    assert(PyStackRef_IsTaggedInt(index));
3707
778k
    assert(PyTuple_CheckExact(seq) || PyList_CheckExact(seq));
3708
778k
    intptr_t i = PyStackRef_UntagInt(index);
3709
778k
    if (PyTuple_CheckExact(seq)) {
3710
446
        size_t size = PyTuple_GET_SIZE(seq);
3711
446
        if ((size_t)i >= size) {
3712
58
            return PyStackRef_NULL;
3713
58
        }
3714
388
        return PyStackRef_FromPyObjectNew(PyTuple_GET_ITEM(seq, i));
3715
388
    }
3716
777k
    PyObject *item = _PyList_GetItemRef((PyListObject *)seq, i);
3717
777k
    if (item == NULL) {
3718
1.73k
        return PyStackRef_NULL;
3719
1.73k
    }
3720
775k
    return PyStackRef_FromPyObjectSteal(item);
3721
777k
}
3722
3723
_PyStackRef _PyForIter_VirtualIteratorNext(PyThreadState* tstate, _PyInterpreterFrame* frame, _PyStackRef iter, _PyStackRef* index_ptr)
3724
14.5M
{
3725
14.5M
    PyObject *iter_o = PyStackRef_AsPyObjectBorrow(iter);
3726
14.5M
    _PyStackRef index = *index_ptr;
3727
14.5M
    if (PyStackRef_IsTaggedInt(index)) {
3728
778k
        *index_ptr = PyStackRef_IncrementTaggedIntNoOverflow(index);
3729
778k
        return foriter_next(iter_o, index);
3730
778k
    }
3731
13.7M
    PyObject *next_o = (*Py_TYPE(iter_o)->tp_iternext)(iter_o);
3732
13.7M
    if (next_o == NULL) {
3733
2.27M
        if (_PyErr_Occurred(tstate)) {
3734
6
            if (_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
3735
0
                _PyEval_MonitorRaise(tstate, frame, frame->instr_ptr);
3736
0
                _PyErr_Clear(tstate);
3737
0
            }
3738
6
            else {
3739
6
                return PyStackRef_ERROR;
3740
6
            }
3741
6
        }
3742
2.27M
        return PyStackRef_NULL;
3743
2.27M
    }
3744
11.4M
    return PyStackRef_FromPyObjectSteal(next_o);
3745
13.7M
}
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
}