Coverage Report

Created: 2026-04-12 06:54

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