Coverage Report

Created: 2026-02-26 06:53

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