blob: ea31179f8629b87695e48d22621a35ab07827fd3 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Execute compiled code */
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003
Guido van Rossum681d79a1995-07-18 14:51:37 +00004/* XXX TO DO:
Guido van Rossum681d79a1995-07-18 14:51:37 +00005 XXX speed up searching for keywords by using a dictionary
Guido van Rossum681d79a1995-07-18 14:51:37 +00006 XXX document it!
7 */
8
Thomas Wouters477c8d52006-05-27 19:21:47 +00009/* enable more aggressive intra-module optimizations, where available */
db3l131d5512021-03-03 22:09:48 -050010/* affects both release and debug builds - see bpo-43271 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000011#define PY_LOCAL_AGGRESSIVE
12
Guido van Rossumb209a111997-04-29 18:18:01 +000013#include "Python.h"
Victor Stinnere560f902020-04-14 18:30:41 +020014#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinner384621c2020-06-22 17:27:35 +020015#include "pycore_call.h" // _PyObject_FastCallDictTstate()
16#include "pycore_ceval.h" // _PyEval_SignalAsyncExc()
17#include "pycore_code.h" // _PyCode_InitOpcache()
18#include "pycore_initconfig.h" // _PyStatus_OK()
19#include "pycore_object.h" // _PyObject_GC_TRACK()
20#include "pycore_pyerrors.h" // _PyErr_Fetch()
21#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere560f902020-04-14 18:30:41 +020022#include "pycore_pymem.h" // _PyMem_IsPtrFreed()
23#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner384621c2020-06-22 17:27:35 +020024#include "pycore_sysmodule.h" // _PySys_Audit()
25#include "pycore_tuple.h" // _PyTuple_ITEMS()
Guido van Rossum10dc2e81990-11-18 17:27:39 +000026
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "code.h"
Benjamin Peterson025e9eb2015-05-05 20:16:41 -040028#include "dictobject.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000029#include "frameobject.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000030#include "opcode.h"
Łukasz Langaa785c872016-09-09 17:37:37 -070031#include "pydtrace.h"
Benjamin Peterson025e9eb2015-05-05 20:16:41 -040032#include "setobject.h"
Guido van Rossum5c5a9382021-01-29 18:02:29 -080033#include "structmember.h" // struct PyMemberDef, T_OFFSET_EX
Guido van Rossum10dc2e81990-11-18 17:27:39 +000034
Guido van Rossumc6004111993-11-05 10:22:19 +000035#include <ctype.h>
36
Mark Shannon8e1b4062021-03-05 14:45:50 +000037typedef struct {
38 PyCodeObject *code; // The code object for the bounds. May be NULL.
39 int instr_prev; // Only valid if code != NULL.
40 PyCodeAddressRange bounds; // Only valid if code != NULL.
41} PyTraceInfo;
42
43
Guido van Rossum408027e1996-12-30 16:17:54 +000044#ifdef Py_DEBUG
Guido van Rossum96a42c81992-01-12 02:29:51 +000045/* For debugging the interpreter: */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046#define LLTRACE 1 /* Low-level trace feature */
47#define CHECKEXC 1 /* Double-check exception checking */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000048#endif
49
Victor Stinner5c75f372019-04-17 23:02:26 +020050#if !defined(Py_BUILD_CORE)
51# error "ceval.c must be build with Py_BUILD_CORE define for best performance"
52#endif
53
Hai Shi46874c22020-01-30 17:20:25 -060054_Py_IDENTIFIER(__name__);
Guido van Rossum5b722181993-03-30 17:46:03 +000055
Guido van Rossum374a9221991-04-04 10:40:29 +000056/* Forward declarations */
Victor Stinner09532fe2019-05-10 23:39:09 +020057Py_LOCAL_INLINE(PyObject *) call_function(
Mark Shannon8e1b4062021-03-05 14:45:50 +000058 PyThreadState *tstate, PyTraceInfo *, PyObject ***pp_stack,
Victor Stinner09532fe2019-05-10 23:39:09 +020059 Py_ssize_t oparg, PyObject *kwnames);
60static PyObject * do_call_core(
Mark Shannon8e1b4062021-03-05 14:45:50 +000061 PyThreadState *tstate, PyTraceInfo *, PyObject *func,
Victor Stinner09532fe2019-05-10 23:39:09 +020062 PyObject *callargs, PyObject *kwdict);
Jeremy Hylton52820442001-01-03 23:52:36 +000063
Guido van Rossum0a066c01992-03-27 17:29:15 +000064#ifdef LLTRACE
Guido van Rossumc2e20742006-02-27 22:32:47 +000065static int lltrace;
Victor Stinner438a12d2019-05-24 17:01:38 +020066static int prtrace(PyThreadState *, PyObject *, const char *);
Guido van Rossum0a066c01992-03-27 17:29:15 +000067#endif
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +010068static int call_trace(Py_tracefunc, PyObject *,
69 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000070 PyTraceInfo *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 int, PyObject *);
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +000072static int call_trace_protected(Py_tracefunc, PyObject *,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +010073 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000074 PyTraceInfo *,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +010075 int, PyObject *);
76static void call_exc_trace(Py_tracefunc, PyObject *,
Mark Shannon86433452021-01-07 16:49:02 +000077 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000078 PyTraceInfo *trace_info);
Tim Peters8a5c3c72004-04-05 19:36:21 +000079static int maybe_call_line_trace(Py_tracefunc, PyObject *,
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000081 PyTraceInfo *);
82static void maybe_dtrace_line(PyFrameObject *, PyTraceInfo *);
Łukasz Langaa785c872016-09-09 17:37:37 -070083static void dtrace_function_entry(PyFrameObject *);
84static void dtrace_function_return(PyFrameObject *);
Michael W. Hudsondd32a912002-08-15 14:59:02 +000085
Victor Stinner438a12d2019-05-24 17:01:38 +020086static PyObject * import_name(PyThreadState *, PyFrameObject *,
87 PyObject *, PyObject *, PyObject *);
88static PyObject * import_from(PyThreadState *, PyObject *, PyObject *);
89static int import_all_from(PyThreadState *, PyObject *, PyObject *);
90static void format_exc_check_arg(PyThreadState *, PyObject *, const char *, PyObject *);
91static void format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
92static PyObject * unicode_concatenate(PyThreadState *, PyObject *, PyObject *,
Serhiy Storchakaab874002016-09-11 13:48:15 +030093 PyFrameObject *, const _Py_CODEUNIT *);
Victor Stinner438a12d2019-05-24 17:01:38 +020094static PyObject * special_lookup(PyThreadState *, PyObject *, _Py_Identifier *);
95static int check_args_iterable(PyThreadState *, PyObject *func, PyObject *vararg);
96static void format_kwargs_error(PyThreadState *, PyObject *func, PyObject *kwargs);
Mark Shannonfee55262019-11-21 09:11:43 +000097static void format_awaitable_error(PyThreadState *, PyTypeObject *, int, int);
Guido van Rossum374a9221991-04-04 10:40:29 +000098
Paul Prescode68140d2000-08-30 20:25:01 +000099#define NAME_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 "name '%.200s' is not defined"
Paul Prescode68140d2000-08-30 20:25:01 +0000101#define UNBOUNDLOCAL_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 "local variable '%.200s' referenced before assignment"
Jeremy Hyltonc76770c2001-04-13 16:51:46 +0000103#define UNBOUNDFREE_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 "free variable '%.200s' referenced before assignment" \
105 " in enclosing scope"
Guido van Rossum374a9221991-04-04 10:40:29 +0000106
Guido van Rossum950361c1997-01-24 13:49:28 +0000107/* Dynamic execution profile */
108#ifdef DYNAMIC_EXECUTION_PROFILE
109#ifdef DXPAIRS
110static long dxpairs[257][256];
111#define dxp dxpairs[256]
112#else
113static long dxp[256];
114#endif
115#endif
116
Inada Naoki91234a12019-06-03 21:30:58 +0900117/* per opcode cache */
Pablo Galindoaf5fa132021-02-28 22:41:09 +0000118static int opcache_min_runs = 1024; /* create opcache when code executed this many times */
Pablo Galindo109826c2020-10-20 06:22:44 +0100119#define OPCODE_CACHE_MAX_TRIES 20
Inada Naoki91234a12019-06-03 21:30:58 +0900120#define OPCACHE_STATS 0 /* Enable stats */
121
Pablo Galindoaf5fa132021-02-28 22:41:09 +0000122// This function allows to deactivate the opcode cache. As different cache mechanisms may hold
123// references, this can mess with the reference leak detector functionality so the cache needs
124// to be deactivated in such scenarios to avoid false positives. See bpo-3714 for more information.
125void
126_PyEval_DeactivateOpCache(void)
127{
128 opcache_min_runs = 0;
129}
130
Inada Naoki91234a12019-06-03 21:30:58 +0900131#if OPCACHE_STATS
132static size_t opcache_code_objects = 0;
133static size_t opcache_code_objects_extra_mem = 0;
134
135static size_t opcache_global_opts = 0;
136static size_t opcache_global_hits = 0;
137static size_t opcache_global_misses = 0;
Pablo Galindo109826c2020-10-20 06:22:44 +0100138
139static size_t opcache_attr_opts = 0;
140static size_t opcache_attr_hits = 0;
141static size_t opcache_attr_misses = 0;
142static size_t opcache_attr_deopts = 0;
143static size_t opcache_attr_total = 0;
Inada Naoki91234a12019-06-03 21:30:58 +0900144#endif
145
Victor Stinner5a3a71d2020-03-19 17:40:12 +0100146
Victor Stinnerda2914d2020-03-20 09:29:08 +0100147#ifndef NDEBUG
148/* Ensure that tstate is valid: sanity check for PyEval_AcquireThread() and
149 PyEval_RestoreThread(). Detect if tstate memory was freed. It can happen
150 when a thread continues to run after Python finalization, especially
151 daemon threads. */
152static int
153is_tstate_valid(PyThreadState *tstate)
154{
155 assert(!_PyMem_IsPtrFreed(tstate));
156 assert(!_PyMem_IsPtrFreed(tstate->interp));
157 return 1;
158}
159#endif
160
161
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000162/* This can set eval_breaker to 0 even though gil_drop_request became
163 1. We believe this is all right because the eval loop will release
164 the GIL eventually anyway. */
Victor Stinnerda2914d2020-03-20 09:29:08 +0100165static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200166COMPUTE_EVAL_BREAKER(PyInterpreterState *interp,
Victor Stinner299b8c62020-05-05 17:40:18 +0200167 struct _ceval_runtime_state *ceval,
168 struct _ceval_state *ceval2)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100169{
Victor Stinner299b8c62020-05-05 17:40:18 +0200170 _Py_atomic_store_relaxed(&ceval2->eval_breaker,
171 _Py_atomic_load_relaxed(&ceval2->gil_drop_request)
Victor Stinner0b1e3302020-05-05 16:14:31 +0200172 | (_Py_atomic_load_relaxed(&ceval->signals_pending)
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200173 && _Py_ThreadCanHandleSignals(interp))
Victor Stinner299b8c62020-05-05 17:40:18 +0200174 | (_Py_atomic_load_relaxed(&ceval2->pending.calls_to_do)
Victor Stinnerd8316882020-03-20 14:50:35 +0100175 && _Py_ThreadCanHandlePendingCalls())
Victor Stinner299b8c62020-05-05 17:40:18 +0200176 | ceval2->pending.async_exc);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100177}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000178
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000179
Victor Stinnerda2914d2020-03-20 09:29:08 +0100180static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200181SET_GIL_DROP_REQUEST(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100182{
Victor Stinner299b8c62020-05-05 17:40:18 +0200183 struct _ceval_state *ceval2 = &interp->ceval;
184 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 1);
185 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100186}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000187
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000188
Victor Stinnerda2914d2020-03-20 09:29:08 +0100189static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200190RESET_GIL_DROP_REQUEST(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100191{
Victor Stinner299b8c62020-05-05 17:40:18 +0200192 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
193 struct _ceval_state *ceval2 = &interp->ceval;
194 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 0);
195 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100196}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000197
Eric Snowfdf282d2019-01-11 14:26:55 -0700198
Victor Stinnerda2914d2020-03-20 09:29:08 +0100199static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200200SIGNAL_PENDING_CALLS(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100201{
Victor Stinner299b8c62020-05-05 17:40:18 +0200202 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
203 struct _ceval_state *ceval2 = &interp->ceval;
204 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 1);
205 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100206}
Eric Snowfdf282d2019-01-11 14:26:55 -0700207
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000208
Victor Stinnerda2914d2020-03-20 09:29:08 +0100209static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200210UNSIGNAL_PENDING_CALLS(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100211{
Victor Stinner299b8c62020-05-05 17:40:18 +0200212 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
213 struct _ceval_state *ceval2 = &interp->ceval;
214 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 0);
215 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100216}
217
218
219static inline void
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100220SIGNAL_PENDING_SIGNALS(PyInterpreterState *interp, int force)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100221{
Victor Stinner299b8c62020-05-05 17:40:18 +0200222 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
223 struct _ceval_state *ceval2 = &interp->ceval;
Victor Stinner0b1e3302020-05-05 16:14:31 +0200224 _Py_atomic_store_relaxed(&ceval->signals_pending, 1);
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100225 if (force) {
226 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
227 }
228 else {
229 /* eval_breaker is not set to 1 if thread_can_handle_signals() is false */
230 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
231 }
Victor Stinnerda2914d2020-03-20 09:29:08 +0100232}
233
234
235static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200236UNSIGNAL_PENDING_SIGNALS(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100237{
Victor Stinner299b8c62020-05-05 17:40:18 +0200238 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
239 struct _ceval_state *ceval2 = &interp->ceval;
Victor Stinner0b1e3302020-05-05 16:14:31 +0200240 _Py_atomic_store_relaxed(&ceval->signals_pending, 0);
Victor Stinner299b8c62020-05-05 17:40:18 +0200241 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100242}
243
244
245static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200246SIGNAL_ASYNC_EXC(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100247{
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200248 struct _ceval_state *ceval2 = &interp->ceval;
Victor Stinnerda2914d2020-03-20 09:29:08 +0100249 ceval2->pending.async_exc = 1;
250 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
251}
252
253
254static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200255UNSIGNAL_ASYNC_EXC(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100256{
Victor Stinner299b8c62020-05-05 17:40:18 +0200257 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
258 struct _ceval_state *ceval2 = &interp->ceval;
259 ceval2->pending.async_exc = 0;
260 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100261}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000262
263
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000264#ifdef HAVE_ERRNO_H
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000265#include <errno.h>
Guido van Rossum2571cc81999-04-07 16:07:23 +0000266#endif
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000267#include "ceval_gil.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000268
Victor Stinner3026cad2020-06-01 16:02:40 +0200269void _Py_NO_RETURN
270_Py_FatalError_TstateNULL(const char *func)
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100271{
Victor Stinner3026cad2020-06-01 16:02:40 +0200272 _Py_FatalErrorFunc(func,
273 "the function must be called with the GIL held, "
274 "but the GIL is released "
275 "(the current Python thread state is NULL)");
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100276}
277
Victor Stinner7be4e352020-05-05 20:27:47 +0200278#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
279int
280_PyEval_ThreadsInitialized(PyInterpreterState *interp)
281{
282 return gil_created(&interp->ceval.gil);
283}
284
285int
286PyEval_ThreadsInitialized(void)
287{
288 // Fatal error if there is no current interpreter
289 PyInterpreterState *interp = PyInterpreterState_Get();
290 return _PyEval_ThreadsInitialized(interp);
291}
292#else
Tim Peters7f468f22004-10-11 02:40:51 +0000293int
Victor Stinner175a7042020-03-10 00:37:48 +0100294_PyEval_ThreadsInitialized(_PyRuntimeState *runtime)
295{
296 return gil_created(&runtime->ceval.gil);
297}
298
299int
Tim Peters7f468f22004-10-11 02:40:51 +0000300PyEval_ThreadsInitialized(void)
301{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100302 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner175a7042020-03-10 00:37:48 +0100303 return _PyEval_ThreadsInitialized(runtime);
Tim Peters7f468f22004-10-11 02:40:51 +0000304}
Victor Stinner7be4e352020-05-05 20:27:47 +0200305#endif
Tim Peters7f468f22004-10-11 02:40:51 +0000306
Victor Stinner111e4ee2020-03-09 21:24:14 +0100307PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200308_PyEval_InitGIL(PyThreadState *tstate)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000309{
Victor Stinner7be4e352020-05-05 20:27:47 +0200310#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner101bf692021-02-19 13:33:31 +0100311 if (!_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200312 /* Currently, the GIL is shared by all interpreters,
313 and only the main interpreter is responsible to create
314 and destroy it. */
315 return _PyStatus_OK();
Victor Stinner111e4ee2020-03-09 21:24:14 +0100316 }
Victor Stinner7be4e352020-05-05 20:27:47 +0200317#endif
Victor Stinner111e4ee2020-03-09 21:24:14 +0100318
Victor Stinner7be4e352020-05-05 20:27:47 +0200319#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
320 struct _gil_runtime_state *gil = &tstate->interp->ceval.gil;
321#else
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200322 struct _gil_runtime_state *gil = &tstate->interp->runtime->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200323#endif
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200324 assert(!gil_created(gil));
Victor Stinner85f5a692020-03-09 22:12:04 +0100325
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200326 PyThread_init_thread();
327 create_gil(gil);
328
329 take_gil(tstate);
330
331 assert(gil_created(gil));
Victor Stinner111e4ee2020-03-09 21:24:14 +0100332 return _PyStatus_OK();
333}
334
335void
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100336_PyEval_FiniGIL(PyInterpreterState *interp)
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200337{
Victor Stinner7be4e352020-05-05 20:27:47 +0200338#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100339 if (!_Py_IsMainInterpreter(interp)) {
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200340 /* Currently, the GIL is shared by all interpreters,
341 and only the main interpreter is responsible to create
342 and destroy it. */
343 return;
344 }
Victor Stinner7be4e352020-05-05 20:27:47 +0200345#endif
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200346
Victor Stinner7be4e352020-05-05 20:27:47 +0200347#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100348 struct _gil_runtime_state *gil = &interp->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200349#else
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100350 struct _gil_runtime_state *gil = &interp->runtime->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200351#endif
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200352 if (!gil_created(gil)) {
353 /* First Py_InitializeFromConfig() call: the GIL doesn't exist
354 yet: do nothing. */
355 return;
356 }
357
358 destroy_gil(gil);
359 assert(!gil_created(gil));
360}
361
362void
Victor Stinner111e4ee2020-03-09 21:24:14 +0100363PyEval_InitThreads(void)
364{
Victor Stinnerb4698ec2020-03-10 01:28:54 +0100365 /* Do nothing: kept for backward compatibility */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000366}
Guido van Rossumff4949e1992-08-05 19:58:53 +0000367
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000368void
Inada Naoki91234a12019-06-03 21:30:58 +0900369_PyEval_Fini(void)
370{
371#if OPCACHE_STATS
372 fprintf(stderr, "-- Opcode cache number of objects = %zd\n",
373 opcache_code_objects);
374
375 fprintf(stderr, "-- Opcode cache total extra mem = %zd\n",
376 opcache_code_objects_extra_mem);
377
378 fprintf(stderr, "\n");
379
380 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL hits = %zd (%d%%)\n",
381 opcache_global_hits,
382 (int) (100.0 * opcache_global_hits /
383 (opcache_global_hits + opcache_global_misses)));
384
385 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL misses = %zd (%d%%)\n",
386 opcache_global_misses,
387 (int) (100.0 * opcache_global_misses /
388 (opcache_global_hits + opcache_global_misses)));
389
390 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL opts = %zd\n",
391 opcache_global_opts);
392
393 fprintf(stderr, "\n");
Pablo Galindo109826c2020-10-20 06:22:44 +0100394
395 fprintf(stderr, "-- Opcode cache LOAD_ATTR hits = %zd (%d%%)\n",
396 opcache_attr_hits,
397 (int) (100.0 * opcache_attr_hits /
398 opcache_attr_total));
399
400 fprintf(stderr, "-- Opcode cache LOAD_ATTR misses = %zd (%d%%)\n",
401 opcache_attr_misses,
402 (int) (100.0 * opcache_attr_misses /
403 opcache_attr_total));
404
405 fprintf(stderr, "-- Opcode cache LOAD_ATTR opts = %zd\n",
406 opcache_attr_opts);
407
408 fprintf(stderr, "-- Opcode cache LOAD_ATTR deopts = %zd\n",
409 opcache_attr_deopts);
410
411 fprintf(stderr, "-- Opcode cache LOAD_ATTR total = %zd\n",
412 opcache_attr_total);
Inada Naoki91234a12019-06-03 21:30:58 +0900413#endif
414}
415
416void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000417PyEval_AcquireLock(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000418{
Victor Stinner09532fe2019-05-10 23:39:09 +0200419 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner09532fe2019-05-10 23:39:09 +0200420 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner3026cad2020-06-01 16:02:40 +0200421 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100422
Victor Stinner85f5a692020-03-09 22:12:04 +0100423 take_gil(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000424}
425
426void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000427PyEval_ReleaseLock(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000428{
Victor Stinner09532fe2019-05-10 23:39:09 +0200429 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnere225beb2019-06-03 18:14:24 +0200430 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 /* This function must succeed when the current thread state is NULL.
Victor Stinner50b48572018-11-01 01:51:40 +0100432 We therefore avoid PyThreadState_Get() which dumps a fatal error
Victor Stinnerda2914d2020-03-20 09:29:08 +0100433 in debug mode. */
Victor Stinner299b8c62020-05-05 17:40:18 +0200434 struct _ceval_runtime_state *ceval = &runtime->ceval;
435 struct _ceval_state *ceval2 = &tstate->interp->ceval;
436 drop_gil(ceval, ceval2, tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000437}
438
439void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100440_PyEval_ReleaseLock(PyThreadState *tstate)
441{
442 struct _ceval_runtime_state *ceval = &tstate->interp->runtime->ceval;
Victor Stinner0b1e3302020-05-05 16:14:31 +0200443 struct _ceval_state *ceval2 = &tstate->interp->ceval;
444 drop_gil(ceval, ceval2, tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100445}
446
447void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000448PyEval_AcquireThread(PyThreadState *tstate)
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000449{
Victor Stinner3026cad2020-06-01 16:02:40 +0200450 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100451
Victor Stinner85f5a692020-03-09 22:12:04 +0100452 take_gil(tstate);
Victor Stinnere225beb2019-06-03 18:14:24 +0200453
Victor Stinner85f5a692020-03-09 22:12:04 +0100454 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinnere838a932020-05-05 19:56:48 +0200455#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
456 (void)_PyThreadState_Swap(gilstate, tstate);
457#else
Victor Stinner85f5a692020-03-09 22:12:04 +0100458 if (_PyThreadState_Swap(gilstate, tstate) != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100459 Py_FatalError("non-NULL old thread state");
Victor Stinner09532fe2019-05-10 23:39:09 +0200460 }
Victor Stinnere838a932020-05-05 19:56:48 +0200461#endif
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000462}
463
464void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000465PyEval_ReleaseThread(PyThreadState *tstate)
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000466{
Victor Stinnerda2914d2020-03-20 09:29:08 +0100467 assert(is_tstate_valid(tstate));
Victor Stinner09532fe2019-05-10 23:39:09 +0200468
Victor Stinner01b1cc12019-11-20 02:27:56 +0100469 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner09532fe2019-05-10 23:39:09 +0200470 PyThreadState *new_tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
471 if (new_tstate != tstate) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100472 Py_FatalError("wrong thread state");
Victor Stinner09532fe2019-05-10 23:39:09 +0200473 }
Victor Stinner0b1e3302020-05-05 16:14:31 +0200474 struct _ceval_runtime_state *ceval = &runtime->ceval;
475 struct _ceval_state *ceval2 = &tstate->interp->ceval;
476 drop_gil(ceval, ceval2, tstate);
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000477}
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000478
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900479#ifdef HAVE_FORK
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200480/* This function is called from PyOS_AfterFork_Child to destroy all threads
Victor Stinner26881c82020-06-02 15:51:37 +0200481 which are not running in the child process, and clear internal locks
482 which might be held by those threads. */
483PyStatus
Victor Stinner317bab02020-06-02 18:44:54 +0200484_PyEval_ReInitThreads(PyThreadState *tstate)
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000485{
Victor Stinner317bab02020-06-02 18:44:54 +0200486 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner7be4e352020-05-05 20:27:47 +0200487
488#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
489 struct _gil_runtime_state *gil = &tstate->interp->ceval.gil;
490#else
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100491 struct _gil_runtime_state *gil = &runtime->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200492#endif
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100493 if (!gil_created(gil)) {
Victor Stinner26881c82020-06-02 15:51:37 +0200494 return _PyStatus_OK();
Victor Stinner09532fe2019-05-10 23:39:09 +0200495 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100496 recreate_gil(gil);
Victor Stinner85f5a692020-03-09 22:12:04 +0100497
498 take_gil(tstate);
Eric Snow8479a342019-03-08 23:44:33 -0700499
Victor Stinner50e6e992020-03-19 02:41:21 +0100500 struct _pending_calls *pending = &tstate->interp->ceval.pending;
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900501 if (_PyThread_at_fork_reinit(&pending->lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200502 return _PyStatus_ERR("Can't reinitialize pending calls lock");
Eric Snow8479a342019-03-08 23:44:33 -0700503 }
Jesse Nollera8513972008-07-17 16:49:17 +0000504
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200505 /* Destroy all threads except the current one */
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100506 _PyThreadState_DeleteExcept(runtime, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200507 return _PyStatus_OK();
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000508}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900509#endif
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000510
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000511/* This function is used to signal that async exceptions are waiting to be
Zackery Spytzeef05962018-09-29 10:07:11 -0600512 raised. */
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000513
514void
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100515_PyEval_SignalAsyncExc(PyInterpreterState *interp)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000516{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100517 SIGNAL_ASYNC_EXC(interp);
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000518}
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000519
Guido van Rossum2fca21f71997-07-18 23:56:58 +0000520PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000521PyEval_SaveThread(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000522{
Victor Stinner09532fe2019-05-10 23:39:09 +0200523 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnere838a932020-05-05 19:56:48 +0200524#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
525 PyThreadState *old_tstate = _PyThreadState_GET();
526 PyThreadState *tstate = _PyThreadState_Swap(&runtime->gilstate, old_tstate);
527#else
Victor Stinner09532fe2019-05-10 23:39:09 +0200528 PyThreadState *tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
Victor Stinnere838a932020-05-05 19:56:48 +0200529#endif
Victor Stinner3026cad2020-06-01 16:02:40 +0200530 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100531
Victor Stinner0b1e3302020-05-05 16:14:31 +0200532 struct _ceval_runtime_state *ceval = &runtime->ceval;
533 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinner7be4e352020-05-05 20:27:47 +0200534#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
535 assert(gil_created(&ceval2->gil));
536#else
Victor Stinnere225beb2019-06-03 18:14:24 +0200537 assert(gil_created(&ceval->gil));
Victor Stinner7be4e352020-05-05 20:27:47 +0200538#endif
Victor Stinner0b1e3302020-05-05 16:14:31 +0200539 drop_gil(ceval, ceval2, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return tstate;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000541}
542
543void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544PyEval_RestoreThread(PyThreadState *tstate)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000545{
Victor Stinner3026cad2020-06-01 16:02:40 +0200546 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100547
Victor Stinner85f5a692020-03-09 22:12:04 +0100548 take_gil(tstate);
Victor Stinner17c68b82020-01-30 12:20:48 +0100549
Victor Stinner85f5a692020-03-09 22:12:04 +0100550 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
551 _PyThreadState_Swap(gilstate, tstate);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000552}
553
554
Guido van Rossuma9672091994-09-14 13:31:22 +0000555/* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
556 signal handlers or Mac I/O completion routines) can schedule calls
557 to a function to be called synchronously.
558 The synchronous function is called with one void* argument.
559 It should return 0 for success or -1 for failure -- failure should
560 be accompanied by an exception.
561
562 If registry succeeds, the registry function returns 0; if it fails
563 (e.g. due to too many pending calls) it returns -1 (without setting
564 an exception condition).
565
566 Note that because registry may occur from within signal handlers,
567 or other asynchronous events, calling malloc() is unsafe!
568
Guido van Rossuma9672091994-09-14 13:31:22 +0000569 Any thread can schedule pending calls, but only the main thread
570 will execute them.
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000571 There is no facility to schedule calls to a particular thread, but
572 that should be easy to change, should that ever be required. In
573 that case, the static variables here should go into the python
574 threadstate.
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000575*/
Guido van Rossuma9672091994-09-14 13:31:22 +0000576
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200577void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200578_PyEval_SignalReceived(PyInterpreterState *interp)
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200579{
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100580#ifdef MS_WINDOWS
581 // bpo-42296: On Windows, _PyEval_SignalReceived() is called from a signal
582 // handler which can run in a thread different than the Python thread, in
583 // which case _Py_ThreadCanHandleSignals() is wrong. Ignore
584 // _Py_ThreadCanHandleSignals() and always set eval_breaker to 1.
585 //
586 // The next eval_frame_handle_pending() call will call
587 // _Py_ThreadCanHandleSignals() to recompute eval_breaker.
588 int force = 1;
589#else
590 int force = 0;
591#endif
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200592 /* bpo-30703: Function called when the C signal handler of Python gets a
Victor Stinner50e6e992020-03-19 02:41:21 +0100593 signal. We cannot queue a callback using _PyEval_AddPendingCall() since
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200594 that function is not async-signal-safe. */
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100595 SIGNAL_PENDING_SIGNALS(interp, force);
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200596}
597
Eric Snow5be45a62019-03-08 22:47:07 -0700598/* Push one item onto the queue while holding the lock. */
599static int
Victor Stinnere225beb2019-06-03 18:14:24 +0200600_push_pending_call(struct _pending_calls *pending,
Eric Snow842a2f02019-03-15 15:47:51 -0600601 int (*func)(void *), void *arg)
Eric Snow5be45a62019-03-08 22:47:07 -0700602{
Eric Snow842a2f02019-03-15 15:47:51 -0600603 int i = pending->last;
Eric Snow5be45a62019-03-08 22:47:07 -0700604 int j = (i + 1) % NPENDINGCALLS;
Eric Snow842a2f02019-03-15 15:47:51 -0600605 if (j == pending->first) {
Eric Snow5be45a62019-03-08 22:47:07 -0700606 return -1; /* Queue full */
607 }
Eric Snow842a2f02019-03-15 15:47:51 -0600608 pending->calls[i].func = func;
609 pending->calls[i].arg = arg;
610 pending->last = j;
Eric Snow5be45a62019-03-08 22:47:07 -0700611 return 0;
612}
613
614/* Pop one item off the queue while holding the lock. */
615static void
Victor Stinnere225beb2019-06-03 18:14:24 +0200616_pop_pending_call(struct _pending_calls *pending,
Eric Snow842a2f02019-03-15 15:47:51 -0600617 int (**func)(void *), void **arg)
Eric Snow5be45a62019-03-08 22:47:07 -0700618{
Eric Snow842a2f02019-03-15 15:47:51 -0600619 int i = pending->first;
620 if (i == pending->last) {
Eric Snow5be45a62019-03-08 22:47:07 -0700621 return; /* Queue empty */
622 }
623
Eric Snow842a2f02019-03-15 15:47:51 -0600624 *func = pending->calls[i].func;
625 *arg = pending->calls[i].arg;
626 pending->first = (i + 1) % NPENDINGCALLS;
Eric Snow5be45a62019-03-08 22:47:07 -0700627}
628
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200629/* This implementation is thread-safe. It allows
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000630 scheduling to be made from any thread, and even from an executing
631 callback.
632 */
633
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000634int
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200635_PyEval_AddPendingCall(PyInterpreterState *interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200636 int (*func)(void *), void *arg)
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000637{
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200638 struct _pending_calls *pending = &interp->ceval.pending;
Eric Snow842a2f02019-03-15 15:47:51 -0600639
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200640 /* Ensure that _PyEval_InitPendingCalls() was called
641 and that _PyEval_FiniPendingCalls() is not called yet. */
642 assert(pending->lock != NULL);
643
Eric Snow842a2f02019-03-15 15:47:51 -0600644 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
Victor Stinnere225beb2019-06-03 18:14:24 +0200645 int result = _push_pending_call(pending, func, arg);
Eric Snow842a2f02019-03-15 15:47:51 -0600646 PyThread_release_lock(pending->lock);
Eric Snow5be45a62019-03-08 22:47:07 -0700647
Victor Stinnere225beb2019-06-03 18:14:24 +0200648 /* signal main loop */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200649 SIGNAL_PENDING_CALLS(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 return result;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000651}
652
Victor Stinner09532fe2019-05-10 23:39:09 +0200653int
654Py_AddPendingCall(int (*func)(void *), void *arg)
655{
Victor Stinner50e6e992020-03-19 02:41:21 +0100656 /* Best-effort to support subinterpreters and calls with the GIL released.
657
658 First attempt _PyThreadState_GET() since it supports subinterpreters.
659
660 If the GIL is released, _PyThreadState_GET() returns NULL . In this
661 case, use PyGILState_GetThisThreadState() which works even if the GIL
662 is released.
663
664 Sadly, PyGILState_GetThisThreadState() doesn't support subinterpreters:
665 see bpo-10915 and bpo-15751.
666
Victor Stinner8849e592020-03-18 19:28:53 +0100667 Py_AddPendingCall() doesn't require the caller to hold the GIL. */
Victor Stinner50e6e992020-03-19 02:41:21 +0100668 PyThreadState *tstate = _PyThreadState_GET();
669 if (tstate == NULL) {
670 tstate = PyGILState_GetThisThreadState();
671 }
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200672
673 PyInterpreterState *interp;
674 if (tstate != NULL) {
675 interp = tstate->interp;
676 }
677 else {
678 /* Last resort: use the main interpreter */
679 interp = _PyRuntime.interpreters.main;
680 }
681 return _PyEval_AddPendingCall(interp, func, arg);
Victor Stinner09532fe2019-05-10 23:39:09 +0200682}
683
Eric Snowfdf282d2019-01-11 14:26:55 -0700684static int
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100685handle_signals(PyThreadState *tstate)
Eric Snowfdf282d2019-01-11 14:26:55 -0700686{
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200687 assert(is_tstate_valid(tstate));
688 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Eric Snow64d6cc82019-02-23 15:40:43 -0700689 return 0;
690 }
Eric Snowfdf282d2019-01-11 14:26:55 -0700691
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200692 UNSIGNAL_PENDING_SIGNALS(tstate->interp);
Victor Stinner72818982020-03-26 22:28:11 +0100693 if (_PyErr_CheckSignalsTstate(tstate) < 0) {
694 /* On failure, re-schedule a call to handle_signals(). */
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100695 SIGNAL_PENDING_SIGNALS(tstate->interp, 0);
Eric Snowfdf282d2019-01-11 14:26:55 -0700696 return -1;
697 }
698 return 0;
699}
700
701static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100702make_pending_calls(PyInterpreterState *interp)
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000703{
Victor Stinnerd8316882020-03-20 14:50:35 +0100704 /* only execute pending calls on main thread */
705 if (!_Py_ThreadCanHandlePendingCalls()) {
Victor Stinnere225beb2019-06-03 18:14:24 +0200706 return 0;
707 }
708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 /* don't perform recursive pending calls */
Victor Stinnerda2914d2020-03-20 09:29:08 +0100710 static int busy = 0;
Eric Snowfdf282d2019-01-11 14:26:55 -0700711 if (busy) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return 0;
Eric Snowfdf282d2019-01-11 14:26:55 -0700713 }
Charles-François Natalif23339a2011-07-23 18:15:43 +0200714 busy = 1;
Victor Stinnerda2914d2020-03-20 09:29:08 +0100715
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200716 /* unsignal before starting to call callbacks, so that any callback
717 added in-between re-signals */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100718 UNSIGNAL_PENDING_CALLS(interp);
Eric Snowfdf282d2019-01-11 14:26:55 -0700719 int res = 0;
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 /* perform a bounded number of calls, in case of recursion */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100722 struct _pending_calls *pending = &interp->ceval.pending;
Eric Snowfdf282d2019-01-11 14:26:55 -0700723 for (int i=0; i<NPENDINGCALLS; i++) {
Eric Snow5be45a62019-03-08 22:47:07 -0700724 int (*func)(void *) = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 void *arg = NULL;
726
727 /* pop one item off the queue while holding the lock */
Eric Snow842a2f02019-03-15 15:47:51 -0600728 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
Victor Stinnere225beb2019-06-03 18:14:24 +0200729 _pop_pending_call(pending, &func, &arg);
Eric Snow842a2f02019-03-15 15:47:51 -0600730 PyThread_release_lock(pending->lock);
Eric Snow5be45a62019-03-08 22:47:07 -0700731
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100732 /* having released the lock, perform the callback */
Eric Snow5be45a62019-03-08 22:47:07 -0700733 if (func == NULL) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100734 break;
Eric Snow5be45a62019-03-08 22:47:07 -0700735 }
Eric Snowfdf282d2019-01-11 14:26:55 -0700736 res = func(arg);
737 if (res) {
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200738 goto error;
739 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 }
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200741
Charles-François Natalif23339a2011-07-23 18:15:43 +0200742 busy = 0;
Eric Snowfdf282d2019-01-11 14:26:55 -0700743 return res;
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200744
745error:
746 busy = 0;
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100747 SIGNAL_PENDING_CALLS(interp);
Eric Snowfdf282d2019-01-11 14:26:55 -0700748 return res;
749}
750
Eric Snow842a2f02019-03-15 15:47:51 -0600751void
Victor Stinner2b1df452020-01-13 18:46:59 +0100752_Py_FinishPendingCalls(PyThreadState *tstate)
Eric Snow842a2f02019-03-15 15:47:51 -0600753{
Eric Snow842a2f02019-03-15 15:47:51 -0600754 assert(PyGILState_Check());
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100755 assert(is_tstate_valid(tstate));
Eric Snow842a2f02019-03-15 15:47:51 -0600756
Victor Stinner50e6e992020-03-19 02:41:21 +0100757 struct _pending_calls *pending = &tstate->interp->ceval.pending;
Victor Stinner09532fe2019-05-10 23:39:09 +0200758
Eric Snow842a2f02019-03-15 15:47:51 -0600759 if (!_Py_atomic_load_relaxed(&(pending->calls_to_do))) {
760 return;
761 }
762
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100763 if (make_pending_calls(tstate->interp) < 0) {
Victor Stinnere225beb2019-06-03 18:14:24 +0200764 PyObject *exc, *val, *tb;
765 _PyErr_Fetch(tstate, &exc, &val, &tb);
766 PyErr_BadInternalCall();
767 _PyErr_ChainExceptions(exc, val, tb);
768 _PyErr_Print(tstate);
Eric Snow842a2f02019-03-15 15:47:51 -0600769 }
770}
771
Eric Snowfdf282d2019-01-11 14:26:55 -0700772/* Py_MakePendingCalls() is a simple wrapper for the sake
773 of backward-compatibility. */
774int
775Py_MakePendingCalls(void)
776{
777 assert(PyGILState_Check());
778
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100779 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100780 assert(is_tstate_valid(tstate));
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100781
Eric Snowfdf282d2019-01-11 14:26:55 -0700782 /* Python signal handler doesn't really queue a callback: it only signals
783 that a signal was received, see _PyEval_SignalReceived(). */
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100784 int res = handle_signals(tstate);
Eric Snowfdf282d2019-01-11 14:26:55 -0700785 if (res != 0) {
786 return res;
787 }
788
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100789 res = make_pending_calls(tstate->interp);
Eric Snowb75b1a352019-04-12 10:20:10 -0600790 if (res != 0) {
791 return res;
792 }
793
794 return 0;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000795}
796
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000797/* The interpreter's recursion limit */
798
Hye-Shik Changb6fa2812005-04-04 15:49:02 +0000799#ifndef Py_DEFAULT_RECURSION_LIMIT
Victor Stinner19c3ac92020-09-23 14:04:57 +0200800# define Py_DEFAULT_RECURSION_LIMIT 1000
Hye-Shik Changb6fa2812005-04-04 15:49:02 +0000801#endif
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600802
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600803void
Victor Stinnerdab84232020-03-17 18:56:44 +0100804_PyEval_InitRuntimeState(struct _ceval_runtime_state *ceval)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600805{
Victor Stinner7be4e352020-05-05 20:27:47 +0200806#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinnerdab84232020-03-17 18:56:44 +0100807 _gil_initialize(&ceval->gil);
Victor Stinner7be4e352020-05-05 20:27:47 +0200808#endif
Victor Stinnerdab84232020-03-17 18:56:44 +0100809}
810
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200811int
Victor Stinnerdab84232020-03-17 18:56:44 +0100812_PyEval_InitState(struct _ceval_state *ceval)
813{
Victor Stinner4e30ed32020-05-05 16:52:52 +0200814 ceval->recursion_limit = Py_DEFAULT_RECURSION_LIMIT;
815
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200816 struct _pending_calls *pending = &ceval->pending;
817 assert(pending->lock == NULL);
818
819 pending->lock = PyThread_allocate_lock();
820 if (pending->lock == NULL) {
821 return -1;
822 }
Victor Stinner7be4e352020-05-05 20:27:47 +0200823
824#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
825 _gil_initialize(&ceval->gil);
826#endif
827
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200828 return 0;
829}
830
831void
832_PyEval_FiniState(struct _ceval_state *ceval)
833{
834 struct _pending_calls *pending = &ceval->pending;
835 if (pending->lock != NULL) {
836 PyThread_free_lock(pending->lock);
837 pending->lock = NULL;
838 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600839}
840
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000841int
842Py_GetRecursionLimit(void)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000843{
Victor Stinner1bcc32f2020-06-10 20:08:26 +0200844 PyInterpreterState *interp = _PyInterpreterState_GET();
845 return interp->ceval.recursion_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000846}
847
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000848void
849Py_SetRecursionLimit(int new_limit)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000850{
Victor Stinner4e30ed32020-05-05 16:52:52 +0200851 PyThreadState *tstate = _PyThreadState_GET();
852 tstate->interp->ceval.recursion_limit = new_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000853}
854
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100855/* The function _Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
Victor Stinner19c3ac92020-09-23 14:04:57 +0200856 if the recursion_depth reaches recursion_limit.
857 If USE_STACKCHECK, the macro decrements recursion_limit
Armin Rigo2b3eb402003-10-28 12:05:48 +0000858 to guarantee that _Py_CheckRecursiveCall() is regularly called.
859 Without USE_STACKCHECK, there is no need for this. */
860int
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100861_Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
Armin Rigo2b3eb402003-10-28 12:05:48 +0000862{
Victor Stinner4e30ed32020-05-05 16:52:52 +0200863 int recursion_limit = tstate->interp->ceval.recursion_limit;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000864
865#ifdef USE_STACKCHECK
pdox18967932017-10-25 23:03:01 -0700866 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (PyOS_CheckStack()) {
868 --tstate->recursion_depth;
Victor Stinner438a12d2019-05-24 17:01:38 +0200869 _PyErr_SetString(tstate, PyExc_MemoryError, "Stack overflow");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return -1;
871 }
pdox18967932017-10-25 23:03:01 -0700872#endif
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000873 if (tstate->recursion_headroom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (tstate->recursion_depth > recursion_limit + 50) {
875 /* Overflowing while handling an overflow. Give up. */
876 Py_FatalError("Cannot recover from stack overflow.");
877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 }
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000879 else {
880 if (tstate->recursion_depth > recursion_limit) {
881 tstate->recursion_headroom++;
882 _PyErr_Format(tstate, PyExc_RecursionError,
883 "maximum recursion depth exceeded%s",
884 where);
885 tstate->recursion_headroom--;
886 --tstate->recursion_depth;
887 return -1;
888 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 }
890 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000891}
892
Brandt Bucher145bf262021-02-26 14:51:55 -0800893
894// PEP 634: Structural Pattern Matching
895
896
897// Return a tuple of values corresponding to keys, with error checks for
898// duplicate/missing keys.
899static PyObject*
900match_keys(PyThreadState *tstate, PyObject *map, PyObject *keys)
901{
902 assert(PyTuple_CheckExact(keys));
903 Py_ssize_t nkeys = PyTuple_GET_SIZE(keys);
904 if (!nkeys) {
905 // No keys means no items.
906 return PyTuple_New(0);
907 }
908 PyObject *seen = NULL;
909 PyObject *dummy = NULL;
910 PyObject *values = NULL;
911 // We use the two argument form of map.get(key, default) for two reasons:
912 // - Atomically check for a key and get its value without error handling.
913 // - Don't cause key creation or resizing in dict subclasses like
914 // collections.defaultdict that define __missing__ (or similar).
915 _Py_IDENTIFIER(get);
916 PyObject *get = _PyObject_GetAttrId(map, &PyId_get);
917 if (get == NULL) {
918 goto fail;
919 }
920 seen = PySet_New(NULL);
921 if (seen == NULL) {
922 goto fail;
923 }
924 // dummy = object()
925 dummy = _PyObject_CallNoArg((PyObject *)&PyBaseObject_Type);
926 if (dummy == NULL) {
927 goto fail;
928 }
929 values = PyList_New(0);
930 if (values == NULL) {
931 goto fail;
932 }
933 for (Py_ssize_t i = 0; i < nkeys; i++) {
934 PyObject *key = PyTuple_GET_ITEM(keys, i);
935 if (PySet_Contains(seen, key) || PySet_Add(seen, key)) {
936 if (!_PyErr_Occurred(tstate)) {
937 // Seen it before!
938 _PyErr_Format(tstate, PyExc_ValueError,
939 "mapping pattern checks duplicate key (%R)", key);
940 }
941 goto fail;
942 }
943 PyObject *value = PyObject_CallFunctionObjArgs(get, key, dummy, NULL);
944 if (value == NULL) {
945 goto fail;
946 }
947 if (value == dummy) {
948 // key not in map!
949 Py_DECREF(value);
950 Py_DECREF(values);
951 // Return None:
952 Py_INCREF(Py_None);
953 values = Py_None;
954 goto done;
955 }
956 PyList_Append(values, value);
957 Py_DECREF(value);
958 }
959 Py_SETREF(values, PyList_AsTuple(values));
960 // Success:
961done:
962 Py_DECREF(get);
963 Py_DECREF(seen);
964 Py_DECREF(dummy);
965 return values;
966fail:
967 Py_XDECREF(get);
968 Py_XDECREF(seen);
969 Py_XDECREF(dummy);
970 Py_XDECREF(values);
971 return NULL;
972}
973
974// Extract a named attribute from the subject, with additional bookkeeping to
975// raise TypeErrors for repeated lookups. On failure, return NULL (with no
976// error set). Use _PyErr_Occurred(tstate) to disambiguate.
977static PyObject*
978match_class_attr(PyThreadState *tstate, PyObject *subject, PyObject *type,
979 PyObject *name, PyObject *seen)
980{
981 assert(PyUnicode_CheckExact(name));
982 assert(PySet_CheckExact(seen));
983 if (PySet_Contains(seen, name) || PySet_Add(seen, name)) {
984 if (!_PyErr_Occurred(tstate)) {
985 // Seen it before!
986 _PyErr_Format(tstate, PyExc_TypeError,
987 "%s() got multiple sub-patterns for attribute %R",
988 ((PyTypeObject*)type)->tp_name, name);
989 }
990 return NULL;
991 }
992 PyObject *attr = PyObject_GetAttr(subject, name);
993 if (attr == NULL && _PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
994 _PyErr_Clear(tstate);
995 }
996 return attr;
997}
998
999// On success (match), return a tuple of extracted attributes. On failure (no
1000// match), return NULL. Use _PyErr_Occurred(tstate) to disambiguate.
1001static PyObject*
1002match_class(PyThreadState *tstate, PyObject *subject, PyObject *type,
1003 Py_ssize_t nargs, PyObject *kwargs)
1004{
1005 if (!PyType_Check(type)) {
1006 const char *e = "called match pattern must be a type";
1007 _PyErr_Format(tstate, PyExc_TypeError, e);
1008 return NULL;
1009 }
1010 assert(PyTuple_CheckExact(kwargs));
1011 // First, an isinstance check:
1012 if (PyObject_IsInstance(subject, type) <= 0) {
1013 return NULL;
1014 }
1015 // So far so good:
1016 PyObject *seen = PySet_New(NULL);
1017 if (seen == NULL) {
1018 return NULL;
1019 }
1020 PyObject *attrs = PyList_New(0);
1021 if (attrs == NULL) {
1022 Py_DECREF(seen);
1023 return NULL;
1024 }
1025 // NOTE: From this point on, goto fail on failure:
1026 PyObject *match_args = NULL;
1027 // First, the positional subpatterns:
1028 if (nargs) {
1029 int match_self = 0;
1030 match_args = PyObject_GetAttrString(type, "__match_args__");
1031 if (match_args) {
Brandt Bucher145bf262021-02-26 14:51:55 -08001032 if (!PyTuple_CheckExact(match_args)) {
Brandt Bucherf84d5a12021-04-05 19:17:08 -07001033 const char *e = "%s.__match_args__ must be a tuple (got %s)";
Brandt Bucher145bf262021-02-26 14:51:55 -08001034 _PyErr_Format(tstate, PyExc_TypeError, e,
1035 ((PyTypeObject *)type)->tp_name,
1036 Py_TYPE(match_args)->tp_name);
1037 goto fail;
1038 }
1039 }
1040 else if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
1041 _PyErr_Clear(tstate);
1042 // _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
1043 // define __match_args__. This is natural behavior for subclasses:
1044 // it's as if __match_args__ is some "magic" value that is lost as
1045 // soon as they redefine it.
1046 match_args = PyTuple_New(0);
1047 match_self = PyType_HasFeature((PyTypeObject*)type,
1048 _Py_TPFLAGS_MATCH_SELF);
1049 }
1050 else {
1051 goto fail;
1052 }
1053 assert(PyTuple_CheckExact(match_args));
1054 Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
1055 if (allowed < nargs) {
1056 const char *plural = (allowed == 1) ? "" : "s";
1057 _PyErr_Format(tstate, PyExc_TypeError,
1058 "%s() accepts %d positional sub-pattern%s (%d given)",
1059 ((PyTypeObject*)type)->tp_name,
1060 allowed, plural, nargs);
1061 goto fail;
1062 }
1063 if (match_self) {
1064 // Easy. Copy the subject itself, and move on to kwargs.
1065 PyList_Append(attrs, subject);
1066 }
1067 else {
1068 for (Py_ssize_t i = 0; i < nargs; i++) {
1069 PyObject *name = PyTuple_GET_ITEM(match_args, i);
1070 if (!PyUnicode_CheckExact(name)) {
1071 _PyErr_Format(tstate, PyExc_TypeError,
1072 "__match_args__ elements must be strings "
1073 "(got %s)", Py_TYPE(name)->tp_name);
1074 goto fail;
1075 }
1076 PyObject *attr = match_class_attr(tstate, subject, type, name,
1077 seen);
1078 if (attr == NULL) {
1079 goto fail;
1080 }
1081 PyList_Append(attrs, attr);
1082 Py_DECREF(attr);
1083 }
1084 }
1085 Py_CLEAR(match_args);
1086 }
1087 // Finally, the keyword subpatterns:
1088 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
1089 PyObject *name = PyTuple_GET_ITEM(kwargs, i);
1090 PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
1091 if (attr == NULL) {
1092 goto fail;
1093 }
1094 PyList_Append(attrs, attr);
1095 Py_DECREF(attr);
1096 }
1097 Py_SETREF(attrs, PyList_AsTuple(attrs));
1098 Py_DECREF(seen);
1099 return attrs;
1100fail:
1101 // We really don't care whether an error was raised or not... that's our
1102 // caller's problem. All we know is that the match failed.
1103 Py_XDECREF(match_args);
1104 Py_DECREF(seen);
1105 Py_DECREF(attrs);
1106 return NULL;
1107}
1108
1109
Victor Stinner09532fe2019-05-10 23:39:09 +02001110static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
Victor Stinner438a12d2019-05-24 17:01:38 +02001111static int unpack_iterable(PyThreadState *, PyObject *, int, int, PyObject **);
Guido van Rossum1aa14831997-01-21 05:34:20 +00001112
Victor Stinnere225beb2019-06-03 18:14:24 +02001113#define _Py_TracingPossible(ceval) ((ceval)->tracing_possible)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001114
Guido van Rossum374a9221991-04-04 10:40:29 +00001115
Guido van Rossumb209a111997-04-29 18:18:01 +00001116PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001117PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001118{
Victor Stinner46496f92021-02-20 15:17:18 +01001119 PyThreadState *tstate = PyThreadState_GET();
Mark Shannon0332e562021-02-01 10:42:03 +00001120 if (locals == NULL) {
1121 locals = globals;
1122 }
Victor Stinnerfc980e02021-03-18 14:51:24 +01001123 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Mark Shannon0332e562021-02-01 10:42:03 +00001124 if (builtins == NULL) {
1125 return NULL;
1126 }
1127 PyFrameConstructor desc = {
1128 .fc_globals = globals,
1129 .fc_builtins = builtins,
1130 .fc_name = ((PyCodeObject *)co)->co_name,
1131 .fc_qualname = ((PyCodeObject *)co)->co_name,
1132 .fc_code = co,
1133 .fc_defaults = NULL,
1134 .fc_kwdefaults = NULL,
1135 .fc_closure = NULL
1136 };
Victor Stinner46496f92021-02-20 15:17:18 +01001137 return _PyEval_Vector(tstate, &desc, locals, NULL, 0, NULL);
Guido van Rossum681d79a1995-07-18 14:51:37 +00001138}
1139
1140
1141/* Interpreter main loop */
1142
Martin v. Löwis8d97e332004-06-27 15:43:12 +00001143PyObject *
Victor Stinnerb9e68122019-11-14 12:20:46 +01001144PyEval_EvalFrame(PyFrameObject *f)
1145{
Victor Stinner0b72b232020-03-12 23:18:39 +01001146 /* Function kept for backward compatibility */
Victor Stinnerb9e68122019-11-14 12:20:46 +01001147 PyThreadState *tstate = _PyThreadState_GET();
1148 return _PyEval_EvalFrame(tstate, f, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001149}
1150
1151PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001152PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Guido van Rossum374a9221991-04-04 10:40:29 +00001153{
Victor Stinnerb9e68122019-11-14 12:20:46 +01001154 PyThreadState *tstate = _PyThreadState_GET();
1155 return _PyEval_EvalFrame(tstate, f, throwflag);
Brett Cannon3cebf932016-09-05 15:33:46 -07001156}
1157
Victor Stinnerda2914d2020-03-20 09:29:08 +01001158
1159/* Handle signals, pending calls, GIL drop request
1160 and asynchronous exception */
1161static int
1162eval_frame_handle_pending(PyThreadState *tstate)
1163{
Victor Stinnerda2914d2020-03-20 09:29:08 +01001164 _PyRuntimeState * const runtime = &_PyRuntime;
1165 struct _ceval_runtime_state *ceval = &runtime->ceval;
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001166
1167 /* Pending signals */
Victor Stinner299b8c62020-05-05 17:40:18 +02001168 if (_Py_atomic_load_relaxed(&ceval->signals_pending)) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001169 if (handle_signals(tstate) != 0) {
1170 return -1;
1171 }
1172 }
1173
1174 /* Pending calls */
Victor Stinner299b8c62020-05-05 17:40:18 +02001175 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinnerda2914d2020-03-20 09:29:08 +01001176 if (_Py_atomic_load_relaxed(&ceval2->pending.calls_to_do)) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001177 if (make_pending_calls(tstate->interp) != 0) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001178 return -1;
1179 }
1180 }
1181
1182 /* GIL drop request */
Victor Stinner0b1e3302020-05-05 16:14:31 +02001183 if (_Py_atomic_load_relaxed(&ceval2->gil_drop_request)) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001184 /* Give another thread a chance */
1185 if (_PyThreadState_Swap(&runtime->gilstate, NULL) != tstate) {
1186 Py_FatalError("tstate mix-up");
1187 }
Victor Stinner0b1e3302020-05-05 16:14:31 +02001188 drop_gil(ceval, ceval2, tstate);
Victor Stinnerda2914d2020-03-20 09:29:08 +01001189
1190 /* Other threads may run now */
1191
1192 take_gil(tstate);
1193
Victor Stinnere838a932020-05-05 19:56:48 +02001194#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1195 (void)_PyThreadState_Swap(&runtime->gilstate, tstate);
1196#else
Victor Stinnerda2914d2020-03-20 09:29:08 +01001197 if (_PyThreadState_Swap(&runtime->gilstate, tstate) != NULL) {
1198 Py_FatalError("orphan tstate");
1199 }
Victor Stinnere838a932020-05-05 19:56:48 +02001200#endif
Victor Stinnerda2914d2020-03-20 09:29:08 +01001201 }
1202
1203 /* Check for asynchronous exception. */
1204 if (tstate->async_exc != NULL) {
1205 PyObject *exc = tstate->async_exc;
1206 tstate->async_exc = NULL;
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001207 UNSIGNAL_ASYNC_EXC(tstate->interp);
Victor Stinnerda2914d2020-03-20 09:29:08 +01001208 _PyErr_SetNone(tstate, exc);
1209 Py_DECREF(exc);
1210 return -1;
1211 }
1212
Victor Stinnerd96a7a82020-11-13 14:44:42 +01001213#ifdef MS_WINDOWS
1214 // bpo-42296: On Windows, _PyEval_SignalReceived() can be called in a
1215 // different thread than the Python thread, in which case
1216 // _Py_ThreadCanHandleSignals() is wrong. Recompute eval_breaker in the
1217 // current Python thread with the correct _Py_ThreadCanHandleSignals()
1218 // value. It prevents to interrupt the eval loop at every instruction if
1219 // the current Python thread cannot handle signals (if
1220 // _Py_ThreadCanHandleSignals() is false).
1221 COMPUTE_EVAL_BREAKER(tstate->interp, ceval, ceval2);
1222#endif
1223
Victor Stinnerda2914d2020-03-20 09:29:08 +01001224 return 0;
1225}
1226
Victor Stinner3c1e4812012-03-26 22:10:51 +02001227
Antoine Pitroub52ec782009-01-25 16:34:23 +00001228/* Computed GOTOs, or
1229 the-optimization-commonly-but-improperly-known-as-"threaded code"
1230 using gcc's labels-as-values extension
1231 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
1232
1233 The traditional bytecode evaluation loop uses a "switch" statement, which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 decent compilers will optimize as a single indirect branch instruction
Antoine Pitroub52ec782009-01-25 16:34:23 +00001235 combined with a lookup table of jump addresses. However, since the
1236 indirect jump instruction is shared by all opcodes, the CPU will have a
1237 hard time making the right prediction for where to jump next (actually,
1238 it will be always wrong except in the uncommon case of a sequence of
1239 several identical opcodes).
1240
1241 "Threaded code" in contrast, uses an explicit jump table and an explicit
1242 indirect jump instruction at the end of each opcode. Since the jump
1243 instruction is at a different address for each opcode, the CPU will make a
1244 separate prediction for each of these instructions, which is equivalent to
1245 predicting the second opcode of each opcode pair. These predictions have
1246 a much better chance to turn out valid, especially in small bytecode loops.
1247
1248 A mispredicted branch on a modern CPU flushes the whole pipeline and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 can cost several CPU cycles (depending on the pipeline depth),
Antoine Pitroub52ec782009-01-25 16:34:23 +00001250 and potentially many more instructions (depending on the pipeline width).
1251 A correctly predicted branch, however, is nearly free.
1252
1253 At the time of this writing, the "threaded code" version is up to 15-20%
1254 faster than the normal "switch" version, depending on the compiler and the
1255 CPU architecture.
1256
1257 We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined,
1258 because it would render the measurements invalid.
1259
1260
1261 NOTE: care must be taken that the compiler doesn't try to "optimize" the
1262 indirect jumps by sharing them between all opcodes. Such optimizations
1263 can be disabled on gcc by using the -fno-gcse flag (or possibly
1264 -fno-crossjumping).
1265*/
1266
Mark Shannon28d28e02021-04-08 11:22:55 +01001267/* Use macros rather than inline functions, to make it as clear as possible
1268 * to the C compiler that the tracing check is a simple test then branch.
1269 * We want to be sure that the compiler knows this before it generates
1270 * the CFG.
1271 */
1272#ifdef LLTRACE
1273#define OR_LLTRACE || lltrace
1274#else
1275#define OR_LLTRACE
1276#endif
1277
1278#ifdef WITH_DTRACE
1279#define OR_DTRACE_LINE || PyDTrace_LINE_ENABLED()
1280#else
1281#define OR_DTRACE_LINE
1282#endif
1283
Antoine Pitrou042b1282010-08-13 21:15:58 +00001284#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitroub52ec782009-01-25 16:34:23 +00001285#undef USE_COMPUTED_GOTOS
Antoine Pitrou042b1282010-08-13 21:15:58 +00001286#define USE_COMPUTED_GOTOS 0
Antoine Pitroub52ec782009-01-25 16:34:23 +00001287#endif
1288
Antoine Pitrou042b1282010-08-13 21:15:58 +00001289#ifdef HAVE_COMPUTED_GOTOS
1290 #ifndef USE_COMPUTED_GOTOS
1291 #define USE_COMPUTED_GOTOS 1
1292 #endif
1293#else
1294 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
1295 #error "Computed gotos are not supported on this compiler."
1296 #endif
1297 #undef USE_COMPUTED_GOTOS
1298 #define USE_COMPUTED_GOTOS 0
1299#endif
1300
1301#if USE_COMPUTED_GOTOS
Mark Shannon28d28e02021-04-08 11:22:55 +01001302#define TARGET(op) op: TARGET_##op
1303#define DISPATCH_GOTO() goto *opcode_targets[opcode]
Antoine Pitroub52ec782009-01-25 16:34:23 +00001304#else
Benjamin Petersonddd19492018-09-16 22:38:02 -07001305#define TARGET(op) op
Mark Shannon28d28e02021-04-08 11:22:55 +01001306#define DISPATCH_GOTO() goto dispatch_opcode
Antoine Pitroub52ec782009-01-25 16:34:23 +00001307#endif
1308
Mark Shannon28d28e02021-04-08 11:22:55 +01001309#define DISPATCH() \
1310 { \
1311 if (_Py_TracingPossible(ceval2) OR_DTRACE_LINE OR_LLTRACE) { \
1312 goto tracing_dispatch; \
1313 } \
1314 f->f_lasti = INSTR_OFFSET(); \
1315 NEXTOPARG(); \
1316 DISPATCH_GOTO(); \
1317 }
1318
Mark Shannon4958f5d2021-03-24 17:56:12 +00001319#define CHECK_EVAL_BREAKER() \
1320 if (_Py_atomic_load_relaxed(eval_breaker)) { \
1321 continue; \
1322 }
1323
Antoine Pitroub52ec782009-01-25 16:34:23 +00001324
Neal Norwitza81d2202002-07-14 00:27:26 +00001325/* Tuple access macros */
1326
1327#ifndef Py_DEBUG
1328#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
1329#else
1330#define GETITEM(v, i) PyTuple_GetItem((v), (i))
1331#endif
1332
Guido van Rossum374a9221991-04-04 10:40:29 +00001333/* Code access macros */
1334
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001335/* The integer overflow is checked by an assertion below. */
Mark Shannonfcb55c02021-04-01 16:00:31 +01001336#define INSTR_OFFSET() ((int)(next_instr - first_instr))
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001337#define NEXTOPARG() do { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001338 _Py_CODEUNIT word = *next_instr; \
1339 opcode = _Py_OPCODE(word); \
1340 oparg = _Py_OPARG(word); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001341 next_instr++; \
1342 } while (0)
Mark Shannonfcb55c02021-04-01 16:00:31 +01001343#define JUMPTO(x) (next_instr = first_instr + (x))
1344#define JUMPBY(x) (next_instr += (x))
Guido van Rossum374a9221991-04-04 10:40:29 +00001345
Raymond Hettingerf606f872003-03-16 03:11:04 +00001346/* OpCode prediction macros
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 Some opcodes tend to come in pairs thus making it possible to
1348 predict the second code when the first is run. For example,
Serhiy Storchakada9c5132016-06-27 18:58:57 +03001349 COMPARE_OP is often followed by POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 Verifying the prediction costs a single high-speed test of a register
1352 variable against a constant. If the pairing was good, then the
1353 processor's own internal branch predication has a high likelihood of
1354 success, resulting in a nearly zero-overhead transition to the
1355 next opcode. A successful prediction saves a trip through the eval-loop
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001356 including its unpredictable switch-case branch. Combined with the
1357 processor's internal branch prediction, a successful PREDICT has the
1358 effect of making the two opcodes run as if they were a single new opcode
1359 with the bodies combined.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001360
Georg Brandl86b2fb92008-07-16 03:43:04 +00001361 If collecting opcode statistics, your choices are to either keep the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 predictions turned-on and interpret the results as if some opcodes
1363 had been combined or turn-off predictions so that the opcode frequency
1364 counter updates for both opcodes.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001365
1366 Opcode prediction is disabled with threaded code, since the latter allows
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 the CPU to record separate branch prediction information for each
1368 opcode.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001369
Raymond Hettingerf606f872003-03-16 03:11:04 +00001370*/
1371
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001372#define PREDICT_ID(op) PRED_##op
1373
Antoine Pitrou042b1282010-08-13 21:15:58 +00001374#if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001375#define PREDICT(op) if (0) goto PREDICT_ID(op)
Raymond Hettingera7216982004-02-08 19:59:27 +00001376#else
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001377#define PREDICT(op) \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001378 do { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001379 _Py_CODEUNIT word = *next_instr; \
1380 opcode = _Py_OPCODE(word); \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001381 if (opcode == op) { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001382 oparg = _Py_OPARG(word); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001383 next_instr++; \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001384 goto PREDICT_ID(op); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001385 } \
1386 } while(0)
Antoine Pitroub52ec782009-01-25 16:34:23 +00001387#endif
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001388#define PREDICTED(op) PREDICT_ID(op):
Antoine Pitroub52ec782009-01-25 16:34:23 +00001389
Raymond Hettingerf606f872003-03-16 03:11:04 +00001390
Guido van Rossum374a9221991-04-04 10:40:29 +00001391/* Stack manipulation macros */
1392
Martin v. Löwis18e16552006-02-15 17:27:45 +00001393/* The stack can grow at most MAXINT deep, as co_nlocals and
1394 co_stacksize are ints. */
Stefan Krahb7e10102010-06-23 18:42:39 +00001395#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
1396#define EMPTY() (STACK_LEVEL() == 0)
1397#define TOP() (stack_pointer[-1])
1398#define SECOND() (stack_pointer[-2])
1399#define THIRD() (stack_pointer[-3])
1400#define FOURTH() (stack_pointer[-4])
1401#define PEEK(n) (stack_pointer[-(n)])
1402#define SET_TOP(v) (stack_pointer[-1] = (v))
1403#define SET_SECOND(v) (stack_pointer[-2] = (v))
1404#define SET_THIRD(v) (stack_pointer[-3] = (v))
1405#define SET_FOURTH(v) (stack_pointer[-4] = (v))
Stefan Krahb7e10102010-06-23 18:42:39 +00001406#define BASIC_STACKADJ(n) (stack_pointer += n)
1407#define BASIC_PUSH(v) (*stack_pointer++ = (v))
1408#define BASIC_POP() (*--stack_pointer)
Guido van Rossum374a9221991-04-04 10:40:29 +00001409
Guido van Rossum96a42c81992-01-12 02:29:51 +00001410#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411#define PUSH(v) { (void)(BASIC_PUSH(v), \
Victor Stinner438a12d2019-05-24 17:01:38 +02001412 lltrace && prtrace(tstate, TOP(), "push")); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001413 assert(STACK_LEVEL() <= co->co_stacksize); }
Victor Stinner438a12d2019-05-24 17:01:38 +02001414#define POP() ((void)(lltrace && prtrace(tstate, TOP(), "pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001415 BASIC_POP())
costypetrisor8ed317f2018-07-31 20:55:14 +00001416#define STACK_GROW(n) do { \
1417 assert(n >= 0); \
1418 (void)(BASIC_STACKADJ(n), \
Victor Stinner438a12d2019-05-24 17:01:38 +02001419 lltrace && prtrace(tstate, TOP(), "stackadj")); \
costypetrisor8ed317f2018-07-31 20:55:14 +00001420 assert(STACK_LEVEL() <= co->co_stacksize); \
1421 } while (0)
1422#define STACK_SHRINK(n) do { \
1423 assert(n >= 0); \
Victor Stinner438a12d2019-05-24 17:01:38 +02001424 (void)(lltrace && prtrace(tstate, TOP(), "stackadj")); \
costypetrisor8ed317f2018-07-31 20:55:14 +00001425 (void)(BASIC_STACKADJ(-n)); \
1426 assert(STACK_LEVEL() <= co->co_stacksize); \
1427 } while (0)
Christian Heimes0449f632007-12-15 01:27:15 +00001428#define EXT_POP(STACK_POINTER) ((void)(lltrace && \
Victor Stinner438a12d2019-05-24 17:01:38 +02001429 prtrace(tstate, (STACK_POINTER)[-1], "ext_pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001430 *--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001431#else
Stefan Krahb7e10102010-06-23 18:42:39 +00001432#define PUSH(v) BASIC_PUSH(v)
1433#define POP() BASIC_POP()
costypetrisor8ed317f2018-07-31 20:55:14 +00001434#define STACK_GROW(n) BASIC_STACKADJ(n)
1435#define STACK_SHRINK(n) BASIC_STACKADJ(-n)
Guido van Rossumc2e20742006-02-27 22:32:47 +00001436#define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001437#endif
1438
Guido van Rossum681d79a1995-07-18 14:51:37 +00001439/* Local variable macros */
1440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441#define GETLOCAL(i) (fastlocals[i])
Guido van Rossumcfbf1a32002-03-28 20:17:52 +00001442
1443/* The SETLOCAL() macro must not DECREF the local variable in-place and
1444 then store the new value; it must copy the old value to a temporary
1445 value, then store the new value, and then DECREF the temporary value.
1446 This is because it is possible that during the DECREF the frame is
1447 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1448 variable would be pointing to already-freed memory. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001450 GETLOCAL(i) = value; \
1451 Py_XDECREF(tmp); } while (0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001452
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001453
1454#define UNWIND_BLOCK(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 while (STACK_LEVEL() > (b)->b_level) { \
1456 PyObject *v = POP(); \
1457 Py_XDECREF(v); \
1458 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001459
1460#define UNWIND_EXCEPT_HANDLER(b) \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001461 do { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 PyObject *type, *value, *traceback; \
Mark Shannonae3087c2017-10-22 22:41:51 +01001463 _PyErr_StackItem *exc_info; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 assert(STACK_LEVEL() >= (b)->b_level + 3); \
1465 while (STACK_LEVEL() > (b)->b_level + 3) { \
1466 value = POP(); \
1467 Py_XDECREF(value); \
1468 } \
Mark Shannonae3087c2017-10-22 22:41:51 +01001469 exc_info = tstate->exc_info; \
1470 type = exc_info->exc_type; \
1471 value = exc_info->exc_value; \
1472 traceback = exc_info->exc_traceback; \
1473 exc_info->exc_type = POP(); \
1474 exc_info->exc_value = POP(); \
1475 exc_info->exc_traceback = POP(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 Py_XDECREF(type); \
1477 Py_XDECREF(value); \
1478 Py_XDECREF(traceback); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001479 } while(0)
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001480
Inada Naoki91234a12019-06-03 21:30:58 +09001481 /* macros for opcode cache */
1482#define OPCACHE_CHECK() \
1483 do { \
1484 co_opcache = NULL; \
1485 if (co->co_opcache != NULL) { \
Pablo Galindo109826c2020-10-20 06:22:44 +01001486 unsigned char co_opcache_offset = \
Inada Naoki91234a12019-06-03 21:30:58 +09001487 co->co_opcache_map[next_instr - first_instr]; \
Pablo Galindo109826c2020-10-20 06:22:44 +01001488 if (co_opcache_offset > 0) { \
1489 assert(co_opcache_offset <= co->co_opcache_size); \
1490 co_opcache = &co->co_opcache[co_opcache_offset - 1]; \
Inada Naoki91234a12019-06-03 21:30:58 +09001491 assert(co_opcache != NULL); \
Inada Naoki91234a12019-06-03 21:30:58 +09001492 } \
1493 } \
1494 } while (0)
1495
Pablo Galindo109826c2020-10-20 06:22:44 +01001496#define OPCACHE_DEOPT() \
1497 do { \
1498 if (co_opcache != NULL) { \
1499 co_opcache->optimized = -1; \
1500 unsigned char co_opcache_offset = \
1501 co->co_opcache_map[next_instr - first_instr]; \
1502 assert(co_opcache_offset <= co->co_opcache_size); \
1503 co->co_opcache_map[co_opcache_offset] = 0; \
1504 co_opcache = NULL; \
1505 } \
1506 } while (0)
1507
1508#define OPCACHE_DEOPT_LOAD_ATTR() \
1509 do { \
1510 if (co_opcache != NULL) { \
1511 OPCACHE_STAT_ATTR_DEOPT(); \
1512 OPCACHE_DEOPT(); \
1513 } \
1514 } while (0)
1515
1516#define OPCACHE_MAYBE_DEOPT_LOAD_ATTR() \
1517 do { \
1518 if (co_opcache != NULL && --co_opcache->optimized <= 0) { \
1519 OPCACHE_DEOPT_LOAD_ATTR(); \
1520 } \
1521 } while (0)
1522
Inada Naoki91234a12019-06-03 21:30:58 +09001523#if OPCACHE_STATS
1524
1525#define OPCACHE_STAT_GLOBAL_HIT() \
1526 do { \
1527 if (co->co_opcache != NULL) opcache_global_hits++; \
1528 } while (0)
1529
1530#define OPCACHE_STAT_GLOBAL_MISS() \
1531 do { \
1532 if (co->co_opcache != NULL) opcache_global_misses++; \
1533 } while (0)
1534
1535#define OPCACHE_STAT_GLOBAL_OPT() \
1536 do { \
1537 if (co->co_opcache != NULL) opcache_global_opts++; \
1538 } while (0)
1539
Pablo Galindo109826c2020-10-20 06:22:44 +01001540#define OPCACHE_STAT_ATTR_HIT() \
1541 do { \
1542 if (co->co_opcache != NULL) opcache_attr_hits++; \
1543 } while (0)
1544
1545#define OPCACHE_STAT_ATTR_MISS() \
1546 do { \
1547 if (co->co_opcache != NULL) opcache_attr_misses++; \
1548 } while (0)
1549
1550#define OPCACHE_STAT_ATTR_OPT() \
1551 do { \
1552 if (co->co_opcache!= NULL) opcache_attr_opts++; \
1553 } while (0)
1554
1555#define OPCACHE_STAT_ATTR_DEOPT() \
1556 do { \
1557 if (co->co_opcache != NULL) opcache_attr_deopts++; \
1558 } while (0)
1559
1560#define OPCACHE_STAT_ATTR_TOTAL() \
1561 do { \
1562 if (co->co_opcache != NULL) opcache_attr_total++; \
1563 } while (0)
1564
Inada Naoki91234a12019-06-03 21:30:58 +09001565#else /* OPCACHE_STATS */
1566
1567#define OPCACHE_STAT_GLOBAL_HIT()
1568#define OPCACHE_STAT_GLOBAL_MISS()
1569#define OPCACHE_STAT_GLOBAL_OPT()
1570
Pablo Galindo109826c2020-10-20 06:22:44 +01001571#define OPCACHE_STAT_ATTR_HIT()
1572#define OPCACHE_STAT_ATTR_MISS()
1573#define OPCACHE_STAT_ATTR_OPT()
1574#define OPCACHE_STAT_ATTR_DEOPT()
1575#define OPCACHE_STAT_ATTR_TOTAL()
1576
Inada Naoki91234a12019-06-03 21:30:58 +09001577#endif
1578
Mark Shannond41bddd2021-03-25 12:00:30 +00001579
1580PyObject* _Py_HOT_FUNCTION
1581_PyEval_EvalFrameDefault(PyThreadState *tstate, PyFrameObject *f, int throwflag)
1582{
1583 _Py_EnsureTstateNotNULL(tstate);
1584
1585#if USE_COMPUTED_GOTOS
1586/* Import the static jump table */
1587#include "opcode_targets.h"
1588#endif
1589
1590#ifdef DXPAIRS
1591 int lastopcode = 0;
1592#endif
1593 PyObject **stack_pointer; /* Next free slot in value stack */
1594 const _Py_CODEUNIT *next_instr;
1595 int opcode; /* Current opcode */
1596 int oparg; /* Current opcode argument, if any */
1597 PyObject **fastlocals, **freevars;
1598 PyObject *retval = NULL; /* Return value */
1599 struct _ceval_state * const ceval2 = &tstate->interp->ceval;
1600 _Py_atomic_int * const eval_breaker = &ceval2->eval_breaker;
1601 PyCodeObject *co;
1602
Mark Shannond41bddd2021-03-25 12:00:30 +00001603 const _Py_CODEUNIT *first_instr;
1604 PyObject *names;
1605 PyObject *consts;
1606 _PyOpcache *co_opcache;
1607
1608#ifdef LLTRACE
1609 _Py_IDENTIFIER(__ltrace__);
1610#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +00001611
Victor Stinnerbe434dc2019-11-05 00:51:22 +01001612 if (_Py_EnterRecursiveCall(tstate, "")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01001614 }
Guido van Rossum8861b741996-07-30 16:49:37 +00001615
Mark Shannon8e1b4062021-03-05 14:45:50 +00001616 PyTraceInfo trace_info;
Mark Shannon28d28e02021-04-08 11:22:55 +01001617 /* Mark trace_info as uninitialized */
Mark Shannon8e1b4062021-03-05 14:45:50 +00001618 trace_info.code = NULL;
1619
1620 /* push frame */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 tstate->frame = f;
Mark Shannon86433452021-01-07 16:49:02 +00001622 co = f->f_code;
Tim Peters5ca576e2001-06-18 22:08:13 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (tstate->use_tracing) {
1625 if (tstate->c_tracefunc != NULL) {
1626 /* tstate->c_tracefunc, if defined, is a
1627 function that will be called on *every* entry
1628 to a code block. Its return value, if not
1629 None, is a function that will be called at
1630 the start of each executed line of code.
1631 (Actually, the function must return itself
1632 in order to continue tracing.) The trace
1633 functions are called with three arguments:
1634 a pointer to the current frame, a string
1635 indicating why the function is called, and
1636 an argument which depends on the situation.
1637 The global trace function is also called
1638 whenever an exception is detected. */
1639 if (call_trace_protected(tstate->c_tracefunc,
1640 tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001641 tstate, f, &trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00001642 PyTrace_CALL, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* Trace function raised an error */
1644 goto exit_eval_frame;
1645 }
1646 }
1647 if (tstate->c_profilefunc != NULL) {
1648 /* Similar for c_profilefunc, except it needn't
1649 return itself and isn't called for "line" events */
1650 if (call_trace_protected(tstate->c_profilefunc,
1651 tstate->c_profileobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001652 tstate, f, &trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00001653 PyTrace_CALL, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* Profile function raised an error */
1655 goto exit_eval_frame;
1656 }
1657 }
1658 }
Neil Schemenauer6c0f2002001-09-04 19:03:35 +00001659
Łukasz Langaa785c872016-09-09 17:37:37 -07001660 if (PyDTrace_FUNCTION_ENTRY_ENABLED())
1661 dtrace_function_entry(f);
1662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 names = co->co_names;
1664 consts = co->co_consts;
1665 fastlocals = f->f_localsplus;
1666 freevars = f->f_localsplus + co->co_nlocals;
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001667 assert(PyBytes_Check(co->co_code));
1668 assert(PyBytes_GET_SIZE(co->co_code) <= INT_MAX);
Serhiy Storchakaab874002016-09-11 13:48:15 +03001669 assert(PyBytes_GET_SIZE(co->co_code) % sizeof(_Py_CODEUNIT) == 0);
1670 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(co->co_code), sizeof(_Py_CODEUNIT)));
1671 first_instr = (_Py_CODEUNIT *) PyBytes_AS_STRING(co->co_code);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001672 /*
1673 f->f_lasti refers to the index of the last instruction,
1674 unless it's -1 in which case next_instr should be first_instr.
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001675
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001676 YIELD_FROM sets f_lasti to itself, in order to repeatedly yield
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05001677 multiple values.
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 When the PREDICT() macros are enabled, some opcode pairs follow in
1680 direct succession without updating f->f_lasti. A successful
1681 prediction effectively links the two codes together as if they
1682 were a single new opcode; accordingly,f->f_lasti will point to
1683 the first code in the pair (for instance, GET_ITER followed by
1684 FOR_ITER is effectively a single opcode and f->f_lasti will point
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001685 to the beginning of the combined pair.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 */
Serhiy Storchakaab874002016-09-11 13:48:15 +03001687 assert(f->f_lasti >= -1);
Mark Shannonfcb55c02021-04-01 16:00:31 +01001688 next_instr = first_instr + f->f_lasti + 1;
Mark Shannoncb9879b2020-07-17 11:44:23 +01001689 stack_pointer = f->f_valuestack + f->f_stackdepth;
1690 /* Set f->f_stackdepth to -1.
1691 * Update when returning or calling trace function.
1692 Having f_stackdepth <= 0 ensures that invalid
1693 values are not visible to the cycle GC.
1694 We choose -1 rather than 0 to assist debugging.
1695 */
1696 f->f_stackdepth = -1;
1697 f->f_state = FRAME_EXECUTING;
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001698
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001699 if (co->co_opcache_flag < opcache_min_runs) {
Inada Naoki91234a12019-06-03 21:30:58 +09001700 co->co_opcache_flag++;
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001701 if (co->co_opcache_flag == opcache_min_runs) {
Inada Naoki91234a12019-06-03 21:30:58 +09001702 if (_PyCode_InitOpcache(co) < 0) {
Victor Stinner25104942020-04-24 02:43:18 +02001703 goto exit_eval_frame;
Inada Naoki91234a12019-06-03 21:30:58 +09001704 }
1705#if OPCACHE_STATS
1706 opcache_code_objects_extra_mem +=
1707 PyBytes_Size(co->co_code) / sizeof(_Py_CODEUNIT) +
1708 sizeof(_PyOpcache) * co->co_opcache_size;
1709 opcache_code_objects++;
1710#endif
1711 }
1712 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001713
Tim Peters5ca576e2001-06-18 22:08:13 +00001714#ifdef LLTRACE
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001715 {
1716 int r = _PyDict_ContainsId(f->f_globals, &PyId___ltrace__);
1717 if (r < 0) {
1718 goto exit_eval_frame;
1719 }
1720 lltrace = r;
1721 }
Tim Peters5ca576e2001-06-18 22:08:13 +00001722#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00001723
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001724 if (throwflag) { /* support for generator.throw() */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001725 goto error;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001726 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001727
Victor Stinnerace47d72013-07-18 01:41:08 +02001728#ifdef Py_DEBUG
Victor Stinner0b72b232020-03-12 23:18:39 +01001729 /* _PyEval_EvalFrameDefault() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +01001730 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +00001731 caller loses its exception */
Victor Stinner438a12d2019-05-24 17:01:38 +02001732 assert(!_PyErr_Occurred(tstate));
Victor Stinnerace47d72013-07-18 01:41:08 +02001733#endif
1734
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001735main_loop:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 for (;;) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1738 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
Victor Stinner438a12d2019-05-24 17:01:38 +02001739 assert(!_PyErr_Occurred(tstate));
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 /* Do periodic things. Doing this every time through
1742 the loop would add too much overhead, so we do it
1743 only every Nth instruction. We also do it if
Chris Jerdonek4a12d122020-05-14 19:25:45 -07001744 ``pending.calls_to_do'' is set, i.e. when an asynchronous
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 event needs attention (e.g. a signal handler or
1746 async I/O handler); see Py_AddPendingCall() and
1747 Py_MakePendingCalls() above. */
Guido van Rossumac7be682001-01-17 15:42:30 +00001748
Eric Snow7bda9de2019-03-08 17:25:54 -07001749 if (_Py_atomic_load_relaxed(eval_breaker)) {
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001750 opcode = _Py_OPCODE(*next_instr);
Mark Shannon28d28e02021-04-08 11:22:55 +01001751 if (opcode != SETUP_FINALLY &&
1752 opcode != SETUP_WITH &&
1753 opcode != BEFORE_ASYNC_WITH &&
1754 opcode != YIELD_FROM) {
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001755 /* Few cases where we skip running signal handlers and other
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07001756 pending calls:
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001757 - If we're about to enter the 'with:'. It will prevent
1758 emitting a resource warning in the common idiom
1759 'with open(path) as file:'.
1760 - If we're about to enter the 'async with:'.
1761 - If we're about to enter the 'try:' of a try/finally (not
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07001762 *very* useful, but might help in some cases and it's
1763 traditional)
1764 - If we're resuming a chain of nested 'yield from' or
1765 'await' calls, then each frame is parked with YIELD_FROM
1766 as its next opcode. If the user hit control-C we want to
1767 wait until we've reached the innermost frame before
1768 running the signal handler and raising KeyboardInterrupt
1769 (see bpo-30039).
1770 */
Mark Shannon28d28e02021-04-08 11:22:55 +01001771 if (eval_frame_handle_pending(tstate) != 0) {
1772 goto error;
1773 }
1774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001776
Mark Shannon28d28e02021-04-08 11:22:55 +01001777 tracing_dispatch:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 f->f_lasti = INSTR_OFFSET();
Mark Shannon28d28e02021-04-08 11:22:55 +01001779 NEXTOPARG();
Guido van Rossumac7be682001-01-17 15:42:30 +00001780
Łukasz Langaa785c872016-09-09 17:37:37 -07001781 if (PyDTrace_LINE_ENABLED())
Mark Shannon8e1b4062021-03-05 14:45:50 +00001782 maybe_dtrace_line(f, &trace_info);
Łukasz Langaa785c872016-09-09 17:37:37 -07001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 /* line-by-line tracing support */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001785
Victor Stinnerdab84232020-03-17 18:56:44 +01001786 if (_Py_TracingPossible(ceval2) &&
Benjamin Peterson51f46162013-01-23 08:38:47 -05001787 tstate->c_tracefunc != NULL && !tstate->tracing) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001788 int err;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02001789 /* see maybe_call_line_trace()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 for expository comments */
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02001791 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Tim Peters8a5c3c72004-04-05 19:36:21 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 err = maybe_call_line_trace(tstate->c_tracefunc,
1794 tstate->c_traceobj,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01001795 tstate, f,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001796 &trace_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 /* Reload possibly changed frame fields */
1798 JUMPTO(f->f_lasti);
Mark Shannoncb9879b2020-07-17 11:44:23 +01001799 stack_pointer = f->f_valuestack+f->f_stackdepth;
1800 f->f_stackdepth = -1;
Mark Shannon28d28e02021-04-08 11:22:55 +01001801 if (err) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* trace function raised an exception */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001803 goto error;
Mark Shannon28d28e02021-04-08 11:22:55 +01001804 }
1805 NEXTOPARG();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 }
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001807
Guido van Rossum96a42c81992-01-12 02:29:51 +00001808#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* Instruction tracing */
Guido van Rossumac7be682001-01-17 15:42:30 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (lltrace) {
1812 if (HAS_ARG(opcode)) {
1813 printf("%d: %d, %d\n",
1814 f->f_lasti, opcode, oparg);
1815 }
1816 else {
1817 printf("%d: %d\n",
1818 f->f_lasti, opcode);
1819 }
1820 }
Guido van Rossum374a9221991-04-04 10:40:29 +00001821#endif
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001822
Mark Shannon28d28e02021-04-08 11:22:55 +01001823 dispatch_opcode:
1824#ifdef DYNAMIC_EXECUTION_PROFILE
1825#ifdef DXPAIRS
1826 dxpairs[lastopcode][opcode]++;
1827 lastopcode = opcode;
1828#endif
1829 dxp[opcode]++;
1830#endif
1831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 switch (opcode) {
Guido van Rossumac7be682001-01-17 15:42:30 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* BEWARE!
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001835 It is essential that any operation that fails must goto error
Mark Shannon28d28e02021-04-08 11:22:55 +01001836 and that all operation that succeed call DISPATCH() ! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001837
Benjamin Petersonddd19492018-09-16 22:38:02 -07001838 case TARGET(NOP): {
Mark Shannon4958f5d2021-03-24 17:56:12 +00001839 DISPATCH();
Benjamin Petersonddd19492018-09-16 22:38:02 -07001840 }
Raymond Hettinger9c18e812004-06-21 16:31:15 +00001841
Benjamin Petersonddd19492018-09-16 22:38:02 -07001842 case TARGET(LOAD_FAST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001843 PyObject *value = GETLOCAL(oparg);
1844 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02001845 format_exc_check_arg(tstate, PyExc_UnboundLocalError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001846 UNBOUNDLOCAL_ERROR_MSG,
1847 PyTuple_GetItem(co->co_varnames, oparg));
1848 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001850 Py_INCREF(value);
1851 PUSH(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001852 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001853 }
1854
Benjamin Petersonddd19492018-09-16 22:38:02 -07001855 case TARGET(LOAD_CONST): {
1856 PREDICTED(LOAD_CONST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001857 PyObject *value = GETITEM(consts, oparg);
1858 Py_INCREF(value);
1859 PUSH(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001860 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001861 }
Neil Schemenauer63543862002-02-17 19:10:14 +00001862
Benjamin Petersonddd19492018-09-16 22:38:02 -07001863 case TARGET(STORE_FAST): {
1864 PREDICTED(STORE_FAST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001865 PyObject *value = POP();
1866 SETLOCAL(oparg, value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001867 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001868 }
Neil Schemenauer63543862002-02-17 19:10:14 +00001869
Benjamin Petersonddd19492018-09-16 22:38:02 -07001870 case TARGET(POP_TOP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001871 PyObject *value = POP();
1872 Py_DECREF(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001873 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001874 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001875
Benjamin Petersonddd19492018-09-16 22:38:02 -07001876 case TARGET(ROT_TWO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001877 PyObject *top = TOP();
1878 PyObject *second = SECOND();
1879 SET_TOP(second);
1880 SET_SECOND(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001881 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001882 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001883
Benjamin Petersonddd19492018-09-16 22:38:02 -07001884 case TARGET(ROT_THREE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001885 PyObject *top = TOP();
1886 PyObject *second = SECOND();
1887 PyObject *third = THIRD();
1888 SET_TOP(second);
1889 SET_SECOND(third);
1890 SET_THIRD(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001891 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001892 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001893
Benjamin Petersonddd19492018-09-16 22:38:02 -07001894 case TARGET(ROT_FOUR): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001895 PyObject *top = TOP();
1896 PyObject *second = SECOND();
1897 PyObject *third = THIRD();
1898 PyObject *fourth = FOURTH();
1899 SET_TOP(second);
1900 SET_SECOND(third);
1901 SET_THIRD(fourth);
1902 SET_FOURTH(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001903 DISPATCH();
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001904 }
1905
Benjamin Petersonddd19492018-09-16 22:38:02 -07001906 case TARGET(DUP_TOP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001907 PyObject *top = TOP();
1908 Py_INCREF(top);
1909 PUSH(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001910 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001911 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001912
Benjamin Petersonddd19492018-09-16 22:38:02 -07001913 case TARGET(DUP_TOP_TWO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001914 PyObject *top = TOP();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001915 PyObject *second = SECOND();
Benjamin Petersonf208df32012-10-12 11:37:56 -04001916 Py_INCREF(top);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001917 Py_INCREF(second);
costypetrisor8ed317f2018-07-31 20:55:14 +00001918 STACK_GROW(2);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001919 SET_TOP(top);
1920 SET_SECOND(second);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001921 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001922 }
Thomas Wouters434d0822000-08-24 20:11:32 +00001923
Benjamin Petersonddd19492018-09-16 22:38:02 -07001924 case TARGET(UNARY_POSITIVE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001925 PyObject *value = TOP();
1926 PyObject *res = PyNumber_Positive(value);
1927 Py_DECREF(value);
1928 SET_TOP(res);
1929 if (res == NULL)
1930 goto error;
1931 DISPATCH();
1932 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001933
Benjamin Petersonddd19492018-09-16 22:38:02 -07001934 case TARGET(UNARY_NEGATIVE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001935 PyObject *value = TOP();
1936 PyObject *res = PyNumber_Negative(value);
1937 Py_DECREF(value);
1938 SET_TOP(res);
1939 if (res == NULL)
1940 goto error;
1941 DISPATCH();
1942 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001943
Benjamin Petersonddd19492018-09-16 22:38:02 -07001944 case TARGET(UNARY_NOT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001945 PyObject *value = TOP();
1946 int err = PyObject_IsTrue(value);
1947 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 if (err == 0) {
1949 Py_INCREF(Py_True);
1950 SET_TOP(Py_True);
1951 DISPATCH();
1952 }
1953 else if (err > 0) {
1954 Py_INCREF(Py_False);
1955 SET_TOP(Py_False);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 DISPATCH();
1957 }
costypetrisor8ed317f2018-07-31 20:55:14 +00001958 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001959 goto error;
1960 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001961
Benjamin Petersonddd19492018-09-16 22:38:02 -07001962 case TARGET(UNARY_INVERT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001963 PyObject *value = TOP();
1964 PyObject *res = PyNumber_Invert(value);
1965 Py_DECREF(value);
1966 SET_TOP(res);
1967 if (res == NULL)
1968 goto error;
1969 DISPATCH();
1970 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001971
Benjamin Petersonddd19492018-09-16 22:38:02 -07001972 case TARGET(BINARY_POWER): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001973 PyObject *exp = POP();
1974 PyObject *base = TOP();
1975 PyObject *res = PyNumber_Power(base, exp, Py_None);
1976 Py_DECREF(base);
1977 Py_DECREF(exp);
1978 SET_TOP(res);
1979 if (res == NULL)
1980 goto error;
1981 DISPATCH();
1982 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001983
Benjamin Petersonddd19492018-09-16 22:38:02 -07001984 case TARGET(BINARY_MULTIPLY): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001985 PyObject *right = POP();
1986 PyObject *left = TOP();
1987 PyObject *res = PyNumber_Multiply(left, right);
1988 Py_DECREF(left);
1989 Py_DECREF(right);
1990 SET_TOP(res);
1991 if (res == NULL)
1992 goto error;
1993 DISPATCH();
1994 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001995
Benjamin Petersonddd19492018-09-16 22:38:02 -07001996 case TARGET(BINARY_MATRIX_MULTIPLY): {
Benjamin Petersond51374e2014-04-09 23:55:56 -04001997 PyObject *right = POP();
1998 PyObject *left = TOP();
1999 PyObject *res = PyNumber_MatrixMultiply(left, right);
2000 Py_DECREF(left);
2001 Py_DECREF(right);
2002 SET_TOP(res);
2003 if (res == NULL)
2004 goto error;
2005 DISPATCH();
2006 }
2007
Benjamin Petersonddd19492018-09-16 22:38:02 -07002008 case TARGET(BINARY_TRUE_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002009 PyObject *divisor = POP();
2010 PyObject *dividend = TOP();
2011 PyObject *quotient = PyNumber_TrueDivide(dividend, divisor);
2012 Py_DECREF(dividend);
2013 Py_DECREF(divisor);
2014 SET_TOP(quotient);
2015 if (quotient == NULL)
2016 goto error;
2017 DISPATCH();
2018 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002019
Benjamin Petersonddd19492018-09-16 22:38:02 -07002020 case TARGET(BINARY_FLOOR_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002021 PyObject *divisor = POP();
2022 PyObject *dividend = TOP();
2023 PyObject *quotient = PyNumber_FloorDivide(dividend, divisor);
2024 Py_DECREF(dividend);
2025 Py_DECREF(divisor);
2026 SET_TOP(quotient);
2027 if (quotient == NULL)
2028 goto error;
2029 DISPATCH();
2030 }
Guido van Rossum4668b002001-08-08 05:00:18 +00002031
Benjamin Petersonddd19492018-09-16 22:38:02 -07002032 case TARGET(BINARY_MODULO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002033 PyObject *divisor = POP();
2034 PyObject *dividend = TOP();
Martijn Pietersd7e64332017-02-23 13:38:04 +00002035 PyObject *res;
2036 if (PyUnicode_CheckExact(dividend) && (
2037 !PyUnicode_Check(divisor) || PyUnicode_CheckExact(divisor))) {
2038 // fast path; string formatting, but not if the RHS is a str subclass
2039 // (see issue28598)
2040 res = PyUnicode_Format(dividend, divisor);
2041 } else {
2042 res = PyNumber_Remainder(dividend, divisor);
2043 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002044 Py_DECREF(divisor);
2045 Py_DECREF(dividend);
2046 SET_TOP(res);
2047 if (res == NULL)
2048 goto error;
2049 DISPATCH();
2050 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002051
Benjamin Petersonddd19492018-09-16 22:38:02 -07002052 case TARGET(BINARY_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002053 PyObject *right = POP();
2054 PyObject *left = TOP();
2055 PyObject *sum;
Victor Stinnerbd0a08e2020-10-01 18:57:37 +02002056 /* NOTE(vstinner): Please don't try to micro-optimize int+int on
Victor Stinnerd65f42a2016-10-20 12:18:10 +02002057 CPython using bytecode, it is simply worthless.
2058 See http://bugs.python.org/issue21955 and
2059 http://bugs.python.org/issue10044 for the discussion. In short,
2060 no patch shown any impact on a realistic benchmark, only a minor
2061 speedup on microbenchmarks. */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002062 if (PyUnicode_CheckExact(left) &&
2063 PyUnicode_CheckExact(right)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002064 sum = unicode_concatenate(tstate, left, right, f, next_instr);
Martin Panter95f53c12016-07-18 08:23:26 +00002065 /* unicode_concatenate consumed the ref to left */
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002066 }
2067 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002068 sum = PyNumber_Add(left, right);
2069 Py_DECREF(left);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002070 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002071 Py_DECREF(right);
2072 SET_TOP(sum);
2073 if (sum == NULL)
2074 goto error;
2075 DISPATCH();
2076 }
2077
Benjamin Petersonddd19492018-09-16 22:38:02 -07002078 case TARGET(BINARY_SUBTRACT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002079 PyObject *right = POP();
2080 PyObject *left = TOP();
2081 PyObject *diff = PyNumber_Subtract(left, right);
2082 Py_DECREF(right);
2083 Py_DECREF(left);
2084 SET_TOP(diff);
2085 if (diff == NULL)
2086 goto error;
2087 DISPATCH();
2088 }
2089
Benjamin Petersonddd19492018-09-16 22:38:02 -07002090 case TARGET(BINARY_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002091 PyObject *sub = POP();
2092 PyObject *container = TOP();
2093 PyObject *res = PyObject_GetItem(container, sub);
2094 Py_DECREF(container);
2095 Py_DECREF(sub);
2096 SET_TOP(res);
2097 if (res == NULL)
2098 goto error;
2099 DISPATCH();
2100 }
2101
Benjamin Petersonddd19492018-09-16 22:38:02 -07002102 case TARGET(BINARY_LSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002103 PyObject *right = POP();
2104 PyObject *left = TOP();
2105 PyObject *res = PyNumber_Lshift(left, right);
2106 Py_DECREF(left);
2107 Py_DECREF(right);
2108 SET_TOP(res);
2109 if (res == NULL)
2110 goto error;
2111 DISPATCH();
2112 }
2113
Benjamin Petersonddd19492018-09-16 22:38:02 -07002114 case TARGET(BINARY_RSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002115 PyObject *right = POP();
2116 PyObject *left = TOP();
2117 PyObject *res = PyNumber_Rshift(left, right);
2118 Py_DECREF(left);
2119 Py_DECREF(right);
2120 SET_TOP(res);
2121 if (res == NULL)
2122 goto error;
2123 DISPATCH();
2124 }
2125
Benjamin Petersonddd19492018-09-16 22:38:02 -07002126 case TARGET(BINARY_AND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002127 PyObject *right = POP();
2128 PyObject *left = TOP();
2129 PyObject *res = PyNumber_And(left, right);
2130 Py_DECREF(left);
2131 Py_DECREF(right);
2132 SET_TOP(res);
2133 if (res == NULL)
2134 goto error;
2135 DISPATCH();
2136 }
2137
Benjamin Petersonddd19492018-09-16 22:38:02 -07002138 case TARGET(BINARY_XOR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002139 PyObject *right = POP();
2140 PyObject *left = TOP();
2141 PyObject *res = PyNumber_Xor(left, right);
2142 Py_DECREF(left);
2143 Py_DECREF(right);
2144 SET_TOP(res);
2145 if (res == NULL)
2146 goto error;
2147 DISPATCH();
2148 }
2149
Benjamin Petersonddd19492018-09-16 22:38:02 -07002150 case TARGET(BINARY_OR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002151 PyObject *right = POP();
2152 PyObject *left = TOP();
2153 PyObject *res = PyNumber_Or(left, right);
2154 Py_DECREF(left);
2155 Py_DECREF(right);
2156 SET_TOP(res);
2157 if (res == NULL)
2158 goto error;
2159 DISPATCH();
2160 }
2161
Benjamin Petersonddd19492018-09-16 22:38:02 -07002162 case TARGET(LIST_APPEND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002163 PyObject *v = POP();
2164 PyObject *list = PEEK(oparg);
2165 int err;
2166 err = PyList_Append(list, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002168 if (err != 0)
2169 goto error;
2170 PREDICT(JUMP_ABSOLUTE);
2171 DISPATCH();
2172 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002173
Benjamin Petersonddd19492018-09-16 22:38:02 -07002174 case TARGET(SET_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002175 PyObject *v = POP();
Raymond Hettinger41862222016-10-15 19:03:06 -07002176 PyObject *set = PEEK(oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002177 int err;
2178 err = PySet_Add(set, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002180 if (err != 0)
2181 goto error;
2182 PREDICT(JUMP_ABSOLUTE);
2183 DISPATCH();
2184 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002185
Benjamin Petersonddd19492018-09-16 22:38:02 -07002186 case TARGET(INPLACE_POWER): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002187 PyObject *exp = POP();
2188 PyObject *base = TOP();
2189 PyObject *res = PyNumber_InPlacePower(base, exp, Py_None);
2190 Py_DECREF(base);
2191 Py_DECREF(exp);
2192 SET_TOP(res);
2193 if (res == NULL)
2194 goto error;
2195 DISPATCH();
2196 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002197
Benjamin Petersonddd19492018-09-16 22:38:02 -07002198 case TARGET(INPLACE_MULTIPLY): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002199 PyObject *right = POP();
2200 PyObject *left = TOP();
2201 PyObject *res = PyNumber_InPlaceMultiply(left, right);
2202 Py_DECREF(left);
2203 Py_DECREF(right);
2204 SET_TOP(res);
2205 if (res == NULL)
2206 goto error;
2207 DISPATCH();
2208 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002209
Benjamin Petersonddd19492018-09-16 22:38:02 -07002210 case TARGET(INPLACE_MATRIX_MULTIPLY): {
Benjamin Petersond51374e2014-04-09 23:55:56 -04002211 PyObject *right = POP();
2212 PyObject *left = TOP();
2213 PyObject *res = PyNumber_InPlaceMatrixMultiply(left, right);
2214 Py_DECREF(left);
2215 Py_DECREF(right);
2216 SET_TOP(res);
2217 if (res == NULL)
2218 goto error;
2219 DISPATCH();
2220 }
2221
Benjamin Petersonddd19492018-09-16 22:38:02 -07002222 case TARGET(INPLACE_TRUE_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002223 PyObject *divisor = POP();
2224 PyObject *dividend = TOP();
2225 PyObject *quotient = PyNumber_InPlaceTrueDivide(dividend, divisor);
2226 Py_DECREF(dividend);
2227 Py_DECREF(divisor);
2228 SET_TOP(quotient);
2229 if (quotient == NULL)
2230 goto error;
2231 DISPATCH();
2232 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002233
Benjamin Petersonddd19492018-09-16 22:38:02 -07002234 case TARGET(INPLACE_FLOOR_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002235 PyObject *divisor = POP();
2236 PyObject *dividend = TOP();
2237 PyObject *quotient = PyNumber_InPlaceFloorDivide(dividend, divisor);
2238 Py_DECREF(dividend);
2239 Py_DECREF(divisor);
2240 SET_TOP(quotient);
2241 if (quotient == NULL)
2242 goto error;
2243 DISPATCH();
2244 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002245
Benjamin Petersonddd19492018-09-16 22:38:02 -07002246 case TARGET(INPLACE_MODULO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002247 PyObject *right = POP();
2248 PyObject *left = TOP();
2249 PyObject *mod = PyNumber_InPlaceRemainder(left, right);
2250 Py_DECREF(left);
2251 Py_DECREF(right);
2252 SET_TOP(mod);
2253 if (mod == NULL)
2254 goto error;
2255 DISPATCH();
2256 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002257
Benjamin Petersonddd19492018-09-16 22:38:02 -07002258 case TARGET(INPLACE_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002259 PyObject *right = POP();
2260 PyObject *left = TOP();
2261 PyObject *sum;
2262 if (PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002263 sum = unicode_concatenate(tstate, left, right, f, next_instr);
Martin Panter95f53c12016-07-18 08:23:26 +00002264 /* unicode_concatenate consumed the ref to left */
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002265 }
2266 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002267 sum = PyNumber_InPlaceAdd(left, right);
2268 Py_DECREF(left);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002269 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002270 Py_DECREF(right);
2271 SET_TOP(sum);
2272 if (sum == NULL)
2273 goto error;
2274 DISPATCH();
2275 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002276
Benjamin Petersonddd19492018-09-16 22:38:02 -07002277 case TARGET(INPLACE_SUBTRACT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002278 PyObject *right = POP();
2279 PyObject *left = TOP();
2280 PyObject *diff = PyNumber_InPlaceSubtract(left, right);
2281 Py_DECREF(left);
2282 Py_DECREF(right);
2283 SET_TOP(diff);
2284 if (diff == NULL)
2285 goto error;
2286 DISPATCH();
2287 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002288
Benjamin Petersonddd19492018-09-16 22:38:02 -07002289 case TARGET(INPLACE_LSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002290 PyObject *right = POP();
2291 PyObject *left = TOP();
2292 PyObject *res = PyNumber_InPlaceLshift(left, right);
2293 Py_DECREF(left);
2294 Py_DECREF(right);
2295 SET_TOP(res);
2296 if (res == NULL)
2297 goto error;
2298 DISPATCH();
2299 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002300
Benjamin Petersonddd19492018-09-16 22:38:02 -07002301 case TARGET(INPLACE_RSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002302 PyObject *right = POP();
2303 PyObject *left = TOP();
2304 PyObject *res = PyNumber_InPlaceRshift(left, right);
2305 Py_DECREF(left);
2306 Py_DECREF(right);
2307 SET_TOP(res);
2308 if (res == NULL)
2309 goto error;
2310 DISPATCH();
2311 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002312
Benjamin Petersonddd19492018-09-16 22:38:02 -07002313 case TARGET(INPLACE_AND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002314 PyObject *right = POP();
2315 PyObject *left = TOP();
2316 PyObject *res = PyNumber_InPlaceAnd(left, right);
2317 Py_DECREF(left);
2318 Py_DECREF(right);
2319 SET_TOP(res);
2320 if (res == NULL)
2321 goto error;
2322 DISPATCH();
2323 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002324
Benjamin Petersonddd19492018-09-16 22:38:02 -07002325 case TARGET(INPLACE_XOR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002326 PyObject *right = POP();
2327 PyObject *left = TOP();
2328 PyObject *res = PyNumber_InPlaceXor(left, right);
2329 Py_DECREF(left);
2330 Py_DECREF(right);
2331 SET_TOP(res);
2332 if (res == NULL)
2333 goto error;
2334 DISPATCH();
2335 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002336
Benjamin Petersonddd19492018-09-16 22:38:02 -07002337 case TARGET(INPLACE_OR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002338 PyObject *right = POP();
2339 PyObject *left = TOP();
2340 PyObject *res = PyNumber_InPlaceOr(left, right);
2341 Py_DECREF(left);
2342 Py_DECREF(right);
2343 SET_TOP(res);
2344 if (res == NULL)
2345 goto error;
2346 DISPATCH();
2347 }
Thomas Wouters434d0822000-08-24 20:11:32 +00002348
Benjamin Petersonddd19492018-09-16 22:38:02 -07002349 case TARGET(STORE_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002350 PyObject *sub = TOP();
2351 PyObject *container = SECOND();
2352 PyObject *v = THIRD();
2353 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002354 STACK_SHRINK(3);
Martin Panter95f53c12016-07-18 08:23:26 +00002355 /* container[sub] = v */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002356 err = PyObject_SetItem(container, sub, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002358 Py_DECREF(container);
2359 Py_DECREF(sub);
2360 if (err != 0)
2361 goto error;
2362 DISPATCH();
2363 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002364
Benjamin Petersonddd19492018-09-16 22:38:02 -07002365 case TARGET(DELETE_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002366 PyObject *sub = TOP();
2367 PyObject *container = SECOND();
2368 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002369 STACK_SHRINK(2);
Martin Panter95f53c12016-07-18 08:23:26 +00002370 /* del container[sub] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002371 err = PyObject_DelItem(container, sub);
2372 Py_DECREF(container);
2373 Py_DECREF(sub);
2374 if (err != 0)
2375 goto error;
2376 DISPATCH();
2377 }
Barry Warsaw23c9ec82000-08-21 15:44:01 +00002378
Benjamin Petersonddd19492018-09-16 22:38:02 -07002379 case TARGET(PRINT_EXPR): {
Victor Stinnercab75e32013-11-06 22:38:37 +01002380 _Py_IDENTIFIER(displayhook);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002381 PyObject *value = POP();
Victor Stinnercab75e32013-11-06 22:38:37 +01002382 PyObject *hook = _PySys_GetObjectId(&PyId_displayhook);
Benjamin Petersonfe1bcb62012-10-12 11:40:01 -04002383 PyObject *res;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002384 if (hook == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002385 _PyErr_SetString(tstate, PyExc_RuntimeError,
2386 "lost sys.displayhook");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002387 Py_DECREF(value);
2388 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 }
Petr Viktorinffd97532020-02-11 17:46:57 +01002390 res = PyObject_CallOneArg(hook, value);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002391 Py_DECREF(value);
2392 if (res == NULL)
2393 goto error;
2394 Py_DECREF(res);
2395 DISPATCH();
2396 }
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +00002397
Benjamin Petersonddd19492018-09-16 22:38:02 -07002398 case TARGET(RAISE_VARARGS): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002399 PyObject *cause = NULL, *exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 switch (oparg) {
2401 case 2:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002402 cause = POP(); /* cause */
Stefan Krahf432a322017-08-21 13:09:59 +02002403 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 case 1:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002405 exc = POP(); /* exc */
Stefan Krahf432a322017-08-21 13:09:59 +02002406 /* fall through */
2407 case 0:
Victor Stinner09532fe2019-05-10 23:39:09 +02002408 if (do_raise(tstate, exc, cause)) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002409 goto exception_unwind;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 break;
2412 default:
Victor Stinner438a12d2019-05-24 17:01:38 +02002413 _PyErr_SetString(tstate, PyExc_SystemError,
2414 "bad RAISE_VARARGS oparg");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 break;
2416 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002417 goto error;
2418 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002419
Benjamin Petersonddd19492018-09-16 22:38:02 -07002420 case TARGET(RETURN_VALUE): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 retval = POP();
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002422 assert(f->f_iblock == 0);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002423 assert(EMPTY());
Mark Shannoncb9879b2020-07-17 11:44:23 +01002424 f->f_state = FRAME_RETURNED;
2425 f->f_stackdepth = 0;
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002426 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002427 }
Guido van Rossumdb3165e1993-10-18 17:06:59 +00002428
Benjamin Petersonddd19492018-09-16 22:38:02 -07002429 case TARGET(GET_AITER): {
Yury Selivanov6ef05902015-05-28 11:21:31 -04002430 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002431 PyObject *iter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002432 PyObject *obj = TOP();
2433 PyTypeObject *type = Py_TYPE(obj);
2434
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002435 if (type->tp_as_async != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002436 getter = type->tp_as_async->am_aiter;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002437 }
Yury Selivanov75445082015-05-11 22:57:16 -04002438
2439 if (getter != NULL) {
2440 iter = (*getter)(obj);
2441 Py_DECREF(obj);
2442 if (iter == NULL) {
2443 SET_TOP(NULL);
2444 goto error;
2445 }
2446 }
2447 else {
2448 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02002449 _PyErr_Format(tstate, PyExc_TypeError,
2450 "'async for' requires an object with "
2451 "__aiter__ method, got %.100s",
2452 type->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -04002453 Py_DECREF(obj);
2454 goto error;
2455 }
2456
Yury Selivanovfaa135a2017-10-06 02:08:57 -04002457 if (Py_TYPE(iter)->tp_as_async == NULL ||
2458 Py_TYPE(iter)->tp_as_async->am_anext == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002459
Yury Selivanov398ff912017-03-02 22:20:00 -05002460 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02002461 _PyErr_Format(tstate, PyExc_TypeError,
2462 "'async for' received an object from __aiter__ "
2463 "that does not implement __anext__: %.100s",
2464 Py_TYPE(iter)->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -04002465 Py_DECREF(iter);
2466 goto error;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002467 }
2468
Yury Selivanovfaa135a2017-10-06 02:08:57 -04002469 SET_TOP(iter);
Yury Selivanov75445082015-05-11 22:57:16 -04002470 DISPATCH();
2471 }
2472
Benjamin Petersonddd19492018-09-16 22:38:02 -07002473 case TARGET(GET_ANEXT): {
Yury Selivanov6ef05902015-05-28 11:21:31 -04002474 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002475 PyObject *next_iter = NULL;
2476 PyObject *awaitable = NULL;
2477 PyObject *aiter = TOP();
2478 PyTypeObject *type = Py_TYPE(aiter);
2479
Yury Selivanoveb636452016-09-08 22:01:51 -07002480 if (PyAsyncGen_CheckExact(aiter)) {
2481 awaitable = type->tp_as_async->am_anext(aiter);
2482 if (awaitable == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002483 goto error;
2484 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002485 } else {
2486 if (type->tp_as_async != NULL){
2487 getter = type->tp_as_async->am_anext;
2488 }
Yury Selivanov75445082015-05-11 22:57:16 -04002489
Yury Selivanoveb636452016-09-08 22:01:51 -07002490 if (getter != NULL) {
2491 next_iter = (*getter)(aiter);
2492 if (next_iter == NULL) {
2493 goto error;
2494 }
2495 }
2496 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02002497 _PyErr_Format(tstate, PyExc_TypeError,
2498 "'async for' requires an iterator with "
2499 "__anext__ method, got %.100s",
2500 type->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07002501 goto error;
2502 }
Yury Selivanov75445082015-05-11 22:57:16 -04002503
Yury Selivanoveb636452016-09-08 22:01:51 -07002504 awaitable = _PyCoro_GetAwaitableIter(next_iter);
2505 if (awaitable == NULL) {
Yury Selivanov398ff912017-03-02 22:20:00 -05002506 _PyErr_FormatFromCause(
Yury Selivanoveb636452016-09-08 22:01:51 -07002507 PyExc_TypeError,
2508 "'async for' received an invalid object "
2509 "from __anext__: %.100s",
2510 Py_TYPE(next_iter)->tp_name);
2511
2512 Py_DECREF(next_iter);
2513 goto error;
2514 } else {
2515 Py_DECREF(next_iter);
2516 }
2517 }
Yury Selivanov75445082015-05-11 22:57:16 -04002518
2519 PUSH(awaitable);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03002520 PREDICT(LOAD_CONST);
Yury Selivanov75445082015-05-11 22:57:16 -04002521 DISPATCH();
2522 }
2523
Benjamin Petersonddd19492018-09-16 22:38:02 -07002524 case TARGET(GET_AWAITABLE): {
2525 PREDICTED(GET_AWAITABLE);
Yury Selivanov75445082015-05-11 22:57:16 -04002526 PyObject *iterable = TOP();
Yury Selivanov5376ba92015-06-22 12:19:30 -04002527 PyObject *iter = _PyCoro_GetAwaitableIter(iterable);
Yury Selivanov75445082015-05-11 22:57:16 -04002528
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03002529 if (iter == NULL) {
Mark Shannonfee55262019-11-21 09:11:43 +00002530 int opcode_at_minus_3 = 0;
2531 if ((next_instr - first_instr) > 2) {
2532 opcode_at_minus_3 = _Py_OPCODE(next_instr[-3]);
2533 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002534 format_awaitable_error(tstate, Py_TYPE(iterable),
Mark Shannonfee55262019-11-21 09:11:43 +00002535 opcode_at_minus_3,
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03002536 _Py_OPCODE(next_instr[-2]));
2537 }
2538
Yury Selivanov75445082015-05-11 22:57:16 -04002539 Py_DECREF(iterable);
2540
Yury Selivanovc724bae2016-03-02 11:30:46 -05002541 if (iter != NULL && PyCoro_CheckExact(iter)) {
2542 PyObject *yf = _PyGen_yf((PyGenObject*)iter);
2543 if (yf != NULL) {
2544 /* `iter` is a coroutine object that is being
2545 awaited, `yf` is a pointer to the current awaitable
2546 being awaited on. */
2547 Py_DECREF(yf);
2548 Py_CLEAR(iter);
Victor Stinner438a12d2019-05-24 17:01:38 +02002549 _PyErr_SetString(tstate, PyExc_RuntimeError,
2550 "coroutine is being awaited already");
Yury Selivanovc724bae2016-03-02 11:30:46 -05002551 /* The code below jumps to `error` if `iter` is NULL. */
2552 }
2553 }
2554
Yury Selivanov75445082015-05-11 22:57:16 -04002555 SET_TOP(iter); /* Even if it's NULL */
2556
2557 if (iter == NULL) {
2558 goto error;
2559 }
2560
Serhiy Storchakada9c5132016-06-27 18:58:57 +03002561 PREDICT(LOAD_CONST);
Yury Selivanov75445082015-05-11 22:57:16 -04002562 DISPATCH();
2563 }
2564
Benjamin Petersonddd19492018-09-16 22:38:02 -07002565 case TARGET(YIELD_FROM): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002566 PyObject *v = POP();
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002567 PyObject *receiver = TOP();
Vladimir Matveev037245c2020-10-09 17:15:15 -07002568 PySendResult gen_status;
2569 if (tstate->c_tracefunc == NULL) {
2570 gen_status = PyIter_Send(receiver, v, &retval);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002571 } else {
Vladimir Matveev037245c2020-10-09 17:15:15 -07002572 _Py_IDENTIFIER(send);
2573 if (v == Py_None && PyIter_Check(receiver)) {
2574 retval = Py_TYPE(receiver)->tp_iternext(receiver);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002575 }
2576 else {
Vladimir Matveev037245c2020-10-09 17:15:15 -07002577 retval = _PyObject_CallMethodIdOneArg(receiver, &PyId_send, v);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002578 }
Vladimir Matveev2b053612020-09-18 18:38:38 -07002579 if (retval == NULL) {
2580 if (tstate->c_tracefunc != NULL
2581 && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
Mark Shannon8e1b4062021-03-05 14:45:50 +00002582 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, &trace_info);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002583 if (_PyGen_FetchStopIterationValue(&retval) == 0) {
2584 gen_status = PYGEN_RETURN;
2585 }
2586 else {
2587 gen_status = PYGEN_ERROR;
2588 }
2589 }
2590 else {
2591 gen_status = PYGEN_NEXT;
2592 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002593 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002594 Py_DECREF(v);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002595 if (gen_status == PYGEN_ERROR) {
2596 assert (retval == NULL);
2597 goto error;
2598 }
2599 if (gen_status == PYGEN_RETURN) {
2600 assert (retval != NULL);
2601
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002602 Py_DECREF(receiver);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002603 SET_TOP(retval);
2604 retval = NULL;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002605 DISPATCH();
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002606 }
Vladimir Matveev2b053612020-09-18 18:38:38 -07002607 assert (gen_status == PYGEN_NEXT);
Martin Panter95f53c12016-07-18 08:23:26 +00002608 /* receiver remains on stack, retval is value to be yielded */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002609 /* and repeat... */
Mark Shannonfcb55c02021-04-01 16:00:31 +01002610 assert(f->f_lasti > 0);
2611 f->f_lasti -= 1;
Mark Shannoncb9879b2020-07-17 11:44:23 +01002612 f->f_state = FRAME_SUSPENDED;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02002613 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002614 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002615 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002616
Benjamin Petersonddd19492018-09-16 22:38:02 -07002617 case TARGET(YIELD_VALUE): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 retval = POP();
Yury Selivanoveb636452016-09-08 22:01:51 -07002619
2620 if (co->co_flags & CO_ASYNC_GENERATOR) {
2621 PyObject *w = _PyAsyncGenValueWrapperNew(retval);
2622 Py_DECREF(retval);
2623 if (w == NULL) {
2624 retval = NULL;
2625 goto error;
2626 }
2627 retval = w;
2628 }
Mark Shannoncb9879b2020-07-17 11:44:23 +01002629 f->f_state = FRAME_SUSPENDED;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02002630 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002631 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002632 }
Tim Peters5ca576e2001-06-18 22:08:13 +00002633
Mark Shannonb37181e2021-04-06 11:48:59 +01002634 case TARGET(GEN_START): {
2635 PyObject *none = POP();
2636 Py_DECREF(none);
2637 if (none != Py_None) {
2638 if (oparg > 2) {
2639 _PyErr_SetString(tstate, PyExc_SystemError,
2640 "Illegal kind for GEN_START");
2641 }
2642 else {
2643 static const char *gen_kind[3] = {
2644 "generator",
2645 "coroutine",
2646 "async generator"
2647 };
2648 _PyErr_Format(tstate, PyExc_TypeError,
2649 "can't send non-None value to a "
2650 "just-started %s",
2651 gen_kind[oparg]);
2652 }
2653 goto error;
2654 }
2655 DISPATCH();
2656 }
2657
Benjamin Petersonddd19492018-09-16 22:38:02 -07002658 case TARGET(POP_EXCEPT): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002659 PyObject *type, *value, *traceback;
2660 _PyErr_StackItem *exc_info;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002661 PyTryBlock *b = PyFrame_BlockPop(f);
2662 if (b->b_type != EXCEPT_HANDLER) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002663 _PyErr_SetString(tstate, PyExc_SystemError,
2664 "popped block is not an except handler");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002665 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002667 assert(STACK_LEVEL() >= (b)->b_level + 3 &&
2668 STACK_LEVEL() <= (b)->b_level + 4);
2669 exc_info = tstate->exc_info;
2670 type = exc_info->exc_type;
2671 value = exc_info->exc_value;
2672 traceback = exc_info->exc_traceback;
2673 exc_info->exc_type = POP();
2674 exc_info->exc_value = POP();
2675 exc_info->exc_traceback = POP();
2676 Py_XDECREF(type);
2677 Py_XDECREF(value);
2678 Py_XDECREF(traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002680 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002681
Benjamin Petersonddd19492018-09-16 22:38:02 -07002682 case TARGET(POP_BLOCK): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002683 PyFrame_BlockPop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002685 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002686
Mark Shannonfee55262019-11-21 09:11:43 +00002687 case TARGET(RERAISE): {
Mark Shannonbf353f32020-12-17 13:55:28 +00002688 assert(f->f_iblock > 0);
2689 if (oparg) {
2690 f->f_lasti = f->f_blockstack[f->f_iblock-1].b_handler;
2691 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002692 PyObject *exc = POP();
Mark Shannonfee55262019-11-21 09:11:43 +00002693 PyObject *val = POP();
2694 PyObject *tb = POP();
2695 assert(PyExceptionClass_Check(exc));
Victor Stinner61f4db82020-01-28 03:37:45 +01002696 _PyErr_Restore(tstate, exc, val, tb);
Mark Shannonfee55262019-11-21 09:11:43 +00002697 goto exception_unwind;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002698 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002699
Benjamin Petersonddd19492018-09-16 22:38:02 -07002700 case TARGET(END_ASYNC_FOR): {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002701 PyObject *exc = POP();
2702 assert(PyExceptionClass_Check(exc));
2703 if (PyErr_GivenExceptionMatches(exc, PyExc_StopAsyncIteration)) {
2704 PyTryBlock *b = PyFrame_BlockPop(f);
2705 assert(b->b_type == EXCEPT_HANDLER);
2706 Py_DECREF(exc);
2707 UNWIND_EXCEPT_HANDLER(b);
2708 Py_DECREF(POP());
2709 JUMPBY(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00002710 DISPATCH();
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002711 }
2712 else {
2713 PyObject *val = POP();
2714 PyObject *tb = POP();
Victor Stinner438a12d2019-05-24 17:01:38 +02002715 _PyErr_Restore(tstate, exc, val, tb);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002716 goto exception_unwind;
2717 }
2718 }
2719
Zackery Spytzce6a0702019-08-25 03:44:09 -06002720 case TARGET(LOAD_ASSERTION_ERROR): {
2721 PyObject *value = PyExc_AssertionError;
2722 Py_INCREF(value);
2723 PUSH(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00002724 DISPATCH();
Zackery Spytzce6a0702019-08-25 03:44:09 -06002725 }
2726
Benjamin Petersonddd19492018-09-16 22:38:02 -07002727 case TARGET(LOAD_BUILD_CLASS): {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002728 _Py_IDENTIFIER(__build_class__);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002729
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002730 PyObject *bc;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002731 if (PyDict_CheckExact(f->f_builtins)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002732 bc = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___build_class__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002733 if (bc == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002734 if (!_PyErr_Occurred(tstate)) {
2735 _PyErr_SetString(tstate, PyExc_NameError,
2736 "__build_class__ not found");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002737 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002738 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002739 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002740 Py_INCREF(bc);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002741 }
2742 else {
2743 PyObject *build_class_str = _PyUnicode_FromId(&PyId___build_class__);
2744 if (build_class_str == NULL)
Serhiy Storchaka70b72f02016-11-08 23:12:46 +02002745 goto error;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002746 bc = PyObject_GetItem(f->f_builtins, build_class_str);
2747 if (bc == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002748 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
2749 _PyErr_SetString(tstate, PyExc_NameError,
2750 "__build_class__ not found");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002751 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002752 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002754 PUSH(bc);
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002755 DISPATCH();
Victor Stinner3c1e4812012-03-26 22:10:51 +02002756 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002757
Benjamin Petersonddd19492018-09-16 22:38:02 -07002758 case TARGET(STORE_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002759 PyObject *name = GETITEM(names, oparg);
2760 PyObject *v = POP();
2761 PyObject *ns = f->f_locals;
2762 int err;
2763 if (ns == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002764 _PyErr_Format(tstate, PyExc_SystemError,
2765 "no locals found when storing %R", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002767 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002769 if (PyDict_CheckExact(ns))
2770 err = PyDict_SetItem(ns, name, v);
2771 else
2772 err = PyObject_SetItem(ns, name, v);
2773 Py_DECREF(v);
2774 if (err != 0)
2775 goto error;
2776 DISPATCH();
2777 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002778
Benjamin Petersonddd19492018-09-16 22:38:02 -07002779 case TARGET(DELETE_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002780 PyObject *name = GETITEM(names, oparg);
2781 PyObject *ns = f->f_locals;
2782 int err;
2783 if (ns == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002784 _PyErr_Format(tstate, PyExc_SystemError,
2785 "no locals when deleting %R", name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002786 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002788 err = PyObject_DelItem(ns, name);
2789 if (err != 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002790 format_exc_check_arg(tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002791 NAME_ERROR_MSG,
2792 name);
2793 goto error;
2794 }
2795 DISPATCH();
2796 }
Guido van Rossum04691fc1992-08-12 15:35:34 +00002797
Benjamin Petersonddd19492018-09-16 22:38:02 -07002798 case TARGET(UNPACK_SEQUENCE): {
2799 PREDICTED(UNPACK_SEQUENCE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002800 PyObject *seq = POP(), *item, **items;
2801 if (PyTuple_CheckExact(seq) &&
2802 PyTuple_GET_SIZE(seq) == oparg) {
2803 items = ((PyTupleObject *)seq)->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 while (oparg--) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002805 item = items[oparg];
2806 Py_INCREF(item);
2807 PUSH(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002809 } else if (PyList_CheckExact(seq) &&
2810 PyList_GET_SIZE(seq) == oparg) {
2811 items = ((PyListObject *)seq)->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 while (oparg--) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002813 item = items[oparg];
2814 Py_INCREF(item);
2815 PUSH(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002817 } else if (unpack_iterable(tstate, seq, oparg, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 stack_pointer + oparg)) {
costypetrisor8ed317f2018-07-31 20:55:14 +00002819 STACK_GROW(oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 } else {
2821 /* unpack_iterable() raised an exception */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002822 Py_DECREF(seq);
2823 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002825 Py_DECREF(seq);
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002826 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 }
Guido van Rossum0368b722007-05-11 16:50:42 +00002828
Benjamin Petersonddd19492018-09-16 22:38:02 -07002829 case TARGET(UNPACK_EX): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002830 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
2831 PyObject *seq = POP();
2832
Victor Stinner438a12d2019-05-24 17:01:38 +02002833 if (unpack_iterable(tstate, seq, oparg & 0xFF, oparg >> 8,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002834 stack_pointer + totalargs)) {
2835 stack_pointer += totalargs;
2836 } else {
2837 Py_DECREF(seq);
2838 goto error;
2839 }
2840 Py_DECREF(seq);
2841 DISPATCH();
2842 }
2843
Benjamin Petersonddd19492018-09-16 22:38:02 -07002844 case TARGET(STORE_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002845 PyObject *name = GETITEM(names, oparg);
2846 PyObject *owner = TOP();
2847 PyObject *v = SECOND();
2848 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002849 STACK_SHRINK(2);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002850 err = PyObject_SetAttr(owner, name, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002852 Py_DECREF(owner);
2853 if (err != 0)
2854 goto error;
2855 DISPATCH();
2856 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002857
Benjamin Petersonddd19492018-09-16 22:38:02 -07002858 case TARGET(DELETE_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002859 PyObject *name = GETITEM(names, oparg);
2860 PyObject *owner = POP();
2861 int err;
2862 err = PyObject_SetAttr(owner, name, (PyObject *)NULL);
2863 Py_DECREF(owner);
2864 if (err != 0)
2865 goto error;
2866 DISPATCH();
2867 }
2868
Benjamin Petersonddd19492018-09-16 22:38:02 -07002869 case TARGET(STORE_GLOBAL): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002870 PyObject *name = GETITEM(names, oparg);
2871 PyObject *v = POP();
2872 int err;
2873 err = PyDict_SetItem(f->f_globals, name, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002875 if (err != 0)
2876 goto error;
2877 DISPATCH();
2878 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002879
Benjamin Petersonddd19492018-09-16 22:38:02 -07002880 case TARGET(DELETE_GLOBAL): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002881 PyObject *name = GETITEM(names, oparg);
2882 int err;
2883 err = PyDict_DelItem(f->f_globals, name);
2884 if (err != 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002885 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2886 format_exc_check_arg(tstate, PyExc_NameError,
2887 NAME_ERROR_MSG, name);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002888 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002889 goto error;
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002890 }
2891 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002892 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002893
Benjamin Petersonddd19492018-09-16 22:38:02 -07002894 case TARGET(LOAD_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002895 PyObject *name = GETITEM(names, oparg);
2896 PyObject *locals = f->f_locals;
2897 PyObject *v;
2898 if (locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002899 _PyErr_Format(tstate, PyExc_SystemError,
2900 "no locals when loading %R", name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002901 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002903 if (PyDict_CheckExact(locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002904 v = PyDict_GetItemWithError(locals, name);
2905 if (v != NULL) {
2906 Py_INCREF(v);
2907 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002908 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002909 goto error;
2910 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 }
2912 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002913 v = PyObject_GetItem(locals, name);
Victor Stinnere20310f2015-11-05 13:56:58 +01002914 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002915 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
Benjamin Peterson92722792012-12-15 12:51:05 -05002916 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02002917 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 }
2919 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002920 if (v == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002921 v = PyDict_GetItemWithError(f->f_globals, name);
2922 if (v != NULL) {
2923 Py_INCREF(v);
2924 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002925 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002926 goto error;
2927 }
2928 else {
Victor Stinnerb0b22422012-04-19 00:57:45 +02002929 if (PyDict_CheckExact(f->f_builtins)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002930 v = PyDict_GetItemWithError(f->f_builtins, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002931 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002932 if (!_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002933 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02002934 tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002935 NAME_ERROR_MSG, name);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002936 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002937 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002938 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002939 Py_INCREF(v);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002940 }
2941 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002942 v = PyObject_GetItem(f->f_builtins, name);
2943 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002944 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Victor Stinnerb0b22422012-04-19 00:57:45 +02002945 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02002946 tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002947 NAME_ERROR_MSG, name);
Victor Stinner438a12d2019-05-24 17:01:38 +02002948 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002949 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002950 }
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002954 PUSH(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002956 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002957
Benjamin Petersonddd19492018-09-16 22:38:02 -07002958 case TARGET(LOAD_GLOBAL): {
Inada Naoki91234a12019-06-03 21:30:58 +09002959 PyObject *name;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002960 PyObject *v;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002961 if (PyDict_CheckExact(f->f_globals)
Victor Stinnerb4efc962015-11-20 09:24:02 +01002962 && PyDict_CheckExact(f->f_builtins))
2963 {
Inada Naoki91234a12019-06-03 21:30:58 +09002964 OPCACHE_CHECK();
2965 if (co_opcache != NULL && co_opcache->optimized > 0) {
2966 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2967
2968 if (lg->globals_ver ==
2969 ((PyDictObject *)f->f_globals)->ma_version_tag
2970 && lg->builtins_ver ==
2971 ((PyDictObject *)f->f_builtins)->ma_version_tag)
2972 {
2973 PyObject *ptr = lg->ptr;
2974 OPCACHE_STAT_GLOBAL_HIT();
2975 assert(ptr != NULL);
2976 Py_INCREF(ptr);
2977 PUSH(ptr);
2978 DISPATCH();
2979 }
2980 }
2981
2982 name = GETITEM(names, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002983 v = _PyDict_LoadGlobal((PyDictObject *)f->f_globals,
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002984 (PyDictObject *)f->f_builtins,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002985 name);
2986 if (v == NULL) {
Victor Stinnera4860542021-02-19 15:08:54 +01002987 if (!_PyErr_Occurred(tstate)) {
Victor Stinnerb4efc962015-11-20 09:24:02 +01002988 /* _PyDict_LoadGlobal() returns NULL without raising
2989 * an exception if the key doesn't exist */
Victor Stinner438a12d2019-05-24 17:01:38 +02002990 format_exc_check_arg(tstate, PyExc_NameError,
Ezio Melotti04a29552013-03-03 15:12:44 +02002991 NAME_ERROR_MSG, name);
Victor Stinnerb4efc962015-11-20 09:24:02 +01002992 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002993 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 }
Inada Naoki91234a12019-06-03 21:30:58 +09002995
2996 if (co_opcache != NULL) {
2997 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2998
2999 if (co_opcache->optimized == 0) {
3000 /* Wasn't optimized before. */
3001 OPCACHE_STAT_GLOBAL_OPT();
3002 } else {
3003 OPCACHE_STAT_GLOBAL_MISS();
3004 }
3005
3006 co_opcache->optimized = 1;
3007 lg->globals_ver =
3008 ((PyDictObject *)f->f_globals)->ma_version_tag;
3009 lg->builtins_ver =
3010 ((PyDictObject *)f->f_builtins)->ma_version_tag;
3011 lg->ptr = v; /* borrowed */
3012 }
3013
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003014 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003016 else {
3017 /* Slow-path if globals or builtins is not a dict */
Victor Stinnerb4efc962015-11-20 09:24:02 +01003018
3019 /* namespace 1: globals */
Inada Naoki91234a12019-06-03 21:30:58 +09003020 name = GETITEM(names, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003021 v = PyObject_GetItem(f->f_globals, name);
3022 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003023 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Victor Stinner60a1d3c2015-11-05 13:55:20 +01003024 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02003025 }
3026 _PyErr_Clear(tstate);
Victor Stinner60a1d3c2015-11-05 13:55:20 +01003027
Victor Stinnerb4efc962015-11-20 09:24:02 +01003028 /* namespace 2: builtins */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003029 v = PyObject_GetItem(f->f_builtins, name);
3030 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003031 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003032 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02003033 tstate, PyExc_NameError,
Ezio Melotti04a29552013-03-03 15:12:44 +02003034 NAME_ERROR_MSG, name);
Victor Stinner438a12d2019-05-24 17:01:38 +02003035 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003036 goto error;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003037 }
3038 }
3039 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003040 PUSH(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003042 }
Guido van Rossum681d79a1995-07-18 14:51:37 +00003043
Benjamin Petersonddd19492018-09-16 22:38:02 -07003044 case TARGET(DELETE_FAST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003045 PyObject *v = GETLOCAL(oparg);
3046 if (v != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 SETLOCAL(oparg, NULL);
3048 DISPATCH();
3049 }
3050 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02003051 tstate, PyExc_UnboundLocalError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 UNBOUNDLOCAL_ERROR_MSG,
3053 PyTuple_GetItem(co->co_varnames, oparg)
3054 );
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003055 goto error;
3056 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003057
Benjamin Petersonddd19492018-09-16 22:38:02 -07003058 case TARGET(DELETE_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003059 PyObject *cell = freevars[oparg];
Raymond Hettingerc32f9db2016-11-12 04:10:35 -05003060 PyObject *oldobj = PyCell_GET(cell);
3061 if (oldobj != NULL) {
3062 PyCell_SET(cell, NULL);
3063 Py_DECREF(oldobj);
Benjamin Peterson00ebe2c2010-09-10 22:02:31 +00003064 DISPATCH();
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003065 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003066 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003067 goto error;
3068 }
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003069
Benjamin Petersonddd19492018-09-16 22:38:02 -07003070 case TARGET(LOAD_CLOSURE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003071 PyObject *cell = freevars[oparg];
3072 Py_INCREF(cell);
3073 PUSH(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003075 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003076
Benjamin Petersonddd19492018-09-16 22:38:02 -07003077 case TARGET(LOAD_CLASSDEREF): {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003078 PyObject *name, *value, *locals = f->f_locals;
Victor Stinnerd3dfd0e2013-05-16 23:48:01 +02003079 Py_ssize_t idx;
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003080 assert(locals);
3081 assert(oparg >= PyTuple_GET_SIZE(co->co_cellvars));
3082 idx = oparg - PyTuple_GET_SIZE(co->co_cellvars);
3083 assert(idx >= 0 && idx < PyTuple_GET_SIZE(co->co_freevars));
3084 name = PyTuple_GET_ITEM(co->co_freevars, idx);
3085 if (PyDict_CheckExact(locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003086 value = PyDict_GetItemWithError(locals, name);
3087 if (value != NULL) {
3088 Py_INCREF(value);
3089 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003090 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003091 goto error;
3092 }
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003093 }
3094 else {
3095 value = PyObject_GetItem(locals, name);
Victor Stinnere20310f2015-11-05 13:56:58 +01003096 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003097 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003098 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02003099 }
3100 _PyErr_Clear(tstate);
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003101 }
3102 }
3103 if (!value) {
3104 PyObject *cell = freevars[oparg];
3105 value = PyCell_GET(cell);
3106 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003107 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003108 goto error;
3109 }
3110 Py_INCREF(value);
3111 }
3112 PUSH(value);
3113 DISPATCH();
3114 }
3115
Benjamin Petersonddd19492018-09-16 22:38:02 -07003116 case TARGET(LOAD_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003117 PyObject *cell = freevars[oparg];
3118 PyObject *value = PyCell_GET(cell);
3119 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003120 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003121 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003123 Py_INCREF(value);
3124 PUSH(value);
3125 DISPATCH();
3126 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003127
Benjamin Petersonddd19492018-09-16 22:38:02 -07003128 case TARGET(STORE_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003129 PyObject *v = POP();
3130 PyObject *cell = freevars[oparg];
Raymond Hettingerb2b15432016-11-11 04:32:11 -08003131 PyObject *oldobj = PyCell_GET(cell);
3132 PyCell_SET(cell, v);
3133 Py_XDECREF(oldobj);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003134 DISPATCH();
3135 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003136
Benjamin Petersonddd19492018-09-16 22:38:02 -07003137 case TARGET(BUILD_STRING): {
Serhiy Storchakaea525a22016-09-06 22:07:53 +03003138 PyObject *str;
3139 PyObject *empty = PyUnicode_New(0, 0);
3140 if (empty == NULL) {
3141 goto error;
3142 }
3143 str = _PyUnicode_JoinArray(empty, stack_pointer - oparg, oparg);
3144 Py_DECREF(empty);
3145 if (str == NULL)
3146 goto error;
3147 while (--oparg >= 0) {
3148 PyObject *item = POP();
3149 Py_DECREF(item);
3150 }
3151 PUSH(str);
3152 DISPATCH();
3153 }
3154
Benjamin Petersonddd19492018-09-16 22:38:02 -07003155 case TARGET(BUILD_TUPLE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003156 PyObject *tup = PyTuple_New(oparg);
3157 if (tup == NULL)
3158 goto error;
3159 while (--oparg >= 0) {
3160 PyObject *item = POP();
3161 PyTuple_SET_ITEM(tup, oparg, item);
3162 }
3163 PUSH(tup);
3164 DISPATCH();
3165 }
3166
Benjamin Petersonddd19492018-09-16 22:38:02 -07003167 case TARGET(BUILD_LIST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003168 PyObject *list = PyList_New(oparg);
3169 if (list == NULL)
3170 goto error;
3171 while (--oparg >= 0) {
3172 PyObject *item = POP();
3173 PyList_SET_ITEM(list, oparg, item);
3174 }
3175 PUSH(list);
3176 DISPATCH();
3177 }
3178
Mark Shannon13bc1392020-01-23 09:25:17 +00003179 case TARGET(LIST_TO_TUPLE): {
3180 PyObject *list = POP();
3181 PyObject *tuple = PyList_AsTuple(list);
3182 Py_DECREF(list);
3183 if (tuple == NULL) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003184 goto error;
Mark Shannon13bc1392020-01-23 09:25:17 +00003185 }
3186 PUSH(tuple);
3187 DISPATCH();
3188 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003189
Mark Shannon13bc1392020-01-23 09:25:17 +00003190 case TARGET(LIST_EXTEND): {
3191 PyObject *iterable = POP();
3192 PyObject *list = PEEK(oparg);
3193 PyObject *none_val = _PyList_Extend((PyListObject *)list, iterable);
3194 if (none_val == NULL) {
3195 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
Victor Stinnera102ed72020-02-07 02:24:48 +01003196 (Py_TYPE(iterable)->tp_iter == NULL && !PySequence_Check(iterable)))
Mark Shannon13bc1392020-01-23 09:25:17 +00003197 {
Victor Stinner61f4db82020-01-28 03:37:45 +01003198 _PyErr_Clear(tstate);
Mark Shannon13bc1392020-01-23 09:25:17 +00003199 _PyErr_Format(tstate, PyExc_TypeError,
3200 "Value after * must be an iterable, not %.200s",
3201 Py_TYPE(iterable)->tp_name);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003202 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003203 Py_DECREF(iterable);
3204 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003205 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003206 Py_DECREF(none_val);
3207 Py_DECREF(iterable);
3208 DISPATCH();
3209 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003210
Mark Shannon13bc1392020-01-23 09:25:17 +00003211 case TARGET(SET_UPDATE): {
3212 PyObject *iterable = POP();
3213 PyObject *set = PEEK(oparg);
3214 int err = _PySet_Update(set, iterable);
3215 Py_DECREF(iterable);
3216 if (err < 0) {
3217 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003218 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003219 DISPATCH();
3220 }
3221
Benjamin Petersonddd19492018-09-16 22:38:02 -07003222 case TARGET(BUILD_SET): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003223 PyObject *set = PySet_New(NULL);
3224 int err = 0;
Raymond Hettinger4c483ad2016-09-08 14:45:40 -07003225 int i;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003226 if (set == NULL)
3227 goto error;
Raymond Hettinger4c483ad2016-09-08 14:45:40 -07003228 for (i = oparg; i > 0; i--) {
3229 PyObject *item = PEEK(i);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003230 if (err == 0)
3231 err = PySet_Add(set, item);
3232 Py_DECREF(item);
3233 }
costypetrisor8ed317f2018-07-31 20:55:14 +00003234 STACK_SHRINK(oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003235 if (err != 0) {
3236 Py_DECREF(set);
3237 goto error;
3238 }
3239 PUSH(set);
3240 DISPATCH();
3241 }
3242
Benjamin Petersonddd19492018-09-16 22:38:02 -07003243 case TARGET(BUILD_MAP): {
Victor Stinner74319ae2016-08-25 00:04:09 +02003244 Py_ssize_t i;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003245 PyObject *map = _PyDict_NewPresized((Py_ssize_t)oparg);
3246 if (map == NULL)
3247 goto error;
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003248 for (i = oparg; i > 0; i--) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003249 int err;
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003250 PyObject *key = PEEK(2*i);
3251 PyObject *value = PEEK(2*i - 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003252 err = PyDict_SetItem(map, key, value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003253 if (err != 0) {
3254 Py_DECREF(map);
3255 goto error;
3256 }
3257 }
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003258
3259 while (oparg--) {
3260 Py_DECREF(POP());
3261 Py_DECREF(POP());
3262 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003263 PUSH(map);
3264 DISPATCH();
3265 }
3266
Benjamin Petersonddd19492018-09-16 22:38:02 -07003267 case TARGET(SETUP_ANNOTATIONS): {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003268 _Py_IDENTIFIER(__annotations__);
3269 int err;
3270 PyObject *ann_dict;
3271 if (f->f_locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003272 _PyErr_Format(tstate, PyExc_SystemError,
3273 "no locals found when setting up annotations");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003274 goto error;
3275 }
3276 /* check if __annotations__ in locals()... */
3277 if (PyDict_CheckExact(f->f_locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003278 ann_dict = _PyDict_GetItemIdWithError(f->f_locals,
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003279 &PyId___annotations__);
3280 if (ann_dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003281 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003282 goto error;
3283 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003284 /* ...if not, create a new one */
3285 ann_dict = PyDict_New();
3286 if (ann_dict == NULL) {
3287 goto error;
3288 }
3289 err = _PyDict_SetItemId(f->f_locals,
3290 &PyId___annotations__, ann_dict);
3291 Py_DECREF(ann_dict);
3292 if (err != 0) {
3293 goto error;
3294 }
3295 }
3296 }
3297 else {
3298 /* do the same if locals() is not a dict */
3299 PyObject *ann_str = _PyUnicode_FromId(&PyId___annotations__);
3300 if (ann_str == NULL) {
Serhiy Storchaka4678b2f2016-11-08 23:13:36 +02003301 goto error;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003302 }
3303 ann_dict = PyObject_GetItem(f->f_locals, ann_str);
3304 if (ann_dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003305 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003306 goto error;
3307 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003308 _PyErr_Clear(tstate);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003309 ann_dict = PyDict_New();
3310 if (ann_dict == NULL) {
3311 goto error;
3312 }
3313 err = PyObject_SetItem(f->f_locals, ann_str, ann_dict);
3314 Py_DECREF(ann_dict);
3315 if (err != 0) {
3316 goto error;
3317 }
3318 }
3319 else {
3320 Py_DECREF(ann_dict);
3321 }
3322 }
3323 DISPATCH();
3324 }
3325
Benjamin Petersonddd19492018-09-16 22:38:02 -07003326 case TARGET(BUILD_CONST_KEY_MAP): {
Victor Stinner74319ae2016-08-25 00:04:09 +02003327 Py_ssize_t i;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003328 PyObject *map;
3329 PyObject *keys = TOP();
3330 if (!PyTuple_CheckExact(keys) ||
3331 PyTuple_GET_SIZE(keys) != (Py_ssize_t)oparg) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003332 _PyErr_SetString(tstate, PyExc_SystemError,
3333 "bad BUILD_CONST_KEY_MAP keys argument");
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003334 goto error;
3335 }
3336 map = _PyDict_NewPresized((Py_ssize_t)oparg);
3337 if (map == NULL) {
3338 goto error;
3339 }
3340 for (i = oparg; i > 0; i--) {
3341 int err;
3342 PyObject *key = PyTuple_GET_ITEM(keys, oparg - i);
3343 PyObject *value = PEEK(i + 1);
3344 err = PyDict_SetItem(map, key, value);
3345 if (err != 0) {
3346 Py_DECREF(map);
3347 goto error;
3348 }
3349 }
3350
3351 Py_DECREF(POP());
3352 while (oparg--) {
3353 Py_DECREF(POP());
3354 }
3355 PUSH(map);
3356 DISPATCH();
3357 }
3358
Mark Shannon8a4cd702020-01-27 09:57:45 +00003359 case TARGET(DICT_UPDATE): {
3360 PyObject *update = POP();
3361 PyObject *dict = PEEK(oparg);
3362 if (PyDict_Update(dict, update) < 0) {
3363 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
3364 _PyErr_Format(tstate, PyExc_TypeError,
3365 "'%.200s' object is not a mapping",
Victor Stinnera102ed72020-02-07 02:24:48 +01003366 Py_TYPE(update)->tp_name);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003367 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003368 Py_DECREF(update);
3369 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003370 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003371 Py_DECREF(update);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003372 DISPATCH();
3373 }
3374
Mark Shannon8a4cd702020-01-27 09:57:45 +00003375 case TARGET(DICT_MERGE): {
3376 PyObject *update = POP();
3377 PyObject *dict = PEEK(oparg);
3378
3379 if (_PyDict_MergeEx(dict, update, 2) < 0) {
3380 format_kwargs_error(tstate, PEEK(2 + oparg), update);
3381 Py_DECREF(update);
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003382 goto error;
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003383 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003384 Py_DECREF(update);
Brandt Bucherf185a732019-09-28 17:12:49 -07003385 PREDICT(CALL_FUNCTION_EX);
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003386 DISPATCH();
3387 }
3388
Benjamin Petersonddd19492018-09-16 22:38:02 -07003389 case TARGET(MAP_ADD): {
Jörn Heisslerc8a35412019-06-22 16:40:55 +02003390 PyObject *value = TOP();
3391 PyObject *key = SECOND();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003392 PyObject *map;
3393 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00003394 STACK_SHRINK(2);
Raymond Hettinger41862222016-10-15 19:03:06 -07003395 map = PEEK(oparg); /* dict */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003396 assert(PyDict_CheckExact(map));
Martin Panter95f53c12016-07-18 08:23:26 +00003397 err = PyDict_SetItem(map, key, value); /* map[key] = value */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003398 Py_DECREF(value);
3399 Py_DECREF(key);
3400 if (err != 0)
3401 goto error;
3402 PREDICT(JUMP_ABSOLUTE);
3403 DISPATCH();
3404 }
3405
Benjamin Petersonddd19492018-09-16 22:38:02 -07003406 case TARGET(LOAD_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003407 PyObject *name = GETITEM(names, oparg);
3408 PyObject *owner = TOP();
Pablo Galindo109826c2020-10-20 06:22:44 +01003409
3410 PyTypeObject *type = Py_TYPE(owner);
3411 PyObject *res;
3412 PyObject **dictptr;
3413 PyObject *dict;
3414 _PyOpCodeOpt_LoadAttr *la;
3415
3416 OPCACHE_STAT_ATTR_TOTAL();
3417
3418 OPCACHE_CHECK();
3419 if (co_opcache != NULL && PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
3420 {
3421 if (co_opcache->optimized > 0) {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003422 // Fast path -- cache hit makes LOAD_ATTR ~30% faster.
Pablo Galindo109826c2020-10-20 06:22:44 +01003423 la = &co_opcache->u.la;
3424 if (la->type == type && la->tp_version_tag == type->tp_version_tag)
3425 {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003426 // Hint >= 0 is a dict index; hint == -1 is a dict miss.
3427 // Hint < -1 is an inverted slot offset: offset is strictly > 0,
3428 // so ~offset is strictly < -1 (assuming 2's complement).
3429 if (la->hint < -1) {
3430 // Even faster path -- slot hint.
3431 Py_ssize_t offset = ~la->hint;
3432 // fprintf(stderr, "Using hint for offset %zd\n", offset);
3433 char *addr = (char *)owner + offset;
3434 res = *(PyObject **)addr;
Pablo Galindo109826c2020-10-20 06:22:44 +01003435 if (res != NULL) {
Pablo Galindo109826c2020-10-20 06:22:44 +01003436 Py_INCREF(res);
3437 SET_TOP(res);
3438 Py_DECREF(owner);
Pablo Galindo109826c2020-10-20 06:22:44 +01003439 DISPATCH();
Pablo Galindo109826c2020-10-20 06:22:44 +01003440 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003441 // Else slot is NULL. Fall through to slow path to raise AttributeError(name).
3442 // Don't DEOPT, since the slot is still there.
Pablo Galindo109826c2020-10-20 06:22:44 +01003443 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003444 // Fast path for dict.
3445 assert(type->tp_dict != NULL);
3446 assert(type->tp_dictoffset > 0);
3447
3448 dictptr = (PyObject **) ((char *)owner + type->tp_dictoffset);
3449 dict = *dictptr;
3450 if (dict != NULL && PyDict_CheckExact(dict)) {
3451 Py_ssize_t hint = la->hint;
3452 Py_INCREF(dict);
3453 res = NULL;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003454 assert(!_PyErr_Occurred(tstate));
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003455 la->hint = _PyDict_GetItemHint((PyDictObject*)dict, name, hint, &res);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003456 if (res != NULL) {
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003457 assert(la->hint >= 0);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003458 if (la->hint == hint && hint >= 0) {
3459 // Our hint has helped -- cache hit.
3460 OPCACHE_STAT_ATTR_HIT();
3461 } else {
3462 // The hint we provided didn't work.
3463 // Maybe next time?
3464 OPCACHE_MAYBE_DEOPT_LOAD_ATTR();
3465 }
3466
3467 Py_INCREF(res);
3468 SET_TOP(res);
3469 Py_DECREF(owner);
3470 Py_DECREF(dict);
3471 DISPATCH();
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003472 }
3473 else {
3474 _PyErr_Clear(tstate);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003475 // This attribute can be missing sometimes;
3476 // we don't want to optimize this lookup.
3477 OPCACHE_DEOPT_LOAD_ATTR();
3478 Py_DECREF(dict);
3479 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003480 }
3481 else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003482 // There is no dict, or __dict__ doesn't satisfy PyDict_CheckExact.
3483 OPCACHE_DEOPT_LOAD_ATTR();
3484 }
Pablo Galindo109826c2020-10-20 06:22:44 +01003485 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003486 }
3487 else {
Pablo Galindo109826c2020-10-20 06:22:44 +01003488 // The type of the object has either been updated,
3489 // or is different. Maybe it will stabilize?
3490 OPCACHE_MAYBE_DEOPT_LOAD_ATTR();
3491 }
Pablo Galindo109826c2020-10-20 06:22:44 +01003492 OPCACHE_STAT_ATTR_MISS();
3493 }
3494
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003495 if (co_opcache != NULL && // co_opcache can be NULL after a DEOPT() call.
Pablo Galindo109826c2020-10-20 06:22:44 +01003496 type->tp_getattro == PyObject_GenericGetAttr)
3497 {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003498 if (type->tp_dict == NULL) {
3499 if (PyType_Ready(type) < 0) {
3500 Py_DECREF(owner);
3501 SET_TOP(NULL);
3502 goto error;
Pablo Galindo109826c2020-10-20 06:22:44 +01003503 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003504 }
3505 PyObject *descr = _PyType_Lookup(type, name);
3506 if (descr != NULL) {
3507 // We found an attribute with a data-like descriptor.
3508 PyTypeObject *dtype = Py_TYPE(descr);
3509 if (dtype == &PyMemberDescr_Type) { // It's a slot
3510 PyMemberDescrObject *member = (PyMemberDescrObject *)descr;
3511 struct PyMemberDef *dmem = member->d_member;
3512 if (dmem->type == T_OBJECT_EX) {
3513 Py_ssize_t offset = dmem->offset;
3514 assert(offset > 0); // 0 would be confused with dict hint == -1 (miss).
Pablo Galindo109826c2020-10-20 06:22:44 +01003515
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003516 if (co_opcache->optimized == 0) {
3517 // First time we optimize this opcode.
3518 OPCACHE_STAT_ATTR_OPT();
3519 co_opcache->optimized = OPCODE_CACHE_MAX_TRIES;
3520 // fprintf(stderr, "Setting hint for %s, offset %zd\n", dmem->name, offset);
3521 }
3522
3523 la = &co_opcache->u.la;
3524 la->type = type;
3525 la->tp_version_tag = type->tp_version_tag;
3526 la->hint = ~offset;
3527
3528 char *addr = (char *)owner + offset;
3529 res = *(PyObject **)addr;
Pablo Galindo109826c2020-10-20 06:22:44 +01003530 if (res != NULL) {
3531 Py_INCREF(res);
Pablo Galindo109826c2020-10-20 06:22:44 +01003532 Py_DECREF(owner);
3533 SET_TOP(res);
3534
Pablo Galindo109826c2020-10-20 06:22:44 +01003535 DISPATCH();
3536 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003537 // Else slot is NULL. Fall through to slow path to raise AttributeError(name).
Pablo Galindo109826c2020-10-20 06:22:44 +01003538 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003539 // Else it's a slot of a different type. We don't handle those.
3540 }
3541 // Else it's some other kind of descriptor that we don't handle.
3542 OPCACHE_DEOPT_LOAD_ATTR();
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003543 }
3544 else if (type->tp_dictoffset > 0) {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003545 // We found an instance with a __dict__.
3546 dictptr = (PyObject **) ((char *)owner + type->tp_dictoffset);
3547 dict = *dictptr;
3548
3549 if (dict != NULL && PyDict_CheckExact(dict)) {
3550 Py_INCREF(dict);
3551 res = NULL;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003552 assert(!_PyErr_Occurred(tstate));
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003553 Py_ssize_t hint = _PyDict_GetItemHint((PyDictObject*)dict, name, -1, &res);
3554 if (res != NULL) {
3555 Py_INCREF(res);
3556 Py_DECREF(dict);
3557 Py_DECREF(owner);
3558 SET_TOP(res);
3559
3560 if (co_opcache->optimized == 0) {
3561 // First time we optimize this opcode.
3562 OPCACHE_STAT_ATTR_OPT();
3563 co_opcache->optimized = OPCODE_CACHE_MAX_TRIES;
3564 }
3565
3566 la = &co_opcache->u.la;
3567 la->type = type;
3568 la->tp_version_tag = type->tp_version_tag;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003569 assert(hint >= 0);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003570 la->hint = hint;
3571
3572 DISPATCH();
3573 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003574 else {
3575 _PyErr_Clear(tstate);
3576 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003577 Py_DECREF(dict);
Pablo Galindo109826c2020-10-20 06:22:44 +01003578 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003579 // There is no dict, or __dict__ doesn't satisfy PyDict_CheckExact.
Pablo Galindo109826c2020-10-20 06:22:44 +01003580 OPCACHE_DEOPT_LOAD_ATTR();
3581 }
3582 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003583 // The object's class does not have a tp_dictoffset we can use.
Pablo Galindo109826c2020-10-20 06:22:44 +01003584 OPCACHE_DEOPT_LOAD_ATTR();
3585 }
3586 } else if (type->tp_getattro != PyObject_GenericGetAttr) {
3587 OPCACHE_DEOPT_LOAD_ATTR();
3588 }
3589 }
3590
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003591 // Slow path.
Pablo Galindo109826c2020-10-20 06:22:44 +01003592 res = PyObject_GetAttr(owner, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003593 Py_DECREF(owner);
3594 SET_TOP(res);
3595 if (res == NULL)
3596 goto error;
3597 DISPATCH();
3598 }
3599
Benjamin Petersonddd19492018-09-16 22:38:02 -07003600 case TARGET(COMPARE_OP): {
Mark Shannon9af0e472020-01-14 10:12:45 +00003601 assert(oparg <= Py_GE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003602 PyObject *right = POP();
3603 PyObject *left = TOP();
Mark Shannon9af0e472020-01-14 10:12:45 +00003604 PyObject *res = PyObject_RichCompare(left, right, oparg);
3605 SET_TOP(res);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003606 Py_DECREF(left);
3607 Py_DECREF(right);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003608 if (res == NULL)
3609 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 PREDICT(POP_JUMP_IF_FALSE);
3611 PREDICT(POP_JUMP_IF_TRUE);
3612 DISPATCH();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003613 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003614
Mark Shannon9af0e472020-01-14 10:12:45 +00003615 case TARGET(IS_OP): {
3616 PyObject *right = POP();
3617 PyObject *left = TOP();
3618 int res = (left == right)^oparg;
3619 PyObject *b = res ? Py_True : Py_False;
3620 Py_INCREF(b);
3621 SET_TOP(b);
3622 Py_DECREF(left);
3623 Py_DECREF(right);
3624 PREDICT(POP_JUMP_IF_FALSE);
3625 PREDICT(POP_JUMP_IF_TRUE);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003626 DISPATCH();
Mark Shannon9af0e472020-01-14 10:12:45 +00003627 }
3628
3629 case TARGET(CONTAINS_OP): {
3630 PyObject *right = POP();
3631 PyObject *left = POP();
3632 int res = PySequence_Contains(right, left);
3633 Py_DECREF(left);
3634 Py_DECREF(right);
3635 if (res < 0) {
3636 goto error;
3637 }
3638 PyObject *b = (res^oparg) ? Py_True : Py_False;
3639 Py_INCREF(b);
3640 PUSH(b);
3641 PREDICT(POP_JUMP_IF_FALSE);
3642 PREDICT(POP_JUMP_IF_TRUE);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003643 DISPATCH();
Mark Shannon9af0e472020-01-14 10:12:45 +00003644 }
3645
3646#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
3647 "BaseException is not allowed"
3648
3649 case TARGET(JUMP_IF_NOT_EXC_MATCH): {
3650 PyObject *right = POP();
3651 PyObject *left = POP();
3652 if (PyTuple_Check(right)) {
3653 Py_ssize_t i, length;
3654 length = PyTuple_GET_SIZE(right);
3655 for (i = 0; i < length; i++) {
3656 PyObject *exc = PyTuple_GET_ITEM(right, i);
3657 if (!PyExceptionClass_Check(exc)) {
3658 _PyErr_SetString(tstate, PyExc_TypeError,
3659 CANNOT_CATCH_MSG);
3660 Py_DECREF(left);
3661 Py_DECREF(right);
3662 goto error;
3663 }
3664 }
3665 }
3666 else {
3667 if (!PyExceptionClass_Check(right)) {
3668 _PyErr_SetString(tstate, PyExc_TypeError,
3669 CANNOT_CATCH_MSG);
3670 Py_DECREF(left);
3671 Py_DECREF(right);
3672 goto error;
3673 }
3674 }
3675 int res = PyErr_GivenExceptionMatches(left, right);
3676 Py_DECREF(left);
3677 Py_DECREF(right);
3678 if (res > 0) {
3679 /* Exception matches -- Do nothing */;
3680 }
3681 else if (res == 0) {
3682 JUMPTO(oparg);
3683 }
3684 else {
3685 goto error;
3686 }
3687 DISPATCH();
3688 }
3689
Benjamin Petersonddd19492018-09-16 22:38:02 -07003690 case TARGET(IMPORT_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003691 PyObject *name = GETITEM(names, oparg);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03003692 PyObject *fromlist = POP();
3693 PyObject *level = TOP();
3694 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02003695 res = import_name(tstate, f, name, fromlist, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03003696 Py_DECREF(level);
3697 Py_DECREF(fromlist);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003698 SET_TOP(res);
3699 if (res == NULL)
3700 goto error;
3701 DISPATCH();
3702 }
3703
Benjamin Petersonddd19492018-09-16 22:38:02 -07003704 case TARGET(IMPORT_STAR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003705 PyObject *from = POP(), *locals;
3706 int err;
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003707 if (PyFrame_FastToLocalsWithError(f) < 0) {
3708 Py_DECREF(from);
Victor Stinner41bb43a2013-10-29 01:19:37 +01003709 goto error;
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003710 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01003711
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003712 locals = f->f_locals;
3713 if (locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003714 _PyErr_SetString(tstate, PyExc_SystemError,
3715 "no locals found during 'import *'");
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003716 Py_DECREF(from);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003717 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003719 err = import_all_from(tstate, locals, from);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 PyFrame_LocalsToFast(f, 0);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003721 Py_DECREF(from);
3722 if (err != 0)
3723 goto error;
3724 DISPATCH();
3725 }
Guido van Rossum25831651993-05-19 14:50:45 +00003726
Benjamin Petersonddd19492018-09-16 22:38:02 -07003727 case TARGET(IMPORT_FROM): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003728 PyObject *name = GETITEM(names, oparg);
3729 PyObject *from = TOP();
3730 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02003731 res = import_from(tstate, from, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003732 PUSH(res);
3733 if (res == NULL)
3734 goto error;
3735 DISPATCH();
3736 }
Thomas Wouters52152252000-08-17 22:55:00 +00003737
Benjamin Petersonddd19492018-09-16 22:38:02 -07003738 case TARGET(JUMP_FORWARD): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 JUMPBY(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003740 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003741 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003742
Benjamin Petersonddd19492018-09-16 22:38:02 -07003743 case TARGET(POP_JUMP_IF_FALSE): {
3744 PREDICTED(POP_JUMP_IF_FALSE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003745 PyObject *cond = POP();
3746 int err;
3747 if (cond == Py_True) {
3748 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003749 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003751 if (cond == Py_False) {
3752 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003754 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003756 err = PyObject_IsTrue(cond);
3757 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 if (err > 0)
Adrian Wielgosik50c28502017-06-23 13:35:41 -07003759 ;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 else if (err == 0)
3761 JUMPTO(oparg);
3762 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003763 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003765 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003766
Benjamin Petersonddd19492018-09-16 22:38:02 -07003767 case TARGET(POP_JUMP_IF_TRUE): {
3768 PREDICTED(POP_JUMP_IF_TRUE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003769 PyObject *cond = POP();
3770 int err;
3771 if (cond == Py_False) {
3772 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003773 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003775 if (cond == Py_True) {
3776 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003778 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003780 err = PyObject_IsTrue(cond);
3781 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 if (err > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 JUMPTO(oparg);
3784 }
3785 else if (err == 0)
3786 ;
3787 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003788 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003790 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003791
Benjamin Petersonddd19492018-09-16 22:38:02 -07003792 case TARGET(JUMP_IF_FALSE_OR_POP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003793 PyObject *cond = TOP();
3794 int err;
3795 if (cond == Py_True) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003796 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003797 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003798 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003800 if (cond == Py_False) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003802 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003804 err = PyObject_IsTrue(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 if (err > 0) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003806 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003807 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 }
3809 else if (err == 0)
3810 JUMPTO(oparg);
3811 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003812 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003814 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003815
Benjamin Petersonddd19492018-09-16 22:38:02 -07003816 case TARGET(JUMP_IF_TRUE_OR_POP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003817 PyObject *cond = TOP();
3818 int err;
3819 if (cond == Py_False) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003820 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003821 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003822 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003824 if (cond == Py_True) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003826 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003828 err = PyObject_IsTrue(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 if (err > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 JUMPTO(oparg);
3831 }
3832 else if (err == 0) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003833 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003834 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 }
3836 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003837 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003839 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003840
Benjamin Petersonddd19492018-09-16 22:38:02 -07003841 case TARGET(JUMP_ABSOLUTE): {
3842 PREDICTED(JUMP_ABSOLUTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003844 CHECK_EVAL_BREAKER();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003846 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003847
Brandt Bucher145bf262021-02-26 14:51:55 -08003848 case TARGET(GET_LEN): {
3849 // PUSH(len(TOS))
3850 Py_ssize_t len_i = PyObject_Length(TOP());
3851 if (len_i < 0) {
3852 goto error;
3853 }
3854 PyObject *len_o = PyLong_FromSsize_t(len_i);
3855 if (len_o == NULL) {
3856 goto error;
3857 }
3858 PUSH(len_o);
3859 DISPATCH();
3860 }
3861
3862 case TARGET(MATCH_CLASS): {
3863 // Pop TOS. On success, set TOS to True and TOS1 to a tuple of
3864 // attributes. On failure, set TOS to False.
3865 PyObject *names = POP();
3866 PyObject *type = TOP();
3867 PyObject *subject = SECOND();
3868 assert(PyTuple_CheckExact(names));
3869 PyObject *attrs = match_class(tstate, subject, type, oparg, names);
3870 Py_DECREF(names);
3871 if (attrs) {
3872 // Success!
3873 assert(PyTuple_CheckExact(attrs));
3874 Py_DECREF(subject);
3875 SET_SECOND(attrs);
3876 }
3877 else if (_PyErr_Occurred(tstate)) {
3878 goto error;
3879 }
3880 Py_DECREF(type);
3881 SET_TOP(PyBool_FromLong(!!attrs));
3882 DISPATCH();
3883 }
3884
3885 case TARGET(MATCH_MAPPING): {
3886 // PUSH(isinstance(TOS, _collections_abc.Mapping))
3887 PyObject *subject = TOP();
3888 // Fast path for dicts:
3889 if (PyDict_Check(subject)) {
3890 Py_INCREF(Py_True);
3891 PUSH(Py_True);
3892 DISPATCH();
3893 }
3894 // Lazily import _collections_abc.Mapping, and keep it handy on the
3895 // PyInterpreterState struct (it gets cleaned up at exit):
3896 PyInterpreterState *interp = PyInterpreterState_Get();
3897 if (interp->map_abc == NULL) {
3898 PyObject *abc = PyImport_ImportModule("_collections_abc");
3899 if (abc == NULL) {
3900 goto error;
3901 }
3902 interp->map_abc = PyObject_GetAttrString(abc, "Mapping");
3903 if (interp->map_abc == NULL) {
3904 goto error;
3905 }
3906 }
3907 int match = PyObject_IsInstance(subject, interp->map_abc);
3908 if (match < 0) {
3909 goto error;
3910 }
3911 PUSH(PyBool_FromLong(match));
3912 DISPATCH();
3913 }
3914
3915 case TARGET(MATCH_SEQUENCE): {
3916 // PUSH(not isinstance(TOS, (bytearray, bytes, str))
3917 // and isinstance(TOS, _collections_abc.Sequence))
3918 PyObject *subject = TOP();
3919 // Fast path for lists and tuples:
3920 if (PyType_FastSubclass(Py_TYPE(subject),
3921 Py_TPFLAGS_LIST_SUBCLASS |
3922 Py_TPFLAGS_TUPLE_SUBCLASS))
3923 {
3924 Py_INCREF(Py_True);
3925 PUSH(Py_True);
3926 DISPATCH();
3927 }
3928 // Bail on some possible Sequences that we intentionally exclude:
3929 if (PyType_FastSubclass(Py_TYPE(subject),
3930 Py_TPFLAGS_BYTES_SUBCLASS |
3931 Py_TPFLAGS_UNICODE_SUBCLASS) ||
3932 PyByteArray_Check(subject))
3933 {
3934 Py_INCREF(Py_False);
3935 PUSH(Py_False);
3936 DISPATCH();
3937 }
3938 // Lazily import _collections_abc.Sequence, and keep it handy on the
3939 // PyInterpreterState struct (it gets cleaned up at exit):
3940 PyInterpreterState *interp = PyInterpreterState_Get();
3941 if (interp->seq_abc == NULL) {
3942 PyObject *abc = PyImport_ImportModule("_collections_abc");
3943 if (abc == NULL) {
3944 goto error;
3945 }
3946 interp->seq_abc = PyObject_GetAttrString(abc, "Sequence");
3947 if (interp->seq_abc == NULL) {
3948 goto error;
3949 }
3950 }
3951 int match = PyObject_IsInstance(subject, interp->seq_abc);
3952 if (match < 0) {
3953 goto error;
3954 }
3955 PUSH(PyBool_FromLong(match));
3956 DISPATCH();
3957 }
3958
3959 case TARGET(MATCH_KEYS): {
3960 // On successful match for all keys, PUSH(values) and PUSH(True).
3961 // Otherwise, PUSH(None) and PUSH(False).
3962 PyObject *keys = TOP();
3963 PyObject *subject = SECOND();
3964 PyObject *values_or_none = match_keys(tstate, subject, keys);
3965 if (values_or_none == NULL) {
3966 goto error;
3967 }
3968 PUSH(values_or_none);
3969 if (values_or_none == Py_None) {
3970 Py_INCREF(Py_False);
3971 PUSH(Py_False);
3972 DISPATCH();
3973 }
3974 assert(PyTuple_CheckExact(values_or_none));
3975 Py_INCREF(Py_True);
3976 PUSH(Py_True);
3977 DISPATCH();
3978 }
3979
3980 case TARGET(COPY_DICT_WITHOUT_KEYS): {
3981 // rest = dict(TOS1)
3982 // for key in TOS:
3983 // del rest[key]
3984 // SET_TOP(rest)
3985 PyObject *keys = TOP();
3986 PyObject *subject = SECOND();
3987 PyObject *rest = PyDict_New();
3988 if (rest == NULL || PyDict_Update(rest, subject)) {
3989 Py_XDECREF(rest);
3990 goto error;
3991 }
3992 // This may seem a bit inefficient, but keys is rarely big enough to
3993 // actually impact runtime.
3994 assert(PyTuple_CheckExact(keys));
3995 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(keys); i++) {
3996 if (PyDict_DelItem(rest, PyTuple_GET_ITEM(keys, i))) {
3997 Py_DECREF(rest);
3998 goto error;
3999 }
4000 }
4001 Py_DECREF(keys);
4002 SET_TOP(rest);
4003 DISPATCH();
4004 }
4005
Benjamin Petersonddd19492018-09-16 22:38:02 -07004006 case TARGET(GET_ITER): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 /* before: [obj]; after [getiter(obj)] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004008 PyObject *iterable = TOP();
Yury Selivanov5376ba92015-06-22 12:19:30 -04004009 PyObject *iter = PyObject_GetIter(iterable);
4010 Py_DECREF(iterable);
4011 SET_TOP(iter);
4012 if (iter == NULL)
4013 goto error;
4014 PREDICT(FOR_ITER);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004015 PREDICT(CALL_FUNCTION);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004016 DISPATCH();
4017 }
4018
Benjamin Petersonddd19492018-09-16 22:38:02 -07004019 case TARGET(GET_YIELD_FROM_ITER): {
Yury Selivanov5376ba92015-06-22 12:19:30 -04004020 /* before: [obj]; after [getiter(obj)] */
4021 PyObject *iterable = TOP();
Yury Selivanov75445082015-05-11 22:57:16 -04004022 PyObject *iter;
Yury Selivanov5376ba92015-06-22 12:19:30 -04004023 if (PyCoro_CheckExact(iterable)) {
4024 /* `iterable` is a coroutine */
4025 if (!(co->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))) {
4026 /* and it is used in a 'yield from' expression of a
4027 regular generator. */
4028 Py_DECREF(iterable);
4029 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02004030 _PyErr_SetString(tstate, PyExc_TypeError,
4031 "cannot 'yield from' a coroutine object "
4032 "in a non-coroutine generator");
Yury Selivanov5376ba92015-06-22 12:19:30 -04004033 goto error;
4034 }
4035 }
4036 else if (!PyGen_CheckExact(iterable)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004037 /* `iterable` is not a generator. */
4038 iter = PyObject_GetIter(iterable);
4039 Py_DECREF(iterable);
4040 SET_TOP(iter);
4041 if (iter == NULL)
4042 goto error;
4043 }
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004044 PREDICT(LOAD_CONST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004045 DISPATCH();
4046 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00004047
Benjamin Petersonddd19492018-09-16 22:38:02 -07004048 case TARGET(FOR_ITER): {
4049 PREDICTED(FOR_ITER);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 /* before: [iter]; after: [iter, iter()] *or* [] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004051 PyObject *iter = TOP();
Victor Stinnera102ed72020-02-07 02:24:48 +01004052 PyObject *next = (*Py_TYPE(iter)->tp_iternext)(iter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004053 if (next != NULL) {
4054 PUSH(next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 PREDICT(STORE_FAST);
4056 PREDICT(UNPACK_SEQUENCE);
4057 DISPATCH();
4058 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004059 if (_PyErr_Occurred(tstate)) {
4060 if (!_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004061 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02004062 }
4063 else if (tstate->c_tracefunc != NULL) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00004064 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, &trace_info);
Victor Stinner438a12d2019-05-24 17:01:38 +02004065 }
4066 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 }
4068 /* iterator ended normally */
costypetrisor8ed317f2018-07-31 20:55:14 +00004069 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004070 Py_DECREF(iter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 JUMPBY(oparg);
4072 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004073 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00004074
Benjamin Petersonddd19492018-09-16 22:38:02 -07004075 case TARGET(SETUP_FINALLY): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004076 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 STACK_LEVEL());
4078 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004079 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004080
Benjamin Petersonddd19492018-09-16 22:38:02 -07004081 case TARGET(BEFORE_ASYNC_WITH): {
Yury Selivanov75445082015-05-11 22:57:16 -04004082 _Py_IDENTIFIER(__aenter__);
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004083 _Py_IDENTIFIER(__aexit__);
Yury Selivanov75445082015-05-11 22:57:16 -04004084 PyObject *mgr = TOP();
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004085 PyObject *enter = special_lookup(tstate, mgr, &PyId___aenter__);
Yury Selivanov75445082015-05-11 22:57:16 -04004086 PyObject *res;
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004087 if (enter == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04004088 goto error;
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004089 }
4090 PyObject *exit = special_lookup(tstate, mgr, &PyId___aexit__);
4091 if (exit == NULL) {
4092 Py_DECREF(enter);
4093 goto error;
4094 }
Yury Selivanov75445082015-05-11 22:57:16 -04004095 SET_TOP(exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004096 Py_DECREF(mgr);
Victor Stinnerf17c3de2016-12-06 18:46:19 +01004097 res = _PyObject_CallNoArg(enter);
Yury Selivanov75445082015-05-11 22:57:16 -04004098 Py_DECREF(enter);
4099 if (res == NULL)
4100 goto error;
4101 PUSH(res);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004102 PREDICT(GET_AWAITABLE);
Yury Selivanov75445082015-05-11 22:57:16 -04004103 DISPATCH();
4104 }
4105
Benjamin Petersonddd19492018-09-16 22:38:02 -07004106 case TARGET(SETUP_ASYNC_WITH): {
Yury Selivanov75445082015-05-11 22:57:16 -04004107 PyObject *res = POP();
4108 /* Setup the finally block before pushing the result
4109 of __aenter__ on the stack. */
4110 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
4111 STACK_LEVEL());
4112 PUSH(res);
4113 DISPATCH();
4114 }
4115
Benjamin Petersonddd19492018-09-16 22:38:02 -07004116 case TARGET(SETUP_WITH): {
Benjamin Petersonce798522012-01-22 11:24:29 -05004117 _Py_IDENTIFIER(__enter__);
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004118 _Py_IDENTIFIER(__exit__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004119 PyObject *mgr = TOP();
Victor Stinner438a12d2019-05-24 17:01:38 +02004120 PyObject *enter = special_lookup(tstate, mgr, &PyId___enter__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004121 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02004122 if (enter == NULL) {
Raymond Hettingera3fec152016-11-21 17:24:23 -08004123 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02004124 }
4125 PyObject *exit = special_lookup(tstate, mgr, &PyId___exit__);
Raymond Hettinger64e2f9a2016-11-22 11:50:40 -08004126 if (exit == NULL) {
4127 Py_DECREF(enter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004128 goto error;
Raymond Hettinger64e2f9a2016-11-22 11:50:40 -08004129 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004130 SET_TOP(exit);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004131 Py_DECREF(mgr);
Victor Stinnerf17c3de2016-12-06 18:46:19 +01004132 res = _PyObject_CallNoArg(enter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004133 Py_DECREF(enter);
4134 if (res == NULL)
4135 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 /* Setup the finally block before pushing the result
4137 of __enter__ on the stack. */
4138 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
4139 STACK_LEVEL());
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004140
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004141 PUSH(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 DISPATCH();
4143 }
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004144
Mark Shannonfee55262019-11-21 09:11:43 +00004145 case TARGET(WITH_EXCEPT_START): {
4146 /* At the top of the stack are 7 values:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 - (TOP, SECOND, THIRD) = exc_info()
Mark Shannonfee55262019-11-21 09:11:43 +00004148 - (FOURTH, FIFTH, SIXTH) = previous exception for EXCEPT_HANDLER
4149 - SEVENTH: the context.__exit__ bound method
4150 We call SEVENTH(TOP, SECOND, THIRD).
4151 Then we push again the TOP exception and the __exit__
4152 return value.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 PyObject *exit_func;
Victor Stinner842cfff2016-12-01 14:45:31 +01004155 PyObject *exc, *val, *tb, *res;
4156
Victor Stinner842cfff2016-12-01 14:45:31 +01004157 exc = TOP();
Mark Shannonfee55262019-11-21 09:11:43 +00004158 val = SECOND();
4159 tb = THIRD();
4160 assert(exc != Py_None);
4161 assert(!PyLong_Check(exc));
4162 exit_func = PEEK(7);
Jeroen Demeyer469d1a72019-07-03 12:52:21 +02004163 PyObject *stack[4] = {NULL, exc, val, tb};
Petr Viktorinffd97532020-02-11 17:46:57 +01004164 res = PyObject_Vectorcall(exit_func, stack + 1,
Jeroen Demeyer469d1a72019-07-03 12:52:21 +02004165 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004166 if (res == NULL)
4167 goto error;
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00004168
Yury Selivanov75445082015-05-11 22:57:16 -04004169 PUSH(res);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004170 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00004172
Benjamin Petersonddd19492018-09-16 22:38:02 -07004173 case TARGET(LOAD_METHOD): {
Andreyb021ba52019-04-29 14:33:26 +10004174 /* Designed to work in tandem with CALL_METHOD. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004175 PyObject *name = GETITEM(names, oparg);
4176 PyObject *obj = TOP();
4177 PyObject *meth = NULL;
4178
4179 int meth_found = _PyObject_GetMethod(obj, name, &meth);
4180
Yury Selivanovf2392132016-12-13 19:03:51 -05004181 if (meth == NULL) {
4182 /* Most likely attribute wasn't found. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004183 goto error;
4184 }
4185
4186 if (meth_found) {
INADA Naoki015bce62017-01-16 17:23:30 +09004187 /* We can bypass temporary bound method object.
4188 meth is unbound method and obj is self.
Victor Stinnera8cb5152017-01-18 14:12:51 +01004189
INADA Naoki015bce62017-01-16 17:23:30 +09004190 meth | self | arg1 | ... | argN
4191 */
4192 SET_TOP(meth);
4193 PUSH(obj); // self
Yury Selivanovf2392132016-12-13 19:03:51 -05004194 }
4195 else {
INADA Naoki015bce62017-01-16 17:23:30 +09004196 /* meth is not an unbound method (but a regular attr, or
4197 something was returned by a descriptor protocol). Set
4198 the second element of the stack to NULL, to signal
Yury Selivanovf2392132016-12-13 19:03:51 -05004199 CALL_METHOD that it's not a method call.
INADA Naoki015bce62017-01-16 17:23:30 +09004200
4201 NULL | meth | arg1 | ... | argN
Yury Selivanovf2392132016-12-13 19:03:51 -05004202 */
INADA Naoki015bce62017-01-16 17:23:30 +09004203 SET_TOP(NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004204 Py_DECREF(obj);
INADA Naoki015bce62017-01-16 17:23:30 +09004205 PUSH(meth);
Yury Selivanovf2392132016-12-13 19:03:51 -05004206 }
4207 DISPATCH();
4208 }
4209
Benjamin Petersonddd19492018-09-16 22:38:02 -07004210 case TARGET(CALL_METHOD): {
Yury Selivanovf2392132016-12-13 19:03:51 -05004211 /* Designed to work in tamdem with LOAD_METHOD. */
INADA Naoki015bce62017-01-16 17:23:30 +09004212 PyObject **sp, *res, *meth;
Yury Selivanovf2392132016-12-13 19:03:51 -05004213
4214 sp = stack_pointer;
4215
INADA Naoki015bce62017-01-16 17:23:30 +09004216 meth = PEEK(oparg + 2);
4217 if (meth == NULL) {
4218 /* `meth` is NULL when LOAD_METHOD thinks that it's not
4219 a method call.
Yury Selivanovf2392132016-12-13 19:03:51 -05004220
4221 Stack layout:
4222
INADA Naoki015bce62017-01-16 17:23:30 +09004223 ... | NULL | callable | arg1 | ... | argN
4224 ^- TOP()
4225 ^- (-oparg)
4226 ^- (-oparg-1)
4227 ^- (-oparg-2)
Yury Selivanovf2392132016-12-13 19:03:51 -05004228
Ville Skyttä49b27342017-08-03 09:00:59 +03004229 `callable` will be POPed by call_function.
INADA Naoki015bce62017-01-16 17:23:30 +09004230 NULL will will be POPed manually later.
Yury Selivanovf2392132016-12-13 19:03:51 -05004231 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00004232 res = call_function(tstate, &trace_info, &sp, oparg, NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004233 stack_pointer = sp;
INADA Naoki015bce62017-01-16 17:23:30 +09004234 (void)POP(); /* POP the NULL. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004235 }
4236 else {
4237 /* This is a method call. Stack layout:
4238
INADA Naoki015bce62017-01-16 17:23:30 +09004239 ... | method | self | arg1 | ... | argN
Yury Selivanovf2392132016-12-13 19:03:51 -05004240 ^- TOP()
4241 ^- (-oparg)
INADA Naoki015bce62017-01-16 17:23:30 +09004242 ^- (-oparg-1)
4243 ^- (-oparg-2)
Yury Selivanovf2392132016-12-13 19:03:51 -05004244
INADA Naoki015bce62017-01-16 17:23:30 +09004245 `self` and `method` will be POPed by call_function.
Yury Selivanovf2392132016-12-13 19:03:51 -05004246 We'll be passing `oparg + 1` to call_function, to
INADA Naoki015bce62017-01-16 17:23:30 +09004247 make it accept the `self` as a first argument.
Yury Selivanovf2392132016-12-13 19:03:51 -05004248 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00004249 res = call_function(tstate, &trace_info, &sp, oparg + 1, NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004250 stack_pointer = sp;
4251 }
4252
4253 PUSH(res);
4254 if (res == NULL)
4255 goto error;
Mark Shannon4958f5d2021-03-24 17:56:12 +00004256 CHECK_EVAL_BREAKER();
Yury Selivanovf2392132016-12-13 19:03:51 -05004257 DISPATCH();
4258 }
4259
Benjamin Petersonddd19492018-09-16 22:38:02 -07004260 case TARGET(CALL_FUNCTION): {
4261 PREDICTED(CALL_FUNCTION);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004262 PyObject **sp, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 sp = stack_pointer;
Mark Shannon8e1b4062021-03-05 14:45:50 +00004264 res = call_function(tstate, &trace_info, &sp, oparg, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 stack_pointer = sp;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004266 PUSH(res);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004267 if (res == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004268 goto error;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004269 }
Mark Shannon4958f5d2021-03-24 17:56:12 +00004270 CHECK_EVAL_BREAKER();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004271 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004273
Benjamin Petersonddd19492018-09-16 22:38:02 -07004274 case TARGET(CALL_FUNCTION_KW): {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004275 PyObject **sp, *res, *names;
4276
4277 names = POP();
Jeroen Demeyer05677862019-08-16 12:41:27 +02004278 assert(PyTuple_Check(names));
4279 assert(PyTuple_GET_SIZE(names) <= oparg);
4280 /* We assume without checking that names contains only strings */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 sp = stack_pointer;
Mark Shannon8e1b4062021-03-05 14:45:50 +00004282 res = call_function(tstate, &trace_info, &sp, oparg, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 stack_pointer = sp;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004284 PUSH(res);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004285 Py_DECREF(names);
4286
4287 if (res == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004288 goto error;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004289 }
Mark Shannon4958f5d2021-03-24 17:56:12 +00004290 CHECK_EVAL_BREAKER();
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004291 DISPATCH();
4292 }
4293
Benjamin Petersonddd19492018-09-16 22:38:02 -07004294 case TARGET(CALL_FUNCTION_EX): {
Brandt Bucherf185a732019-09-28 17:12:49 -07004295 PREDICTED(CALL_FUNCTION_EX);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004296 PyObject *func, *callargs, *kwargs = NULL, *result;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004297 if (oparg & 0x01) {
4298 kwargs = POP();
Serhiy Storchakab7281052016-09-12 00:52:40 +03004299 if (!PyDict_CheckExact(kwargs)) {
4300 PyObject *d = PyDict_New();
4301 if (d == NULL)
4302 goto error;
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02004303 if (_PyDict_MergeEx(d, kwargs, 2) < 0) {
Serhiy Storchakab7281052016-09-12 00:52:40 +03004304 Py_DECREF(d);
Victor Stinner438a12d2019-05-24 17:01:38 +02004305 format_kwargs_error(tstate, SECOND(), kwargs);
Victor Stinnereece2222016-09-12 11:16:37 +02004306 Py_DECREF(kwargs);
Serhiy Storchakab7281052016-09-12 00:52:40 +03004307 goto error;
4308 }
4309 Py_DECREF(kwargs);
4310 kwargs = d;
4311 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004312 assert(PyDict_CheckExact(kwargs));
4313 }
4314 callargs = POP();
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004315 func = TOP();
Serhiy Storchaka63dc5482016-09-22 19:41:20 +03004316 if (!PyTuple_CheckExact(callargs)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02004317 if (check_args_iterable(tstate, func, callargs) < 0) {
Victor Stinnereece2222016-09-12 11:16:37 +02004318 Py_DECREF(callargs);
Serhiy Storchakab7281052016-09-12 00:52:40 +03004319 goto error;
4320 }
4321 Py_SETREF(callargs, PySequence_Tuple(callargs));
4322 if (callargs == NULL) {
4323 goto error;
4324 }
4325 }
Serhiy Storchaka63dc5482016-09-22 19:41:20 +03004326 assert(PyTuple_CheckExact(callargs));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004327
Mark Shannon8e1b4062021-03-05 14:45:50 +00004328 result = do_call_core(tstate, &trace_info, func, callargs, kwargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004329 Py_DECREF(func);
4330 Py_DECREF(callargs);
4331 Py_XDECREF(kwargs);
4332
4333 SET_TOP(result);
4334 if (result == NULL) {
4335 goto error;
4336 }
Mark Shannon4958f5d2021-03-24 17:56:12 +00004337 CHECK_EVAL_BREAKER();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004338 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004340
Benjamin Petersonddd19492018-09-16 22:38:02 -07004341 case TARGET(MAKE_FUNCTION): {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004342 PyObject *qualname = POP();
4343 PyObject *codeobj = POP();
4344 PyFunctionObject *func = (PyFunctionObject *)
4345 PyFunction_NewWithQualName(codeobj, f->f_globals, qualname);
Guido van Rossum4f72a782006-10-27 23:31:49 +00004346
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004347 Py_DECREF(codeobj);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004348 Py_DECREF(qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004349 if (func == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004350 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 }
Neal Norwitzc1505362006-12-28 06:47:50 +00004352
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004353 if (oparg & 0x08) {
4354 assert(PyTuple_CheckExact(TOP()));
Mark Shannond6c33fb2021-01-29 13:24:55 +00004355 func->func_closure = POP();
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004356 }
4357 if (oparg & 0x04) {
Yurii Karabas73019792020-11-25 12:43:18 +02004358 assert(PyTuple_CheckExact(TOP()));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004359 func->func_annotations = POP();
4360 }
4361 if (oparg & 0x02) {
4362 assert(PyDict_CheckExact(TOP()));
4363 func->func_kwdefaults = POP();
4364 }
4365 if (oparg & 0x01) {
4366 assert(PyTuple_CheckExact(TOP()));
4367 func->func_defaults = POP();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 }
Neal Norwitzc1505362006-12-28 06:47:50 +00004369
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004370 PUSH((PyObject *)func);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004371 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004373
Benjamin Petersonddd19492018-09-16 22:38:02 -07004374 case TARGET(BUILD_SLICE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004375 PyObject *start, *stop, *step, *slice;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 if (oparg == 3)
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004377 step = POP();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004379 step = NULL;
4380 stop = POP();
4381 start = TOP();
4382 slice = PySlice_New(start, stop, step);
4383 Py_DECREF(start);
4384 Py_DECREF(stop);
4385 Py_XDECREF(step);
4386 SET_TOP(slice);
4387 if (slice == NULL)
4388 goto error;
4389 DISPATCH();
4390 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004391
Benjamin Petersonddd19492018-09-16 22:38:02 -07004392 case TARGET(FORMAT_VALUE): {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004393 /* Handles f-string value formatting. */
4394 PyObject *result;
4395 PyObject *fmt_spec;
4396 PyObject *value;
4397 PyObject *(*conv_fn)(PyObject *);
4398 int which_conversion = oparg & FVC_MASK;
4399 int have_fmt_spec = (oparg & FVS_MASK) == FVS_HAVE_SPEC;
4400
4401 fmt_spec = have_fmt_spec ? POP() : NULL;
Eric V. Smith135d5f42016-02-05 18:23:08 -05004402 value = POP();
Eric V. Smitha78c7952015-11-03 12:45:05 -05004403
4404 /* See if any conversion is specified. */
4405 switch (which_conversion) {
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004406 case FVC_NONE: conv_fn = NULL; break;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004407 case FVC_STR: conv_fn = PyObject_Str; break;
4408 case FVC_REPR: conv_fn = PyObject_Repr; break;
4409 case FVC_ASCII: conv_fn = PyObject_ASCII; break;
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004410 default:
Victor Stinner438a12d2019-05-24 17:01:38 +02004411 _PyErr_Format(tstate, PyExc_SystemError,
4412 "unexpected conversion flag %d",
4413 which_conversion);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004414 goto error;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004415 }
4416
4417 /* If there's a conversion function, call it and replace
4418 value with that result. Otherwise, just use value,
4419 without conversion. */
Eric V. Smitheb588a12016-02-05 18:26:20 -05004420 if (conv_fn != NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004421 result = conv_fn(value);
4422 Py_DECREF(value);
Eric V. Smitheb588a12016-02-05 18:26:20 -05004423 if (result == NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004424 Py_XDECREF(fmt_spec);
4425 goto error;
4426 }
4427 value = result;
4428 }
4429
4430 /* If value is a unicode object, and there's no fmt_spec,
4431 then we know the result of format(value) is value
4432 itself. In that case, skip calling format(). I plan to
4433 move this optimization in to PyObject_Format()
4434 itself. */
4435 if (PyUnicode_CheckExact(value) && fmt_spec == NULL) {
4436 /* Do nothing, just transfer ownership to result. */
4437 result = value;
4438 } else {
4439 /* Actually call format(). */
4440 result = PyObject_Format(value, fmt_spec);
4441 Py_DECREF(value);
4442 Py_XDECREF(fmt_spec);
Eric V. Smitheb588a12016-02-05 18:26:20 -05004443 if (result == NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004444 goto error;
Eric V. Smitheb588a12016-02-05 18:26:20 -05004445 }
Eric V. Smitha78c7952015-11-03 12:45:05 -05004446 }
4447
Eric V. Smith135d5f42016-02-05 18:23:08 -05004448 PUSH(result);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004449 DISPATCH();
4450 }
4451
Benjamin Petersonddd19492018-09-16 22:38:02 -07004452 case TARGET(EXTENDED_ARG): {
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03004453 int oldoparg = oparg;
4454 NEXTOPARG();
4455 oparg |= oldoparg << 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 goto dispatch_opcode;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004457 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004458
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004459
Antoine Pitrou042b1282010-08-13 21:15:58 +00004460#if USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 _unknown_opcode:
Antoine Pitroub52ec782009-01-25 16:34:23 +00004462#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 default:
4464 fprintf(stderr,
4465 "XXX lineno: %d, opcode: %d\n",
4466 PyFrame_GetLineNumber(f),
4467 opcode);
Victor Stinner438a12d2019-05-24 17:01:38 +02004468 _PyErr_SetString(tstate, PyExc_SystemError, "unknown opcode");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004469 goto error;
Guido van Rossum04691fc1992-08-12 15:35:34 +00004470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 } /* switch */
Guido van Rossum374a9221991-04-04 10:40:29 +00004472
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004473 /* This should never be reached. Every opcode should end with DISPATCH()
4474 or goto error. */
Barry Warsawb2e57942017-09-14 18:13:16 -07004475 Py_UNREACHABLE();
Guido van Rossumac7be682001-01-17 15:42:30 +00004476
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004477error:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004478 /* Double-check exception status. */
Victor Stinner365b6932013-07-12 00:11:58 +02004479#ifdef NDEBUG
Victor Stinner438a12d2019-05-24 17:01:38 +02004480 if (!_PyErr_Occurred(tstate)) {
4481 _PyErr_SetString(tstate, PyExc_SystemError,
4482 "error return without exception set");
4483 }
Victor Stinner365b6932013-07-12 00:11:58 +02004484#else
Victor Stinner438a12d2019-05-24 17:01:38 +02004485 assert(_PyErr_Occurred(tstate));
Victor Stinner365b6932013-07-12 00:11:58 +02004486#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00004487
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004488 /* Log traceback info. */
4489 PyTraceBack_Here(f);
Guido van Rossumac7be682001-01-17 15:42:30 +00004490
Mark Shannoncb9879b2020-07-17 11:44:23 +01004491 if (tstate->c_tracefunc != NULL) {
4492 /* Make sure state is set to FRAME_EXECUTING for tracing */
4493 assert(f->f_state == FRAME_EXECUTING);
4494 f->f_state = FRAME_UNWINDING;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01004495 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004496 tstate, f, &trace_info);
Mark Shannoncb9879b2020-07-17 11:44:23 +01004497 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004498exception_unwind:
Mark Shannoncb9879b2020-07-17 11:44:23 +01004499 f->f_state = FRAME_UNWINDING;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004500 /* Unwind stacks if an exception occurred */
4501 while (f->f_iblock > 0) {
4502 /* Pop the current block. */
4503 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00004504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 if (b->b_type == EXCEPT_HANDLER) {
4506 UNWIND_EXCEPT_HANDLER(b);
4507 continue;
4508 }
4509 UNWIND_BLOCK(b);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004510 if (b->b_type == SETUP_FINALLY) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 PyObject *exc, *val, *tb;
4512 int handler = b->b_handler;
Mark Shannonae3087c2017-10-22 22:41:51 +01004513 _PyErr_StackItem *exc_info = tstate->exc_info;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 /* Beware, this invalidates all b->b_* fields */
Mark Shannonbf353f32020-12-17 13:55:28 +00004515 PyFrame_BlockSetup(f, EXCEPT_HANDLER, f->f_lasti, STACK_LEVEL());
Mark Shannonae3087c2017-10-22 22:41:51 +01004516 PUSH(exc_info->exc_traceback);
4517 PUSH(exc_info->exc_value);
4518 if (exc_info->exc_type != NULL) {
4519 PUSH(exc_info->exc_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 }
4521 else {
4522 Py_INCREF(Py_None);
4523 PUSH(Py_None);
4524 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004525 _PyErr_Fetch(tstate, &exc, &val, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 /* Make the raw exception data
4527 available to the handler,
4528 so a program can emulate the
4529 Python main loop. */
Victor Stinner438a12d2019-05-24 17:01:38 +02004530 _PyErr_NormalizeException(tstate, &exc, &val, &tb);
Victor Stinner7eab0d02013-07-15 21:16:27 +02004531 if (tb != NULL)
4532 PyException_SetTraceback(val, tb);
4533 else
4534 PyException_SetTraceback(val, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 Py_INCREF(exc);
Mark Shannonae3087c2017-10-22 22:41:51 +01004536 exc_info->exc_type = exc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 Py_INCREF(val);
Mark Shannonae3087c2017-10-22 22:41:51 +01004538 exc_info->exc_value = val;
4539 exc_info->exc_traceback = tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 if (tb == NULL)
4541 tb = Py_None;
4542 Py_INCREF(tb);
4543 PUSH(tb);
4544 PUSH(val);
4545 PUSH(exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 JUMPTO(handler);
Victor Stinnerdab84232020-03-17 18:56:44 +01004547 if (_Py_TracingPossible(ceval2)) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00004548 trace_info.instr_prev = INT_MAX;
Mark Shannonfee55262019-11-21 09:11:43 +00004549 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004550 /* Resume normal execution */
Mark Shannoncb9879b2020-07-17 11:44:23 +01004551 f->f_state = FRAME_EXECUTING;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004552 goto main_loop;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 }
4554 } /* unwind stack */
Guido van Rossum374a9221991-04-04 10:40:29 +00004555
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004556 /* End the loop as we still have an error */
4557 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 } /* main loop */
Guido van Rossumac7be682001-01-17 15:42:30 +00004559
Pablo Galindof00828a2019-05-09 16:52:02 +01004560 assert(retval == NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02004561 assert(_PyErr_Occurred(tstate));
Pablo Galindof00828a2019-05-09 16:52:02 +01004562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 /* Pop remaining stack entries. */
4564 while (!EMPTY()) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004565 PyObject *o = POP();
4566 Py_XDECREF(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 }
Mark Shannoncb9879b2020-07-17 11:44:23 +01004568 f->f_stackdepth = 0;
4569 f->f_state = FRAME_RAISED;
Mark Shannone7c9f4a2020-01-13 12:51:26 +00004570exiting:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 if (tstate->use_tracing) {
Benjamin Peterson51f46162013-01-23 08:38:47 -05004572 if (tstate->c_tracefunc) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004573 if (call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004574 tstate, f, &trace_info, PyTrace_RETURN, retval)) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004575 Py_CLEAR(retval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 }
4577 }
4578 if (tstate->c_profilefunc) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004579 if (call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004580 tstate, f, &trace_info, PyTrace_RETURN, retval)) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004581 Py_CLEAR(retval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 }
4583 }
4584 }
Guido van Rossuma4240131997-01-21 21:18:36 +00004585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 /* pop frame */
Thomas Woutersce272b62007-09-19 21:19:28 +00004587exit_eval_frame:
Łukasz Langaa785c872016-09-09 17:37:37 -07004588 if (PyDTrace_FUNCTION_RETURN_ENABLED())
4589 dtrace_function_return(f);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01004590 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 tstate->frame = f->f_back;
Guido van Rossumac7be682001-01-17 15:42:30 +00004592
Victor Stinner0b72b232020-03-12 23:18:39 +01004593 return _Py_CheckFunctionResult(tstate, NULL, retval, __func__);
Guido van Rossum374a9221991-04-04 10:40:29 +00004594}
4595
Benjamin Petersonb204a422011-06-05 22:04:07 -05004596static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004597format_missing(PyThreadState *tstate, const char *kind,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004598 PyCodeObject *co, PyObject *names, PyObject *qualname)
Benjamin Petersone109c702011-06-24 09:37:26 -05004599{
4600 int err;
4601 Py_ssize_t len = PyList_GET_SIZE(names);
4602 PyObject *name_str, *comma, *tail, *tmp;
4603
4604 assert(PyList_CheckExact(names));
4605 assert(len >= 1);
4606 /* Deal with the joys of natural language. */
4607 switch (len) {
4608 case 1:
4609 name_str = PyList_GET_ITEM(names, 0);
4610 Py_INCREF(name_str);
4611 break;
4612 case 2:
4613 name_str = PyUnicode_FromFormat("%U and %U",
4614 PyList_GET_ITEM(names, len - 2),
4615 PyList_GET_ITEM(names, len - 1));
4616 break;
4617 default:
4618 tail = PyUnicode_FromFormat(", %U, and %U",
4619 PyList_GET_ITEM(names, len - 2),
4620 PyList_GET_ITEM(names, len - 1));
Benjamin Petersond1ab6082012-06-01 11:18:22 -07004621 if (tail == NULL)
4622 return;
Benjamin Petersone109c702011-06-24 09:37:26 -05004623 /* Chop off the last two objects in the list. This shouldn't actually
4624 fail, but we can't be too careful. */
4625 err = PyList_SetSlice(names, len - 2, len, NULL);
4626 if (err == -1) {
4627 Py_DECREF(tail);
4628 return;
4629 }
4630 /* Stitch everything up into a nice comma-separated list. */
4631 comma = PyUnicode_FromString(", ");
4632 if (comma == NULL) {
4633 Py_DECREF(tail);
4634 return;
4635 }
4636 tmp = PyUnicode_Join(comma, names);
4637 Py_DECREF(comma);
4638 if (tmp == NULL) {
4639 Py_DECREF(tail);
4640 return;
4641 }
4642 name_str = PyUnicode_Concat(tmp, tail);
4643 Py_DECREF(tmp);
4644 Py_DECREF(tail);
4645 break;
4646 }
4647 if (name_str == NULL)
4648 return;
Victor Stinner438a12d2019-05-24 17:01:38 +02004649 _PyErr_Format(tstate, PyExc_TypeError,
4650 "%U() missing %i required %s argument%s: %U",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004651 qualname,
Victor Stinner438a12d2019-05-24 17:01:38 +02004652 len,
4653 kind,
4654 len == 1 ? "" : "s",
4655 name_str);
Benjamin Petersone109c702011-06-24 09:37:26 -05004656 Py_DECREF(name_str);
4657}
4658
4659static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004660missing_arguments(PyThreadState *tstate, PyCodeObject *co,
4661 Py_ssize_t missing, Py_ssize_t defcount,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004662 PyObject **fastlocals, PyObject *qualname)
Benjamin Petersone109c702011-06-24 09:37:26 -05004663{
Victor Stinner74319ae2016-08-25 00:04:09 +02004664 Py_ssize_t i, j = 0;
4665 Py_ssize_t start, end;
4666 int positional = (defcount != -1);
Benjamin Petersone109c702011-06-24 09:37:26 -05004667 const char *kind = positional ? "positional" : "keyword-only";
4668 PyObject *missing_names;
4669
4670 /* Compute the names of the arguments that are missing. */
4671 missing_names = PyList_New(missing);
4672 if (missing_names == NULL)
4673 return;
4674 if (positional) {
4675 start = 0;
Pablo Galindocd74e662019-06-01 18:08:04 +01004676 end = co->co_argcount - defcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05004677 }
4678 else {
Pablo Galindocd74e662019-06-01 18:08:04 +01004679 start = co->co_argcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05004680 end = start + co->co_kwonlyargcount;
4681 }
4682 for (i = start; i < end; i++) {
4683 if (GETLOCAL(i) == NULL) {
4684 PyObject *raw = PyTuple_GET_ITEM(co->co_varnames, i);
4685 PyObject *name = PyObject_Repr(raw);
4686 if (name == NULL) {
4687 Py_DECREF(missing_names);
4688 return;
4689 }
4690 PyList_SET_ITEM(missing_names, j++, name);
4691 }
4692 }
4693 assert(j == missing);
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004694 format_missing(tstate, kind, co, missing_names, qualname);
Benjamin Petersone109c702011-06-24 09:37:26 -05004695 Py_DECREF(missing_names);
4696}
4697
4698static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004699too_many_positional(PyThreadState *tstate, PyCodeObject *co,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004700 Py_ssize_t given, PyObject *defaults,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004701 PyObject **fastlocals, PyObject *qualname)
Benjamin Petersonb204a422011-06-05 22:04:07 -05004702{
4703 int plural;
Victor Stinner74319ae2016-08-25 00:04:09 +02004704 Py_ssize_t kwonly_given = 0;
4705 Py_ssize_t i;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004706 PyObject *sig, *kwonly_sig;
Victor Stinner74319ae2016-08-25 00:04:09 +02004707 Py_ssize_t co_argcount = co->co_argcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004708
Benjamin Petersone109c702011-06-24 09:37:26 -05004709 assert((co->co_flags & CO_VARARGS) == 0);
4710 /* Count missing keyword-only args. */
Pablo Galindocd74e662019-06-01 18:08:04 +01004711 for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
Victor Stinner74319ae2016-08-25 00:04:09 +02004712 if (GETLOCAL(i) != NULL) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004713 kwonly_given++;
Victor Stinner74319ae2016-08-25 00:04:09 +02004714 }
4715 }
Mark Shannond6c33fb2021-01-29 13:24:55 +00004716 Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
Benjamin Petersone109c702011-06-24 09:37:26 -05004717 if (defcount) {
Pablo Galindocd74e662019-06-01 18:08:04 +01004718 Py_ssize_t atleast = co_argcount - defcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004719 plural = 1;
Pablo Galindocd74e662019-06-01 18:08:04 +01004720 sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004721 }
4722 else {
Pablo Galindocd74e662019-06-01 18:08:04 +01004723 plural = (co_argcount != 1);
4724 sig = PyUnicode_FromFormat("%zd", co_argcount);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004725 }
4726 if (sig == NULL)
4727 return;
4728 if (kwonly_given) {
Victor Stinner74319ae2016-08-25 00:04:09 +02004729 const char *format = " positional argument%s (and %zd keyword-only argument%s)";
4730 kwonly_sig = PyUnicode_FromFormat(format,
4731 given != 1 ? "s" : "",
4732 kwonly_given,
4733 kwonly_given != 1 ? "s" : "");
Benjamin Petersonb204a422011-06-05 22:04:07 -05004734 if (kwonly_sig == NULL) {
4735 Py_DECREF(sig);
4736 return;
4737 }
4738 }
4739 else {
4740 /* This will not fail. */
4741 kwonly_sig = PyUnicode_FromString("");
Benjamin Petersone109c702011-06-24 09:37:26 -05004742 assert(kwonly_sig != NULL);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004743 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004744 _PyErr_Format(tstate, PyExc_TypeError,
4745 "%U() takes %U positional argument%s but %zd%U %s given",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004746 qualname,
Victor Stinner438a12d2019-05-24 17:01:38 +02004747 sig,
4748 plural ? "s" : "",
4749 given,
4750 kwonly_sig,
4751 given == 1 && !kwonly_given ? "was" : "were");
Benjamin Petersonb204a422011-06-05 22:04:07 -05004752 Py_DECREF(sig);
4753 Py_DECREF(kwonly_sig);
4754}
4755
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004756static int
Victor Stinner438a12d2019-05-24 17:01:38 +02004757positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
Mark Shannon0332e562021-02-01 10:42:03 +00004758 Py_ssize_t kwcount, PyObject* kwnames,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004759 PyObject *qualname)
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004760{
4761 int posonly_conflicts = 0;
4762 PyObject* posonly_names = PyList_New(0);
4763
4764 for(int k=0; k < co->co_posonlyargcount; k++){
4765 PyObject* posonly_name = PyTuple_GET_ITEM(co->co_varnames, k);
4766
4767 for (int k2=0; k2<kwcount; k2++){
4768 /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
Mark Shannon0332e562021-02-01 10:42:03 +00004769 PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004770 if (kwname == posonly_name){
4771 if(PyList_Append(posonly_names, kwname) != 0) {
4772 goto fail;
4773 }
4774 posonly_conflicts++;
4775 continue;
4776 }
4777
4778 int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
4779
4780 if ( cmp > 0) {
4781 if(PyList_Append(posonly_names, kwname) != 0) {
4782 goto fail;
4783 }
4784 posonly_conflicts++;
4785 } else if (cmp < 0) {
4786 goto fail;
4787 }
4788
4789 }
4790 }
4791 if (posonly_conflicts) {
4792 PyObject* comma = PyUnicode_FromString(", ");
4793 if (comma == NULL) {
4794 goto fail;
4795 }
4796 PyObject* error_names = PyUnicode_Join(comma, posonly_names);
4797 Py_DECREF(comma);
4798 if (error_names == NULL) {
4799 goto fail;
4800 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004801 _PyErr_Format(tstate, PyExc_TypeError,
4802 "%U() got some positional-only arguments passed"
4803 " as keyword arguments: '%U'",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004804 qualname, error_names);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004805 Py_DECREF(error_names);
4806 goto fail;
4807 }
4808
4809 Py_DECREF(posonly_names);
4810 return 0;
4811
4812fail:
4813 Py_XDECREF(posonly_names);
4814 return 1;
4815
4816}
4817
Skip Montanaro786ea6b2004-03-01 15:44:05 +00004818
Mark Shannon0332e562021-02-01 10:42:03 +00004819PyFrameObject *
4820_PyEval_MakeFrameVector(PyThreadState *tstate,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004821 PyFrameConstructor *con, PyObject *locals,
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02004822 PyObject *const *args, Py_ssize_t argcount,
Mark Shannon0332e562021-02-01 10:42:03 +00004823 PyObject *kwnames)
Tim Peters5ca576e2001-06-18 22:08:13 +00004824{
Victor Stinnerda2914d2020-03-20 09:29:08 +01004825 assert(is_tstate_valid(tstate));
Victor Stinnerb5e170f2019-11-16 01:03:22 +01004826
Mark Shannond6c33fb2021-01-29 13:24:55 +00004827 PyCodeObject *co = (PyCodeObject*)con->fc_code;
4828 assert(con->fc_defaults == NULL || PyTuple_CheckExact(con->fc_defaults));
Pablo Galindocd74e662019-06-01 18:08:04 +01004829 const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
Tim Peters5ca576e2001-06-18 22:08:13 +00004830
Victor Stinnerc7020012016-08-16 23:40:29 +02004831 /* Create the frame */
Mark Shannon0332e562021-02-01 10:42:03 +00004832 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, con, locals);
Victor Stinnerc7020012016-08-16 23:40:29 +02004833 if (f == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834 return NULL;
Victor Stinnerc7020012016-08-16 23:40:29 +02004835 }
Victor Stinner232dda62020-06-04 15:19:02 +02004836 PyObject **fastlocals = f->f_localsplus;
4837 PyObject **freevars = f->f_localsplus + co->co_nlocals;
Tim Peters5ca576e2001-06-18 22:08:13 +00004838
Victor Stinnerc7020012016-08-16 23:40:29 +02004839 /* Create a dictionary for keyword parameters (**kwags) */
Victor Stinner232dda62020-06-04 15:19:02 +02004840 PyObject *kwdict;
4841 Py_ssize_t i;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004842 if (co->co_flags & CO_VARKEYWORDS) {
4843 kwdict = PyDict_New();
4844 if (kwdict == NULL)
4845 goto fail;
4846 i = total_args;
Victor Stinnerc7020012016-08-16 23:40:29 +02004847 if (co->co_flags & CO_VARARGS) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004848 i++;
Victor Stinnerc7020012016-08-16 23:40:29 +02004849 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004850 SETLOCAL(i, kwdict);
4851 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004852 else {
4853 kwdict = NULL;
4854 }
4855
Pablo Galindocd74e662019-06-01 18:08:04 +01004856 /* Copy all positional arguments into local variables */
Victor Stinner232dda62020-06-04 15:19:02 +02004857 Py_ssize_t j, n;
Pablo Galindocd74e662019-06-01 18:08:04 +01004858 if (argcount > co->co_argcount) {
4859 n = co->co_argcount;
Victor Stinnerc7020012016-08-16 23:40:29 +02004860 }
4861 else {
4862 n = argcount;
4863 }
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004864 for (j = 0; j < n; j++) {
Victor Stinner232dda62020-06-04 15:19:02 +02004865 PyObject *x = args[j];
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004866 Py_INCREF(x);
4867 SETLOCAL(j, x);
4868 }
4869
Victor Stinnerc7020012016-08-16 23:40:29 +02004870 /* Pack other positional arguments into the *args argument */
Benjamin Petersonb204a422011-06-05 22:04:07 -05004871 if (co->co_flags & CO_VARARGS) {
Victor Stinner232dda62020-06-04 15:19:02 +02004872 PyObject *u = _PyTuple_FromArray(args + n, argcount - n);
Victor Stinnerc7020012016-08-16 23:40:29 +02004873 if (u == NULL) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004874 goto fail;
Victor Stinnerc7020012016-08-16 23:40:29 +02004875 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004876 SETLOCAL(total_args, u);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004877 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004878
Mark Shannon0332e562021-02-01 10:42:03 +00004879 /* Handle keyword arguments */
4880 if (kwnames != NULL) {
4881 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
4882 for (i = 0; i < kwcount; i++) {
4883 PyObject **co_varnames;
4884 PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
4885 PyObject *value = args[i+argcount];
4886 Py_ssize_t j;
Victor Stinnerc7020012016-08-16 23:40:29 +02004887
Mark Shannon0332e562021-02-01 10:42:03 +00004888 if (keyword == NULL || !PyUnicode_Check(keyword)) {
4889 _PyErr_Format(tstate, PyExc_TypeError,
4890 "%U() keywords must be strings",
Mark Shannond6c33fb2021-01-29 13:24:55 +00004891 con->fc_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 goto fail;
Victor Stinner6fea7f72016-08-22 23:17:30 +02004893 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004894
Mark Shannon0332e562021-02-01 10:42:03 +00004895 /* Speed hack: do raw pointer compares. As names are
4896 normally interned this should almost always hit. */
4897 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
4898 for (j = co->co_posonlyargcount; j < total_args; j++) {
4899 PyObject *varname = co_varnames[j];
4900 if (varname == keyword) {
4901 goto kw_found;
4902 }
4903 }
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004904
Mark Shannon0332e562021-02-01 10:42:03 +00004905 /* Slow fallback, just in case */
4906 for (j = co->co_posonlyargcount; j < total_args; j++) {
4907 PyObject *varname = co_varnames[j];
4908 int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
4909 if (cmp > 0) {
4910 goto kw_found;
4911 }
4912 else if (cmp < 0) {
4913 goto fail;
4914 }
4915 }
4916
4917 assert(j >= total_args);
4918 if (kwdict == NULL) {
4919
4920 if (co->co_posonlyargcount
4921 && positional_only_passed_as_keyword(tstate, co,
4922 kwcount, kwnames,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004923 con->fc_qualname))
Mark Shannon0332e562021-02-01 10:42:03 +00004924 {
4925 goto fail;
4926 }
4927
4928 _PyErr_Format(tstate, PyExc_TypeError,
4929 "%U() got an unexpected keyword argument '%S'",
4930 con->fc_qualname, keyword);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004931 goto fail;
4932 }
4933
Mark Shannon0332e562021-02-01 10:42:03 +00004934 if (PyDict_SetItem(kwdict, keyword, value) == -1) {
4935 goto fail;
4936 }
4937 continue;
Victor Stinnerc7020012016-08-16 23:40:29 +02004938
Mark Shannon0332e562021-02-01 10:42:03 +00004939 kw_found:
4940 if (GETLOCAL(j) != NULL) {
4941 _PyErr_Format(tstate, PyExc_TypeError,
4942 "%U() got multiple values for argument '%S'",
Mark Shannond6c33fb2021-01-29 13:24:55 +00004943 con->fc_qualname, keyword);
Mark Shannon0332e562021-02-01 10:42:03 +00004944 goto fail;
4945 }
4946 Py_INCREF(value);
4947 SETLOCAL(j, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004950
4951 /* Check the number of positional arguments */
Pablo Galindocd74e662019-06-01 18:08:04 +01004952 if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00004953 too_many_positional(tstate, co, argcount, con->fc_defaults, fastlocals,
4954 con->fc_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 goto fail;
4956 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004957
4958 /* Add missing positional arguments (copy default values from defs) */
Pablo Galindocd74e662019-06-01 18:08:04 +01004959 if (argcount < co->co_argcount) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00004960 Py_ssize_t defcount = con->fc_defaults == NULL ? 0 : PyTuple_GET_SIZE(con->fc_defaults);
Pablo Galindocd74e662019-06-01 18:08:04 +01004961 Py_ssize_t m = co->co_argcount - defcount;
Victor Stinner17061a92016-08-16 23:39:42 +02004962 Py_ssize_t missing = 0;
4963 for (i = argcount; i < m; i++) {
4964 if (GETLOCAL(i) == NULL) {
Benjamin Petersone109c702011-06-24 09:37:26 -05004965 missing++;
Victor Stinner17061a92016-08-16 23:39:42 +02004966 }
4967 }
Benjamin Petersone109c702011-06-24 09:37:26 -05004968 if (missing) {
Victor Stinner232dda62020-06-04 15:19:02 +02004969 missing_arguments(tstate, co, missing, defcount, fastlocals,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004970 con->fc_qualname);
Benjamin Petersone109c702011-06-24 09:37:26 -05004971 goto fail;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004972 }
4973 if (n > m)
4974 i = n - m;
4975 else
4976 i = 0;
Mark Shannond6c33fb2021-01-29 13:24:55 +00004977 if (defcount) {
4978 PyObject **defs = &PyTuple_GET_ITEM(con->fc_defaults, 0);
4979 for (; i < defcount; i++) {
4980 if (GETLOCAL(m+i) == NULL) {
4981 PyObject *def = defs[i];
4982 Py_INCREF(def);
4983 SETLOCAL(m+i, def);
4984 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004985 }
4986 }
4987 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004988
4989 /* Add missing keyword arguments (copy default values from kwdefs) */
Benjamin Petersonb204a422011-06-05 22:04:07 -05004990 if (co->co_kwonlyargcount > 0) {
Victor Stinner17061a92016-08-16 23:39:42 +02004991 Py_ssize_t missing = 0;
Pablo Galindocd74e662019-06-01 18:08:04 +01004992 for (i = co->co_argcount; i < total_args; i++) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004993 if (GETLOCAL(i) != NULL)
4994 continue;
Victor Stinner232dda62020-06-04 15:19:02 +02004995 PyObject *varname = PyTuple_GET_ITEM(co->co_varnames, i);
Mark Shannond6c33fb2021-01-29 13:24:55 +00004996 if (con->fc_kwdefaults != NULL) {
4997 PyObject *def = PyDict_GetItemWithError(con->fc_kwdefaults, varname);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004998 if (def) {
4999 Py_INCREF(def);
5000 SETLOCAL(i, def);
5001 continue;
5002 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005003 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02005004 goto fail;
5005 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05005006 }
Benjamin Petersone109c702011-06-24 09:37:26 -05005007 missing++;
5008 }
5009 if (missing) {
Victor Stinner232dda62020-06-04 15:19:02 +02005010 missing_arguments(tstate, co, missing, -1, fastlocals,
Mark Shannond6c33fb2021-01-29 13:24:55 +00005011 con->fc_qualname);
Benjamin Petersonb204a422011-06-05 22:04:07 -05005012 goto fail;
5013 }
5014 }
5015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 /* Allocate and initialize storage for cell vars, and copy free
Benjamin Peterson90037602011-06-25 22:54:45 -05005017 vars into frame. */
5018 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 PyObject *c;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +02005020 Py_ssize_t arg;
Benjamin Peterson90037602011-06-25 22:54:45 -05005021 /* Possibly account for the cell variable being an argument. */
5022 if (co->co_cell2arg != NULL &&
Guido van Rossum6832c812013-05-10 08:47:42 -07005023 (arg = co->co_cell2arg[i]) != CO_CELL_NOT_AN_ARG) {
Benjamin Peterson90037602011-06-25 22:54:45 -05005024 c = PyCell_New(GETLOCAL(arg));
Benjamin Peterson159ae412013-05-12 18:16:06 -05005025 /* Clear the local copy. */
5026 SETLOCAL(arg, NULL);
Guido van Rossum6832c812013-05-10 08:47:42 -07005027 }
5028 else {
Benjamin Peterson90037602011-06-25 22:54:45 -05005029 c = PyCell_New(NULL);
Guido van Rossum6832c812013-05-10 08:47:42 -07005030 }
Benjamin Peterson159ae412013-05-12 18:16:06 -05005031 if (c == NULL)
5032 goto fail;
Benjamin Peterson90037602011-06-25 22:54:45 -05005033 SETLOCAL(co->co_nlocals + i, c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 }
Victor Stinnerc7020012016-08-16 23:40:29 +02005035
5036 /* Copy closure variables to free variables */
Benjamin Peterson90037602011-06-25 22:54:45 -05005037 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00005038 PyObject *o = PyTuple_GET_ITEM(con->fc_closure, i);
Benjamin Peterson90037602011-06-25 22:54:45 -05005039 Py_INCREF(o);
5040 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 }
Tim Peters5ca576e2001-06-18 22:08:13 +00005042
Mark Shannon0332e562021-02-01 10:42:03 +00005043 return f;
Tim Peters5ca576e2001-06-18 22:08:13 +00005044
Thomas Woutersce272b62007-09-19 21:19:28 +00005045fail: /* Jump here from prelude on failure */
Tim Peters5ca576e2001-06-18 22:08:13 +00005046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 /* decref'ing the frame can cause __del__ methods to get invoked,
5048 which can call back into Python. While we're done with the
5049 current Python frame (f), the associated C stack is still in use,
5050 so recursion_depth must be boosted for the duration.
5051 */
INADA Naoki5a625d02016-12-24 20:19:08 +09005052 if (Py_REFCNT(f) > 1) {
5053 Py_DECREF(f);
5054 _PyObject_GC_TRACK(f);
5055 }
5056 else {
5057 ++tstate->recursion_depth;
5058 Py_DECREF(f);
5059 --tstate->recursion_depth;
5060 }
Mark Shannon0332e562021-02-01 10:42:03 +00005061 return NULL;
5062}
5063
5064static PyObject *
5065make_coro(PyFrameConstructor *con, PyFrameObject *f)
5066{
5067 assert (((PyCodeObject *)con->fc_code)->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR));
5068 PyObject *gen;
5069 int is_coro = ((PyCodeObject *)con->fc_code)->co_flags & CO_COROUTINE;
5070
5071 /* Don't need to keep the reference to f_back, it will be set
5072 * when the generator is resumed. */
5073 Py_CLEAR(f->f_back);
5074
5075 /* Create a new generator that owns the ready to run frame
5076 * and return that as the value. */
5077 if (is_coro) {
5078 gen = PyCoro_New(f, con->fc_name, con->fc_qualname);
5079 } else if (((PyCodeObject *)con->fc_code)->co_flags & CO_ASYNC_GENERATOR) {
5080 gen = PyAsyncGen_New(f, con->fc_name, con->fc_qualname);
5081 } else {
5082 gen = PyGen_NewWithQualName(f, con->fc_name, con->fc_qualname);
5083 }
5084 if (gen == NULL) {
5085 return NULL;
5086 }
5087
5088 _PyObject_GC_TRACK(f);
5089
5090 return gen;
5091}
5092
5093PyObject *
5094_PyEval_Vector(PyThreadState *tstate, PyFrameConstructor *con,
5095 PyObject *locals,
5096 PyObject* const* args, size_t argcount,
5097 PyObject *kwnames)
5098{
5099 PyFrameObject *f = _PyEval_MakeFrameVector(
5100 tstate, con, locals, args, argcount, kwnames);
5101 if (f == NULL) {
5102 return NULL;
5103 }
5104 if (((PyCodeObject *)con->fc_code)->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
5105 return make_coro(con, f);
5106 }
5107 PyObject *retval = _PyEval_EvalFrame(tstate, f, 0);
5108
5109 /* decref'ing the frame can cause __del__ methods to get invoked,
5110 which can call back into Python. While we're done with the
5111 current Python frame (f), the associated C stack is still in use,
5112 so recursion_depth must be boosted for the duration.
5113 */
5114 if (Py_REFCNT(f) > 1) {
5115 Py_DECREF(f);
5116 _PyObject_GC_TRACK(f);
5117 }
5118 else {
5119 ++tstate->recursion_depth;
5120 Py_DECREF(f);
5121 --tstate->recursion_depth;
5122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 return retval;
Tim Peters5ca576e2001-06-18 22:08:13 +00005124}
5125
Mark Shannond6c33fb2021-01-29 13:24:55 +00005126/* Legacy API */
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005127PyObject *
Mark Shannon0332e562021-02-01 10:42:03 +00005128PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
5129 PyObject *const *args, int argcount,
5130 PyObject *const *kws, int kwcount,
5131 PyObject *const *defs, int defcount,
5132 PyObject *kwdefs, PyObject *closure)
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005133{
Victor Stinner46496f92021-02-20 15:17:18 +01005134 PyThreadState *tstate = _PyThreadState_GET();
Mark Shannon0332e562021-02-01 10:42:03 +00005135 PyObject *res;
Mark Shannond6c33fb2021-01-29 13:24:55 +00005136 PyObject *defaults = _PyTuple_FromArray(defs, defcount);
5137 if (defaults == NULL) {
5138 return NULL;
5139 }
Victor Stinnerfc980e02021-03-18 14:51:24 +01005140 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Mark Shannond6c33fb2021-01-29 13:24:55 +00005141 if (builtins == NULL) {
5142 Py_DECREF(defaults);
5143 return NULL;
5144 }
Mark Shannon0332e562021-02-01 10:42:03 +00005145 if (locals == NULL) {
5146 locals = globals;
5147 }
5148 PyObject *kwnames;
5149 PyObject *const *allargs;
5150 PyObject **newargs;
5151 if (kwcount == 0) {
5152 allargs = args;
5153 kwnames = NULL;
5154 }
5155 else {
5156 kwnames = PyTuple_New(kwcount);
5157 if (kwnames == NULL) {
5158 res = NULL;
5159 goto fail;
5160 }
5161 newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
5162 if (newargs == NULL) {
5163 res = NULL;
5164 Py_DECREF(kwnames);
5165 goto fail;
5166 }
5167 for (int i = 0; i < argcount; i++) {
5168 newargs[i] = args[i];
5169 }
5170 for (int i = 0; i < kwcount; i++) {
5171 Py_INCREF(kws[2*i]);
5172 PyTuple_SET_ITEM(kwnames, i, kws[2*i]);
5173 newargs[argcount+i] = kws[2*i+1];
5174 }
5175 allargs = newargs;
5176 }
5177 PyObject **kwargs = PyMem_Malloc(sizeof(PyObject *)*kwcount);
5178 if (kwargs == NULL) {
5179 res = NULL;
5180 Py_DECREF(kwnames);
5181 goto fail;
5182 }
5183 for (int i = 0; i < kwcount; i++) {
5184 Py_INCREF(kws[2*i]);
5185 PyTuple_SET_ITEM(kwnames, i, kws[2*i]);
5186 kwargs[i] = kws[2*i+1];
5187 }
Mark Shannond6c33fb2021-01-29 13:24:55 +00005188 PyFrameConstructor constr = {
5189 .fc_globals = globals,
5190 .fc_builtins = builtins,
Mark Shannon0332e562021-02-01 10:42:03 +00005191 .fc_name = ((PyCodeObject *)_co)->co_name,
5192 .fc_qualname = ((PyCodeObject *)_co)->co_name,
Mark Shannond6c33fb2021-01-29 13:24:55 +00005193 .fc_code = _co,
5194 .fc_defaults = defaults,
5195 .fc_kwdefaults = kwdefs,
5196 .fc_closure = closure
5197 };
Mark Shannon0332e562021-02-01 10:42:03 +00005198 res = _PyEval_Vector(tstate, &constr, locals,
Victor Stinner44085a32021-02-18 19:20:16 +01005199 allargs, argcount,
5200 kwnames);
Mark Shannon0332e562021-02-01 10:42:03 +00005201 if (kwcount) {
5202 Py_DECREF(kwnames);
5203 PyMem_Free(newargs);
5204 }
5205fail:
Mark Shannond6c33fb2021-01-29 13:24:55 +00005206 Py_DECREF(defaults);
Mark Shannond6c33fb2021-01-29 13:24:55 +00005207 return res;
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005208}
5209
Tim Peters5ca576e2001-06-18 22:08:13 +00005210
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005211static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02005212special_lookup(PyThreadState *tstate, PyObject *o, _Py_Identifier *id)
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005215 res = _PyObject_LookupSpecial(o, id);
Victor Stinner438a12d2019-05-24 17:01:38 +02005216 if (res == NULL && !_PyErr_Occurred(tstate)) {
Victor Stinner4804b5b2020-05-12 01:43:38 +02005217 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(id));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 return NULL;
5219 }
5220 return res;
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005221}
5222
5223
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005224/* Logic for the raise statement (too complicated for inlining).
5225 This *consumes* a reference count to each of its arguments. */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005226static int
Victor Stinner09532fe2019-05-10 23:39:09 +02005227do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 PyObject *type = NULL, *value = NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00005230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 if (exc == NULL) {
5232 /* Reraise */
Mark Shannonae3087c2017-10-22 22:41:51 +01005233 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005234 PyObject *tb;
Mark Shannonae3087c2017-10-22 22:41:51 +01005235 type = exc_info->exc_type;
5236 value = exc_info->exc_value;
5237 tb = exc_info->exc_traceback;
Victor Stinnereec93312016-08-18 18:13:10 +02005238 if (type == Py_None || type == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005239 _PyErr_SetString(tstate, PyExc_RuntimeError,
5240 "No active exception to reraise");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005241 return 0;
5242 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 Py_XINCREF(type);
5244 Py_XINCREF(value);
5245 Py_XINCREF(tb);
Victor Stinner438a12d2019-05-24 17:01:38 +02005246 _PyErr_Restore(tstate, type, value, tb);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005247 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 }
Guido van Rossumac7be682001-01-17 15:42:30 +00005249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 /* We support the following forms of raise:
5251 raise
Collin Winter828f04a2007-08-31 00:04:24 +00005252 raise <instance>
5253 raise <type> */
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 if (PyExceptionClass_Check(exc)) {
5256 type = exc;
Victor Stinnera5ed5f02016-12-06 18:45:50 +01005257 value = _PyObject_CallNoArg(exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 if (value == NULL)
5259 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05005260 if (!PyExceptionInstance_Check(value)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005261 _PyErr_Format(tstate, PyExc_TypeError,
5262 "calling %R should have returned an instance of "
5263 "BaseException, not %R",
5264 type, Py_TYPE(value));
5265 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05005266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 }
5268 else if (PyExceptionInstance_Check(exc)) {
5269 value = exc;
5270 type = PyExceptionInstance_Class(exc);
5271 Py_INCREF(type);
5272 }
5273 else {
5274 /* Not something you can raise. You get an exception
5275 anyway, just not what you specified :-) */
5276 Py_DECREF(exc);
Victor Stinner438a12d2019-05-24 17:01:38 +02005277 _PyErr_SetString(tstate, PyExc_TypeError,
5278 "exceptions must derive from BaseException");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 goto raise_error;
5280 }
Collin Winter828f04a2007-08-31 00:04:24 +00005281
Serhiy Storchakac0191582016-09-27 11:37:10 +03005282 assert(type != NULL);
5283 assert(value != NULL);
5284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 if (cause) {
5286 PyObject *fixed_cause;
5287 if (PyExceptionClass_Check(cause)) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01005288 fixed_cause = _PyObject_CallNoArg(cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 if (fixed_cause == NULL)
5290 goto raise_error;
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005291 Py_DECREF(cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005293 else if (PyExceptionInstance_Check(cause)) {
5294 fixed_cause = cause;
5295 }
5296 else if (cause == Py_None) {
5297 Py_DECREF(cause);
5298 fixed_cause = NULL;
5299 }
5300 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005301 _PyErr_SetString(tstate, PyExc_TypeError,
5302 "exception causes must derive from "
5303 "BaseException");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 goto raise_error;
5305 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005306 PyException_SetCause(value, fixed_cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 }
Collin Winter828f04a2007-08-31 00:04:24 +00005308
Victor Stinner438a12d2019-05-24 17:01:38 +02005309 _PyErr_SetObject(tstate, type, value);
Victor Stinner61f4db82020-01-28 03:37:45 +01005310 /* _PyErr_SetObject incref's its arguments */
Serhiy Storchakac0191582016-09-27 11:37:10 +03005311 Py_DECREF(value);
5312 Py_DECREF(type);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005313 return 0;
Collin Winter828f04a2007-08-31 00:04:24 +00005314
5315raise_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 Py_XDECREF(value);
5317 Py_XDECREF(type);
5318 Py_XDECREF(cause);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005319 return 0;
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005320}
5321
Tim Petersd6d010b2001-06-21 02:49:55 +00005322/* Iterate v argcnt times and store the results on the stack (via decreasing
Guido van Rossum0368b722007-05-11 16:50:42 +00005323 sp). Return 1 for success, 0 if error.
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00005324
Guido van Rossum0368b722007-05-11 16:50:42 +00005325 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
5326 with a variable target.
5327*/
Tim Petersd6d010b2001-06-21 02:49:55 +00005328
Barry Warsawe42b18f1997-08-25 22:13:04 +00005329static int
Victor Stinner438a12d2019-05-24 17:01:38 +02005330unpack_iterable(PyThreadState *tstate, PyObject *v,
5331 int argcnt, int argcntafter, PyObject **sp)
Barry Warsawe42b18f1997-08-25 22:13:04 +00005332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 int i = 0, j = 0;
5334 Py_ssize_t ll = 0;
5335 PyObject *it; /* iter(v) */
5336 PyObject *w;
5337 PyObject *l = NULL; /* variable list */
Guido van Rossumac7be682001-01-17 15:42:30 +00005338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 assert(v != NULL);
Tim Petersd6d010b2001-06-21 02:49:55 +00005340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 it = PyObject_GetIter(v);
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005342 if (it == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005343 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
Victor Stinnera102ed72020-02-07 02:24:48 +01005344 Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005345 {
Victor Stinner438a12d2019-05-24 17:01:38 +02005346 _PyErr_Format(tstate, PyExc_TypeError,
5347 "cannot unpack non-iterable %.200s object",
Victor Stinnera102ed72020-02-07 02:24:48 +01005348 Py_TYPE(v)->tp_name);
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005349 }
5350 return 0;
5351 }
Tim Petersd6d010b2001-06-21 02:49:55 +00005352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 for (; i < argcnt; i++) {
5354 w = PyIter_Next(it);
5355 if (w == NULL) {
5356 /* Iterator done, via error or exhaustion. */
Victor Stinner438a12d2019-05-24 17:01:38 +02005357 if (!_PyErr_Occurred(tstate)) {
R David Murray4171bbe2015-04-15 17:08:45 -04005358 if (argcntafter == -1) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005359 _PyErr_Format(tstate, PyExc_ValueError,
5360 "not enough values to unpack "
5361 "(expected %d, got %d)",
5362 argcnt, i);
R David Murray4171bbe2015-04-15 17:08:45 -04005363 }
5364 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005365 _PyErr_Format(tstate, PyExc_ValueError,
5366 "not enough values to unpack "
5367 "(expected at least %d, got %d)",
5368 argcnt + argcntafter, i);
R David Murray4171bbe2015-04-15 17:08:45 -04005369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 }
5371 goto Error;
5372 }
5373 *--sp = w;
5374 }
Tim Petersd6d010b2001-06-21 02:49:55 +00005375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 if (argcntafter == -1) {
5377 /* We better have exhausted the iterator now. */
5378 w = PyIter_Next(it);
5379 if (w == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005380 if (_PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 goto Error;
5382 Py_DECREF(it);
5383 return 1;
5384 }
5385 Py_DECREF(w);
Victor Stinner438a12d2019-05-24 17:01:38 +02005386 _PyErr_Format(tstate, PyExc_ValueError,
5387 "too many values to unpack (expected %d)",
5388 argcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 goto Error;
5390 }
Guido van Rossum0368b722007-05-11 16:50:42 +00005391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 l = PySequence_List(it);
5393 if (l == NULL)
5394 goto Error;
5395 *--sp = l;
5396 i++;
Guido van Rossum0368b722007-05-11 16:50:42 +00005397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 ll = PyList_GET_SIZE(l);
5399 if (ll < argcntafter) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005400 _PyErr_Format(tstate, PyExc_ValueError,
R David Murray4171bbe2015-04-15 17:08:45 -04005401 "not enough values to unpack (expected at least %d, got %zd)",
5402 argcnt + argcntafter, argcnt + ll);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 goto Error;
5404 }
Guido van Rossum0368b722007-05-11 16:50:42 +00005405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 /* Pop the "after-variable" args off the list. */
5407 for (j = argcntafter; j > 0; j--, i++) {
5408 *--sp = PyList_GET_ITEM(l, ll - j);
5409 }
5410 /* Resize the list. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005411 Py_SET_SIZE(l, ll - argcntafter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 Py_DECREF(it);
5413 return 1;
Guido van Rossum0368b722007-05-11 16:50:42 +00005414
Tim Petersd6d010b2001-06-21 02:49:55 +00005415Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 for (; i > 0; i--, sp++)
5417 Py_DECREF(*sp);
5418 Py_XDECREF(it);
5419 return 0;
Barry Warsawe42b18f1997-08-25 22:13:04 +00005420}
5421
Guido van Rossum96a42c81992-01-12 02:29:51 +00005422#ifdef LLTRACE
Guido van Rossum3f5da241990-12-20 15:06:42 +00005423static int
Victor Stinner438a12d2019-05-24 17:01:38 +02005424prtrace(PyThreadState *tstate, PyObject *v, const char *str)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 printf("%s ", str);
Victor Stinner438a12d2019-05-24 17:01:38 +02005427 if (PyObject_Print(v, stdout, 0) != 0) {
5428 /* Don't know what else to do */
5429 _PyErr_Clear(tstate);
5430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 printf("\n");
5432 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005433}
Guido van Rossum3f5da241990-12-20 15:06:42 +00005434#endif
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005435
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005436static void
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005437call_exc_trace(Py_tracefunc func, PyObject *self,
Mark Shannon86433452021-01-07 16:49:02 +00005438 PyThreadState *tstate,
5439 PyFrameObject *f,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005440 PyTraceInfo *trace_info)
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005441{
Victor Stinneraaa8ed82013-07-10 13:57:55 +02005442 PyObject *type, *value, *traceback, *orig_traceback, *arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 int err;
Victor Stinner438a12d2019-05-24 17:01:38 +02005444 _PyErr_Fetch(tstate, &type, &value, &orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 if (value == NULL) {
5446 value = Py_None;
5447 Py_INCREF(value);
5448 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005449 _PyErr_NormalizeException(tstate, &type, &value, &orig_traceback);
Antoine Pitrou89335212013-11-23 14:05:23 +01005450 traceback = (orig_traceback != NULL) ? orig_traceback : Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 arg = PyTuple_Pack(3, type, value, traceback);
5452 if (arg == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005453 _PyErr_Restore(tstate, type, value, orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 return;
5455 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00005456 err = call_trace(func, self, tstate, f, trace_info, PyTrace_EXCEPTION, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 Py_DECREF(arg);
Victor Stinner438a12d2019-05-24 17:01:38 +02005458 if (err == 0) {
5459 _PyErr_Restore(tstate, type, value, orig_traceback);
5460 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 else {
5462 Py_XDECREF(type);
5463 Py_XDECREF(value);
Victor Stinneraaa8ed82013-07-10 13:57:55 +02005464 Py_XDECREF(orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 }
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005466}
5467
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +00005468static int
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005469call_trace_protected(Py_tracefunc func, PyObject *obj,
5470 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005471 PyTraceInfo *trace_info,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 int what, PyObject *arg)
Fred Drake4ec5d562001-10-04 19:26:43 +00005473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 PyObject *type, *value, *traceback;
5475 int err;
Victor Stinner438a12d2019-05-24 17:01:38 +02005476 _PyErr_Fetch(tstate, &type, &value, &traceback);
Mark Shannon8e1b4062021-03-05 14:45:50 +00005477 err = call_trace(func, obj, tstate, frame, trace_info, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 if (err == 0)
5479 {
Victor Stinner438a12d2019-05-24 17:01:38 +02005480 _PyErr_Restore(tstate, type, value, traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 return 0;
5482 }
5483 else {
5484 Py_XDECREF(type);
5485 Py_XDECREF(value);
5486 Py_XDECREF(traceback);
5487 return -1;
5488 }
Fred Drake4ec5d562001-10-04 19:26:43 +00005489}
5490
Mark Shannon8e1b4062021-03-05 14:45:50 +00005491static void
5492initialize_trace_info(PyTraceInfo *trace_info, PyFrameObject *frame)
5493{
5494 if (trace_info->code != frame->f_code) {
5495 trace_info->code = frame->f_code;
5496 trace_info->instr_prev = -1;
5497 _PyCode_InitAddressRange(frame->f_code, &trace_info->bounds);
5498 }
5499}
5500
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005501static int
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005502call_trace(Py_tracefunc func, PyObject *obj,
5503 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005504 PyTraceInfo *trace_info,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 int what, PyObject *arg)
Guido van Rossum96a42c81992-01-12 02:29:51 +00005506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 int result;
5508 if (tstate->tracing)
5509 return 0;
5510 tstate->tracing++;
5511 tstate->use_tracing = 0;
Mark Shannon86433452021-01-07 16:49:02 +00005512 if (frame->f_lasti < 0) {
5513 frame->f_lineno = frame->f_code->co_firstlineno;
5514 }
5515 else {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005516 initialize_trace_info(trace_info, frame);
Mark Shannonfcb55c02021-04-01 16:00:31 +01005517 frame->f_lineno = _PyCode_CheckLineNumber(frame->f_lasti*2, &trace_info->bounds);
Mark Shannon86433452021-01-07 16:49:02 +00005518 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 result = func(obj, frame, what, arg);
Mark Shannon86433452021-01-07 16:49:02 +00005520 frame->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
5522 || (tstate->c_profilefunc != NULL));
5523 tstate->tracing--;
5524 return result;
Guido van Rossum96a42c81992-01-12 02:29:51 +00005525}
5526
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005527PyObject *
5528_PyEval_CallTracing(PyObject *func, PyObject *args)
5529{
Victor Stinner50b48572018-11-01 01:51:40 +01005530 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 int save_tracing = tstate->tracing;
5532 int save_use_tracing = tstate->use_tracing;
5533 PyObject *result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 tstate->tracing = 0;
5536 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
5537 || (tstate->c_profilefunc != NULL));
5538 result = PyObject_Call(func, args, NULL);
5539 tstate->tracing = save_tracing;
5540 tstate->use_tracing = save_use_tracing;
5541 return result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005542}
5543
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005544/* See Objects/lnotab_notes.txt for a description of how tracing works. */
Michael W. Hudson006c7522002-11-08 13:08:46 +00005545static int
Tim Peters8a5c3c72004-04-05 19:36:21 +00005546maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005547 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005548 PyTraceInfo *trace_info)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00005549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 int result = 0;
Michael W. Hudson006c7522002-11-08 13:08:46 +00005551
Nick Coghlan5a851672017-09-08 10:14:16 +10005552 /* If the last instruction falls at the start of a line or if it
5553 represents a jump backwards, update the frame's line number and
5554 then call the trace function if we're tracing source lines.
5555 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00005556 initialize_trace_info(trace_info, frame);
5557 int lastline = trace_info->bounds.ar_line;
Mark Shannonfcb55c02021-04-01 16:00:31 +01005558 int line = _PyCode_CheckLineNumber(frame->f_lasti*2, &trace_info->bounds);
Mark Shannonee9f98d2021-01-05 12:04:10 +00005559 if (line != -1 && frame->f_trace_lines) {
5560 /* Trace backward edges or first instruction of a new line */
Mark Shannon8e1b4062021-03-05 14:45:50 +00005561 if (frame->f_lasti < trace_info->instr_prev ||
Mark Shannonfcb55c02021-04-01 16:00:31 +01005562 (line != lastline && frame->f_lasti*2 == trace_info->bounds.ar_start))
Mark Shannonee9f98d2021-01-05 12:04:10 +00005563 {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005564 result = call_trace(func, obj, tstate, frame, trace_info, PyTrace_LINE, Py_None);
Nick Coghlan5a851672017-09-08 10:14:16 +10005565 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 }
George King20faa682017-10-18 17:44:22 -07005567 /* Always emit an opcode event if we're tracing all opcodes. */
5568 if (frame->f_trace_opcodes) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005569 result = call_trace(func, obj, tstate, frame, trace_info, PyTrace_OPCODE, Py_None);
George King20faa682017-10-18 17:44:22 -07005570 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00005571 trace_info->instr_prev = frame->f_lasti;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 return result;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00005573}
5574
Victor Stinner309d7cc2020-03-13 16:39:12 +01005575int
5576_PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
5577{
Victor Stinnerda2914d2020-03-20 09:29:08 +01005578 assert(is_tstate_valid(tstate));
Victor Stinner309d7cc2020-03-13 16:39:12 +01005579 /* The caller must hold the GIL */
5580 assert(PyGILState_Check());
5581
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005582 /* Call _PySys_Audit() in the context of the current thread state,
Victor Stinner309d7cc2020-03-13 16:39:12 +01005583 even if tstate is not the current thread state. */
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005584 PyThreadState *current_tstate = _PyThreadState_GET();
5585 if (_PySys_Audit(current_tstate, "sys.setprofile", NULL) < 0) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01005586 return -1;
5587 }
5588
5589 PyObject *profileobj = tstate->c_profileobj;
5590
5591 tstate->c_profilefunc = NULL;
5592 tstate->c_profileobj = NULL;
5593 /* Must make sure that tracing is not ignored if 'profileobj' is freed */
5594 tstate->use_tracing = tstate->c_tracefunc != NULL;
5595 Py_XDECREF(profileobj);
5596
5597 Py_XINCREF(arg);
5598 tstate->c_profileobj = arg;
5599 tstate->c_profilefunc = func;
5600
5601 /* Flag that tracing or profiling is turned on */
5602 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
5603 return 0;
5604}
5605
Fred Drake5755ce62001-06-27 19:19:46 +00005606void
5607PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
Fred Draked0838392001-06-16 21:02:31 +00005608{
Victor Stinner309d7cc2020-03-13 16:39:12 +01005609 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerf6a58502020-03-16 17:41:44 +01005610 if (_PyEval_SetProfile(tstate, func, arg) < 0) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005611 /* Log _PySys_Audit() error */
Victor Stinnerf6a58502020-03-16 17:41:44 +01005612 _PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL);
5613 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01005614}
5615
5616int
5617_PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
5618{
Victor Stinnerda2914d2020-03-20 09:29:08 +01005619 assert(is_tstate_valid(tstate));
Victor Stinner309d7cc2020-03-13 16:39:12 +01005620 /* The caller must hold the GIL */
5621 assert(PyGILState_Check());
5622
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005623 /* Call _PySys_Audit() in the context of the current thread state,
Victor Stinner309d7cc2020-03-13 16:39:12 +01005624 even if tstate is not the current thread state. */
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005625 PyThreadState *current_tstate = _PyThreadState_GET();
5626 if (_PySys_Audit(current_tstate, "sys.settrace", NULL) < 0) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01005627 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005628 }
5629
Victor Stinnerda2914d2020-03-20 09:29:08 +01005630 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinner309d7cc2020-03-13 16:39:12 +01005631 PyObject *traceobj = tstate->c_traceobj;
Victor Stinnerda2914d2020-03-20 09:29:08 +01005632 ceval2->tracing_possible += (func != NULL) - (tstate->c_tracefunc != NULL);
Victor Stinner309d7cc2020-03-13 16:39:12 +01005633
5634 tstate->c_tracefunc = NULL;
5635 tstate->c_traceobj = NULL;
5636 /* Must make sure that profiling is not ignored if 'traceobj' is freed */
5637 tstate->use_tracing = (tstate->c_profilefunc != NULL);
5638 Py_XDECREF(traceobj);
5639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 Py_XINCREF(arg);
Victor Stinner309d7cc2020-03-13 16:39:12 +01005641 tstate->c_traceobj = arg;
5642 tstate->c_tracefunc = func;
5643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005644 /* Flag that tracing or profiling is turned on */
Victor Stinner309d7cc2020-03-13 16:39:12 +01005645 tstate->use_tracing = ((func != NULL)
5646 || (tstate->c_profilefunc != NULL));
5647
5648 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00005649}
5650
5651void
5652PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
5653{
Victor Stinner309d7cc2020-03-13 16:39:12 +01005654 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerf6a58502020-03-16 17:41:44 +01005655 if (_PyEval_SetTrace(tstate, func, arg) < 0) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005656 /* Log _PySys_Audit() error */
Victor Stinnerf6a58502020-03-16 17:41:44 +01005657 _PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL);
5658 }
Fred Draked0838392001-06-16 21:02:31 +00005659}
5660
Victor Stinner309d7cc2020-03-13 16:39:12 +01005661
Yury Selivanov75445082015-05-11 22:57:16 -04005662void
Victor Stinner838f2642019-06-13 22:41:23 +02005663_PyEval_SetCoroutineOriginTrackingDepth(PyThreadState *tstate, int new_depth)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005664{
5665 assert(new_depth >= 0);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005666 tstate->coroutine_origin_tracking_depth = new_depth;
5667}
5668
5669int
5670_PyEval_GetCoroutineOriginTrackingDepth(void)
5671{
Victor Stinner50b48572018-11-01 01:51:40 +01005672 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005673 return tstate->coroutine_origin_tracking_depth;
5674}
5675
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005676int
Yury Selivanoveb636452016-09-08 22:01:51 -07005677_PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
5678{
Victor Stinner50b48572018-11-01 01:51:40 +01005679 PyThreadState *tstate = _PyThreadState_GET();
Steve Dowerb82e17e2019-05-23 08:45:22 -07005680
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005681 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005682 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005683 }
5684
Yury Selivanoveb636452016-09-08 22:01:51 -07005685 Py_XINCREF(firstiter);
5686 Py_XSETREF(tstate->async_gen_firstiter, firstiter);
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005687 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07005688}
5689
5690PyObject *
5691_PyEval_GetAsyncGenFirstiter(void)
5692{
Victor Stinner50b48572018-11-01 01:51:40 +01005693 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07005694 return tstate->async_gen_firstiter;
5695}
5696
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005697int
Yury Selivanoveb636452016-09-08 22:01:51 -07005698_PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
5699{
Victor Stinner50b48572018-11-01 01:51:40 +01005700 PyThreadState *tstate = _PyThreadState_GET();
Steve Dowerb82e17e2019-05-23 08:45:22 -07005701
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005702 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005703 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005704 }
5705
Yury Selivanoveb636452016-09-08 22:01:51 -07005706 Py_XINCREF(finalizer);
5707 Py_XSETREF(tstate->async_gen_finalizer, finalizer);
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005708 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07005709}
5710
5711PyObject *
5712_PyEval_GetAsyncGenFinalizer(void)
5713{
Victor Stinner50b48572018-11-01 01:51:40 +01005714 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07005715 return tstate->async_gen_finalizer;
5716}
5717
Victor Stinner438a12d2019-05-24 17:01:38 +02005718PyFrameObject *
5719PyEval_GetFrame(void)
5720{
5721 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005722 return tstate->frame;
Victor Stinner438a12d2019-05-24 17:01:38 +02005723}
5724
Guido van Rossumb209a111997-04-29 18:18:01 +00005725PyObject *
Victor Stinner46496f92021-02-20 15:17:18 +01005726_PyEval_GetBuiltins(PyThreadState *tstate)
5727{
5728 PyFrameObject *frame = tstate->frame;
5729 if (frame != NULL) {
5730 return frame->f_builtins;
5731 }
5732 return tstate->interp->builtins;
5733}
5734
5735PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005736PyEval_GetBuiltins(void)
Guido van Rossum6135a871995-01-09 17:53:26 +00005737{
Victor Stinner438a12d2019-05-24 17:01:38 +02005738 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner46496f92021-02-20 15:17:18 +01005739 return _PyEval_GetBuiltins(tstate);
Guido van Rossum6135a871995-01-09 17:53:26 +00005740}
5741
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005742/* Convenience function to get a builtin from its name */
5743PyObject *
5744_PyEval_GetBuiltinId(_Py_Identifier *name)
5745{
Victor Stinner438a12d2019-05-24 17:01:38 +02005746 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005747 PyObject *attr = _PyDict_GetItemIdWithError(PyEval_GetBuiltins(), name);
5748 if (attr) {
5749 Py_INCREF(attr);
5750 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005751 else if (!_PyErr_Occurred(tstate)) {
5752 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(name));
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005753 }
5754 return attr;
5755}
5756
Guido van Rossumb209a111997-04-29 18:18:01 +00005757PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005758PyEval_GetLocals(void)
Guido van Rossum5b722181993-03-30 17:46:03 +00005759{
Victor Stinner438a12d2019-05-24 17:01:38 +02005760 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005761 PyFrameObject *current_frame = tstate->frame;
Victor Stinner41bb43a2013-10-29 01:19:37 +01005762 if (current_frame == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005763 _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 return NULL;
Victor Stinner41bb43a2013-10-29 01:19:37 +01005765 }
5766
Victor Stinner438a12d2019-05-24 17:01:38 +02005767 if (PyFrame_FastToLocalsWithError(current_frame) < 0) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01005768 return NULL;
Victor Stinner438a12d2019-05-24 17:01:38 +02005769 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01005770
5771 assert(current_frame->f_locals != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 return current_frame->f_locals;
Guido van Rossum5b722181993-03-30 17:46:03 +00005773}
5774
Guido van Rossumb209a111997-04-29 18:18:01 +00005775PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005776PyEval_GetGlobals(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +00005777{
Victor Stinner438a12d2019-05-24 17:01:38 +02005778 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005779 PyFrameObject *current_frame = tstate->frame;
Victor Stinner438a12d2019-05-24 17:01:38 +02005780 if (current_frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 return NULL;
Victor Stinner438a12d2019-05-24 17:01:38 +02005782 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01005783
5784 assert(current_frame->f_globals != NULL);
5785 return current_frame->f_globals;
Guido van Rossum3f5da241990-12-20 15:06:42 +00005786}
5787
Guido van Rossum6135a871995-01-09 17:53:26 +00005788int
Tim Peters5ba58662001-07-16 02:29:45 +00005789PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Jeremy Hylton061d1062001-03-22 02:32:48 +00005790{
Victor Stinner438a12d2019-05-24 17:01:38 +02005791 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005792 PyFrameObject *current_frame = tstate->frame;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 int result = cf->cf_flags != 0;
Tim Peters5ba58662001-07-16 02:29:45 +00005794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005795 if (current_frame != NULL) {
5796 const int codeflags = current_frame->f_code->co_flags;
5797 const int compilerflags = codeflags & PyCF_MASK;
5798 if (compilerflags) {
5799 result = 1;
5800 cf->cf_flags |= compilerflags;
5801 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00005802#if 0 /* future keyword */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 if (codeflags & CO_GENERATOR_ALLOWED) {
5804 result = 1;
5805 cf->cf_flags |= CO_GENERATOR_ALLOWED;
5806 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00005807#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 }
5809 return result;
Jeremy Hylton061d1062001-03-22 02:32:48 +00005810}
5811
Guido van Rossum3f5da241990-12-20 15:06:42 +00005812
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00005813const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005814PyEval_GetFuncName(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00005815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 if (PyMethod_Check(func))
5817 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
5818 else if (PyFunction_Check(func))
Serhiy Storchaka06515832016-11-20 09:13:07 +02005819 return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 else if (PyCFunction_Check(func))
5821 return ((PyCFunctionObject*)func)->m_ml->ml_name;
5822 else
Victor Stinnera102ed72020-02-07 02:24:48 +01005823 return Py_TYPE(func)->tp_name;
Jeremy Hylton512a2372001-04-11 13:52:29 +00005824}
5825
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00005826const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005827PyEval_GetFuncDesc(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00005828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 if (PyMethod_Check(func))
5830 return "()";
5831 else if (PyFunction_Check(func))
5832 return "()";
5833 else if (PyCFunction_Check(func))
5834 return "()";
5835 else
5836 return " object";
Jeremy Hylton512a2372001-04-11 13:52:29 +00005837}
5838
Armin Rigo1c2d7e52005-09-20 18:34:01 +00005839#define C_TRACE(x, call) \
Nicholas Bastind858a772004-06-25 23:31:06 +00005840if (tstate->use_tracing && tstate->c_profilefunc) { \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005841 if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005842 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005843 PyTrace_C_CALL, func)) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 x = NULL; \
5845 } \
5846 else { \
5847 x = call; \
5848 if (tstate->c_profilefunc != NULL) { \
5849 if (x == NULL) { \
5850 call_trace_protected(tstate->c_profilefunc, \
5851 tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005852 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005853 PyTrace_C_EXCEPTION, func); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 /* XXX should pass (type, value, tb) */ \
5855 } else { \
5856 if (call_trace(tstate->c_profilefunc, \
5857 tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005858 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005859 PyTrace_C_RETURN, func)) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005860 Py_DECREF(x); \
5861 x = NULL; \
5862 } \
5863 } \
5864 } \
5865 } \
Nicholas Bastind858a772004-06-25 23:31:06 +00005866} else { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005867 x = call; \
5868 }
Nicholas Bastinc69ebe82004-03-24 21:57:10 +00005869
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005870
5871static PyObject *
5872trace_call_function(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005873 PyTraceInfo *trace_info,
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005874 PyObject *func,
5875 PyObject **args, Py_ssize_t nargs,
5876 PyObject *kwnames)
5877{
5878 PyObject *x;
scoder4c9ea092020-05-12 16:12:41 +02005879 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005880 C_TRACE(x, PyObject_Vectorcall(func, args, nargs, kwnames));
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005881 return x;
5882 }
Andy Lesterdffe4c02020-03-04 07:15:20 -06005883 else if (Py_IS_TYPE(func, &PyMethodDescr_Type) && nargs > 0) {
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005884 /* We need to create a temporary bound method as argument
5885 for profiling.
5886
5887 If nargs == 0, then this cannot work because we have no
5888 "self". In any case, the call itself would raise
5889 TypeError (foo needs an argument), so we just skip
5890 profiling. */
5891 PyObject *self = args[0];
5892 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5893 if (func == NULL) {
5894 return NULL;
5895 }
Petr Viktorinffd97532020-02-11 17:46:57 +01005896 C_TRACE(x, PyObject_Vectorcall(func,
Jeroen Demeyer0d722f32019-07-05 14:48:24 +02005897 args+1, nargs-1,
5898 kwnames));
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005899 Py_DECREF(func);
5900 return x;
5901 }
Petr Viktorinffd97532020-02-11 17:46:57 +01005902 return PyObject_Vectorcall(func, args, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005903}
5904
Victor Stinner415c5102017-01-11 00:54:57 +01005905/* Issue #29227: Inline call_function() into _PyEval_EvalFrameDefault()
5906 to reduce the stack consumption. */
5907Py_LOCAL_INLINE(PyObject *) _Py_HOT_FUNCTION
Mark Shannon86433452021-01-07 16:49:02 +00005908call_function(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005909 PyTraceInfo *trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00005910 PyObject ***pp_stack,
5911 Py_ssize_t oparg,
5912 PyObject *kwnames)
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005913{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005914 PyObject **pfunc = (*pp_stack) - oparg - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005915 PyObject *func = *pfunc;
5916 PyObject *x, *w;
Victor Stinnerd8735722016-09-09 12:36:44 -07005917 Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
5918 Py_ssize_t nargs = oparg - nkwargs;
INADA Naoki5566bbb2017-02-03 07:43:03 +09005919 PyObject **stack = (*pp_stack) - nargs - nkwargs;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005920
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005921 if (tstate->use_tracing) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005922 x = trace_call_function(tstate, trace_info, func, stack, nargs, kwnames);
INADA Naoki5566bbb2017-02-03 07:43:03 +09005923 }
Victor Stinner4a7cc882015-03-06 23:35:27 +01005924 else {
Petr Viktorinffd97532020-02-11 17:46:57 +01005925 x = PyObject_Vectorcall(func, stack, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 }
Tim Peters8a5c3c72004-04-05 19:36:21 +00005927
Victor Stinner438a12d2019-05-24 17:01:38 +02005928 assert((x != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005929
Victor Stinnerc22bfaa2017-02-12 19:27:05 +01005930 /* Clear the stack of the function object. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005931 while ((*pp_stack) > pfunc) {
5932 w = EXT_POP(*pp_stack);
5933 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005934 }
Victor Stinnerace47d72013-07-18 01:41:08 +02005935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 return x;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005937}
5938
Jeremy Hylton52820442001-01-03 23:52:36 +00005939static PyObject *
Mark Shannon86433452021-01-07 16:49:02 +00005940do_call_core(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005941 PyTraceInfo *trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00005942 PyObject *func,
5943 PyObject *callargs,
5944 PyObject *kwdict)
Jeremy Hylton52820442001-01-03 23:52:36 +00005945{
jdemeyere89de732018-09-19 12:06:20 +02005946 PyObject *result;
5947
scoder4c9ea092020-05-12 16:12:41 +02005948 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
Jeroen Demeyer7a6873c2019-09-11 13:01:01 +02005949 C_TRACE(result, PyObject_Call(func, callargs, kwdict));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005950 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 }
Andy Lesterdffe4c02020-03-04 07:15:20 -06005952 else if (Py_IS_TYPE(func, &PyMethodDescr_Type)) {
jdemeyere89de732018-09-19 12:06:20 +02005953 Py_ssize_t nargs = PyTuple_GET_SIZE(callargs);
5954 if (nargs > 0 && tstate->use_tracing) {
5955 /* We need to create a temporary bound method as argument
5956 for profiling.
5957
5958 If nargs == 0, then this cannot work because we have no
5959 "self". In any case, the call itself would raise
5960 TypeError (foo needs an argument), so we just skip
5961 profiling. */
5962 PyObject *self = PyTuple_GET_ITEM(callargs, 0);
5963 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5964 if (func == NULL) {
5965 return NULL;
5966 }
5967
Victor Stinner4d231bc2019-11-14 13:36:21 +01005968 C_TRACE(result, _PyObject_FastCallDictTstate(
5969 tstate, func,
5970 &_PyTuple_ITEMS(callargs)[1],
5971 nargs - 1,
5972 kwdict));
jdemeyere89de732018-09-19 12:06:20 +02005973 Py_DECREF(func);
5974 return result;
5975 }
Victor Stinner74319ae2016-08-25 00:04:09 +02005976 }
jdemeyere89de732018-09-19 12:06:20 +02005977 return PyObject_Call(func, callargs, kwdict);
Jeremy Hylton52820442001-01-03 23:52:36 +00005978}
5979
Serhiy Storchaka483405b2015-02-17 10:14:30 +02005980/* Extract a slice index from a PyLong or an object with the
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005981 nb_index slot defined, and store in *pi.
5982 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
Xiang Zhang2ddf5a12017-05-10 18:19:41 +08005983 and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
Martin v. Löwisdde99d22006-02-17 15:57:41 +00005984 Return 0 on error, 1 on success.
Tim Peterscb479e72001-12-16 19:11:44 +00005985*/
Guido van Rossum20c6add2000-05-08 14:06:50 +00005986int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005987_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005988{
Victor Stinner438a12d2019-05-24 17:01:38 +02005989 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03005990 if (v != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005991 Py_ssize_t x;
Victor Stinnera15e2602020-04-08 02:01:56 +02005992 if (_PyIndex_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 x = PyNumber_AsSsize_t(v, NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02005994 if (x == -1 && _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 return 0;
5996 }
5997 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005998 _PyErr_SetString(tstate, PyExc_TypeError,
5999 "slice indices must be integers or "
6000 "None or have an __index__ method");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 return 0;
6002 }
6003 *pi = x;
6004 }
6005 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00006006}
6007
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006008int
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006009_PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006010{
Victor Stinner438a12d2019-05-24 17:01:38 +02006011 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006012 Py_ssize_t x;
Victor Stinnera15e2602020-04-08 02:01:56 +02006013 if (_PyIndex_Check(v)) {
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006014 x = PyNumber_AsSsize_t(v, NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02006015 if (x == -1 && _PyErr_Occurred(tstate))
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006016 return 0;
6017 }
6018 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006019 _PyErr_SetString(tstate, PyExc_TypeError,
6020 "slice indices must be integers or "
6021 "have an __index__ method");
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006022 return 0;
6023 }
6024 *pi = x;
6025 return 1;
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006026}
6027
Thomas Wouters52152252000-08-17 22:55:00 +00006028static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006029import_name(PyThreadState *tstate, PyFrameObject *f,
6030 PyObject *name, PyObject *fromlist, PyObject *level)
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006031{
6032 _Py_IDENTIFIER(__import__);
Victor Stinnerdf142fd2016-08-20 00:44:42 +02006033 PyObject *import_func, *res;
6034 PyObject* stack[5];
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006035
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006036 import_func = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___import__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006037 if (import_func == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006038 if (!_PyErr_Occurred(tstate)) {
6039 _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006040 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006041 return NULL;
6042 }
6043
6044 /* Fast path for not overloaded __import__. */
Victor Stinner438a12d2019-05-24 17:01:38 +02006045 if (import_func == tstate->interp->import_func) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006046 int ilevel = _PyLong_AsInt(level);
Victor Stinner438a12d2019-05-24 17:01:38 +02006047 if (ilevel == -1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006048 return NULL;
6049 }
6050 res = PyImport_ImportModuleLevelObject(
6051 name,
6052 f->f_globals,
6053 f->f_locals == NULL ? Py_None : f->f_locals,
6054 fromlist,
6055 ilevel);
6056 return res;
6057 }
6058
6059 Py_INCREF(import_func);
Victor Stinnerdf142fd2016-08-20 00:44:42 +02006060
6061 stack[0] = name;
6062 stack[1] = f->f_globals;
6063 stack[2] = f->f_locals == NULL ? Py_None : f->f_locals;
6064 stack[3] = fromlist;
6065 stack[4] = level;
Victor Stinner559bb6a2016-08-22 22:48:54 +02006066 res = _PyObject_FastCall(import_func, stack, 5);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006067 Py_DECREF(import_func);
6068 return res;
6069}
6070
6071static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006072import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
Guido van Rossume9736fc1990-11-18 17:33:06 +00006073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006074 PyObject *x;
Xiang Zhang4830f582017-03-21 11:13:42 +08006075 PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg;
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00006076
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006077 if (_PyObject_LookupAttr(v, name, &x) != 0) {
Antoine Pitrou0373a102014-10-13 20:19:45 +02006078 return x;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006079 }
Antoine Pitrou0373a102014-10-13 20:19:45 +02006080 /* Issue #17636: in case this failed because of a circular relative
6081 import, try to fallback on reading the module directly from
6082 sys.modules. */
Antoine Pitrou0373a102014-10-13 20:19:45 +02006083 pkgname = _PyObject_GetAttrId(v, &PyId___name__);
Brett Cannon3008bc02015-08-11 18:01:31 -07006084 if (pkgname == NULL) {
6085 goto error;
6086 }
Oren Milman6db70332017-09-19 14:23:01 +03006087 if (!PyUnicode_Check(pkgname)) {
6088 Py_CLEAR(pkgname);
6089 goto error;
6090 }
Antoine Pitrou0373a102014-10-13 20:19:45 +02006091 fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
Brett Cannon3008bc02015-08-11 18:01:31 -07006092 if (fullmodname == NULL) {
Xiang Zhang4830f582017-03-21 11:13:42 +08006093 Py_DECREF(pkgname);
Antoine Pitrou0373a102014-10-13 20:19:45 +02006094 return NULL;
Brett Cannon3008bc02015-08-11 18:01:31 -07006095 }
Eric Snow3f9eee62017-09-15 16:35:20 -06006096 x = PyImport_GetModule(fullmodname);
Antoine Pitrou0373a102014-10-13 20:19:45 +02006097 Py_DECREF(fullmodname);
Victor Stinner438a12d2019-05-24 17:01:38 +02006098 if (x == NULL && !_PyErr_Occurred(tstate)) {
Brett Cannon3008bc02015-08-11 18:01:31 -07006099 goto error;
6100 }
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006101 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006102 return x;
Brett Cannon3008bc02015-08-11 18:01:31 -07006103 error:
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006104 pkgpath = PyModule_GetFilenameObject(v);
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006105 if (pkgname == NULL) {
6106 pkgname_or_unknown = PyUnicode_FromString("<unknown module name>");
6107 if (pkgname_or_unknown == NULL) {
6108 Py_XDECREF(pkgpath);
6109 return NULL;
6110 }
6111 } else {
6112 pkgname_or_unknown = pkgname;
6113 }
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006114
6115 if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006116 _PyErr_Clear(tstate);
Xiang Zhang4830f582017-03-21 11:13:42 +08006117 errmsg = PyUnicode_FromFormat(
6118 "cannot import name %R from %R (unknown location)",
6119 name, pkgname_or_unknown
6120 );
Stefan Krah027b09c2019-03-25 21:50:58 +01006121 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
Xiang Zhang4830f582017-03-21 11:13:42 +08006122 PyErr_SetImportError(errmsg, pkgname, NULL);
6123 }
6124 else {
Anthony Sottile65366bc2019-09-09 08:17:50 -07006125 _Py_IDENTIFIER(__spec__);
6126 PyObject *spec = _PyObject_GetAttrId(v, &PyId___spec__);
Anthony Sottile65366bc2019-09-09 08:17:50 -07006127 const char *fmt =
6128 _PyModuleSpec_IsInitializing(spec) ?
6129 "cannot import name %R from partially initialized module %R "
6130 "(most likely due to a circular import) (%S)" :
6131 "cannot import name %R from %R (%S)";
6132 Py_XDECREF(spec);
6133
6134 errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
Stefan Krah027b09c2019-03-25 21:50:58 +01006135 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
Xiang Zhang4830f582017-03-21 11:13:42 +08006136 PyErr_SetImportError(errmsg, pkgname, pkgpath);
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006137 }
6138
Xiang Zhang4830f582017-03-21 11:13:42 +08006139 Py_XDECREF(errmsg);
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006140 Py_XDECREF(pkgname_or_unknown);
6141 Py_XDECREF(pkgpath);
Brett Cannon3008bc02015-08-11 18:01:31 -07006142 return NULL;
Thomas Wouters52152252000-08-17 22:55:00 +00006143}
Guido van Rossumac7be682001-01-17 15:42:30 +00006144
Thomas Wouters52152252000-08-17 22:55:00 +00006145static int
Victor Stinner438a12d2019-05-24 17:01:38 +02006146import_all_from(PyThreadState *tstate, PyObject *locals, PyObject *v)
Thomas Wouters52152252000-08-17 22:55:00 +00006147{
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02006148 _Py_IDENTIFIER(__all__);
6149 _Py_IDENTIFIER(__dict__);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006150 PyObject *all, *dict, *name, *value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006151 int skip_leading_underscores = 0;
6152 int pos, err;
Thomas Wouters52152252000-08-17 22:55:00 +00006153
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006154 if (_PyObject_LookupAttrId(v, &PyId___all__, &all) < 0) {
6155 return -1; /* Unexpected error */
6156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006157 if (all == NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006158 if (_PyObject_LookupAttrId(v, &PyId___dict__, &dict) < 0) {
6159 return -1;
6160 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006161 if (dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006162 _PyErr_SetString(tstate, PyExc_ImportError,
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006163 "from-import-* object has no __dict__ and no __all__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006164 return -1;
6165 }
6166 all = PyMapping_Keys(dict);
6167 Py_DECREF(dict);
6168 if (all == NULL)
6169 return -1;
6170 skip_leading_underscores = 1;
6171 }
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00006172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006173 for (pos = 0, err = 0; ; pos++) {
6174 name = PySequence_GetItem(all, pos);
6175 if (name == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006176 if (!_PyErr_ExceptionMatches(tstate, PyExc_IndexError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006177 err = -1;
Victor Stinner438a12d2019-05-24 17:01:38 +02006178 }
6179 else {
6180 _PyErr_Clear(tstate);
6181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006182 break;
6183 }
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006184 if (!PyUnicode_Check(name)) {
6185 PyObject *modname = _PyObject_GetAttrId(v, &PyId___name__);
6186 if (modname == NULL) {
6187 Py_DECREF(name);
6188 err = -1;
6189 break;
6190 }
6191 if (!PyUnicode_Check(modname)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006192 _PyErr_Format(tstate, PyExc_TypeError,
6193 "module __name__ must be a string, not %.100s",
6194 Py_TYPE(modname)->tp_name);
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006195 }
6196 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006197 _PyErr_Format(tstate, PyExc_TypeError,
6198 "%s in %U.%s must be str, not %.100s",
6199 skip_leading_underscores ? "Key" : "Item",
6200 modname,
6201 skip_leading_underscores ? "__dict__" : "__all__",
6202 Py_TYPE(name)->tp_name);
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006203 }
6204 Py_DECREF(modname);
6205 Py_DECREF(name);
6206 err = -1;
6207 break;
6208 }
6209 if (skip_leading_underscores) {
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03006210 if (PyUnicode_READY(name) == -1) {
6211 Py_DECREF(name);
6212 err = -1;
6213 break;
6214 }
6215 if (PyUnicode_READ_CHAR(name, 0) == '_') {
6216 Py_DECREF(name);
6217 continue;
6218 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006219 }
6220 value = PyObject_GetAttr(v, name);
6221 if (value == NULL)
6222 err = -1;
6223 else if (PyDict_CheckExact(locals))
6224 err = PyDict_SetItem(locals, name, value);
6225 else
6226 err = PyObject_SetItem(locals, name, value);
6227 Py_DECREF(name);
6228 Py_XDECREF(value);
6229 if (err != 0)
6230 break;
6231 }
6232 Py_DECREF(all);
6233 return err;
Guido van Rossume9736fc1990-11-18 17:33:06 +00006234}
6235
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006236static int
Victor Stinner438a12d2019-05-24 17:01:38 +02006237check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006238{
Victor Stinnera102ed72020-02-07 02:24:48 +01006239 if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006240 /* check_args_iterable() may be called with a live exception:
6241 * clear it to prevent calling _PyObject_FunctionStr() with an
6242 * exception set. */
Victor Stinner61f4db82020-01-28 03:37:45 +01006243 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006244 PyObject *funcstr = _PyObject_FunctionStr(func);
6245 if (funcstr != NULL) {
6246 _PyErr_Format(tstate, PyExc_TypeError,
6247 "%U argument after * must be an iterable, not %.200s",
6248 funcstr, Py_TYPE(args)->tp_name);
6249 Py_DECREF(funcstr);
6250 }
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006251 return -1;
6252 }
6253 return 0;
6254}
6255
6256static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006257format_kwargs_error(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006258{
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006259 /* _PyDict_MergeEx raises attribute
6260 * error (percolated from an attempt
6261 * to get 'keys' attribute) instead of
6262 * a type error if its second argument
6263 * is not a mapping.
6264 */
Victor Stinner438a12d2019-05-24 17:01:38 +02006265 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Victor Stinner61f4db82020-01-28 03:37:45 +01006266 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006267 PyObject *funcstr = _PyObject_FunctionStr(func);
6268 if (funcstr != NULL) {
6269 _PyErr_Format(
6270 tstate, PyExc_TypeError,
6271 "%U argument after ** must be a mapping, not %.200s",
6272 funcstr, Py_TYPE(kwargs)->tp_name);
6273 Py_DECREF(funcstr);
6274 }
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006275 }
Victor Stinner438a12d2019-05-24 17:01:38 +02006276 else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006277 PyObject *exc, *val, *tb;
Victor Stinner438a12d2019-05-24 17:01:38 +02006278 _PyErr_Fetch(tstate, &exc, &val, &tb);
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006279 if (val && PyTuple_Check(val) && PyTuple_GET_SIZE(val) == 1) {
Victor Stinner61f4db82020-01-28 03:37:45 +01006280 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006281 PyObject *funcstr = _PyObject_FunctionStr(func);
6282 if (funcstr != NULL) {
6283 PyObject *key = PyTuple_GET_ITEM(val, 0);
6284 _PyErr_Format(
6285 tstate, PyExc_TypeError,
6286 "%U got multiple values for keyword argument '%S'",
6287 funcstr, key);
6288 Py_DECREF(funcstr);
6289 }
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006290 Py_XDECREF(exc);
6291 Py_XDECREF(val);
6292 Py_XDECREF(tb);
6293 }
6294 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006295 _PyErr_Restore(tstate, exc, val, tb);
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006296 }
6297 }
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006298}
6299
Guido van Rossumac7be682001-01-17 15:42:30 +00006300static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006301format_exc_check_arg(PyThreadState *tstate, PyObject *exc,
6302 const char *format_str, PyObject *obj)
Paul Prescode68140d2000-08-30 20:25:01 +00006303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006304 const char *obj_str;
Paul Prescode68140d2000-08-30 20:25:01 +00006305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 if (!obj)
6307 return;
Paul Prescode68140d2000-08-30 20:25:01 +00006308
Serhiy Storchaka06515832016-11-20 09:13:07 +02006309 obj_str = PyUnicode_AsUTF8(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006310 if (!obj_str)
6311 return;
Paul Prescode68140d2000-08-30 20:25:01 +00006312
Victor Stinner438a12d2019-05-24 17:01:38 +02006313 _PyErr_Format(tstate, exc, format_str, obj_str);
Paul Prescode68140d2000-08-30 20:25:01 +00006314}
Guido van Rossum950361c1997-01-24 13:49:28 +00006315
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006316static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006317format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006318{
6319 PyObject *name;
6320 /* Don't stomp existing exception */
Victor Stinner438a12d2019-05-24 17:01:38 +02006321 if (_PyErr_Occurred(tstate))
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006322 return;
6323 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
6324 name = PyTuple_GET_ITEM(co->co_cellvars,
6325 oparg);
Victor Stinner438a12d2019-05-24 17:01:38 +02006326 format_exc_check_arg(tstate,
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006327 PyExc_UnboundLocalError,
6328 UNBOUNDLOCAL_ERROR_MSG,
6329 name);
6330 } else {
6331 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
6332 PyTuple_GET_SIZE(co->co_cellvars));
Victor Stinner438a12d2019-05-24 17:01:38 +02006333 format_exc_check_arg(tstate, PyExc_NameError,
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006334 UNBOUNDFREE_ERROR_MSG, name);
6335 }
6336}
6337
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006338static void
Mark Shannonfee55262019-11-21 09:11:43 +00006339format_awaitable_error(PyThreadState *tstate, PyTypeObject *type, int prevprevopcode, int prevopcode)
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006340{
6341 if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
6342 if (prevopcode == BEFORE_ASYNC_WITH) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006343 _PyErr_Format(tstate, PyExc_TypeError,
6344 "'async with' received an object from __aenter__ "
6345 "that does not implement __await__: %.100s",
6346 type->tp_name);
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006347 }
Mark Shannonfee55262019-11-21 09:11:43 +00006348 else if (prevopcode == WITH_EXCEPT_START || (prevopcode == CALL_FUNCTION && prevprevopcode == DUP_TOP)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006349 _PyErr_Format(tstate, PyExc_TypeError,
6350 "'async with' received an object from __aexit__ "
6351 "that does not implement __await__: %.100s",
6352 type->tp_name);
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006353 }
6354 }
6355}
6356
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006357static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006358unicode_concatenate(PyThreadState *tstate, PyObject *v, PyObject *w,
Serhiy Storchakaab874002016-09-11 13:48:15 +03006359 PyFrameObject *f, const _Py_CODEUNIT *next_instr)
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006360{
6361 PyObject *res;
6362 if (Py_REFCNT(v) == 2) {
6363 /* In the common case, there are 2 references to the value
6364 * stored in 'variable' when the += is performed: one on the
6365 * value stack (in 'v') and one still stored in the
6366 * 'variable'. We try to delete the variable now to reduce
6367 * the refcnt to 1.
6368 */
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006369 int opcode, oparg;
6370 NEXTOPARG();
6371 switch (opcode) {
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006372 case STORE_FAST:
6373 {
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006374 PyObject **fastlocals = f->f_localsplus;
6375 if (GETLOCAL(oparg) == v)
6376 SETLOCAL(oparg, NULL);
6377 break;
6378 }
6379 case STORE_DEREF:
6380 {
6381 PyObject **freevars = (f->f_localsplus +
6382 f->f_code->co_nlocals);
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006383 PyObject *c = freevars[oparg];
Raymond Hettingerc32f9db2016-11-12 04:10:35 -05006384 if (PyCell_GET(c) == v) {
6385 PyCell_SET(c, NULL);
6386 Py_DECREF(v);
6387 }
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006388 break;
6389 }
6390 case STORE_NAME:
6391 {
6392 PyObject *names = f->f_code->co_names;
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006393 PyObject *name = GETITEM(names, oparg);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006394 PyObject *locals = f->f_locals;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006395 if (locals && PyDict_CheckExact(locals)) {
6396 PyObject *w = PyDict_GetItemWithError(locals, name);
6397 if ((w == v && PyDict_DelItem(locals, name) != 0) ||
Victor Stinner438a12d2019-05-24 17:01:38 +02006398 (w == NULL && _PyErr_Occurred(tstate)))
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006399 {
6400 Py_DECREF(v);
6401 return NULL;
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006402 }
6403 }
6404 break;
6405 }
6406 }
6407 }
6408 res = v;
6409 PyUnicode_Append(&res, w);
6410 return res;
6411}
6412
Guido van Rossum950361c1997-01-24 13:49:28 +00006413#ifdef DYNAMIC_EXECUTION_PROFILE
6414
Skip Montanarof118cb12001-10-15 20:51:38 +00006415static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00006416getarray(long a[256])
Guido van Rossum950361c1997-01-24 13:49:28 +00006417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006418 int i;
6419 PyObject *l = PyList_New(256);
6420 if (l == NULL) return NULL;
6421 for (i = 0; i < 256; i++) {
6422 PyObject *x = PyLong_FromLong(a[i]);
6423 if (x == NULL) {
6424 Py_DECREF(l);
6425 return NULL;
6426 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07006427 PyList_SET_ITEM(l, i, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006428 }
6429 for (i = 0; i < 256; i++)
6430 a[i] = 0;
6431 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00006432}
6433
6434PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00006435_Py_GetDXProfile(PyObject *self, PyObject *args)
Guido van Rossum950361c1997-01-24 13:49:28 +00006436{
6437#ifndef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006438 return getarray(dxp);
Guido van Rossum950361c1997-01-24 13:49:28 +00006439#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006440 int i;
6441 PyObject *l = PyList_New(257);
6442 if (l == NULL) return NULL;
6443 for (i = 0; i < 257; i++) {
6444 PyObject *x = getarray(dxpairs[i]);
6445 if (x == NULL) {
6446 Py_DECREF(l);
6447 return NULL;
6448 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07006449 PyList_SET_ITEM(l, i, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006450 }
6451 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00006452#endif
6453}
6454
6455#endif
Brett Cannon5c4de282016-09-07 11:16:41 -07006456
6457Py_ssize_t
6458_PyEval_RequestCodeExtraIndex(freefunc free)
6459{
Victor Stinner81a7be32020-04-14 15:14:01 +02006460 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannon5c4de282016-09-07 11:16:41 -07006461 Py_ssize_t new_index;
6462
Dino Viehlandf3cffd22017-06-21 14:44:36 -07006463 if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
Brett Cannon5c4de282016-09-07 11:16:41 -07006464 return -1;
6465 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -07006466 new_index = interp->co_extra_user_count++;
6467 interp->co_extra_freefuncs[new_index] = free;
Brett Cannon5c4de282016-09-07 11:16:41 -07006468 return new_index;
6469}
Łukasz Langaa785c872016-09-09 17:37:37 -07006470
6471static void
6472dtrace_function_entry(PyFrameObject *f)
6473{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006474 const char *filename;
6475 const char *funcname;
Łukasz Langaa785c872016-09-09 17:37:37 -07006476 int lineno;
6477
Victor Stinner6d86a232020-04-29 00:56:58 +02006478 PyCodeObject *code = f->f_code;
6479 filename = PyUnicode_AsUTF8(code->co_filename);
6480 funcname = PyUnicode_AsUTF8(code->co_name);
Mark Shannonfcb55c02021-04-01 16:00:31 +01006481 lineno = PyFrame_GetLineNumber(f);
Łukasz Langaa785c872016-09-09 17:37:37 -07006482
Andy Lestere6be9b52020-02-11 20:28:35 -06006483 PyDTrace_FUNCTION_ENTRY(filename, funcname, lineno);
Łukasz Langaa785c872016-09-09 17:37:37 -07006484}
6485
6486static void
6487dtrace_function_return(PyFrameObject *f)
6488{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006489 const char *filename;
6490 const char *funcname;
Łukasz Langaa785c872016-09-09 17:37:37 -07006491 int lineno;
6492
Victor Stinner6d86a232020-04-29 00:56:58 +02006493 PyCodeObject *code = f->f_code;
6494 filename = PyUnicode_AsUTF8(code->co_filename);
6495 funcname = PyUnicode_AsUTF8(code->co_name);
Mark Shannonfcb55c02021-04-01 16:00:31 +01006496 lineno = PyFrame_GetLineNumber(f);
Łukasz Langaa785c872016-09-09 17:37:37 -07006497
Andy Lestere6be9b52020-02-11 20:28:35 -06006498 PyDTrace_FUNCTION_RETURN(filename, funcname, lineno);
Łukasz Langaa785c872016-09-09 17:37:37 -07006499}
6500
6501/* DTrace equivalent of maybe_call_line_trace. */
6502static void
6503maybe_dtrace_line(PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00006504 PyTraceInfo *trace_info)
Łukasz Langaa785c872016-09-09 17:37:37 -07006505{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006506 const char *co_filename, *co_name;
Łukasz Langaa785c872016-09-09 17:37:37 -07006507
6508 /* If the last instruction executed isn't in the current
6509 instruction window, reset the window.
6510 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00006511 initialize_trace_info(trace_info, frame);
Mark Shannonfcb55c02021-04-01 16:00:31 +01006512 int line = _PyCode_CheckLineNumber(frame->f_lasti*2, &trace_info->bounds);
Łukasz Langaa785c872016-09-09 17:37:37 -07006513 /* If the last instruction falls at the start of a line or if
6514 it represents a jump backwards, update the frame's line
6515 number and call the trace function. */
Mark Shannon8e1b4062021-03-05 14:45:50 +00006516 if (line != frame->f_lineno || frame->f_lasti < trace_info->instr_prev) {
Mark Shannon877df852020-11-12 09:43:29 +00006517 if (line != -1) {
6518 frame->f_lineno = line;
6519 co_filename = PyUnicode_AsUTF8(frame->f_code->co_filename);
6520 if (!co_filename)
6521 co_filename = "?";
6522 co_name = PyUnicode_AsUTF8(frame->f_code->co_name);
6523 if (!co_name)
6524 co_name = "?";
6525 PyDTrace_LINE(co_filename, co_name, line);
6526 }
Łukasz Langaa785c872016-09-09 17:37:37 -07006527 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00006528 trace_info->instr_prev = frame->f_lasti;
Łukasz Langaa785c872016-09-09 17:37:37 -07006529}
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006530
6531
6532/* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
6533 for the limited API. */
6534
6535#undef Py_EnterRecursiveCall
6536
6537int Py_EnterRecursiveCall(const char *where)
6538{
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006539 return _Py_EnterRecursiveCall_inline(where);
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006540}
6541
6542#undef Py_LeaveRecursiveCall
6543
6544void Py_LeaveRecursiveCall(void)
6545{
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006546 _Py_LeaveRecursiveCall_inline();
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006547}