Coverage Report

Created: 2026-05-30 06:18

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