Coverage Report

Created: 2025-11-24 06:11

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