Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Python/ceval.c
12 views
1
/* Execute compiled code */
2
3
#define _PY_INTERPRETER
4
5
#include "Python.h"
6
#include "pycore_abstract.h" // _PyIndex_Check()
7
#include "pycore_call.h" // _PyObject_CallNoArgs()
8
#include "pycore_ceval.h" // _PyEval_SignalAsyncExc()
9
#include "pycore_code.h"
10
#include "pycore_function.h"
11
#include "pycore_intrinsics.h"
12
#include "pycore_long.h" // _PyLong_GetZero()
13
#include "pycore_instruments.h"
14
#include "pycore_object.h" // _PyObject_GC_TRACK()
15
#include "pycore_moduleobject.h" // PyModuleObject
16
#include "pycore_opcode.h" // EXTRA_CASES
17
#include "pycore_opcode_utils.h" // MAKE_FUNCTION_*
18
#include "pycore_pyerrors.h" // _PyErr_GetRaisedException()
19
#include "pycore_pystate.h" // _PyInterpreterState_GET()
20
#include "pycore_range.h" // _PyRangeIterObject
21
#include "pycore_sliceobject.h" // _PyBuildSlice_ConsumeRefs
22
#include "pycore_sysmodule.h" // _PySys_Audit()
23
#include "pycore_tuple.h" // _PyTuple_ITEMS()
24
#include "pycore_typeobject.h" // _PySuper_Lookup()
25
#include "pycore_uops.h" // _PyUOpExecutorObject
26
#include "pycore_emscripten_signal.h" // _Py_CHECK_EMSCRIPTEN_SIGNALS
27
28
#include "pycore_dict.h"
29
#include "dictobject.h"
30
#include "pycore_frame.h"
31
#include "frameobject.h" // _PyInterpreterFrame_GetLine
32
#include "opcode.h"
33
#include "opcode_metadata.h"
34
#include "pydtrace.h"
35
#include "setobject.h"
36
#include "structmember.h" // struct PyMemberDef, T_OFFSET_EX
37
38
#include <ctype.h>
39
#include <stdbool.h>
40
41
#ifdef Py_DEBUG
42
/* For debugging the interpreter: */
43
# define LLTRACE 1 /* Low-level trace feature */
44
#endif
45
46
#if !defined(Py_BUILD_CORE)
47
# error "ceval.c must be build with Py_BUILD_CORE define for best performance"
48
#endif
49
50
#if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
51
// GH-89279: The MSVC compiler does not inline these static inline functions
52
// in PGO build in _PyEval_EvalFrameDefault(), because this function is over
53
// the limit of PGO, and that limit cannot be configured.
54
// Define them as macros to make sure that they are always inlined by the
55
// preprocessor.
56
57
#undef Py_DECREF
58
#define Py_DECREF(arg) \
59
do { \
60
PyObject *op = _PyObject_CAST(arg); \
61
if (_Py_IsImmortal(op)) { \
62
break; \
63
} \
64
_Py_DECREF_STAT_INC(); \
65
if (--op->ob_refcnt == 0) { \
66
destructor dealloc = Py_TYPE(op)->tp_dealloc; \
67
(*dealloc)(op); \
68
} \
69
} while (0)
70
71
#undef Py_XDECREF
72
#define Py_XDECREF(arg) \
73
do { \
74
PyObject *xop = _PyObject_CAST(arg); \
75
if (xop != NULL) { \
76
Py_DECREF(xop); \
77
} \
78
} while (0)
79
80
#undef Py_IS_TYPE
81
#define Py_IS_TYPE(ob, type) \
82
(_PyObject_CAST(ob)->ob_type == (type))
83
84
#undef _Py_DECREF_SPECIALIZED
85
#define _Py_DECREF_SPECIALIZED(arg, dealloc) \
86
do { \
87
PyObject *op = _PyObject_CAST(arg); \
88
if (_Py_IsImmortal(op)) { \
89
break; \
90
} \
91
_Py_DECREF_STAT_INC(); \
92
if (--op->ob_refcnt == 0) { \
93
destructor d = (destructor)(dealloc); \
94
d(op); \
95
} \
96
} while (0)
97
#endif
98
99
// GH-89279: Similar to above, force inlining by using a macro.
100
#if defined(_MSC_VER) && SIZEOF_INT == 4
101
#define _Py_atomic_load_relaxed_int32(ATOMIC_VAL) (assert(sizeof((ATOMIC_VAL)->_value) == 4), *((volatile int*)&((ATOMIC_VAL)->_value)))
102
#else
103
#define _Py_atomic_load_relaxed_int32(ATOMIC_VAL) _Py_atomic_load_relaxed(ATOMIC_VAL)
104
#endif
105
106
107
#ifdef LLTRACE
108
static void
109
dump_stack(_PyInterpreterFrame *frame, PyObject **stack_pointer)
110
{
111
PyObject **stack_base = _PyFrame_Stackbase(frame);
112
PyObject *exc = PyErr_GetRaisedException();
113
printf(" stack=[");
114
for (PyObject **ptr = stack_base; ptr < stack_pointer; ptr++) {
115
if (ptr != stack_base) {
116
printf(", ");
117
}
118
if (PyObject_Print(*ptr, stdout, 0) != 0) {
119
PyErr_Clear();
120
printf("<%s object at %p>",
121
Py_TYPE(*ptr)->tp_name, (void *)(*ptr));
122
}
123
}
124
printf("]\n");
125
fflush(stdout);
126
PyErr_SetRaisedException(exc);
127
}
128
129
static void
130
lltrace_instruction(_PyInterpreterFrame *frame,
131
PyObject **stack_pointer,
132
_Py_CODEUNIT *next_instr)
133
{
134
if (frame->owner == FRAME_OWNED_BY_CSTACK) {
135
return;
136
}
137
/* This dump_stack() operation is risky, since the repr() of some
138
objects enters the interpreter recursively. It is also slow.
139
So you might want to comment it out. */
140
dump_stack(frame, stack_pointer);
141
int oparg = next_instr->op.arg;
142
int opcode = next_instr->op.code;
143
const char *opname = _PyOpcode_OpName[opcode];
144
assert(opname != NULL);
145
int offset = (int)(next_instr - _PyCode_CODE(_PyFrame_GetCode(frame)));
146
if (OPCODE_HAS_ARG((int)_PyOpcode_Deopt[opcode])) {
147
printf("%d: %s %d\n", offset * 2, opname, oparg);
148
}
149
else {
150
printf("%d: %s\n", offset * 2, opname);
151
}
152
fflush(stdout);
153
}
154
static void
155
lltrace_resume_frame(_PyInterpreterFrame *frame)
156
{
157
PyObject *fobj = frame->f_funcobj;
158
if (!PyCode_Check(frame->f_executable) ||
159
fobj == NULL ||
160
!PyFunction_Check(fobj)
161
) {
162
printf("\nResuming frame.\n");
163
return;
164
}
165
PyFunctionObject *f = (PyFunctionObject *)fobj;
166
PyObject *exc = PyErr_GetRaisedException();
167
PyObject *name = f->func_qualname;
168
if (name == NULL) {
169
name = f->func_name;
170
}
171
printf("\nResuming frame");
172
if (name) {
173
printf(" for ");
174
if (PyObject_Print(name, stdout, 0) < 0) {
175
PyErr_Clear();
176
}
177
}
178
if (f->func_module) {
179
printf(" in module ");
180
if (PyObject_Print(f->func_module, stdout, 0) < 0) {
181
PyErr_Clear();
182
}
183
}
184
printf("\n");
185
fflush(stdout);
186
PyErr_SetRaisedException(exc);
187
}
188
#endif
189
190
static void monitor_raise(PyThreadState *tstate,
191
_PyInterpreterFrame *frame,
192
_Py_CODEUNIT *instr);
193
static int monitor_stop_iteration(PyThreadState *tstate,
194
_PyInterpreterFrame *frame,
195
_Py_CODEUNIT *instr);
196
static void monitor_unwind(PyThreadState *tstate,
197
_PyInterpreterFrame *frame,
198
_Py_CODEUNIT *instr);
199
static void monitor_handled(PyThreadState *tstate,
200
_PyInterpreterFrame *frame,
201
_Py_CODEUNIT *instr, PyObject *exc);
202
static void monitor_throw(PyThreadState *tstate,
203
_PyInterpreterFrame *frame,
204
_Py_CODEUNIT *instr);
205
206
static PyObject * import_name(PyThreadState *, _PyInterpreterFrame *,
207
PyObject *, PyObject *, PyObject *);
208
static PyObject * import_from(PyThreadState *, PyObject *, PyObject *);
209
static void format_exc_check_arg(PyThreadState *, PyObject *, const char *, PyObject *);
210
static void format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
211
static int check_args_iterable(PyThreadState *, PyObject *func, PyObject *vararg);
212
static int check_except_type_valid(PyThreadState *tstate, PyObject* right);
213
static int check_except_star_type_valid(PyThreadState *tstate, PyObject* right);
214
static void format_kwargs_error(PyThreadState *, PyObject *func, PyObject *kwargs);
215
static void format_awaitable_error(PyThreadState *, PyTypeObject *, int);
216
static int get_exception_handler(PyCodeObject *, int, int*, int*, int*);
217
static _PyInterpreterFrame *
218
_PyEvalFramePushAndInit(PyThreadState *tstate, PyFunctionObject *func,
219
PyObject *locals, PyObject* const* args,
220
size_t argcount, PyObject *kwnames);
221
static _PyInterpreterFrame *
222
_PyEvalFramePushAndInit_Ex(PyThreadState *tstate, PyFunctionObject *func,
223
PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs);
224
static void
225
_PyEvalFrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame *frame);
226
227
#define UNBOUNDLOCAL_ERROR_MSG \
228
"cannot access local variable '%s' where it is not associated with a value"
229
#define UNBOUNDFREE_ERROR_MSG \
230
"cannot access free variable '%s' where it is not associated with a" \
231
" value in enclosing scope"
232
233
#ifdef HAVE_ERRNO_H
234
#include <errno.h>
235
#endif
236
237
int
238
Py_GetRecursionLimit(void)
239
{
240
PyInterpreterState *interp = _PyInterpreterState_GET();
241
return interp->ceval.recursion_limit;
242
}
243
244
void
245
Py_SetRecursionLimit(int new_limit)
246
{
247
PyInterpreterState *interp = _PyInterpreterState_GET();
248
interp->ceval.recursion_limit = new_limit;
249
for (PyThreadState *p = interp->threads.head; p != NULL; p = p->next) {
250
int depth = p->py_recursion_limit - p->py_recursion_remaining;
251
p->py_recursion_limit = new_limit;
252
p->py_recursion_remaining = new_limit - depth;
253
}
254
}
255
256
/* The function _Py_EnterRecursiveCallTstate() only calls _Py_CheckRecursiveCall()
257
if the recursion_depth reaches recursion_limit. */
258
int
259
_Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
260
{
261
#ifdef USE_STACKCHECK
262
if (PyOS_CheckStack()) {
263
++tstate->c_recursion_remaining;
264
_PyErr_SetString(tstate, PyExc_MemoryError, "Stack overflow");
265
return -1;
266
}
267
#endif
268
if (tstate->recursion_headroom) {
269
if (tstate->c_recursion_remaining < -50) {
270
/* Overflowing while handling an overflow. Give up. */
271
Py_FatalError("Cannot recover from stack overflow.");
272
}
273
}
274
else {
275
if (tstate->c_recursion_remaining <= 0) {
276
tstate->recursion_headroom++;
277
_PyErr_Format(tstate, PyExc_RecursionError,
278
"maximum recursion depth exceeded%s",
279
where);
280
tstate->recursion_headroom--;
281
++tstate->c_recursion_remaining;
282
return -1;
283
}
284
}
285
return 0;
286
}
287
288
289
static const binaryfunc binary_ops[] = {
290
[NB_ADD] = PyNumber_Add,
291
[NB_AND] = PyNumber_And,
292
[NB_FLOOR_DIVIDE] = PyNumber_FloorDivide,
293
[NB_LSHIFT] = PyNumber_Lshift,
294
[NB_MATRIX_MULTIPLY] = PyNumber_MatrixMultiply,
295
[NB_MULTIPLY] = PyNumber_Multiply,
296
[NB_REMAINDER] = PyNumber_Remainder,
297
[NB_OR] = PyNumber_Or,
298
[NB_POWER] = _PyNumber_PowerNoMod,
299
[NB_RSHIFT] = PyNumber_Rshift,
300
[NB_SUBTRACT] = PyNumber_Subtract,
301
[NB_TRUE_DIVIDE] = PyNumber_TrueDivide,
302
[NB_XOR] = PyNumber_Xor,
303
[NB_INPLACE_ADD] = PyNumber_InPlaceAdd,
304
[NB_INPLACE_AND] = PyNumber_InPlaceAnd,
305
[NB_INPLACE_FLOOR_DIVIDE] = PyNumber_InPlaceFloorDivide,
306
[NB_INPLACE_LSHIFT] = PyNumber_InPlaceLshift,
307
[NB_INPLACE_MATRIX_MULTIPLY] = PyNumber_InPlaceMatrixMultiply,
308
[NB_INPLACE_MULTIPLY] = PyNumber_InPlaceMultiply,
309
[NB_INPLACE_REMAINDER] = PyNumber_InPlaceRemainder,
310
[NB_INPLACE_OR] = PyNumber_InPlaceOr,
311
[NB_INPLACE_POWER] = _PyNumber_InPlacePowerNoMod,
312
[NB_INPLACE_RSHIFT] = PyNumber_InPlaceRshift,
313
[NB_INPLACE_SUBTRACT] = PyNumber_InPlaceSubtract,
314
[NB_INPLACE_TRUE_DIVIDE] = PyNumber_InPlaceTrueDivide,
315
[NB_INPLACE_XOR] = PyNumber_InPlaceXor,
316
};
317
318
319
// PEP 634: Structural Pattern Matching
320
321
322
// Return a tuple of values corresponding to keys, with error checks for
323
// duplicate/missing keys.
324
static PyObject*
325
match_keys(PyThreadState *tstate, PyObject *map, PyObject *keys)
326
{
327
assert(PyTuple_CheckExact(keys));
328
Py_ssize_t nkeys = PyTuple_GET_SIZE(keys);
329
if (!nkeys) {
330
// No keys means no items.
331
return PyTuple_New(0);
332
}
333
PyObject *seen = NULL;
334
PyObject *dummy = NULL;
335
PyObject *values = NULL;
336
PyObject *get = NULL;
337
// We use the two argument form of map.get(key, default) for two reasons:
338
// - Atomically check for a key and get its value without error handling.
339
// - Don't cause key creation or resizing in dict subclasses like
340
// collections.defaultdict that define __missing__ (or similar).
341
int meth_found = _PyObject_GetMethod(map, &_Py_ID(get), &get);
342
if (get == NULL) {
343
goto fail;
344
}
345
seen = PySet_New(NULL);
346
if (seen == NULL) {
347
goto fail;
348
}
349
// dummy = object()
350
dummy = _PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
351
if (dummy == NULL) {
352
goto fail;
353
}
354
values = PyTuple_New(nkeys);
355
if (values == NULL) {
356
goto fail;
357
}
358
for (Py_ssize_t i = 0; i < nkeys; i++) {
359
PyObject *key = PyTuple_GET_ITEM(keys, i);
360
if (PySet_Contains(seen, key) || PySet_Add(seen, key)) {
361
if (!_PyErr_Occurred(tstate)) {
362
// Seen it before!
363
_PyErr_Format(tstate, PyExc_ValueError,
364
"mapping pattern checks duplicate key (%R)", key);
365
}
366
goto fail;
367
}
368
PyObject *args[] = { map, key, dummy };
369
PyObject *value = NULL;
370
if (meth_found) {
371
value = PyObject_Vectorcall(get, args, 3, NULL);
372
}
373
else {
374
value = PyObject_Vectorcall(get, &args[1], 2, NULL);
375
}
376
if (value == NULL) {
377
goto fail;
378
}
379
if (value == dummy) {
380
// key not in map!
381
Py_DECREF(value);
382
Py_DECREF(values);
383
// Return None:
384
values = Py_NewRef(Py_None);
385
goto done;
386
}
387
PyTuple_SET_ITEM(values, i, value);
388
}
389
// Success:
390
done:
391
Py_DECREF(get);
392
Py_DECREF(seen);
393
Py_DECREF(dummy);
394
return values;
395
fail:
396
Py_XDECREF(get);
397
Py_XDECREF(seen);
398
Py_XDECREF(dummy);
399
Py_XDECREF(values);
400
return NULL;
401
}
402
403
// Extract a named attribute from the subject, with additional bookkeeping to
404
// raise TypeErrors for repeated lookups. On failure, return NULL (with no
405
// error set). Use _PyErr_Occurred(tstate) to disambiguate.
406
static PyObject*
407
match_class_attr(PyThreadState *tstate, PyObject *subject, PyObject *type,
408
PyObject *name, PyObject *seen)
409
{
410
assert(PyUnicode_CheckExact(name));
411
assert(PySet_CheckExact(seen));
412
if (PySet_Contains(seen, name) || PySet_Add(seen, name)) {
413
if (!_PyErr_Occurred(tstate)) {
414
// Seen it before!
415
_PyErr_Format(tstate, PyExc_TypeError,
416
"%s() got multiple sub-patterns for attribute %R",
417
((PyTypeObject*)type)->tp_name, name);
418
}
419
return NULL;
420
}
421
PyObject *attr = PyObject_GetAttr(subject, name);
422
if (attr == NULL && _PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
423
_PyErr_Clear(tstate);
424
}
425
return attr;
426
}
427
428
// On success (match), return a tuple of extracted attributes. On failure (no
429
// match), return NULL. Use _PyErr_Occurred(tstate) to disambiguate.
430
static PyObject*
431
match_class(PyThreadState *tstate, PyObject *subject, PyObject *type,
432
Py_ssize_t nargs, PyObject *kwargs)
433
{
434
if (!PyType_Check(type)) {
435
const char *e = "called match pattern must be a class";
436
_PyErr_Format(tstate, PyExc_TypeError, e);
437
return NULL;
438
}
439
assert(PyTuple_CheckExact(kwargs));
440
// First, an isinstance check:
441
if (PyObject_IsInstance(subject, type) <= 0) {
442
return NULL;
443
}
444
// So far so good:
445
PyObject *seen = PySet_New(NULL);
446
if (seen == NULL) {
447
return NULL;
448
}
449
PyObject *attrs = PyList_New(0);
450
if (attrs == NULL) {
451
Py_DECREF(seen);
452
return NULL;
453
}
454
// NOTE: From this point on, goto fail on failure:
455
PyObject *match_args = NULL;
456
// First, the positional subpatterns:
457
if (nargs) {
458
int match_self = 0;
459
match_args = PyObject_GetAttrString(type, "__match_args__");
460
if (match_args) {
461
if (!PyTuple_CheckExact(match_args)) {
462
const char *e = "%s.__match_args__ must be a tuple (got %s)";
463
_PyErr_Format(tstate, PyExc_TypeError, e,
464
((PyTypeObject *)type)->tp_name,
465
Py_TYPE(match_args)->tp_name);
466
goto fail;
467
}
468
}
469
else if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
470
_PyErr_Clear(tstate);
471
// _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
472
// define __match_args__. This is natural behavior for subclasses:
473
// it's as if __match_args__ is some "magic" value that is lost as
474
// soon as they redefine it.
475
match_args = PyTuple_New(0);
476
match_self = PyType_HasFeature((PyTypeObject*)type,
477
_Py_TPFLAGS_MATCH_SELF);
478
}
479
else {
480
goto fail;
481
}
482
assert(PyTuple_CheckExact(match_args));
483
Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
484
if (allowed < nargs) {
485
const char *plural = (allowed == 1) ? "" : "s";
486
_PyErr_Format(tstate, PyExc_TypeError,
487
"%s() accepts %d positional sub-pattern%s (%d given)",
488
((PyTypeObject*)type)->tp_name,
489
allowed, plural, nargs);
490
goto fail;
491
}
492
if (match_self) {
493
// Easy. Copy the subject itself, and move on to kwargs.
494
PyList_Append(attrs, subject);
495
}
496
else {
497
for (Py_ssize_t i = 0; i < nargs; i++) {
498
PyObject *name = PyTuple_GET_ITEM(match_args, i);
499
if (!PyUnicode_CheckExact(name)) {
500
_PyErr_Format(tstate, PyExc_TypeError,
501
"__match_args__ elements must be strings "
502
"(got %s)", Py_TYPE(name)->tp_name);
503
goto fail;
504
}
505
PyObject *attr = match_class_attr(tstate, subject, type, name,
506
seen);
507
if (attr == NULL) {
508
goto fail;
509
}
510
PyList_Append(attrs, attr);
511
Py_DECREF(attr);
512
}
513
}
514
Py_CLEAR(match_args);
515
}
516
// Finally, the keyword subpatterns:
517
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
518
PyObject *name = PyTuple_GET_ITEM(kwargs, i);
519
PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
520
if (attr == NULL) {
521
goto fail;
522
}
523
PyList_Append(attrs, attr);
524
Py_DECREF(attr);
525
}
526
Py_SETREF(attrs, PyList_AsTuple(attrs));
527
Py_DECREF(seen);
528
return attrs;
529
fail:
530
// We really don't care whether an error was raised or not... that's our
531
// caller's problem. All we know is that the match failed.
532
Py_XDECREF(match_args);
533
Py_DECREF(seen);
534
Py_DECREF(attrs);
535
return NULL;
536
}
537
538
539
static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
540
static int exception_group_match(
541
PyObject* exc_value, PyObject *match_type,
542
PyObject **match, PyObject **rest);
543
544
static int unpack_iterable(PyThreadState *, PyObject *, int, int, PyObject **);
545
546
PyObject *
547
PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
548
{
549
PyThreadState *tstate = _PyThreadState_GET();
550
if (locals == NULL) {
551
locals = globals;
552
}
553
PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
554
if (builtins == NULL) {
555
return NULL;
556
}
557
PyFrameConstructor desc = {
558
.fc_globals = globals,
559
.fc_builtins = builtins,
560
.fc_name = ((PyCodeObject *)co)->co_name,
561
.fc_qualname = ((PyCodeObject *)co)->co_name,
562
.fc_code = co,
563
.fc_defaults = NULL,
564
.fc_kwdefaults = NULL,
565
.fc_closure = NULL
566
};
567
PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
568
if (func == NULL) {
569
return NULL;
570
}
571
EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
572
PyObject *res = _PyEval_Vector(tstate, func, locals, NULL, 0, NULL);
573
Py_DECREF(func);
574
return res;
575
}
576
577
578
/* Interpreter main loop */
579
580
PyObject *
581
PyEval_EvalFrame(PyFrameObject *f)
582
{
583
/* Function kept for backward compatibility */
584
PyThreadState *tstate = _PyThreadState_GET();
585
return _PyEval_EvalFrame(tstate, f->f_frame, 0);
586
}
587
588
PyObject *
589
PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
590
{
591
PyThreadState *tstate = _PyThreadState_GET();
592
return _PyEval_EvalFrame(tstate, f->f_frame, throwflag);
593
}
594
595
#include "ceval_macros.h"
596
597
598
int _Py_CheckRecursiveCallPy(
599
PyThreadState *tstate)
600
{
601
if (tstate->recursion_headroom) {
602
if (tstate->py_recursion_remaining < -50) {
603
/* Overflowing while handling an overflow. Give up. */
604
Py_FatalError("Cannot recover from Python stack overflow.");
605
}
606
}
607
else {
608
if (tstate->py_recursion_remaining <= 0) {
609
tstate->recursion_headroom++;
610
_PyErr_Format(tstate, PyExc_RecursionError,
611
"maximum recursion depth exceeded");
612
tstate->recursion_headroom--;
613
return -1;
614
}
615
}
616
return 0;
617
}
618
619
static inline int _Py_EnterRecursivePy(PyThreadState *tstate) {
620
return (tstate->py_recursion_remaining-- <= 0) &&
621
_Py_CheckRecursiveCallPy(tstate);
622
}
623
624
625
static inline void _Py_LeaveRecursiveCallPy(PyThreadState *tstate) {
626
tstate->py_recursion_remaining++;
627
}
628
629
static const _Py_CODEUNIT _Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS[] = {
630
/* Put a NOP at the start, so that the IP points into
631
* the code, rather than before it */
632
{ .op.code = NOP, .op.arg = 0 },
633
{ .op.code = INTERPRETER_EXIT, .op.arg = 0 },
634
{ .op.code = RESUME, .op.arg = 0 }
635
};
636
637
extern const struct _PyCode_DEF(8) _Py_InitCleanup;
638
639
/* Disable unused label warnings. They are handy for debugging, even
640
if computed gotos aren't used. */
641
642
/* TBD - what about other compilers? */
643
#if defined(__GNUC__)
644
# pragma GCC diagnostic push
645
# pragma GCC diagnostic ignored "-Wunused-label"
646
#elif defined(_MSC_VER) /* MS_WINDOWS */
647
# pragma warning(push)
648
# pragma warning(disable:4102)
649
#endif
650
651
PyObject* _Py_HOT_FUNCTION
652
_PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
653
{
654
_Py_EnsureTstateNotNULL(tstate);
655
CALL_STAT_INC(pyeval_calls);
656
657
#if USE_COMPUTED_GOTOS
658
/* Import the static jump table */
659
#include "opcode_targets.h"
660
#endif
661
662
#ifdef Py_STATS
663
int lastopcode = 0;
664
#endif
665
// opcode is an 8-bit value to improve the code generated by MSVC
666
// for the big switch below (in combination with the EXTRA_CASES macro).
667
uint8_t opcode; /* Current opcode */
668
int oparg; /* Current opcode argument, if any */
669
#ifdef LLTRACE
670
int lltrace = 0;
671
#endif
672
673
_PyCFrame cframe;
674
_PyInterpreterFrame entry_frame;
675
PyObject *kwnames = NULL; // Borrowed reference. Reset by CALL instructions.
676
677
/* WARNING: Because the _PyCFrame lives on the C stack,
678
* but can be accessed from a heap allocated object (tstate)
679
* strict stack discipline must be maintained.
680
*/
681
_PyCFrame *prev_cframe = tstate->cframe;
682
cframe.previous = prev_cframe;
683
tstate->cframe = &cframe;
684
685
#ifdef Py_DEBUG
686
/* Set these to invalid but identifiable values for debugging. */
687
entry_frame.f_funcobj = (PyObject*)0xaaa0;
688
entry_frame.f_locals = (PyObject*)0xaaa1;
689
entry_frame.frame_obj = (PyFrameObject*)0xaaa2;
690
entry_frame.f_globals = (PyObject*)0xaaa3;
691
entry_frame.f_builtins = (PyObject*)0xaaa4;
692
#endif
693
entry_frame.f_executable = Py_None;
694
entry_frame.prev_instr = (_Py_CODEUNIT *)_Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS;
695
entry_frame.stacktop = 0;
696
entry_frame.owner = FRAME_OWNED_BY_CSTACK;
697
entry_frame.return_offset = 0;
698
/* Push frame */
699
entry_frame.previous = prev_cframe->current_frame;
700
frame->previous = &entry_frame;
701
cframe.current_frame = frame;
702
703
if (_Py_EnterRecursiveCallTstate(tstate, "")) {
704
tstate->c_recursion_remaining--;
705
tstate->py_recursion_remaining--;
706
goto exit_unwind;
707
}
708
709
/* support for generator.throw() */
710
if (throwflag) {
711
if (_Py_EnterRecursivePy(tstate)) {
712
goto exit_unwind;
713
}
714
/* Because this avoids the RESUME,
715
* we need to update instrumentation */
716
_Py_Instrument(_PyFrame_GetCode(frame), tstate->interp);
717
monitor_throw(tstate, frame, frame->prev_instr);
718
/* TO DO -- Monitor throw entry. */
719
goto resume_with_error;
720
}
721
722
/* Local "register" variables.
723
* These are cached values from the frame and code object. */
724
725
_Py_CODEUNIT *next_instr;
726
PyObject **stack_pointer;
727
728
/* Sets the above local variables from the frame */
729
#define SET_LOCALS_FROM_FRAME() \
730
/* Jump back to the last instruction executed... */ \
731
next_instr = frame->prev_instr + 1; \
732
stack_pointer = _PyFrame_GetStackPointer(frame);
733
734
start_frame:
735
if (_Py_EnterRecursivePy(tstate)) {
736
goto exit_unwind;
737
}
738
739
resume_frame:
740
SET_LOCALS_FROM_FRAME();
741
742
#ifdef LLTRACE
743
{
744
if (frame != &entry_frame && GLOBALS()) {
745
int r = PyDict_Contains(GLOBALS(), &_Py_ID(__lltrace__));
746
if (r < 0) {
747
goto exit_unwind;
748
}
749
lltrace = r;
750
}
751
if (lltrace) {
752
lltrace_resume_frame(frame);
753
}
754
}
755
#endif
756
757
#ifdef Py_DEBUG
758
/* _PyEval_EvalFrameDefault() must not be called with an exception set,
759
because it can clear it (directly or indirectly) and so the
760
caller loses its exception */
761
assert(!_PyErr_Occurred(tstate));
762
#endif
763
764
DISPATCH();
765
766
handle_eval_breaker:
767
768
/* Do periodic things, like check for signals and async I/0.
769
* We need to do reasonably frequently, but not too frequently.
770
* All loops should include a check of the eval breaker.
771
* We also check on return from any builtin function.
772
*
773
* ## More Details ###
774
*
775
* The eval loop (this function) normally executes the instructions
776
* of a code object sequentially. However, the runtime supports a
777
* number of out-of-band execution scenarios that may pause that
778
* sequential execution long enough to do that out-of-band work
779
* in the current thread using the current PyThreadState.
780
*
781
* The scenarios include:
782
*
783
* - cyclic garbage collection
784
* - GIL drop requests
785
* - "async" exceptions
786
* - "pending calls" (some only in the main thread)
787
* - signal handling (only in the main thread)
788
*
789
* When the need for one of the above is detected, the eval loop
790
* pauses long enough to handle the detected case. Then, if doing
791
* so didn't trigger an exception, the eval loop resumes executing
792
* the sequential instructions.
793
*
794
* To make this work, the eval loop periodically checks if any
795
* of the above needs to happen. The individual checks can be
796
* expensive if computed each time, so a while back we switched
797
* to using pre-computed, per-interpreter variables for the checks,
798
* and later consolidated that to a single "eval breaker" variable
799
* (now a PyInterpreterState field).
800
*
801
* For the longest time, the eval breaker check would happen
802
* frequently, every 5 or so times through the loop, regardless
803
* of what instruction ran last or what would run next. Then, in
804
* early 2021 (gh-18334, commit 4958f5d), we switched to checking
805
* the eval breaker less frequently, by hard-coding the check to
806
* specific places in the eval loop (e.g. certain instructions).
807
* The intent then was to check after returning from calls
808
* and on the back edges of loops.
809
*
810
* In addition to being more efficient, that approach keeps
811
* the eval loop from running arbitrary code between instructions
812
* that don't handle that well. (See gh-74174.)
813
*
814
* Currently, the eval breaker check happens here at the
815
* "handle_eval_breaker" label. Some instructions come here
816
* explicitly (goto) and some indirectly. Notably, the check
817
* happens on back edges in the control flow graph, which
818
* pretty much applies to all loops and most calls.
819
* (See bytecodes.c for exact information.)
820
*
821
* One consequence of this approach is that it might not be obvious
822
* how to force any specific thread to pick up the eval breaker,
823
* or for any specific thread to not pick it up. Mostly this
824
* involves judicious uses of locks and careful ordering of code,
825
* while avoiding code that might trigger the eval breaker
826
* until so desired.
827
*/
828
if (_Py_HandlePending(tstate) != 0) {
829
goto error;
830
}
831
DISPATCH();
832
833
{
834
/* Start instructions */
835
#if !USE_COMPUTED_GOTOS
836
dispatch_opcode:
837
switch (opcode)
838
#endif
839
{
840
841
#include "generated_cases.c.h"
842
843
/* INSTRUMENTED_LINE has to be here, rather than in bytecodes.c,
844
* because it needs to capture frame->prev_instr before it is updated,
845
* as happens in the standard instruction prologue.
846
*/
847
#if USE_COMPUTED_GOTOS
848
TARGET_INSTRUMENTED_LINE:
849
#else
850
case INSTRUMENTED_LINE:
851
#endif
852
{
853
_Py_CODEUNIT *prev = frame->prev_instr;
854
_Py_CODEUNIT *here = frame->prev_instr = next_instr;
855
_PyFrame_SetStackPointer(frame, stack_pointer);
856
int original_opcode = _Py_call_instrumentation_line(
857
tstate, frame, here, prev);
858
stack_pointer = _PyFrame_GetStackPointer(frame);
859
if (original_opcode < 0) {
860
next_instr = here+1;
861
goto error;
862
}
863
next_instr = frame->prev_instr;
864
if (next_instr != here) {
865
DISPATCH();
866
}
867
if (_PyOpcode_Caches[original_opcode]) {
868
_PyBinaryOpCache *cache = (_PyBinaryOpCache *)(next_instr+1);
869
/* Prevent the underlying instruction from specializing
870
* and overwriting the instrumentation. */
871
INCREMENT_ADAPTIVE_COUNTER(cache->counter);
872
}
873
opcode = original_opcode;
874
DISPATCH_GOTO();
875
}
876
877
878
#if USE_COMPUTED_GOTOS
879
_unknown_opcode:
880
#else
881
EXTRA_CASES // From pycore_opcode.h, a 'case' for each unused opcode
882
#endif
883
/* Tell C compilers not to hold the opcode variable in the loop.
884
next_instr points the current instruction without TARGET(). */
885
opcode = next_instr->op.code;
886
_PyErr_Format(tstate, PyExc_SystemError,
887
"%U:%d: unknown opcode %d",
888
_PyFrame_GetCode(frame)->co_filename,
889
PyUnstable_InterpreterFrame_GetLine(frame),
890
opcode);
891
goto error;
892
893
} /* End instructions */
894
895
/* This should never be reached. Every opcode should end with DISPATCH()
896
or goto error. */
897
Py_UNREACHABLE();
898
899
unbound_local_error:
900
{
901
format_exc_check_arg(tstate, PyExc_UnboundLocalError,
902
UNBOUNDLOCAL_ERROR_MSG,
903
PyTuple_GetItem(_PyFrame_GetCode(frame)->co_localsplusnames, oparg)
904
);
905
goto error;
906
}
907
908
pop_4_error:
909
STACK_SHRINK(1);
910
pop_3_error:
911
STACK_SHRINK(1);
912
pop_2_error:
913
STACK_SHRINK(1);
914
pop_1_error:
915
STACK_SHRINK(1);
916
error:
917
kwnames = NULL;
918
/* Double-check exception status. */
919
#ifdef NDEBUG
920
if (!_PyErr_Occurred(tstate)) {
921
_PyErr_SetString(tstate, PyExc_SystemError,
922
"error return without exception set");
923
}
924
#else
925
assert(_PyErr_Occurred(tstate));
926
#endif
927
928
/* Log traceback info. */
929
assert(frame != &entry_frame);
930
if (!_PyFrame_IsIncomplete(frame)) {
931
PyFrameObject *f = _PyFrame_GetFrameObject(frame);
932
if (f != NULL) {
933
PyTraceBack_Here(f);
934
}
935
}
936
monitor_raise(tstate, frame, next_instr-1);
937
938
exception_unwind:
939
{
940
/* We can't use frame->f_lasti here, as RERAISE may have set it */
941
int offset = INSTR_OFFSET()-1;
942
int level, handler, lasti;
943
if (get_exception_handler(_PyFrame_GetCode(frame), offset, &level, &handler, &lasti) == 0) {
944
// No handlers, so exit.
945
assert(_PyErr_Occurred(tstate));
946
947
/* Pop remaining stack entries. */
948
PyObject **stackbase = _PyFrame_Stackbase(frame);
949
while (stack_pointer > stackbase) {
950
PyObject *o = POP();
951
Py_XDECREF(o);
952
}
953
assert(STACK_LEVEL() == 0);
954
_PyFrame_SetStackPointer(frame, stack_pointer);
955
monitor_unwind(tstate, frame, next_instr-1);
956
goto exit_unwind;
957
}
958
959
assert(STACK_LEVEL() >= level);
960
PyObject **new_top = _PyFrame_Stackbase(frame) + level;
961
while (stack_pointer > new_top) {
962
PyObject *v = POP();
963
Py_XDECREF(v);
964
}
965
if (lasti) {
966
int frame_lasti = _PyInterpreterFrame_LASTI(frame);
967
PyObject *lasti = PyLong_FromLong(frame_lasti);
968
if (lasti == NULL) {
969
goto exception_unwind;
970
}
971
PUSH(lasti);
972
}
973
974
/* Make the raw exception data
975
available to the handler,
976
so a program can emulate the
977
Python main loop. */
978
PyObject *exc = _PyErr_GetRaisedException(tstate);
979
PUSH(exc);
980
JUMPTO(handler);
981
monitor_handled(tstate, frame, next_instr, exc);
982
/* Resume normal execution */
983
DISPATCH();
984
}
985
}
986
987
exit_unwind:
988
assert(_PyErr_Occurred(tstate));
989
_Py_LeaveRecursiveCallPy(tstate);
990
assert(frame != &entry_frame);
991
// GH-99729: We need to unlink the frame *before* clearing it:
992
_PyInterpreterFrame *dying = frame;
993
frame = cframe.current_frame = dying->previous;
994
_PyEvalFrameClearAndPop(tstate, dying);
995
frame->return_offset = 0;
996
if (frame == &entry_frame) {
997
/* Restore previous cframe and exit */
998
tstate->cframe = cframe.previous;
999
assert(tstate->cframe->current_frame == frame->previous);
1000
_Py_LeaveRecursiveCallTstate(tstate);
1001
return NULL;
1002
}
1003
1004
resume_with_error:
1005
SET_LOCALS_FROM_FRAME();
1006
goto error;
1007
1008
}
1009
#if defined(__GNUC__)
1010
# pragma GCC diagnostic pop
1011
#elif defined(_MSC_VER) /* MS_WINDOWS */
1012
# pragma warning(pop)
1013
#endif
1014
1015
static void
1016
format_missing(PyThreadState *tstate, const char *kind,
1017
PyCodeObject *co, PyObject *names, PyObject *qualname)
1018
{
1019
int err;
1020
Py_ssize_t len = PyList_GET_SIZE(names);
1021
PyObject *name_str, *comma, *tail, *tmp;
1022
1023
assert(PyList_CheckExact(names));
1024
assert(len >= 1);
1025
/* Deal with the joys of natural language. */
1026
switch (len) {
1027
case 1:
1028
name_str = PyList_GET_ITEM(names, 0);
1029
Py_INCREF(name_str);
1030
break;
1031
case 2:
1032
name_str = PyUnicode_FromFormat("%U and %U",
1033
PyList_GET_ITEM(names, len - 2),
1034
PyList_GET_ITEM(names, len - 1));
1035
break;
1036
default:
1037
tail = PyUnicode_FromFormat(", %U, and %U",
1038
PyList_GET_ITEM(names, len - 2),
1039
PyList_GET_ITEM(names, len - 1));
1040
if (tail == NULL)
1041
return;
1042
/* Chop off the last two objects in the list. This shouldn't actually
1043
fail, but we can't be too careful. */
1044
err = PyList_SetSlice(names, len - 2, len, NULL);
1045
if (err == -1) {
1046
Py_DECREF(tail);
1047
return;
1048
}
1049
/* Stitch everything up into a nice comma-separated list. */
1050
comma = PyUnicode_FromString(", ");
1051
if (comma == NULL) {
1052
Py_DECREF(tail);
1053
return;
1054
}
1055
tmp = PyUnicode_Join(comma, names);
1056
Py_DECREF(comma);
1057
if (tmp == NULL) {
1058
Py_DECREF(tail);
1059
return;
1060
}
1061
name_str = PyUnicode_Concat(tmp, tail);
1062
Py_DECREF(tmp);
1063
Py_DECREF(tail);
1064
break;
1065
}
1066
if (name_str == NULL)
1067
return;
1068
_PyErr_Format(tstate, PyExc_TypeError,
1069
"%U() missing %i required %s argument%s: %U",
1070
qualname,
1071
len,
1072
kind,
1073
len == 1 ? "" : "s",
1074
name_str);
1075
Py_DECREF(name_str);
1076
}
1077
1078
static void
1079
missing_arguments(PyThreadState *tstate, PyCodeObject *co,
1080
Py_ssize_t missing, Py_ssize_t defcount,
1081
PyObject **localsplus, PyObject *qualname)
1082
{
1083
Py_ssize_t i, j = 0;
1084
Py_ssize_t start, end;
1085
int positional = (defcount != -1);
1086
const char *kind = positional ? "positional" : "keyword-only";
1087
PyObject *missing_names;
1088
1089
/* Compute the names of the arguments that are missing. */
1090
missing_names = PyList_New(missing);
1091
if (missing_names == NULL)
1092
return;
1093
if (positional) {
1094
start = 0;
1095
end = co->co_argcount - defcount;
1096
}
1097
else {
1098
start = co->co_argcount;
1099
end = start + co->co_kwonlyargcount;
1100
}
1101
for (i = start; i < end; i++) {
1102
if (localsplus[i] == NULL) {
1103
PyObject *raw = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1104
PyObject *name = PyObject_Repr(raw);
1105
if (name == NULL) {
1106
Py_DECREF(missing_names);
1107
return;
1108
}
1109
PyList_SET_ITEM(missing_names, j++, name);
1110
}
1111
}
1112
assert(j == missing);
1113
format_missing(tstate, kind, co, missing_names, qualname);
1114
Py_DECREF(missing_names);
1115
}
1116
1117
static void
1118
too_many_positional(PyThreadState *tstate, PyCodeObject *co,
1119
Py_ssize_t given, PyObject *defaults,
1120
PyObject **localsplus, PyObject *qualname)
1121
{
1122
int plural;
1123
Py_ssize_t kwonly_given = 0;
1124
Py_ssize_t i;
1125
PyObject *sig, *kwonly_sig;
1126
Py_ssize_t co_argcount = co->co_argcount;
1127
1128
assert((co->co_flags & CO_VARARGS) == 0);
1129
/* Count missing keyword-only args. */
1130
for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
1131
if (localsplus[i] != NULL) {
1132
kwonly_given++;
1133
}
1134
}
1135
Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
1136
if (defcount) {
1137
Py_ssize_t atleast = co_argcount - defcount;
1138
plural = 1;
1139
sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
1140
}
1141
else {
1142
plural = (co_argcount != 1);
1143
sig = PyUnicode_FromFormat("%zd", co_argcount);
1144
}
1145
if (sig == NULL)
1146
return;
1147
if (kwonly_given) {
1148
const char *format = " positional argument%s (and %zd keyword-only argument%s)";
1149
kwonly_sig = PyUnicode_FromFormat(format,
1150
given != 1 ? "s" : "",
1151
kwonly_given,
1152
kwonly_given != 1 ? "s" : "");
1153
if (kwonly_sig == NULL) {
1154
Py_DECREF(sig);
1155
return;
1156
}
1157
}
1158
else {
1159
/* This will not fail. */
1160
kwonly_sig = PyUnicode_FromString("");
1161
assert(kwonly_sig != NULL);
1162
}
1163
_PyErr_Format(tstate, PyExc_TypeError,
1164
"%U() takes %U positional argument%s but %zd%U %s given",
1165
qualname,
1166
sig,
1167
plural ? "s" : "",
1168
given,
1169
kwonly_sig,
1170
given == 1 && !kwonly_given ? "was" : "were");
1171
Py_DECREF(sig);
1172
Py_DECREF(kwonly_sig);
1173
}
1174
1175
static int
1176
positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
1177
Py_ssize_t kwcount, PyObject* kwnames,
1178
PyObject *qualname)
1179
{
1180
int posonly_conflicts = 0;
1181
PyObject* posonly_names = PyList_New(0);
1182
if (posonly_names == NULL) {
1183
goto fail;
1184
}
1185
for(int k=0; k < co->co_posonlyargcount; k++){
1186
PyObject* posonly_name = PyTuple_GET_ITEM(co->co_localsplusnames, k);
1187
1188
for (int k2=0; k2<kwcount; k2++){
1189
/* Compare the pointers first and fallback to PyObject_RichCompareBool*/
1190
PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
1191
if (kwname == posonly_name){
1192
if(PyList_Append(posonly_names, kwname) != 0) {
1193
goto fail;
1194
}
1195
posonly_conflicts++;
1196
continue;
1197
}
1198
1199
int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
1200
1201
if ( cmp > 0) {
1202
if(PyList_Append(posonly_names, kwname) != 0) {
1203
goto fail;
1204
}
1205
posonly_conflicts++;
1206
} else if (cmp < 0) {
1207
goto fail;
1208
}
1209
1210
}
1211
}
1212
if (posonly_conflicts) {
1213
PyObject* comma = PyUnicode_FromString(", ");
1214
if (comma == NULL) {
1215
goto fail;
1216
}
1217
PyObject* error_names = PyUnicode_Join(comma, posonly_names);
1218
Py_DECREF(comma);
1219
if (error_names == NULL) {
1220
goto fail;
1221
}
1222
_PyErr_Format(tstate, PyExc_TypeError,
1223
"%U() got some positional-only arguments passed"
1224
" as keyword arguments: '%U'",
1225
qualname, error_names);
1226
Py_DECREF(error_names);
1227
goto fail;
1228
}
1229
1230
Py_DECREF(posonly_names);
1231
return 0;
1232
1233
fail:
1234
Py_XDECREF(posonly_names);
1235
return 1;
1236
1237
}
1238
1239
1240
static inline unsigned char *
1241
scan_back_to_entry_start(unsigned char *p) {
1242
for (; (p[0]&128) == 0; p--);
1243
return p;
1244
}
1245
1246
static inline unsigned char *
1247
skip_to_next_entry(unsigned char *p, unsigned char *end) {
1248
while (p < end && ((p[0] & 128) == 0)) {
1249
p++;
1250
}
1251
return p;
1252
}
1253
1254
1255
#define MAX_LINEAR_SEARCH 40
1256
1257
static int
1258
get_exception_handler(PyCodeObject *code, int index, int *level, int *handler, int *lasti)
1259
{
1260
unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code->co_exceptiontable);
1261
unsigned char *end = start + PyBytes_GET_SIZE(code->co_exceptiontable);
1262
/* Invariants:
1263
* start_table == end_table OR
1264
* start_table points to a legal entry and end_table points
1265
* beyond the table or to a legal entry that is after index.
1266
*/
1267
if (end - start > MAX_LINEAR_SEARCH) {
1268
int offset;
1269
parse_varint(start, &offset);
1270
if (offset > index) {
1271
return 0;
1272
}
1273
do {
1274
unsigned char * mid = start + ((end-start)>>1);
1275
mid = scan_back_to_entry_start(mid);
1276
parse_varint(mid, &offset);
1277
if (offset > index) {
1278
end = mid;
1279
}
1280
else {
1281
start = mid;
1282
}
1283
1284
} while (end - start > MAX_LINEAR_SEARCH);
1285
}
1286
unsigned char *scan = start;
1287
while (scan < end) {
1288
int start_offset, size;
1289
scan = parse_varint(scan, &start_offset);
1290
if (start_offset > index) {
1291
break;
1292
}
1293
scan = parse_varint(scan, &size);
1294
if (start_offset + size > index) {
1295
scan = parse_varint(scan, handler);
1296
int depth_and_lasti;
1297
parse_varint(scan, &depth_and_lasti);
1298
*level = depth_and_lasti >> 1;
1299
*lasti = depth_and_lasti & 1;
1300
return 1;
1301
}
1302
scan = skip_to_next_entry(scan, end);
1303
}
1304
return 0;
1305
}
1306
1307
static int
1308
initialize_locals(PyThreadState *tstate, PyFunctionObject *func,
1309
PyObject **localsplus, PyObject *const *args,
1310
Py_ssize_t argcount, PyObject *kwnames)
1311
{
1312
PyCodeObject *co = (PyCodeObject*)func->func_code;
1313
const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
1314
1315
/* Create a dictionary for keyword parameters (**kwags) */
1316
PyObject *kwdict;
1317
Py_ssize_t i;
1318
if (co->co_flags & CO_VARKEYWORDS) {
1319
kwdict = PyDict_New();
1320
if (kwdict == NULL) {
1321
goto fail_pre_positional;
1322
}
1323
i = total_args;
1324
if (co->co_flags & CO_VARARGS) {
1325
i++;
1326
}
1327
assert(localsplus[i] == NULL);
1328
localsplus[i] = kwdict;
1329
}
1330
else {
1331
kwdict = NULL;
1332
}
1333
1334
/* Copy all positional arguments into local variables */
1335
Py_ssize_t j, n;
1336
if (argcount > co->co_argcount) {
1337
n = co->co_argcount;
1338
}
1339
else {
1340
n = argcount;
1341
}
1342
for (j = 0; j < n; j++) {
1343
PyObject *x = args[j];
1344
assert(localsplus[j] == NULL);
1345
localsplus[j] = x;
1346
}
1347
1348
/* Pack other positional arguments into the *args argument */
1349
if (co->co_flags & CO_VARARGS) {
1350
PyObject *u = NULL;
1351
if (argcount == n) {
1352
u = Py_NewRef(&_Py_SINGLETON(tuple_empty));
1353
}
1354
else {
1355
assert(args != NULL);
1356
u = _PyTuple_FromArraySteal(args + n, argcount - n);
1357
}
1358
if (u == NULL) {
1359
goto fail_post_positional;
1360
}
1361
assert(localsplus[total_args] == NULL);
1362
localsplus[total_args] = u;
1363
}
1364
else if (argcount > n) {
1365
/* Too many postional args. Error is reported later */
1366
for (j = n; j < argcount; j++) {
1367
Py_DECREF(args[j]);
1368
}
1369
}
1370
1371
/* Handle keyword arguments */
1372
if (kwnames != NULL) {
1373
Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1374
for (i = 0; i < kwcount; i++) {
1375
PyObject **co_varnames;
1376
PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
1377
PyObject *value = args[i+argcount];
1378
Py_ssize_t j;
1379
1380
if (keyword == NULL || !PyUnicode_Check(keyword)) {
1381
_PyErr_Format(tstate, PyExc_TypeError,
1382
"%U() keywords must be strings",
1383
func->func_qualname);
1384
goto kw_fail;
1385
}
1386
1387
/* Speed hack: do raw pointer compares. As names are
1388
normally interned this should almost always hit. */
1389
co_varnames = ((PyTupleObject *)(co->co_localsplusnames))->ob_item;
1390
for (j = co->co_posonlyargcount; j < total_args; j++) {
1391
PyObject *varname = co_varnames[j];
1392
if (varname == keyword) {
1393
goto kw_found;
1394
}
1395
}
1396
1397
/* Slow fallback, just in case */
1398
for (j = co->co_posonlyargcount; j < total_args; j++) {
1399
PyObject *varname = co_varnames[j];
1400
int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
1401
if (cmp > 0) {
1402
goto kw_found;
1403
}
1404
else if (cmp < 0) {
1405
goto kw_fail;
1406
}
1407
}
1408
1409
assert(j >= total_args);
1410
if (kwdict == NULL) {
1411
1412
if (co->co_posonlyargcount
1413
&& positional_only_passed_as_keyword(tstate, co,
1414
kwcount, kwnames,
1415
func->func_qualname))
1416
{
1417
goto kw_fail;
1418
}
1419
1420
_PyErr_Format(tstate, PyExc_TypeError,
1421
"%U() got an unexpected keyword argument '%S'",
1422
func->func_qualname, keyword);
1423
goto kw_fail;
1424
}
1425
1426
if (PyDict_SetItem(kwdict, keyword, value) == -1) {
1427
goto kw_fail;
1428
}
1429
Py_DECREF(value);
1430
continue;
1431
1432
kw_fail:
1433
for (;i < kwcount; i++) {
1434
PyObject *value = args[i+argcount];
1435
Py_DECREF(value);
1436
}
1437
goto fail_post_args;
1438
1439
kw_found:
1440
if (localsplus[j] != NULL) {
1441
_PyErr_Format(tstate, PyExc_TypeError,
1442
"%U() got multiple values for argument '%S'",
1443
func->func_qualname, keyword);
1444
goto kw_fail;
1445
}
1446
localsplus[j] = value;
1447
}
1448
}
1449
1450
/* Check the number of positional arguments */
1451
if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
1452
too_many_positional(tstate, co, argcount, func->func_defaults, localsplus,
1453
func->func_qualname);
1454
goto fail_post_args;
1455
}
1456
1457
/* Add missing positional arguments (copy default values from defs) */
1458
if (argcount < co->co_argcount) {
1459
Py_ssize_t defcount = func->func_defaults == NULL ? 0 : PyTuple_GET_SIZE(func->func_defaults);
1460
Py_ssize_t m = co->co_argcount - defcount;
1461
Py_ssize_t missing = 0;
1462
for (i = argcount; i < m; i++) {
1463
if (localsplus[i] == NULL) {
1464
missing++;
1465
}
1466
}
1467
if (missing) {
1468
missing_arguments(tstate, co, missing, defcount, localsplus,
1469
func->func_qualname);
1470
goto fail_post_args;
1471
}
1472
if (n > m)
1473
i = n - m;
1474
else
1475
i = 0;
1476
if (defcount) {
1477
PyObject **defs = &PyTuple_GET_ITEM(func->func_defaults, 0);
1478
for (; i < defcount; i++) {
1479
if (localsplus[m+i] == NULL) {
1480
PyObject *def = defs[i];
1481
localsplus[m+i] = Py_NewRef(def);
1482
}
1483
}
1484
}
1485
}
1486
1487
/* Add missing keyword arguments (copy default values from kwdefs) */
1488
if (co->co_kwonlyargcount > 0) {
1489
Py_ssize_t missing = 0;
1490
for (i = co->co_argcount; i < total_args; i++) {
1491
if (localsplus[i] != NULL)
1492
continue;
1493
PyObject *varname = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1494
if (func->func_kwdefaults != NULL) {
1495
PyObject *def = PyDict_GetItemWithError(func->func_kwdefaults, varname);
1496
if (def) {
1497
localsplus[i] = Py_NewRef(def);
1498
continue;
1499
}
1500
else if (_PyErr_Occurred(tstate)) {
1501
goto fail_post_args;
1502
}
1503
}
1504
missing++;
1505
}
1506
if (missing) {
1507
missing_arguments(tstate, co, missing, -1, localsplus,
1508
func->func_qualname);
1509
goto fail_post_args;
1510
}
1511
}
1512
return 0;
1513
1514
fail_pre_positional:
1515
for (j = 0; j < argcount; j++) {
1516
Py_DECREF(args[j]);
1517
}
1518
/* fall through */
1519
fail_post_positional:
1520
if (kwnames) {
1521
Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1522
for (j = argcount; j < argcount+kwcount; j++) {
1523
Py_DECREF(args[j]);
1524
}
1525
}
1526
/* fall through */
1527
fail_post_args:
1528
return -1;
1529
}
1530
1531
static void
1532
clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1533
{
1534
assert(frame->owner == FRAME_OWNED_BY_THREAD);
1535
// Make sure that this is, indeed, the top frame. We can't check this in
1536
// _PyThreadState_PopFrame, since f_code is already cleared at that point:
1537
assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize ==
1538
tstate->datastack_top);
1539
tstate->c_recursion_remaining--;
1540
assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1541
_PyFrame_ClearExceptCode(frame);
1542
Py_DECREF(frame->f_executable);
1543
tstate->c_recursion_remaining++;
1544
_PyThreadState_PopFrame(tstate, frame);
1545
}
1546
1547
static void
1548
clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
1549
{
1550
assert(frame->owner == FRAME_OWNED_BY_GENERATOR);
1551
PyGenObject *gen = _PyFrame_GetGenerator(frame);
1552
gen->gi_frame_state = FRAME_CLEARED;
1553
assert(tstate->exc_info == &gen->gi_exc_state);
1554
tstate->exc_info = gen->gi_exc_state.previous_item;
1555
gen->gi_exc_state.previous_item = NULL;
1556
tstate->c_recursion_remaining--;
1557
assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
1558
_PyFrame_ClearExceptCode(frame);
1559
tstate->c_recursion_remaining++;
1560
frame->previous = NULL;
1561
}
1562
1563
static void
1564
_PyEvalFrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame)
1565
{
1566
if (frame->owner == FRAME_OWNED_BY_THREAD) {
1567
clear_thread_frame(tstate, frame);
1568
}
1569
else {
1570
clear_gen_frame(tstate, frame);
1571
}
1572
}
1573
1574
/* Consumes references to func, locals and all the args */
1575
static _PyInterpreterFrame *
1576
_PyEvalFramePushAndInit(PyThreadState *tstate, PyFunctionObject *func,
1577
PyObject *locals, PyObject* const* args,
1578
size_t argcount, PyObject *kwnames)
1579
{
1580
PyCodeObject * code = (PyCodeObject *)func->func_code;
1581
CALL_STAT_INC(frames_pushed);
1582
_PyInterpreterFrame *frame = _PyThreadState_PushFrame(tstate, code->co_framesize);
1583
if (frame == NULL) {
1584
goto fail;
1585
}
1586
_PyFrame_Initialize(frame, func, locals, code, 0);
1587
if (initialize_locals(tstate, func, frame->localsplus, args, argcount, kwnames)) {
1588
assert(frame->owner == FRAME_OWNED_BY_THREAD);
1589
clear_thread_frame(tstate, frame);
1590
return NULL;
1591
}
1592
return frame;
1593
fail:
1594
/* Consume the references */
1595
for (size_t i = 0; i < argcount; i++) {
1596
Py_DECREF(args[i]);
1597
}
1598
if (kwnames) {
1599
Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1600
for (Py_ssize_t i = 0; i < kwcount; i++) {
1601
Py_DECREF(args[i+argcount]);
1602
}
1603
}
1604
PyErr_NoMemory();
1605
return NULL;
1606
}
1607
1608
/* Same as _PyEvalFramePushAndInit but takes an args tuple and kwargs dict.
1609
Steals references to func, callargs and kwargs.
1610
*/
1611
static _PyInterpreterFrame *
1612
_PyEvalFramePushAndInit_Ex(PyThreadState *tstate, PyFunctionObject *func,
1613
PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs)
1614
{
1615
bool has_dict = (kwargs != NULL && PyDict_GET_SIZE(kwargs) > 0);
1616
PyObject *kwnames = NULL;
1617
PyObject *const *newargs;
1618
if (has_dict) {
1619
newargs = _PyStack_UnpackDict(tstate, _PyTuple_ITEMS(callargs), nargs, kwargs, &kwnames);
1620
if (newargs == NULL) {
1621
Py_DECREF(func);
1622
goto error;
1623
}
1624
}
1625
else {
1626
newargs = &PyTuple_GET_ITEM(callargs, 0);
1627
/* We need to incref all our args since the new frame steals the references. */
1628
for (Py_ssize_t i = 0; i < nargs; ++i) {
1629
Py_INCREF(PyTuple_GET_ITEM(callargs, i));
1630
}
1631
}
1632
_PyInterpreterFrame *new_frame = _PyEvalFramePushAndInit(
1633
tstate, (PyFunctionObject *)func, locals,
1634
newargs, nargs, kwnames
1635
);
1636
if (has_dict) {
1637
_PyStack_UnpackDict_FreeNoDecRef(newargs, kwnames);
1638
}
1639
/* No need to decref func here because the reference has been stolen by
1640
_PyEvalFramePushAndInit.
1641
*/
1642
Py_DECREF(callargs);
1643
Py_XDECREF(kwargs);
1644
return new_frame;
1645
error:
1646
Py_DECREF(callargs);
1647
Py_XDECREF(kwargs);
1648
return NULL;
1649
}
1650
1651
PyObject *
1652
_PyEval_Vector(PyThreadState *tstate, PyFunctionObject *func,
1653
PyObject *locals,
1654
PyObject* const* args, size_t argcount,
1655
PyObject *kwnames)
1656
{
1657
/* _PyEvalFramePushAndInit consumes the references
1658
* to func, locals and all its arguments */
1659
Py_INCREF(func);
1660
Py_XINCREF(locals);
1661
for (size_t i = 0; i < argcount; i++) {
1662
Py_INCREF(args[i]);
1663
}
1664
if (kwnames) {
1665
Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
1666
for (Py_ssize_t i = 0; i < kwcount; i++) {
1667
Py_INCREF(args[i+argcount]);
1668
}
1669
}
1670
_PyInterpreterFrame *frame = _PyEvalFramePushAndInit(
1671
tstate, func, locals, args, argcount, kwnames);
1672
if (frame == NULL) {
1673
return NULL;
1674
}
1675
EVAL_CALL_STAT_INC(EVAL_CALL_VECTOR);
1676
return _PyEval_EvalFrame(tstate, frame, 0);
1677
}
1678
1679
/* Legacy API */
1680
PyObject *
1681
PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
1682
PyObject *const *args, int argcount,
1683
PyObject *const *kws, int kwcount,
1684
PyObject *const *defs, int defcount,
1685
PyObject *kwdefs, PyObject *closure)
1686
{
1687
PyThreadState *tstate = _PyThreadState_GET();
1688
PyObject *res = NULL;
1689
PyObject *defaults = _PyTuple_FromArray(defs, defcount);
1690
if (defaults == NULL) {
1691
return NULL;
1692
}
1693
PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
1694
if (builtins == NULL) {
1695
Py_DECREF(defaults);
1696
return NULL;
1697
}
1698
if (locals == NULL) {
1699
locals = globals;
1700
}
1701
PyObject *kwnames = NULL;
1702
PyObject *const *allargs;
1703
PyObject **newargs = NULL;
1704
PyFunctionObject *func = NULL;
1705
if (kwcount == 0) {
1706
allargs = args;
1707
}
1708
else {
1709
kwnames = PyTuple_New(kwcount);
1710
if (kwnames == NULL) {
1711
goto fail;
1712
}
1713
newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
1714
if (newargs == NULL) {
1715
goto fail;
1716
}
1717
for (int i = 0; i < argcount; i++) {
1718
newargs[i] = args[i];
1719
}
1720
for (int i = 0; i < kwcount; i++) {
1721
PyTuple_SET_ITEM(kwnames, i, Py_NewRef(kws[2*i]));
1722
newargs[argcount+i] = kws[2*i+1];
1723
}
1724
allargs = newargs;
1725
}
1726
PyFrameConstructor constr = {
1727
.fc_globals = globals,
1728
.fc_builtins = builtins,
1729
.fc_name = ((PyCodeObject *)_co)->co_name,
1730
.fc_qualname = ((PyCodeObject *)_co)->co_name,
1731
.fc_code = _co,
1732
.fc_defaults = defaults,
1733
.fc_kwdefaults = kwdefs,
1734
.fc_closure = closure
1735
};
1736
func = _PyFunction_FromConstructor(&constr);
1737
if (func == NULL) {
1738
goto fail;
1739
}
1740
EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
1741
res = _PyEval_Vector(tstate, func, locals,
1742
allargs, argcount,
1743
kwnames);
1744
fail:
1745
Py_XDECREF(func);
1746
Py_XDECREF(kwnames);
1747
PyMem_Free(newargs);
1748
Py_DECREF(defaults);
1749
return res;
1750
}
1751
1752
1753
/* Logic for the raise statement (too complicated for inlining).
1754
This *consumes* a reference count to each of its arguments. */
1755
static int
1756
do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
1757
{
1758
PyObject *type = NULL, *value = NULL;
1759
1760
if (exc == NULL) {
1761
/* Reraise */
1762
_PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
1763
exc = exc_info->exc_value;
1764
if (Py_IsNone(exc) || exc == NULL) {
1765
_PyErr_SetString(tstate, PyExc_RuntimeError,
1766
"No active exception to reraise");
1767
return 0;
1768
}
1769
Py_INCREF(exc);
1770
assert(PyExceptionInstance_Check(exc));
1771
_PyErr_SetRaisedException(tstate, exc);
1772
return 1;
1773
}
1774
1775
/* We support the following forms of raise:
1776
raise
1777
raise <instance>
1778
raise <type> */
1779
1780
if (PyExceptionClass_Check(exc)) {
1781
type = exc;
1782
value = _PyObject_CallNoArgs(exc);
1783
if (value == NULL)
1784
goto raise_error;
1785
if (!PyExceptionInstance_Check(value)) {
1786
_PyErr_Format(tstate, PyExc_TypeError,
1787
"calling %R should have returned an instance of "
1788
"BaseException, not %R",
1789
type, Py_TYPE(value));
1790
goto raise_error;
1791
}
1792
}
1793
else if (PyExceptionInstance_Check(exc)) {
1794
value = exc;
1795
type = PyExceptionInstance_Class(exc);
1796
Py_INCREF(type);
1797
}
1798
else {
1799
/* Not something you can raise. You get an exception
1800
anyway, just not what you specified :-) */
1801
Py_DECREF(exc);
1802
_PyErr_SetString(tstate, PyExc_TypeError,
1803
"exceptions must derive from BaseException");
1804
goto raise_error;
1805
}
1806
1807
assert(type != NULL);
1808
assert(value != NULL);
1809
1810
if (cause) {
1811
PyObject *fixed_cause;
1812
if (PyExceptionClass_Check(cause)) {
1813
fixed_cause = _PyObject_CallNoArgs(cause);
1814
if (fixed_cause == NULL)
1815
goto raise_error;
1816
Py_DECREF(cause);
1817
}
1818
else if (PyExceptionInstance_Check(cause)) {
1819
fixed_cause = cause;
1820
}
1821
else if (Py_IsNone(cause)) {
1822
Py_DECREF(cause);
1823
fixed_cause = NULL;
1824
}
1825
else {
1826
_PyErr_SetString(tstate, PyExc_TypeError,
1827
"exception causes must derive from "
1828
"BaseException");
1829
goto raise_error;
1830
}
1831
PyException_SetCause(value, fixed_cause);
1832
}
1833
1834
_PyErr_SetObject(tstate, type, value);
1835
/* _PyErr_SetObject incref's its arguments */
1836
Py_DECREF(value);
1837
Py_DECREF(type);
1838
return 0;
1839
1840
raise_error:
1841
Py_XDECREF(value);
1842
Py_XDECREF(type);
1843
Py_XDECREF(cause);
1844
return 0;
1845
}
1846
1847
/* Logic for matching an exception in an except* clause (too
1848
complicated for inlining).
1849
*/
1850
1851
static int
1852
exception_group_match(PyObject* exc_value, PyObject *match_type,
1853
PyObject **match, PyObject **rest)
1854
{
1855
if (Py_IsNone(exc_value)) {
1856
*match = Py_NewRef(Py_None);
1857
*rest = Py_NewRef(Py_None);
1858
return 0;
1859
}
1860
assert(PyExceptionInstance_Check(exc_value));
1861
1862
if (PyErr_GivenExceptionMatches(exc_value, match_type)) {
1863
/* Full match of exc itself */
1864
bool is_eg = _PyBaseExceptionGroup_Check(exc_value);
1865
if (is_eg) {
1866
*match = Py_NewRef(exc_value);
1867
}
1868
else {
1869
/* naked exception - wrap it */
1870
PyObject *excs = PyTuple_Pack(1, exc_value);
1871
if (excs == NULL) {
1872
return -1;
1873
}
1874
PyObject *wrapped = _PyExc_CreateExceptionGroup("", excs);
1875
Py_DECREF(excs);
1876
if (wrapped == NULL) {
1877
return -1;
1878
}
1879
*match = wrapped;
1880
}
1881
*rest = Py_NewRef(Py_None);
1882
return 0;
1883
}
1884
1885
/* exc_value does not match match_type.
1886
* Check for partial match if it's an exception group.
1887
*/
1888
if (_PyBaseExceptionGroup_Check(exc_value)) {
1889
PyObject *pair = PyObject_CallMethod(exc_value, "split", "(O)",
1890
match_type);
1891
if (pair == NULL) {
1892
return -1;
1893
}
1894
assert(PyTuple_CheckExact(pair));
1895
assert(PyTuple_GET_SIZE(pair) == 2);
1896
*match = Py_NewRef(PyTuple_GET_ITEM(pair, 0));
1897
*rest = Py_NewRef(PyTuple_GET_ITEM(pair, 1));
1898
Py_DECREF(pair);
1899
return 0;
1900
}
1901
/* no match */
1902
*match = Py_NewRef(Py_None);
1903
*rest = Py_NewRef(exc_value);
1904
return 0;
1905
}
1906
1907
/* Iterate v argcnt times and store the results on the stack (via decreasing
1908
sp). Return 1 for success, 0 if error.
1909
1910
If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
1911
with a variable target.
1912
*/
1913
1914
static int
1915
unpack_iterable(PyThreadState *tstate, PyObject *v,
1916
int argcnt, int argcntafter, PyObject **sp)
1917
{
1918
int i = 0, j = 0;
1919
Py_ssize_t ll = 0;
1920
PyObject *it; /* iter(v) */
1921
PyObject *w;
1922
PyObject *l = NULL; /* variable list */
1923
1924
assert(v != NULL);
1925
1926
it = PyObject_GetIter(v);
1927
if (it == NULL) {
1928
if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
1929
Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
1930
{
1931
_PyErr_Format(tstate, PyExc_TypeError,
1932
"cannot unpack non-iterable %.200s object",
1933
Py_TYPE(v)->tp_name);
1934
}
1935
return 0;
1936
}
1937
1938
for (; i < argcnt; i++) {
1939
w = PyIter_Next(it);
1940
if (w == NULL) {
1941
/* Iterator done, via error or exhaustion. */
1942
if (!_PyErr_Occurred(tstate)) {
1943
if (argcntafter == -1) {
1944
_PyErr_Format(tstate, PyExc_ValueError,
1945
"not enough values to unpack "
1946
"(expected %d, got %d)",
1947
argcnt, i);
1948
}
1949
else {
1950
_PyErr_Format(tstate, PyExc_ValueError,
1951
"not enough values to unpack "
1952
"(expected at least %d, got %d)",
1953
argcnt + argcntafter, i);
1954
}
1955
}
1956
goto Error;
1957
}
1958
*--sp = w;
1959
}
1960
1961
if (argcntafter == -1) {
1962
/* We better have exhausted the iterator now. */
1963
w = PyIter_Next(it);
1964
if (w == NULL) {
1965
if (_PyErr_Occurred(tstate))
1966
goto Error;
1967
Py_DECREF(it);
1968
return 1;
1969
}
1970
Py_DECREF(w);
1971
_PyErr_Format(tstate, PyExc_ValueError,
1972
"too many values to unpack (expected %d)",
1973
argcnt);
1974
goto Error;
1975
}
1976
1977
l = PySequence_List(it);
1978
if (l == NULL)
1979
goto Error;
1980
*--sp = l;
1981
i++;
1982
1983
ll = PyList_GET_SIZE(l);
1984
if (ll < argcntafter) {
1985
_PyErr_Format(tstate, PyExc_ValueError,
1986
"not enough values to unpack (expected at least %d, got %zd)",
1987
argcnt + argcntafter, argcnt + ll);
1988
goto Error;
1989
}
1990
1991
/* Pop the "after-variable" args off the list. */
1992
for (j = argcntafter; j > 0; j--, i++) {
1993
*--sp = PyList_GET_ITEM(l, ll - j);
1994
}
1995
/* Resize the list. */
1996
Py_SET_SIZE(l, ll - argcntafter);
1997
Py_DECREF(it);
1998
return 1;
1999
2000
Error:
2001
for (; i > 0; i--, sp++)
2002
Py_DECREF(*sp);
2003
Py_XDECREF(it);
2004
return 0;
2005
}
2006
2007
static int
2008
do_monitor_exc(PyThreadState *tstate, _PyInterpreterFrame *frame,
2009
_Py_CODEUNIT *instr, int event)
2010
{
2011
assert(event < PY_MONITORING_UNGROUPED_EVENTS);
2012
PyObject *exc = PyErr_GetRaisedException();
2013
assert(exc != NULL);
2014
int err = _Py_call_instrumentation_arg(tstate, event, frame, instr, exc);
2015
if (err == 0) {
2016
PyErr_SetRaisedException(exc);
2017
}
2018
else {
2019
Py_DECREF(exc);
2020
}
2021
return err;
2022
}
2023
2024
static inline int
2025
no_tools_for_event(PyThreadState *tstate, _PyInterpreterFrame *frame, int event)
2026
{
2027
_PyCoMonitoringData *data = _PyFrame_GetCode(frame)->_co_monitoring;
2028
if (data) {
2029
if (data->active_monitors.tools[event] == 0) {
2030
return 1;
2031
}
2032
}
2033
else {
2034
if (tstate->interp->monitors.tools[event] == 0) {
2035
return 1;
2036
}
2037
}
2038
return 0;
2039
}
2040
2041
static void
2042
monitor_raise(PyThreadState *tstate, _PyInterpreterFrame *frame,
2043
_Py_CODEUNIT *instr)
2044
{
2045
if (no_tools_for_event(tstate, frame, PY_MONITORING_EVENT_RAISE)) {
2046
return;
2047
}
2048
do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RAISE);
2049
}
2050
2051
static int
2052
monitor_stop_iteration(PyThreadState *tstate, _PyInterpreterFrame *frame,
2053
_Py_CODEUNIT *instr)
2054
{
2055
if (no_tools_for_event(tstate, frame, PY_MONITORING_EVENT_STOP_ITERATION)) {
2056
return 0;
2057
}
2058
return do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_STOP_ITERATION);
2059
}
2060
2061
static void
2062
monitor_unwind(PyThreadState *tstate,
2063
_PyInterpreterFrame *frame,
2064
_Py_CODEUNIT *instr)
2065
{
2066
if (no_tools_for_event(tstate, frame, PY_MONITORING_EVENT_PY_UNWIND)) {
2067
return;
2068
}
2069
_Py_call_instrumentation_exc0(tstate, PY_MONITORING_EVENT_PY_UNWIND, frame, instr);
2070
}
2071
2072
2073
static void
2074
monitor_handled(PyThreadState *tstate,
2075
_PyInterpreterFrame *frame,
2076
_Py_CODEUNIT *instr, PyObject *exc)
2077
{
2078
if (no_tools_for_event(tstate, frame, PY_MONITORING_EVENT_EXCEPTION_HANDLED)) {
2079
return;
2080
}
2081
_Py_call_instrumentation_arg(tstate, PY_MONITORING_EVENT_EXCEPTION_HANDLED, frame, instr, exc);
2082
}
2083
2084
static void
2085
monitor_throw(PyThreadState *tstate,
2086
_PyInterpreterFrame *frame,
2087
_Py_CODEUNIT *instr)
2088
{
2089
if (no_tools_for_event(tstate, frame, PY_MONITORING_EVENT_PY_THROW)) {
2090
return;
2091
}
2092
_Py_call_instrumentation_exc0(tstate, PY_MONITORING_EVENT_PY_THROW, frame, instr);
2093
}
2094
2095
void
2096
PyThreadState_EnterTracing(PyThreadState *tstate)
2097
{
2098
assert(tstate->tracing >= 0);
2099
tstate->tracing++;
2100
}
2101
2102
void
2103
PyThreadState_LeaveTracing(PyThreadState *tstate)
2104
{
2105
assert(tstate->tracing > 0);
2106
tstate->tracing--;
2107
}
2108
2109
2110
PyObject*
2111
_PyEval_CallTracing(PyObject *func, PyObject *args)
2112
{
2113
// Save and disable tracing
2114
PyThreadState *tstate = _PyThreadState_GET();
2115
int save_tracing = tstate->tracing;
2116
tstate->tracing = 0;
2117
2118
// Call the tracing function
2119
PyObject *result = PyObject_Call(func, args, NULL);
2120
2121
// Restore tracing
2122
tstate->tracing = save_tracing;
2123
return result;
2124
}
2125
2126
void
2127
PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
2128
{
2129
PyThreadState *tstate = _PyThreadState_GET();
2130
if (_PyEval_SetProfile(tstate, func, arg) < 0) {
2131
/* Log _PySys_Audit() error */
2132
_PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL);
2133
}
2134
}
2135
2136
void
2137
PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *arg)
2138
{
2139
PyThreadState *this_tstate = _PyThreadState_GET();
2140
PyInterpreterState* interp = this_tstate->interp;
2141
2142
_PyRuntimeState *runtime = &_PyRuntime;
2143
HEAD_LOCK(runtime);
2144
PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
2145
HEAD_UNLOCK(runtime);
2146
2147
while (ts) {
2148
if (_PyEval_SetProfile(ts, func, arg) < 0) {
2149
_PyErr_WriteUnraisableMsg("in PyEval_SetProfileAllThreads", NULL);
2150
}
2151
HEAD_LOCK(runtime);
2152
ts = PyThreadState_Next(ts);
2153
HEAD_UNLOCK(runtime);
2154
}
2155
}
2156
2157
void
2158
PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
2159
{
2160
PyThreadState *tstate = _PyThreadState_GET();
2161
if (_PyEval_SetTrace(tstate, func, arg) < 0) {
2162
/* Log _PySys_Audit() error */
2163
_PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL);
2164
}
2165
}
2166
2167
void
2168
PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *arg)
2169
{
2170
PyThreadState *this_tstate = _PyThreadState_GET();
2171
PyInterpreterState* interp = this_tstate->interp;
2172
2173
_PyRuntimeState *runtime = &_PyRuntime;
2174
HEAD_LOCK(runtime);
2175
PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
2176
HEAD_UNLOCK(runtime);
2177
2178
while (ts) {
2179
if (_PyEval_SetTrace(ts, func, arg) < 0) {
2180
_PyErr_WriteUnraisableMsg("in PyEval_SetTraceAllThreads", NULL);
2181
}
2182
HEAD_LOCK(runtime);
2183
ts = PyThreadState_Next(ts);
2184
HEAD_UNLOCK(runtime);
2185
}
2186
}
2187
2188
int
2189
_PyEval_SetCoroutineOriginTrackingDepth(int depth)
2190
{
2191
PyThreadState *tstate = _PyThreadState_GET();
2192
if (depth < 0) {
2193
_PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
2194
return -1;
2195
}
2196
tstate->coroutine_origin_tracking_depth = depth;
2197
return 0;
2198
}
2199
2200
2201
int
2202
_PyEval_GetCoroutineOriginTrackingDepth(void)
2203
{
2204
PyThreadState *tstate = _PyThreadState_GET();
2205
return tstate->coroutine_origin_tracking_depth;
2206
}
2207
2208
int
2209
_PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
2210
{
2211
PyThreadState *tstate = _PyThreadState_GET();
2212
2213
if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
2214
return -1;
2215
}
2216
2217
Py_XSETREF(tstate->async_gen_firstiter, Py_XNewRef(firstiter));
2218
return 0;
2219
}
2220
2221
PyObject *
2222
_PyEval_GetAsyncGenFirstiter(void)
2223
{
2224
PyThreadState *tstate = _PyThreadState_GET();
2225
return tstate->async_gen_firstiter;
2226
}
2227
2228
int
2229
_PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
2230
{
2231
PyThreadState *tstate = _PyThreadState_GET();
2232
2233
if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
2234
return -1;
2235
}
2236
2237
Py_XSETREF(tstate->async_gen_finalizer, Py_XNewRef(finalizer));
2238
return 0;
2239
}
2240
2241
PyObject *
2242
_PyEval_GetAsyncGenFinalizer(void)
2243
{
2244
PyThreadState *tstate = _PyThreadState_GET();
2245
return tstate->async_gen_finalizer;
2246
}
2247
2248
_PyInterpreterFrame *
2249
_PyEval_GetFrame(void)
2250
{
2251
PyThreadState *tstate = _PyThreadState_GET();
2252
return _PyThreadState_GetFrame(tstate);
2253
}
2254
2255
PyFrameObject *
2256
PyEval_GetFrame(void)
2257
{
2258
_PyInterpreterFrame *frame = _PyEval_GetFrame();
2259
if (frame == NULL) {
2260
return NULL;
2261
}
2262
PyFrameObject *f = _PyFrame_GetFrameObject(frame);
2263
if (f == NULL) {
2264
PyErr_Clear();
2265
}
2266
return f;
2267
}
2268
2269
PyObject *
2270
_PyEval_GetBuiltins(PyThreadState *tstate)
2271
{
2272
_PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
2273
if (frame != NULL) {
2274
return frame->f_builtins;
2275
}
2276
return tstate->interp->builtins;
2277
}
2278
2279
PyObject *
2280
PyEval_GetBuiltins(void)
2281
{
2282
PyThreadState *tstate = _PyThreadState_GET();
2283
return _PyEval_GetBuiltins(tstate);
2284
}
2285
2286
/* Convenience function to get a builtin from its name */
2287
PyObject *
2288
_PyEval_GetBuiltin(PyObject *name)
2289
{
2290
PyThreadState *tstate = _PyThreadState_GET();
2291
PyObject *attr = PyDict_GetItemWithError(PyEval_GetBuiltins(), name);
2292
if (attr) {
2293
Py_INCREF(attr);
2294
}
2295
else if (!_PyErr_Occurred(tstate)) {
2296
_PyErr_SetObject(tstate, PyExc_AttributeError, name);
2297
}
2298
return attr;
2299
}
2300
2301
PyObject *
2302
_PyEval_GetBuiltinId(_Py_Identifier *name)
2303
{
2304
return _PyEval_GetBuiltin(_PyUnicode_FromId(name));
2305
}
2306
2307
PyObject *
2308
PyEval_GetLocals(void)
2309
{
2310
PyThreadState *tstate = _PyThreadState_GET();
2311
_PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2312
if (current_frame == NULL) {
2313
_PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
2314
return NULL;
2315
}
2316
2317
if (_PyFrame_FastToLocalsWithError(current_frame) < 0) {
2318
return NULL;
2319
}
2320
2321
PyObject *locals = current_frame->f_locals;
2322
assert(locals != NULL);
2323
return locals;
2324
}
2325
2326
PyObject *
2327
PyEval_GetGlobals(void)
2328
{
2329
PyThreadState *tstate = _PyThreadState_GET();
2330
_PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
2331
if (current_frame == NULL) {
2332
return NULL;
2333
}
2334
return current_frame->f_globals;
2335
}
2336
2337
int
2338
PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
2339
{
2340
PyThreadState *tstate = _PyThreadState_GET();
2341
_PyInterpreterFrame *current_frame = tstate->cframe->current_frame;
2342
int result = cf->cf_flags != 0;
2343
2344
if (current_frame != NULL) {
2345
const int codeflags = _PyFrame_GetCode(current_frame)->co_flags;
2346
const int compilerflags = codeflags & PyCF_MASK;
2347
if (compilerflags) {
2348
result = 1;
2349
cf->cf_flags |= compilerflags;
2350
}
2351
}
2352
return result;
2353
}
2354
2355
2356
const char *
2357
PyEval_GetFuncName(PyObject *func)
2358
{
2359
if (PyMethod_Check(func))
2360
return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
2361
else if (PyFunction_Check(func))
2362
return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
2363
else if (PyCFunction_Check(func))
2364
return ((PyCFunctionObject*)func)->m_ml->ml_name;
2365
else
2366
return Py_TYPE(func)->tp_name;
2367
}
2368
2369
const char *
2370
PyEval_GetFuncDesc(PyObject *func)
2371
{
2372
if (PyMethod_Check(func))
2373
return "()";
2374
else if (PyFunction_Check(func))
2375
return "()";
2376
else if (PyCFunction_Check(func))
2377
return "()";
2378
else
2379
return " object";
2380
}
2381
2382
/* Extract a slice index from a PyLong or an object with the
2383
nb_index slot defined, and store in *pi.
2384
Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
2385
and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
2386
Return 0 on error, 1 on success.
2387
*/
2388
int
2389
_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
2390
{
2391
PyThreadState *tstate = _PyThreadState_GET();
2392
if (!Py_IsNone(v)) {
2393
Py_ssize_t x;
2394
if (_PyIndex_Check(v)) {
2395
x = PyNumber_AsSsize_t(v, NULL);
2396
if (x == -1 && _PyErr_Occurred(tstate))
2397
return 0;
2398
}
2399
else {
2400
_PyErr_SetString(tstate, PyExc_TypeError,
2401
"slice indices must be integers or "
2402
"None or have an __index__ method");
2403
return 0;
2404
}
2405
*pi = x;
2406
}
2407
return 1;
2408
}
2409
2410
int
2411
_PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
2412
{
2413
PyThreadState *tstate = _PyThreadState_GET();
2414
Py_ssize_t x;
2415
if (_PyIndex_Check(v)) {
2416
x = PyNumber_AsSsize_t(v, NULL);
2417
if (x == -1 && _PyErr_Occurred(tstate))
2418
return 0;
2419
}
2420
else {
2421
_PyErr_SetString(tstate, PyExc_TypeError,
2422
"slice indices must be integers or "
2423
"have an __index__ method");
2424
return 0;
2425
}
2426
*pi = x;
2427
return 1;
2428
}
2429
2430
static PyObject *
2431
import_name(PyThreadState *tstate, _PyInterpreterFrame *frame,
2432
PyObject *name, PyObject *fromlist, PyObject *level)
2433
{
2434
PyObject *import_func = _PyDict_GetItemWithError(frame->f_builtins,
2435
&_Py_ID(__import__));
2436
if (import_func == NULL) {
2437
if (!_PyErr_Occurred(tstate)) {
2438
_PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
2439
}
2440
return NULL;
2441
}
2442
2443
PyObject *locals = frame->f_locals;
2444
if (locals == NULL) {
2445
locals = Py_None;
2446
}
2447
2448
/* Fast path for not overloaded __import__. */
2449
if (_PyImport_IsDefaultImportFunc(tstate->interp, import_func)) {
2450
int ilevel = _PyLong_AsInt(level);
2451
if (ilevel == -1 && _PyErr_Occurred(tstate)) {
2452
return NULL;
2453
}
2454
return PyImport_ImportModuleLevelObject(
2455
name,
2456
frame->f_globals,
2457
locals,
2458
fromlist,
2459
ilevel);
2460
}
2461
2462
PyObject* args[5] = {name, frame->f_globals, locals, fromlist, level};
2463
Py_INCREF(import_func);
2464
PyObject *res = PyObject_Vectorcall(import_func, args, 5, NULL);
2465
Py_DECREF(import_func);
2466
return res;
2467
}
2468
2469
static PyObject *
2470
import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
2471
{
2472
PyObject *x;
2473
PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg;
2474
2475
if (_PyObject_LookupAttr(v, name, &x) != 0) {
2476
return x;
2477
}
2478
/* Issue #17636: in case this failed because of a circular relative
2479
import, try to fallback on reading the module directly from
2480
sys.modules. */
2481
pkgname = PyObject_GetAttr(v, &_Py_ID(__name__));
2482
if (pkgname == NULL) {
2483
goto error;
2484
}
2485
if (!PyUnicode_Check(pkgname)) {
2486
Py_CLEAR(pkgname);
2487
goto error;
2488
}
2489
fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
2490
if (fullmodname == NULL) {
2491
Py_DECREF(pkgname);
2492
return NULL;
2493
}
2494
x = PyImport_GetModule(fullmodname);
2495
Py_DECREF(fullmodname);
2496
if (x == NULL && !_PyErr_Occurred(tstate)) {
2497
goto error;
2498
}
2499
Py_DECREF(pkgname);
2500
return x;
2501
error:
2502
pkgpath = PyModule_GetFilenameObject(v);
2503
if (pkgname == NULL) {
2504
pkgname_or_unknown = PyUnicode_FromString("<unknown module name>");
2505
if (pkgname_or_unknown == NULL) {
2506
Py_XDECREF(pkgpath);
2507
return NULL;
2508
}
2509
} else {
2510
pkgname_or_unknown = pkgname;
2511
}
2512
2513
if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
2514
_PyErr_Clear(tstate);
2515
errmsg = PyUnicode_FromFormat(
2516
"cannot import name %R from %R (unknown location)",
2517
name, pkgname_or_unknown
2518
);
2519
/* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
2520
_PyErr_SetImportErrorWithNameFrom(errmsg, pkgname, NULL, name);
2521
}
2522
else {
2523
PyObject *spec = PyObject_GetAttr(v, &_Py_ID(__spec__));
2524
const char *fmt =
2525
_PyModuleSpec_IsInitializing(spec) ?
2526
"cannot import name %R from partially initialized module %R "
2527
"(most likely due to a circular import) (%S)" :
2528
"cannot import name %R from %R (%S)";
2529
Py_XDECREF(spec);
2530
2531
errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
2532
/* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
2533
_PyErr_SetImportErrorWithNameFrom(errmsg, pkgname, pkgpath, name);
2534
}
2535
2536
Py_XDECREF(errmsg);
2537
Py_XDECREF(pkgname_or_unknown);
2538
Py_XDECREF(pkgpath);
2539
return NULL;
2540
}
2541
2542
#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
2543
"BaseException is not allowed"
2544
2545
#define CANNOT_EXCEPT_STAR_EG "catching ExceptionGroup with except* "\
2546
"is not allowed. Use except instead."
2547
2548
static int
2549
check_except_type_valid(PyThreadState *tstate, PyObject* right)
2550
{
2551
if (PyTuple_Check(right)) {
2552
Py_ssize_t i, length;
2553
length = PyTuple_GET_SIZE(right);
2554
for (i = 0; i < length; i++) {
2555
PyObject *exc = PyTuple_GET_ITEM(right, i);
2556
if (!PyExceptionClass_Check(exc)) {
2557
_PyErr_SetString(tstate, PyExc_TypeError,
2558
CANNOT_CATCH_MSG);
2559
return -1;
2560
}
2561
}
2562
}
2563
else {
2564
if (!PyExceptionClass_Check(right)) {
2565
_PyErr_SetString(tstate, PyExc_TypeError,
2566
CANNOT_CATCH_MSG);
2567
return -1;
2568
}
2569
}
2570
return 0;
2571
}
2572
2573
static int
2574
check_except_star_type_valid(PyThreadState *tstate, PyObject* right)
2575
{
2576
if (check_except_type_valid(tstate, right) < 0) {
2577
return -1;
2578
}
2579
2580
/* reject except *ExceptionGroup */
2581
2582
int is_subclass = 0;
2583
if (PyTuple_Check(right)) {
2584
Py_ssize_t length = PyTuple_GET_SIZE(right);
2585
for (Py_ssize_t i = 0; i < length; i++) {
2586
PyObject *exc = PyTuple_GET_ITEM(right, i);
2587
is_subclass = PyObject_IsSubclass(exc, PyExc_BaseExceptionGroup);
2588
if (is_subclass < 0) {
2589
return -1;
2590
}
2591
if (is_subclass) {
2592
break;
2593
}
2594
}
2595
}
2596
else {
2597
is_subclass = PyObject_IsSubclass(right, PyExc_BaseExceptionGroup);
2598
if (is_subclass < 0) {
2599
return -1;
2600
}
2601
}
2602
if (is_subclass) {
2603
_PyErr_SetString(tstate, PyExc_TypeError,
2604
CANNOT_EXCEPT_STAR_EG);
2605
return -1;
2606
}
2607
return 0;
2608
}
2609
2610
static int
2611
check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
2612
{
2613
if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
2614
/* check_args_iterable() may be called with a live exception:
2615
* clear it to prevent calling _PyObject_FunctionStr() with an
2616
* exception set. */
2617
_PyErr_Clear(tstate);
2618
PyObject *funcstr = _PyObject_FunctionStr(func);
2619
if (funcstr != NULL) {
2620
_PyErr_Format(tstate, PyExc_TypeError,
2621
"%U argument after * must be an iterable, not %.200s",
2622
funcstr, Py_TYPE(args)->tp_name);
2623
Py_DECREF(funcstr);
2624
}
2625
return -1;
2626
}
2627
return 0;
2628
}
2629
2630
static void
2631
format_kwargs_error(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
2632
{
2633
/* _PyDict_MergeEx raises attribute
2634
* error (percolated from an attempt
2635
* to get 'keys' attribute) instead of
2636
* a type error if its second argument
2637
* is not a mapping.
2638
*/
2639
if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
2640
_PyErr_Clear(tstate);
2641
PyObject *funcstr = _PyObject_FunctionStr(func);
2642
if (funcstr != NULL) {
2643
_PyErr_Format(
2644
tstate, PyExc_TypeError,
2645
"%U argument after ** must be a mapping, not %.200s",
2646
funcstr, Py_TYPE(kwargs)->tp_name);
2647
Py_DECREF(funcstr);
2648
}
2649
}
2650
else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2651
PyObject *exc = _PyErr_GetRaisedException(tstate);
2652
PyObject *args = ((PyBaseExceptionObject *)exc)->args;
2653
if (exc && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1) {
2654
_PyErr_Clear(tstate);
2655
PyObject *funcstr = _PyObject_FunctionStr(func);
2656
if (funcstr != NULL) {
2657
PyObject *key = PyTuple_GET_ITEM(args, 0);
2658
_PyErr_Format(
2659
tstate, PyExc_TypeError,
2660
"%U got multiple values for keyword argument '%S'",
2661
funcstr, key);
2662
Py_DECREF(funcstr);
2663
}
2664
Py_XDECREF(exc);
2665
}
2666
else {
2667
_PyErr_SetRaisedException(tstate, exc);
2668
}
2669
}
2670
}
2671
2672
static void
2673
format_exc_check_arg(PyThreadState *tstate, PyObject *exc,
2674
const char *format_str, PyObject *obj)
2675
{
2676
const char *obj_str;
2677
2678
if (!obj)
2679
return;
2680
2681
obj_str = PyUnicode_AsUTF8(obj);
2682
if (!obj_str)
2683
return;
2684
2685
_PyErr_Format(tstate, exc, format_str, obj_str);
2686
2687
if (exc == PyExc_NameError) {
2688
// Include the name in the NameError exceptions to offer suggestions later.
2689
PyObject *exc = PyErr_GetRaisedException();
2690
if (PyErr_GivenExceptionMatches(exc, PyExc_NameError)) {
2691
if (((PyNameErrorObject*)exc)->name == NULL) {
2692
// We do not care if this fails because we are going to restore the
2693
// NameError anyway.
2694
(void)PyObject_SetAttr(exc, &_Py_ID(name), obj);
2695
}
2696
}
2697
PyErr_SetRaisedException(exc);
2698
}
2699
}
2700
2701
static void
2702
format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
2703
{
2704
PyObject *name;
2705
/* Don't stomp existing exception */
2706
if (_PyErr_Occurred(tstate))
2707
return;
2708
name = PyTuple_GET_ITEM(co->co_localsplusnames, oparg);
2709
if (oparg < PyCode_GetFirstFree(co)) {
2710
format_exc_check_arg(tstate, PyExc_UnboundLocalError,
2711
UNBOUNDLOCAL_ERROR_MSG, name);
2712
} else {
2713
format_exc_check_arg(tstate, PyExc_NameError,
2714
UNBOUNDFREE_ERROR_MSG, name);
2715
}
2716
}
2717
2718
static void
2719
format_awaitable_error(PyThreadState *tstate, PyTypeObject *type, int oparg)
2720
{
2721
if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
2722
if (oparg == 1) {
2723
_PyErr_Format(tstate, PyExc_TypeError,
2724
"'async with' received an object from __aenter__ "
2725
"that does not implement __await__: %.100s",
2726
type->tp_name);
2727
}
2728
else if (oparg == 2) {
2729
_PyErr_Format(tstate, PyExc_TypeError,
2730
"'async with' received an object from __aexit__ "
2731
"that does not implement __await__: %.100s",
2732
type->tp_name);
2733
}
2734
}
2735
}
2736
2737
2738
Py_ssize_t
2739
PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
2740
{
2741
PyInterpreterState *interp = _PyInterpreterState_GET();
2742
Py_ssize_t new_index;
2743
2744
if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
2745
return -1;
2746
}
2747
new_index = interp->co_extra_user_count++;
2748
interp->co_extra_freefuncs[new_index] = free;
2749
return new_index;
2750
}
2751
2752
/* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
2753
for the limited API. */
2754
2755
int Py_EnterRecursiveCall(const char *where)
2756
{
2757
return _Py_EnterRecursiveCall(where);
2758
}
2759
2760
void Py_LeaveRecursiveCall(void)
2761
{
2762
_Py_LeaveRecursiveCall();
2763
}
2764
2765
///////////////////// Experimental UOp Interpreter /////////////////////
2766
2767
#undef DEOPT_IF
2768
#define DEOPT_IF(COND, INSTNAME) \
2769
if ((COND)) { \
2770
goto deoptimize; \
2771
}
2772
2773
_PyInterpreterFrame *
2774
_PyUopExecute(_PyExecutorObject *executor, _PyInterpreterFrame *frame, PyObject **stack_pointer)
2775
{
2776
#ifdef LLTRACE
2777
char *uop_debug = Py_GETENV("PYTHONUOPSDEBUG");
2778
int lltrace = 0;
2779
if (uop_debug != NULL && *uop_debug >= '0') {
2780
lltrace = *uop_debug - '0'; // TODO: Parse an int and all that
2781
}
2782
if (lltrace >= 2) {
2783
PyCodeObject *code = _PyFrame_GetCode(frame);
2784
_Py_CODEUNIT *instr = frame->prev_instr + 1;
2785
fprintf(stderr,
2786
"Entering _PyUopExecute for %s (%s:%d) at offset %ld\n",
2787
PyUnicode_AsUTF8(code->co_qualname),
2788
PyUnicode_AsUTF8(code->co_filename),
2789
code->co_firstlineno,
2790
(long)(instr - (_Py_CODEUNIT *)code->co_code_adaptive));
2791
}
2792
#endif
2793
2794
PyThreadState *tstate = _PyThreadState_GET();
2795
_PyUOpExecutorObject *self = (_PyUOpExecutorObject *)executor;
2796
2797
// Equivalent to CHECK_EVAL_BREAKER()
2798
_Py_CHECK_EMSCRIPTEN_SIGNALS_PERIODICALLY();
2799
if (_Py_atomic_load_relaxed_int32(&tstate->interp->ceval.eval_breaker)) {
2800
if (_Py_HandlePending(tstate) != 0) {
2801
goto error;
2802
}
2803
}
2804
2805
OBJECT_STAT_INC(optimization_traces_executed);
2806
_Py_CODEUNIT *ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive - 1;
2807
int pc = 0;
2808
int opcode;
2809
uint64_t operand;
2810
int oparg;
2811
for (;;) {
2812
opcode = self->trace[pc].opcode;
2813
operand = self->trace[pc].operand;
2814
oparg = (int)operand;
2815
#ifdef LLTRACE
2816
if (lltrace >= 3) {
2817
const char *opname = opcode < 256 ? _PyOpcode_OpName[opcode] : _PyOpcode_uop_name[opcode];
2818
int stack_level = (int)(stack_pointer - _PyFrame_Stackbase(frame));
2819
fprintf(stderr, " uop %s, operand %" PRIu64 ", stack_level %d\n",
2820
opname, operand, stack_level);
2821
}
2822
#endif
2823
pc++;
2824
OBJECT_STAT_INC(optimization_uops_executed);
2825
switch (opcode) {
2826
2827
#undef ENABLE_SPECIALIZATION
2828
#define ENABLE_SPECIALIZATION 0
2829
#include "executor_cases.c.h"
2830
2831
case SET_IP:
2832
{
2833
frame->prev_instr = ip_offset + oparg;
2834
break;
2835
}
2836
2837
case EXIT_TRACE:
2838
{
2839
_PyFrame_SetStackPointer(frame, stack_pointer);
2840
Py_DECREF(self);
2841
return frame;
2842
}
2843
2844
default:
2845
{
2846
fprintf(stderr, "Unknown uop %d, operand %" PRIu64 "\n", opcode, operand);
2847
Py_FatalError("Unknown uop");
2848
}
2849
2850
}
2851
}
2852
2853
pop_4_error:
2854
STACK_SHRINK(1);
2855
pop_3_error:
2856
STACK_SHRINK(1);
2857
pop_2_error:
2858
STACK_SHRINK(1);
2859
pop_1_error:
2860
STACK_SHRINK(1);
2861
error:
2862
// On ERROR_IF we return NULL as the frame.
2863
// The caller recovers the frame from cframe.current_frame.
2864
#ifdef LLTRACE
2865
if (lltrace >= 2) {
2866
fprintf(stderr, "Error: [Opcode %d, operand %" PRIu64 "]\n", opcode, operand);
2867
}
2868
#endif
2869
_PyFrame_SetStackPointer(frame, stack_pointer);
2870
Py_DECREF(self);
2871
return NULL;
2872
2873
deoptimize:
2874
// On DEOPT_IF we just repeat the last instruction.
2875
// This presumes nothing was popped from the stack (nor pushed).
2876
#ifdef LLTRACE
2877
if (lltrace >= 2) {
2878
fprintf(stderr, "DEOPT: [Opcode %d, operand %" PRIu64 "]\n", opcode, operand);
2879
}
2880
#endif
2881
_PyFrame_SetStackPointer(frame, stack_pointer);
2882
Py_DECREF(self);
2883
return frame;
2884
}
2885
2886