Coverage Report

Created: 2026-02-09 07:07

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