blob: 7418b15176d2ae80151536dab661e43caa41d4a1 [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) {
1032 if (PyList_CheckExact(match_args)) {
1033 Py_SETREF(match_args, PyList_AsTuple(match_args));
1034 }
1035 if (match_args == NULL) {
1036 goto fail;
1037 }
1038 if (!PyTuple_CheckExact(match_args)) {
1039 const char *e = "%s.__match_args__ must be a list or tuple "
1040 "(got %s)";
1041 _PyErr_Format(tstate, PyExc_TypeError, e,
1042 ((PyTypeObject *)type)->tp_name,
1043 Py_TYPE(match_args)->tp_name);
1044 goto fail;
1045 }
1046 }
1047 else if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
1048 _PyErr_Clear(tstate);
1049 // _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
1050 // define __match_args__. This is natural behavior for subclasses:
1051 // it's as if __match_args__ is some "magic" value that is lost as
1052 // soon as they redefine it.
1053 match_args = PyTuple_New(0);
1054 match_self = PyType_HasFeature((PyTypeObject*)type,
1055 _Py_TPFLAGS_MATCH_SELF);
1056 }
1057 else {
1058 goto fail;
1059 }
1060 assert(PyTuple_CheckExact(match_args));
1061 Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
1062 if (allowed < nargs) {
1063 const char *plural = (allowed == 1) ? "" : "s";
1064 _PyErr_Format(tstate, PyExc_TypeError,
1065 "%s() accepts %d positional sub-pattern%s (%d given)",
1066 ((PyTypeObject*)type)->tp_name,
1067 allowed, plural, nargs);
1068 goto fail;
1069 }
1070 if (match_self) {
1071 // Easy. Copy the subject itself, and move on to kwargs.
1072 PyList_Append(attrs, subject);
1073 }
1074 else {
1075 for (Py_ssize_t i = 0; i < nargs; i++) {
1076 PyObject *name = PyTuple_GET_ITEM(match_args, i);
1077 if (!PyUnicode_CheckExact(name)) {
1078 _PyErr_Format(tstate, PyExc_TypeError,
1079 "__match_args__ elements must be strings "
1080 "(got %s)", Py_TYPE(name)->tp_name);
1081 goto fail;
1082 }
1083 PyObject *attr = match_class_attr(tstate, subject, type, name,
1084 seen);
1085 if (attr == NULL) {
1086 goto fail;
1087 }
1088 PyList_Append(attrs, attr);
1089 Py_DECREF(attr);
1090 }
1091 }
1092 Py_CLEAR(match_args);
1093 }
1094 // Finally, the keyword subpatterns:
1095 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
1096 PyObject *name = PyTuple_GET_ITEM(kwargs, i);
1097 PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
1098 if (attr == NULL) {
1099 goto fail;
1100 }
1101 PyList_Append(attrs, attr);
1102 Py_DECREF(attr);
1103 }
1104 Py_SETREF(attrs, PyList_AsTuple(attrs));
1105 Py_DECREF(seen);
1106 return attrs;
1107fail:
1108 // We really don't care whether an error was raised or not... that's our
1109 // caller's problem. All we know is that the match failed.
1110 Py_XDECREF(match_args);
1111 Py_DECREF(seen);
1112 Py_DECREF(attrs);
1113 return NULL;
1114}
1115
1116
Victor Stinner09532fe2019-05-10 23:39:09 +02001117static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
Victor Stinner438a12d2019-05-24 17:01:38 +02001118static int unpack_iterable(PyThreadState *, PyObject *, int, int, PyObject **);
Guido van Rossum1aa14831997-01-21 05:34:20 +00001119
Victor Stinnere225beb2019-06-03 18:14:24 +02001120#define _Py_TracingPossible(ceval) ((ceval)->tracing_possible)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001121
Guido van Rossum374a9221991-04-04 10:40:29 +00001122
Guido van Rossumb209a111997-04-29 18:18:01 +00001123PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001124PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001125{
Victor Stinner46496f92021-02-20 15:17:18 +01001126 PyThreadState *tstate = PyThreadState_GET();
Mark Shannon0332e562021-02-01 10:42:03 +00001127 if (locals == NULL) {
1128 locals = globals;
1129 }
Victor Stinner46496f92021-02-20 15:17:18 +01001130 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals);
Mark Shannon0332e562021-02-01 10:42:03 +00001131 if (builtins == NULL) {
1132 return NULL;
1133 }
1134 PyFrameConstructor desc = {
1135 .fc_globals = globals,
1136 .fc_builtins = builtins,
1137 .fc_name = ((PyCodeObject *)co)->co_name,
1138 .fc_qualname = ((PyCodeObject *)co)->co_name,
1139 .fc_code = co,
1140 .fc_defaults = NULL,
1141 .fc_kwdefaults = NULL,
1142 .fc_closure = NULL
1143 };
Victor Stinner46496f92021-02-20 15:17:18 +01001144 return _PyEval_Vector(tstate, &desc, locals, NULL, 0, NULL);
Guido van Rossum681d79a1995-07-18 14:51:37 +00001145}
1146
1147
1148/* Interpreter main loop */
1149
Martin v. Löwis8d97e332004-06-27 15:43:12 +00001150PyObject *
Victor Stinnerb9e68122019-11-14 12:20:46 +01001151PyEval_EvalFrame(PyFrameObject *f)
1152{
Victor Stinner0b72b232020-03-12 23:18:39 +01001153 /* Function kept for backward compatibility */
Victor Stinnerb9e68122019-11-14 12:20:46 +01001154 PyThreadState *tstate = _PyThreadState_GET();
1155 return _PyEval_EvalFrame(tstate, f, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001156}
1157
1158PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001159PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Guido van Rossum374a9221991-04-04 10:40:29 +00001160{
Victor Stinnerb9e68122019-11-14 12:20:46 +01001161 PyThreadState *tstate = _PyThreadState_GET();
1162 return _PyEval_EvalFrame(tstate, f, throwflag);
Brett Cannon3cebf932016-09-05 15:33:46 -07001163}
1164
Victor Stinnerda2914d2020-03-20 09:29:08 +01001165
1166/* Handle signals, pending calls, GIL drop request
1167 and asynchronous exception */
1168static int
1169eval_frame_handle_pending(PyThreadState *tstate)
1170{
Victor Stinnerda2914d2020-03-20 09:29:08 +01001171 _PyRuntimeState * const runtime = &_PyRuntime;
1172 struct _ceval_runtime_state *ceval = &runtime->ceval;
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001173
1174 /* Pending signals */
Victor Stinner299b8c62020-05-05 17:40:18 +02001175 if (_Py_atomic_load_relaxed(&ceval->signals_pending)) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001176 if (handle_signals(tstate) != 0) {
1177 return -1;
1178 }
1179 }
1180
1181 /* Pending calls */
Victor Stinner299b8c62020-05-05 17:40:18 +02001182 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinnerda2914d2020-03-20 09:29:08 +01001183 if (_Py_atomic_load_relaxed(&ceval2->pending.calls_to_do)) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001184 if (make_pending_calls(tstate->interp) != 0) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001185 return -1;
1186 }
1187 }
1188
1189 /* GIL drop request */
Victor Stinner0b1e3302020-05-05 16:14:31 +02001190 if (_Py_atomic_load_relaxed(&ceval2->gil_drop_request)) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001191 /* Give another thread a chance */
1192 if (_PyThreadState_Swap(&runtime->gilstate, NULL) != tstate) {
1193 Py_FatalError("tstate mix-up");
1194 }
Victor Stinner0b1e3302020-05-05 16:14:31 +02001195 drop_gil(ceval, ceval2, tstate);
Victor Stinnerda2914d2020-03-20 09:29:08 +01001196
1197 /* Other threads may run now */
1198
1199 take_gil(tstate);
1200
Victor Stinnere838a932020-05-05 19:56:48 +02001201#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1202 (void)_PyThreadState_Swap(&runtime->gilstate, tstate);
1203#else
Victor Stinnerda2914d2020-03-20 09:29:08 +01001204 if (_PyThreadState_Swap(&runtime->gilstate, tstate) != NULL) {
1205 Py_FatalError("orphan tstate");
1206 }
Victor Stinnere838a932020-05-05 19:56:48 +02001207#endif
Victor Stinnerda2914d2020-03-20 09:29:08 +01001208 }
1209
1210 /* Check for asynchronous exception. */
1211 if (tstate->async_exc != NULL) {
1212 PyObject *exc = tstate->async_exc;
1213 tstate->async_exc = NULL;
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001214 UNSIGNAL_ASYNC_EXC(tstate->interp);
Victor Stinnerda2914d2020-03-20 09:29:08 +01001215 _PyErr_SetNone(tstate, exc);
1216 Py_DECREF(exc);
1217 return -1;
1218 }
1219
Victor Stinnerd96a7a82020-11-13 14:44:42 +01001220#ifdef MS_WINDOWS
1221 // bpo-42296: On Windows, _PyEval_SignalReceived() can be called in a
1222 // different thread than the Python thread, in which case
1223 // _Py_ThreadCanHandleSignals() is wrong. Recompute eval_breaker in the
1224 // current Python thread with the correct _Py_ThreadCanHandleSignals()
1225 // value. It prevents to interrupt the eval loop at every instruction if
1226 // the current Python thread cannot handle signals (if
1227 // _Py_ThreadCanHandleSignals() is false).
1228 COMPUTE_EVAL_BREAKER(tstate->interp, ceval, ceval2);
1229#endif
1230
Victor Stinnerda2914d2020-03-20 09:29:08 +01001231 return 0;
1232}
1233
Victor Stinnerc6944e72016-11-11 02:13:35 +01001234PyObject* _Py_HOT_FUNCTION
Victor Stinner0b72b232020-03-12 23:18:39 +01001235_PyEval_EvalFrameDefault(PyThreadState *tstate, PyFrameObject *f, int throwflag)
Brett Cannon3cebf932016-09-05 15:33:46 -07001236{
Victor Stinner3026cad2020-06-01 16:02:40 +02001237 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner0b72b232020-03-12 23:18:39 +01001238
Guido van Rossum950361c1997-01-24 13:49:28 +00001239#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 int lastopcode = 0;
Guido van Rossum950361c1997-01-24 13:49:28 +00001241#endif
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001242 PyObject **stack_pointer; /* Next free slot in value stack */
Serhiy Storchakaab874002016-09-11 13:48:15 +03001243 const _Py_CODEUNIT *next_instr;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001244 int opcode; /* Current opcode */
1245 int oparg; /* Current opcode argument, if any */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001246 PyObject **fastlocals, **freevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 PyObject *retval = NULL; /* Return value */
Victor Stinnerdab84232020-03-17 18:56:44 +01001248 struct _ceval_state * const ceval2 = &tstate->interp->ceval;
Victor Stinner50e6e992020-03-19 02:41:21 +01001249 _Py_atomic_int * const eval_breaker = &ceval2->eval_breaker;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 PyCodeObject *co;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 /* when tracing we set things up so that
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 not (instr_lb <= current_bytecode_offset < instr_ub)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 is true when the line being executed has changed. The
1257 initial values are such as to make this false the first
1258 time it is tested. */
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001259
Serhiy Storchakaab874002016-09-11 13:48:15 +03001260 const _Py_CODEUNIT *first_instr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyObject *names;
1262 PyObject *consts;
Inada Naoki91234a12019-06-03 21:30:58 +09001263 _PyOpcache *co_opcache;
Guido van Rossum374a9221991-04-04 10:40:29 +00001264
Brett Cannon368b4b72012-04-02 12:17:59 -04001265#ifdef LLTRACE
Victor Stinner3c1e4812012-03-26 22:10:51 +02001266 _Py_IDENTIFIER(__ltrace__);
Brett Cannon368b4b72012-04-02 12:17:59 -04001267#endif
Victor Stinner3c1e4812012-03-26 22:10:51 +02001268
Antoine Pitroub52ec782009-01-25 16:34:23 +00001269/* Computed GOTOs, or
1270 the-optimization-commonly-but-improperly-known-as-"threaded code"
1271 using gcc's labels-as-values extension
1272 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
1273
1274 The traditional bytecode evaluation loop uses a "switch" statement, which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 decent compilers will optimize as a single indirect branch instruction
Antoine Pitroub52ec782009-01-25 16:34:23 +00001276 combined with a lookup table of jump addresses. However, since the
1277 indirect jump instruction is shared by all opcodes, the CPU will have a
1278 hard time making the right prediction for where to jump next (actually,
1279 it will be always wrong except in the uncommon case of a sequence of
1280 several identical opcodes).
1281
1282 "Threaded code" in contrast, uses an explicit jump table and an explicit
1283 indirect jump instruction at the end of each opcode. Since the jump
1284 instruction is at a different address for each opcode, the CPU will make a
1285 separate prediction for each of these instructions, which is equivalent to
1286 predicting the second opcode of each opcode pair. These predictions have
1287 a much better chance to turn out valid, especially in small bytecode loops.
1288
1289 A mispredicted branch on a modern CPU flushes the whole pipeline and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 can cost several CPU cycles (depending on the pipeline depth),
Antoine Pitroub52ec782009-01-25 16:34:23 +00001291 and potentially many more instructions (depending on the pipeline width).
1292 A correctly predicted branch, however, is nearly free.
1293
1294 At the time of this writing, the "threaded code" version is up to 15-20%
1295 faster than the normal "switch" version, depending on the compiler and the
1296 CPU architecture.
1297
1298 We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined,
1299 because it would render the measurements invalid.
1300
1301
1302 NOTE: care must be taken that the compiler doesn't try to "optimize" the
1303 indirect jumps by sharing them between all opcodes. Such optimizations
1304 can be disabled on gcc by using the -fno-gcse flag (or possibly
1305 -fno-crossjumping).
1306*/
1307
Antoine Pitrou042b1282010-08-13 21:15:58 +00001308#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitroub52ec782009-01-25 16:34:23 +00001309#undef USE_COMPUTED_GOTOS
Antoine Pitrou042b1282010-08-13 21:15:58 +00001310#define USE_COMPUTED_GOTOS 0
Antoine Pitroub52ec782009-01-25 16:34:23 +00001311#endif
1312
Antoine Pitrou042b1282010-08-13 21:15:58 +00001313#ifdef HAVE_COMPUTED_GOTOS
1314 #ifndef USE_COMPUTED_GOTOS
1315 #define USE_COMPUTED_GOTOS 1
1316 #endif
1317#else
1318 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
1319 #error "Computed gotos are not supported on this compiler."
1320 #endif
1321 #undef USE_COMPUTED_GOTOS
1322 #define USE_COMPUTED_GOTOS 0
1323#endif
1324
1325#if USE_COMPUTED_GOTOS
Antoine Pitroub52ec782009-01-25 16:34:23 +00001326/* Import the static jump table */
1327#include "opcode_targets.h"
1328
Antoine Pitroub52ec782009-01-25 16:34:23 +00001329#define TARGET(op) \
Benjamin Petersonddd19492018-09-16 22:38:02 -07001330 op: \
1331 TARGET_##op
Antoine Pitroub52ec782009-01-25 16:34:23 +00001332
Antoine Pitroub52ec782009-01-25 16:34:23 +00001333#ifdef LLTRACE
1334#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 { \
Victor Stinnerdab84232020-03-17 18:56:44 +01001336 if (!lltrace && !_Py_TracingPossible(ceval2) && !PyDTrace_LINE_ENABLED()) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 f->f_lasti = INSTR_OFFSET(); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001338 NEXTOPARG(); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001339 goto *opcode_targets[opcode]; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 } \
1341 goto fast_next_opcode; \
1342 }
Antoine Pitroub52ec782009-01-25 16:34:23 +00001343#else
1344#define FAST_DISPATCH() \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 { \
Victor Stinnerdab84232020-03-17 18:56:44 +01001346 if (!_Py_TracingPossible(ceval2) && !PyDTrace_LINE_ENABLED()) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 f->f_lasti = INSTR_OFFSET(); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001348 NEXTOPARG(); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001349 goto *opcode_targets[opcode]; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 } \
1351 goto fast_next_opcode; \
1352 }
Antoine Pitroub52ec782009-01-25 16:34:23 +00001353#endif
1354
Victor Stinner09532fe2019-05-10 23:39:09 +02001355#define DISPATCH() \
1356 { \
1357 if (!_Py_atomic_load_relaxed(eval_breaker)) { \
1358 FAST_DISPATCH(); \
1359 } \
1360 continue; \
1361 }
1362
Antoine Pitroub52ec782009-01-25 16:34:23 +00001363#else
Benjamin Petersonddd19492018-09-16 22:38:02 -07001364#define TARGET(op) op
Antoine Pitroub52ec782009-01-25 16:34:23 +00001365#define FAST_DISPATCH() goto fast_next_opcode
Victor Stinner09532fe2019-05-10 23:39:09 +02001366#define DISPATCH() continue
Antoine Pitroub52ec782009-01-25 16:34:23 +00001367#endif
1368
1369
Neal Norwitza81d2202002-07-14 00:27:26 +00001370/* Tuple access macros */
1371
1372#ifndef Py_DEBUG
1373#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
1374#else
1375#define GETITEM(v, i) PyTuple_GetItem((v), (i))
1376#endif
1377
Guido van Rossum374a9221991-04-04 10:40:29 +00001378/* Code access macros */
1379
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001380/* The integer overflow is checked by an assertion below. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001381#define INSTR_OFFSET() \
1382 (sizeof(_Py_CODEUNIT) * (int)(next_instr - first_instr))
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001383#define NEXTOPARG() do { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001384 _Py_CODEUNIT word = *next_instr; \
1385 opcode = _Py_OPCODE(word); \
1386 oparg = _Py_OPARG(word); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001387 next_instr++; \
1388 } while (0)
Serhiy Storchakaab874002016-09-11 13:48:15 +03001389#define JUMPTO(x) (next_instr = first_instr + (x) / sizeof(_Py_CODEUNIT))
1390#define JUMPBY(x) (next_instr += (x) / sizeof(_Py_CODEUNIT))
Guido van Rossum374a9221991-04-04 10:40:29 +00001391
Raymond Hettingerf606f872003-03-16 03:11:04 +00001392/* OpCode prediction macros
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 Some opcodes tend to come in pairs thus making it possible to
1394 predict the second code when the first is run. For example,
Serhiy Storchakada9c5132016-06-27 18:58:57 +03001395 COMPARE_OP is often followed by POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 Verifying the prediction costs a single high-speed test of a register
1398 variable against a constant. If the pairing was good, then the
1399 processor's own internal branch predication has a high likelihood of
1400 success, resulting in a nearly zero-overhead transition to the
1401 next opcode. A successful prediction saves a trip through the eval-loop
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001402 including its unpredictable switch-case branch. Combined with the
1403 processor's internal branch prediction, a successful PREDICT has the
1404 effect of making the two opcodes run as if they were a single new opcode
1405 with the bodies combined.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001406
Georg Brandl86b2fb92008-07-16 03:43:04 +00001407 If collecting opcode statistics, your choices are to either keep the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 predictions turned-on and interpret the results as if some opcodes
1409 had been combined or turn-off predictions so that the opcode frequency
1410 counter updates for both opcodes.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001411
1412 Opcode prediction is disabled with threaded code, since the latter allows
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 the CPU to record separate branch prediction information for each
1414 opcode.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001415
Raymond Hettingerf606f872003-03-16 03:11:04 +00001416*/
1417
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001418#define PREDICT_ID(op) PRED_##op
1419
Antoine Pitrou042b1282010-08-13 21:15:58 +00001420#if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001421#define PREDICT(op) if (0) goto PREDICT_ID(op)
Raymond Hettingera7216982004-02-08 19:59:27 +00001422#else
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001423#define PREDICT(op) \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001424 do { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001425 _Py_CODEUNIT word = *next_instr; \
1426 opcode = _Py_OPCODE(word); \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001427 if (opcode == op) { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001428 oparg = _Py_OPARG(word); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001429 next_instr++; \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001430 goto PREDICT_ID(op); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001431 } \
1432 } while(0)
Antoine Pitroub52ec782009-01-25 16:34:23 +00001433#endif
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001434#define PREDICTED(op) PREDICT_ID(op):
Antoine Pitroub52ec782009-01-25 16:34:23 +00001435
Raymond Hettingerf606f872003-03-16 03:11:04 +00001436
Guido van Rossum374a9221991-04-04 10:40:29 +00001437/* Stack manipulation macros */
1438
Martin v. Löwis18e16552006-02-15 17:27:45 +00001439/* The stack can grow at most MAXINT deep, as co_nlocals and
1440 co_stacksize are ints. */
Stefan Krahb7e10102010-06-23 18:42:39 +00001441#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
1442#define EMPTY() (STACK_LEVEL() == 0)
1443#define TOP() (stack_pointer[-1])
1444#define SECOND() (stack_pointer[-2])
1445#define THIRD() (stack_pointer[-3])
1446#define FOURTH() (stack_pointer[-4])
1447#define PEEK(n) (stack_pointer[-(n)])
1448#define SET_TOP(v) (stack_pointer[-1] = (v))
1449#define SET_SECOND(v) (stack_pointer[-2] = (v))
1450#define SET_THIRD(v) (stack_pointer[-3] = (v))
1451#define SET_FOURTH(v) (stack_pointer[-4] = (v))
Stefan Krahb7e10102010-06-23 18:42:39 +00001452#define BASIC_STACKADJ(n) (stack_pointer += n)
1453#define BASIC_PUSH(v) (*stack_pointer++ = (v))
1454#define BASIC_POP() (*--stack_pointer)
Guido van Rossum374a9221991-04-04 10:40:29 +00001455
Guido van Rossum96a42c81992-01-12 02:29:51 +00001456#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457#define PUSH(v) { (void)(BASIC_PUSH(v), \
Victor Stinner438a12d2019-05-24 17:01:38 +02001458 lltrace && prtrace(tstate, TOP(), "push")); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001459 assert(STACK_LEVEL() <= co->co_stacksize); }
Victor Stinner438a12d2019-05-24 17:01:38 +02001460#define POP() ((void)(lltrace && prtrace(tstate, TOP(), "pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001461 BASIC_POP())
costypetrisor8ed317f2018-07-31 20:55:14 +00001462#define STACK_GROW(n) do { \
1463 assert(n >= 0); \
1464 (void)(BASIC_STACKADJ(n), \
Victor Stinner438a12d2019-05-24 17:01:38 +02001465 lltrace && prtrace(tstate, TOP(), "stackadj")); \
costypetrisor8ed317f2018-07-31 20:55:14 +00001466 assert(STACK_LEVEL() <= co->co_stacksize); \
1467 } while (0)
1468#define STACK_SHRINK(n) do { \
1469 assert(n >= 0); \
Victor Stinner438a12d2019-05-24 17:01:38 +02001470 (void)(lltrace && prtrace(tstate, TOP(), "stackadj")); \
costypetrisor8ed317f2018-07-31 20:55:14 +00001471 (void)(BASIC_STACKADJ(-n)); \
1472 assert(STACK_LEVEL() <= co->co_stacksize); \
1473 } while (0)
Christian Heimes0449f632007-12-15 01:27:15 +00001474#define EXT_POP(STACK_POINTER) ((void)(lltrace && \
Victor Stinner438a12d2019-05-24 17:01:38 +02001475 prtrace(tstate, (STACK_POINTER)[-1], "ext_pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001476 *--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001477#else
Stefan Krahb7e10102010-06-23 18:42:39 +00001478#define PUSH(v) BASIC_PUSH(v)
1479#define POP() BASIC_POP()
costypetrisor8ed317f2018-07-31 20:55:14 +00001480#define STACK_GROW(n) BASIC_STACKADJ(n)
1481#define STACK_SHRINK(n) BASIC_STACKADJ(-n)
Guido van Rossumc2e20742006-02-27 22:32:47 +00001482#define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001483#endif
1484
Guido van Rossum681d79a1995-07-18 14:51:37 +00001485/* Local variable macros */
1486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487#define GETLOCAL(i) (fastlocals[i])
Guido van Rossumcfbf1a32002-03-28 20:17:52 +00001488
1489/* The SETLOCAL() macro must not DECREF the local variable in-place and
1490 then store the new value; it must copy the old value to a temporary
1491 value, then store the new value, and then DECREF the temporary value.
1492 This is because it is possible that during the DECREF the frame is
1493 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1494 variable would be pointing to already-freed memory. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001496 GETLOCAL(i) = value; \
1497 Py_XDECREF(tmp); } while (0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001498
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001499
1500#define UNWIND_BLOCK(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 while (STACK_LEVEL() > (b)->b_level) { \
1502 PyObject *v = POP(); \
1503 Py_XDECREF(v); \
1504 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001505
1506#define UNWIND_EXCEPT_HANDLER(b) \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001507 do { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 PyObject *type, *value, *traceback; \
Mark Shannonae3087c2017-10-22 22:41:51 +01001509 _PyErr_StackItem *exc_info; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 assert(STACK_LEVEL() >= (b)->b_level + 3); \
1511 while (STACK_LEVEL() > (b)->b_level + 3) { \
1512 value = POP(); \
1513 Py_XDECREF(value); \
1514 } \
Mark Shannonae3087c2017-10-22 22:41:51 +01001515 exc_info = tstate->exc_info; \
1516 type = exc_info->exc_type; \
1517 value = exc_info->exc_value; \
1518 traceback = exc_info->exc_traceback; \
1519 exc_info->exc_type = POP(); \
1520 exc_info->exc_value = POP(); \
1521 exc_info->exc_traceback = POP(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_XDECREF(type); \
1523 Py_XDECREF(value); \
1524 Py_XDECREF(traceback); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001525 } while(0)
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001526
Inada Naoki91234a12019-06-03 21:30:58 +09001527 /* macros for opcode cache */
1528#define OPCACHE_CHECK() \
1529 do { \
1530 co_opcache = NULL; \
1531 if (co->co_opcache != NULL) { \
Pablo Galindo109826c2020-10-20 06:22:44 +01001532 unsigned char co_opcache_offset = \
Inada Naoki91234a12019-06-03 21:30:58 +09001533 co->co_opcache_map[next_instr - first_instr]; \
Pablo Galindo109826c2020-10-20 06:22:44 +01001534 if (co_opcache_offset > 0) { \
1535 assert(co_opcache_offset <= co->co_opcache_size); \
1536 co_opcache = &co->co_opcache[co_opcache_offset - 1]; \
Inada Naoki91234a12019-06-03 21:30:58 +09001537 assert(co_opcache != NULL); \
Inada Naoki91234a12019-06-03 21:30:58 +09001538 } \
1539 } \
1540 } while (0)
1541
Pablo Galindo109826c2020-10-20 06:22:44 +01001542#define OPCACHE_DEOPT() \
1543 do { \
1544 if (co_opcache != NULL) { \
1545 co_opcache->optimized = -1; \
1546 unsigned char co_opcache_offset = \
1547 co->co_opcache_map[next_instr - first_instr]; \
1548 assert(co_opcache_offset <= co->co_opcache_size); \
1549 co->co_opcache_map[co_opcache_offset] = 0; \
1550 co_opcache = NULL; \
1551 } \
1552 } while (0)
1553
1554#define OPCACHE_DEOPT_LOAD_ATTR() \
1555 do { \
1556 if (co_opcache != NULL) { \
1557 OPCACHE_STAT_ATTR_DEOPT(); \
1558 OPCACHE_DEOPT(); \
1559 } \
1560 } while (0)
1561
1562#define OPCACHE_MAYBE_DEOPT_LOAD_ATTR() \
1563 do { \
1564 if (co_opcache != NULL && --co_opcache->optimized <= 0) { \
1565 OPCACHE_DEOPT_LOAD_ATTR(); \
1566 } \
1567 } while (0)
1568
Inada Naoki91234a12019-06-03 21:30:58 +09001569#if OPCACHE_STATS
1570
1571#define OPCACHE_STAT_GLOBAL_HIT() \
1572 do { \
1573 if (co->co_opcache != NULL) opcache_global_hits++; \
1574 } while (0)
1575
1576#define OPCACHE_STAT_GLOBAL_MISS() \
1577 do { \
1578 if (co->co_opcache != NULL) opcache_global_misses++; \
1579 } while (0)
1580
1581#define OPCACHE_STAT_GLOBAL_OPT() \
1582 do { \
1583 if (co->co_opcache != NULL) opcache_global_opts++; \
1584 } while (0)
1585
Pablo Galindo109826c2020-10-20 06:22:44 +01001586#define OPCACHE_STAT_ATTR_HIT() \
1587 do { \
1588 if (co->co_opcache != NULL) opcache_attr_hits++; \
1589 } while (0)
1590
1591#define OPCACHE_STAT_ATTR_MISS() \
1592 do { \
1593 if (co->co_opcache != NULL) opcache_attr_misses++; \
1594 } while (0)
1595
1596#define OPCACHE_STAT_ATTR_OPT() \
1597 do { \
1598 if (co->co_opcache!= NULL) opcache_attr_opts++; \
1599 } while (0)
1600
1601#define OPCACHE_STAT_ATTR_DEOPT() \
1602 do { \
1603 if (co->co_opcache != NULL) opcache_attr_deopts++; \
1604 } while (0)
1605
1606#define OPCACHE_STAT_ATTR_TOTAL() \
1607 do { \
1608 if (co->co_opcache != NULL) opcache_attr_total++; \
1609 } while (0)
1610
Inada Naoki91234a12019-06-03 21:30:58 +09001611#else /* OPCACHE_STATS */
1612
1613#define OPCACHE_STAT_GLOBAL_HIT()
1614#define OPCACHE_STAT_GLOBAL_MISS()
1615#define OPCACHE_STAT_GLOBAL_OPT()
1616
Pablo Galindo109826c2020-10-20 06:22:44 +01001617#define OPCACHE_STAT_ATTR_HIT()
1618#define OPCACHE_STAT_ATTR_MISS()
1619#define OPCACHE_STAT_ATTR_OPT()
1620#define OPCACHE_STAT_ATTR_DEOPT()
1621#define OPCACHE_STAT_ATTR_TOTAL()
1622
Inada Naoki91234a12019-06-03 21:30:58 +09001623#endif
1624
Guido van Rossuma027efa1997-05-05 20:56:21 +00001625/* Start of code */
1626
Victor Stinnerbe434dc2019-11-05 00:51:22 +01001627 if (_Py_EnterRecursiveCall(tstate, "")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01001629 }
Guido van Rossum8861b741996-07-30 16:49:37 +00001630
Mark Shannon8e1b4062021-03-05 14:45:50 +00001631 PyTraceInfo trace_info;
1632 /* Mark trace_info as initialized */
1633 trace_info.code = NULL;
1634
1635 /* push frame */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 tstate->frame = f;
Mark Shannon86433452021-01-07 16:49:02 +00001637 co = f->f_code;
Tim Peters5ca576e2001-06-18 22:08:13 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (tstate->use_tracing) {
1640 if (tstate->c_tracefunc != NULL) {
1641 /* tstate->c_tracefunc, if defined, is a
1642 function that will be called on *every* entry
1643 to a code block. Its return value, if not
1644 None, is a function that will be called at
1645 the start of each executed line of code.
1646 (Actually, the function must return itself
1647 in order to continue tracing.) The trace
1648 functions are called with three arguments:
1649 a pointer to the current frame, a string
1650 indicating why the function is called, and
1651 an argument which depends on the situation.
1652 The global trace function is also called
1653 whenever an exception is detected. */
1654 if (call_trace_protected(tstate->c_tracefunc,
1655 tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001656 tstate, f, &trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00001657 PyTrace_CALL, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 /* Trace function raised an error */
1659 goto exit_eval_frame;
1660 }
1661 }
1662 if (tstate->c_profilefunc != NULL) {
1663 /* Similar for c_profilefunc, except it needn't
1664 return itself and isn't called for "line" events */
1665 if (call_trace_protected(tstate->c_profilefunc,
1666 tstate->c_profileobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001667 tstate, f, &trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00001668 PyTrace_CALL, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* Profile function raised an error */
1670 goto exit_eval_frame;
1671 }
1672 }
1673 }
Neil Schemenauer6c0f2002001-09-04 19:03:35 +00001674
Łukasz Langaa785c872016-09-09 17:37:37 -07001675 if (PyDTrace_FUNCTION_ENTRY_ENABLED())
1676 dtrace_function_entry(f);
1677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 names = co->co_names;
1679 consts = co->co_consts;
1680 fastlocals = f->f_localsplus;
1681 freevars = f->f_localsplus + co->co_nlocals;
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001682 assert(PyBytes_Check(co->co_code));
1683 assert(PyBytes_GET_SIZE(co->co_code) <= INT_MAX);
Serhiy Storchakaab874002016-09-11 13:48:15 +03001684 assert(PyBytes_GET_SIZE(co->co_code) % sizeof(_Py_CODEUNIT) == 0);
1685 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(co->co_code), sizeof(_Py_CODEUNIT)));
1686 first_instr = (_Py_CODEUNIT *) PyBytes_AS_STRING(co->co_code);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001687 /*
1688 f->f_lasti refers to the index of the last instruction,
1689 unless it's -1 in which case next_instr should be first_instr.
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001690
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001691 YIELD_FROM sets f_lasti to itself, in order to repeatedly yield
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05001692 multiple values.
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 When the PREDICT() macros are enabled, some opcode pairs follow in
1695 direct succession without updating f->f_lasti. A successful
1696 prediction effectively links the two codes together as if they
1697 were a single new opcode; accordingly,f->f_lasti will point to
1698 the first code in the pair (for instance, GET_ITER followed by
1699 FOR_ITER is effectively a single opcode and f->f_lasti will point
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001700 to the beginning of the combined pair.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 */
Serhiy Storchakaab874002016-09-11 13:48:15 +03001702 assert(f->f_lasti >= -1);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001703 next_instr = first_instr;
1704 if (f->f_lasti >= 0) {
Serhiy Storchakaab874002016-09-11 13:48:15 +03001705 assert(f->f_lasti % sizeof(_Py_CODEUNIT) == 0);
1706 next_instr += f->f_lasti / sizeof(_Py_CODEUNIT) + 1;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001707 }
Mark Shannoncb9879b2020-07-17 11:44:23 +01001708 stack_pointer = f->f_valuestack + f->f_stackdepth;
1709 /* Set f->f_stackdepth to -1.
1710 * Update when returning or calling trace function.
1711 Having f_stackdepth <= 0 ensures that invalid
1712 values are not visible to the cycle GC.
1713 We choose -1 rather than 0 to assist debugging.
1714 */
1715 f->f_stackdepth = -1;
1716 f->f_state = FRAME_EXECUTING;
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001717
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001718 if (co->co_opcache_flag < opcache_min_runs) {
Inada Naoki91234a12019-06-03 21:30:58 +09001719 co->co_opcache_flag++;
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001720 if (co->co_opcache_flag == opcache_min_runs) {
Inada Naoki91234a12019-06-03 21:30:58 +09001721 if (_PyCode_InitOpcache(co) < 0) {
Victor Stinner25104942020-04-24 02:43:18 +02001722 goto exit_eval_frame;
Inada Naoki91234a12019-06-03 21:30:58 +09001723 }
1724#if OPCACHE_STATS
1725 opcache_code_objects_extra_mem +=
1726 PyBytes_Size(co->co_code) / sizeof(_Py_CODEUNIT) +
1727 sizeof(_PyOpcache) * co->co_opcache_size;
1728 opcache_code_objects++;
1729#endif
1730 }
1731 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001732
Tim Peters5ca576e2001-06-18 22:08:13 +00001733#ifdef LLTRACE
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001734 {
1735 int r = _PyDict_ContainsId(f->f_globals, &PyId___ltrace__);
1736 if (r < 0) {
1737 goto exit_eval_frame;
1738 }
1739 lltrace = r;
1740 }
Tim Peters5ca576e2001-06-18 22:08:13 +00001741#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00001742
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001743 if (throwflag) { /* support for generator.throw() */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001744 goto error;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001745 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001746
Victor Stinnerace47d72013-07-18 01:41:08 +02001747#ifdef Py_DEBUG
Victor Stinner0b72b232020-03-12 23:18:39 +01001748 /* _PyEval_EvalFrameDefault() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +01001749 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +00001750 caller loses its exception */
Victor Stinner438a12d2019-05-24 17:01:38 +02001751 assert(!_PyErr_Occurred(tstate));
Victor Stinnerace47d72013-07-18 01:41:08 +02001752#endif
1753
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001754main_loop:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 for (;;) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1757 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
Victor Stinner438a12d2019-05-24 17:01:38 +02001758 assert(!_PyErr_Occurred(tstate));
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 /* Do periodic things. Doing this every time through
1761 the loop would add too much overhead, so we do it
1762 only every Nth instruction. We also do it if
Chris Jerdonek4a12d122020-05-14 19:25:45 -07001763 ``pending.calls_to_do'' is set, i.e. when an asynchronous
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 event needs attention (e.g. a signal handler or
1765 async I/O handler); see Py_AddPendingCall() and
1766 Py_MakePendingCalls() above. */
Guido van Rossumac7be682001-01-17 15:42:30 +00001767
Eric Snow7bda9de2019-03-08 17:25:54 -07001768 if (_Py_atomic_load_relaxed(eval_breaker)) {
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001769 opcode = _Py_OPCODE(*next_instr);
1770 if (opcode == SETUP_FINALLY ||
1771 opcode == SETUP_WITH ||
1772 opcode == BEFORE_ASYNC_WITH ||
1773 opcode == YIELD_FROM) {
1774 /* Few cases where we skip running signal handlers and other
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07001775 pending calls:
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001776 - If we're about to enter the 'with:'. It will prevent
1777 emitting a resource warning in the common idiom
1778 'with open(path) as file:'.
1779 - If we're about to enter the 'async with:'.
1780 - If we're about to enter the 'try:' of a try/finally (not
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07001781 *very* useful, but might help in some cases and it's
1782 traditional)
1783 - If we're resuming a chain of nested 'yield from' or
1784 'await' calls, then each frame is parked with YIELD_FROM
1785 as its next opcode. If the user hit control-C we want to
1786 wait until we've reached the innermost frame before
1787 running the signal handler and raising KeyboardInterrupt
1788 (see bpo-30039).
1789 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 goto fast_next_opcode;
1791 }
Eric Snowfdf282d2019-01-11 14:26:55 -07001792
Victor Stinnerda2914d2020-03-20 09:29:08 +01001793 if (eval_frame_handle_pending(tstate) != 0) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001794 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 }
1796 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 fast_next_opcode:
1799 f->f_lasti = INSTR_OFFSET();
Guido van Rossumac7be682001-01-17 15:42:30 +00001800
Łukasz Langaa785c872016-09-09 17:37:37 -07001801 if (PyDTrace_LINE_ENABLED())
Mark Shannon8e1b4062021-03-05 14:45:50 +00001802 maybe_dtrace_line(f, &trace_info);
Łukasz Langaa785c872016-09-09 17:37:37 -07001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* line-by-line tracing support */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001805
Victor Stinnerdab84232020-03-17 18:56:44 +01001806 if (_Py_TracingPossible(ceval2) &&
Benjamin Peterson51f46162013-01-23 08:38:47 -05001807 tstate->c_tracefunc != NULL && !tstate->tracing) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001808 int err;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02001809 /* see maybe_call_line_trace()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 for expository comments */
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02001811 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Tim Peters8a5c3c72004-04-05 19:36:21 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 err = maybe_call_line_trace(tstate->c_tracefunc,
1814 tstate->c_traceobj,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01001815 tstate, f,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001816 &trace_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* Reload possibly changed frame fields */
1818 JUMPTO(f->f_lasti);
Mark Shannoncb9879b2020-07-17 11:44:23 +01001819 stack_pointer = f->f_valuestack+f->f_stackdepth;
1820 f->f_stackdepth = -1;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001821 if (err)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 /* trace function raised an exception */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001823 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 }
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 /* Extract opcode and argument */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001827
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001828 NEXTOPARG();
Stefan Krahb7e10102010-06-23 18:42:39 +00001829 dispatch_opcode:
Guido van Rossum950361c1997-01-24 13:49:28 +00001830#ifdef DYNAMIC_EXECUTION_PROFILE
1831#ifdef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 dxpairs[lastopcode][opcode]++;
1833 lastopcode = opcode;
Guido van Rossum950361c1997-01-24 13:49:28 +00001834#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 dxp[opcode]++;
Guido van Rossum950361c1997-01-24 13:49:28 +00001836#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00001837
Guido van Rossum96a42c81992-01-12 02:29:51 +00001838#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 /* Instruction tracing */
Guido van Rossumac7be682001-01-17 15:42:30 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (lltrace) {
1842 if (HAS_ARG(opcode)) {
1843 printf("%d: %d, %d\n",
1844 f->f_lasti, opcode, oparg);
1845 }
1846 else {
1847 printf("%d: %d\n",
1848 f->f_lasti, opcode);
1849 }
1850 }
Guido van Rossum374a9221991-04-04 10:40:29 +00001851#endif
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 switch (opcode) {
Guido van Rossumac7be682001-01-17 15:42:30 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 /* BEWARE!
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001856 It is essential that any operation that fails must goto error
1857 and that all operation that succeed call [FAST_]DISPATCH() ! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001858
Benjamin Petersonddd19492018-09-16 22:38:02 -07001859 case TARGET(NOP): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 FAST_DISPATCH();
Benjamin Petersonddd19492018-09-16 22:38:02 -07001861 }
Raymond Hettinger9c18e812004-06-21 16:31:15 +00001862
Benjamin Petersonddd19492018-09-16 22:38:02 -07001863 case TARGET(LOAD_FAST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001864 PyObject *value = GETLOCAL(oparg);
1865 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02001866 format_exc_check_arg(tstate, PyExc_UnboundLocalError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001867 UNBOUNDLOCAL_ERROR_MSG,
1868 PyTuple_GetItem(co->co_varnames, oparg));
1869 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001871 Py_INCREF(value);
1872 PUSH(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001874 }
1875
Benjamin Petersonddd19492018-09-16 22:38:02 -07001876 case TARGET(LOAD_CONST): {
1877 PREDICTED(LOAD_CONST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001878 PyObject *value = GETITEM(consts, oparg);
1879 Py_INCREF(value);
1880 PUSH(value);
1881 FAST_DISPATCH();
1882 }
Neil Schemenauer63543862002-02-17 19:10:14 +00001883
Benjamin Petersonddd19492018-09-16 22:38:02 -07001884 case TARGET(STORE_FAST): {
1885 PREDICTED(STORE_FAST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001886 PyObject *value = POP();
1887 SETLOCAL(oparg, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001889 }
Neil Schemenauer63543862002-02-17 19:10:14 +00001890
Benjamin Petersonddd19492018-09-16 22:38:02 -07001891 case TARGET(POP_TOP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001892 PyObject *value = POP();
1893 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001895 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001896
Benjamin Petersonddd19492018-09-16 22:38:02 -07001897 case TARGET(ROT_TWO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001898 PyObject *top = TOP();
1899 PyObject *second = SECOND();
1900 SET_TOP(second);
1901 SET_SECOND(top);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001903 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001904
Benjamin Petersonddd19492018-09-16 22:38:02 -07001905 case TARGET(ROT_THREE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001906 PyObject *top = TOP();
1907 PyObject *second = SECOND();
1908 PyObject *third = THIRD();
1909 SET_TOP(second);
1910 SET_SECOND(third);
1911 SET_THIRD(top);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001913 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001914
Benjamin Petersonddd19492018-09-16 22:38:02 -07001915 case TARGET(ROT_FOUR): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001916 PyObject *top = TOP();
1917 PyObject *second = SECOND();
1918 PyObject *third = THIRD();
1919 PyObject *fourth = FOURTH();
1920 SET_TOP(second);
1921 SET_SECOND(third);
1922 SET_THIRD(fourth);
1923 SET_FOURTH(top);
1924 FAST_DISPATCH();
1925 }
1926
Benjamin Petersonddd19492018-09-16 22:38:02 -07001927 case TARGET(DUP_TOP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001928 PyObject *top = TOP();
1929 Py_INCREF(top);
1930 PUSH(top);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001932 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001933
Benjamin Petersonddd19492018-09-16 22:38:02 -07001934 case TARGET(DUP_TOP_TWO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001935 PyObject *top = TOP();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001936 PyObject *second = SECOND();
Benjamin Petersonf208df32012-10-12 11:37:56 -04001937 Py_INCREF(top);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001938 Py_INCREF(second);
costypetrisor8ed317f2018-07-31 20:55:14 +00001939 STACK_GROW(2);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001940 SET_TOP(top);
1941 SET_SECOND(second);
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00001942 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001943 }
Thomas Wouters434d0822000-08-24 20:11:32 +00001944
Benjamin Petersonddd19492018-09-16 22:38:02 -07001945 case TARGET(UNARY_POSITIVE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001946 PyObject *value = TOP();
1947 PyObject *res = PyNumber_Positive(value);
1948 Py_DECREF(value);
1949 SET_TOP(res);
1950 if (res == NULL)
1951 goto error;
1952 DISPATCH();
1953 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001954
Benjamin Petersonddd19492018-09-16 22:38:02 -07001955 case TARGET(UNARY_NEGATIVE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001956 PyObject *value = TOP();
1957 PyObject *res = PyNumber_Negative(value);
1958 Py_DECREF(value);
1959 SET_TOP(res);
1960 if (res == NULL)
1961 goto error;
1962 DISPATCH();
1963 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001964
Benjamin Petersonddd19492018-09-16 22:38:02 -07001965 case TARGET(UNARY_NOT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001966 PyObject *value = TOP();
1967 int err = PyObject_IsTrue(value);
1968 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 if (err == 0) {
1970 Py_INCREF(Py_True);
1971 SET_TOP(Py_True);
1972 DISPATCH();
1973 }
1974 else if (err > 0) {
1975 Py_INCREF(Py_False);
1976 SET_TOP(Py_False);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 DISPATCH();
1978 }
costypetrisor8ed317f2018-07-31 20:55:14 +00001979 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001980 goto error;
1981 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001982
Benjamin Petersonddd19492018-09-16 22:38:02 -07001983 case TARGET(UNARY_INVERT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001984 PyObject *value = TOP();
1985 PyObject *res = PyNumber_Invert(value);
1986 Py_DECREF(value);
1987 SET_TOP(res);
1988 if (res == NULL)
1989 goto error;
1990 DISPATCH();
1991 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001992
Benjamin Petersonddd19492018-09-16 22:38:02 -07001993 case TARGET(BINARY_POWER): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001994 PyObject *exp = POP();
1995 PyObject *base = TOP();
1996 PyObject *res = PyNumber_Power(base, exp, Py_None);
1997 Py_DECREF(base);
1998 Py_DECREF(exp);
1999 SET_TOP(res);
2000 if (res == NULL)
2001 goto error;
2002 DISPATCH();
2003 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002004
Benjamin Petersonddd19492018-09-16 22:38:02 -07002005 case TARGET(BINARY_MULTIPLY): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002006 PyObject *right = POP();
2007 PyObject *left = TOP();
2008 PyObject *res = PyNumber_Multiply(left, right);
2009 Py_DECREF(left);
2010 Py_DECREF(right);
2011 SET_TOP(res);
2012 if (res == NULL)
2013 goto error;
2014 DISPATCH();
2015 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002016
Benjamin Petersonddd19492018-09-16 22:38:02 -07002017 case TARGET(BINARY_MATRIX_MULTIPLY): {
Benjamin Petersond51374e2014-04-09 23:55:56 -04002018 PyObject *right = POP();
2019 PyObject *left = TOP();
2020 PyObject *res = PyNumber_MatrixMultiply(left, right);
2021 Py_DECREF(left);
2022 Py_DECREF(right);
2023 SET_TOP(res);
2024 if (res == NULL)
2025 goto error;
2026 DISPATCH();
2027 }
2028
Benjamin Petersonddd19492018-09-16 22:38:02 -07002029 case TARGET(BINARY_TRUE_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002030 PyObject *divisor = POP();
2031 PyObject *dividend = TOP();
2032 PyObject *quotient = PyNumber_TrueDivide(dividend, divisor);
2033 Py_DECREF(dividend);
2034 Py_DECREF(divisor);
2035 SET_TOP(quotient);
2036 if (quotient == NULL)
2037 goto error;
2038 DISPATCH();
2039 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002040
Benjamin Petersonddd19492018-09-16 22:38:02 -07002041 case TARGET(BINARY_FLOOR_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002042 PyObject *divisor = POP();
2043 PyObject *dividend = TOP();
2044 PyObject *quotient = PyNumber_FloorDivide(dividend, divisor);
2045 Py_DECREF(dividend);
2046 Py_DECREF(divisor);
2047 SET_TOP(quotient);
2048 if (quotient == NULL)
2049 goto error;
2050 DISPATCH();
2051 }
Guido van Rossum4668b002001-08-08 05:00:18 +00002052
Benjamin Petersonddd19492018-09-16 22:38:02 -07002053 case TARGET(BINARY_MODULO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002054 PyObject *divisor = POP();
2055 PyObject *dividend = TOP();
Martijn Pietersd7e64332017-02-23 13:38:04 +00002056 PyObject *res;
2057 if (PyUnicode_CheckExact(dividend) && (
2058 !PyUnicode_Check(divisor) || PyUnicode_CheckExact(divisor))) {
2059 // fast path; string formatting, but not if the RHS is a str subclass
2060 // (see issue28598)
2061 res = PyUnicode_Format(dividend, divisor);
2062 } else {
2063 res = PyNumber_Remainder(dividend, divisor);
2064 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002065 Py_DECREF(divisor);
2066 Py_DECREF(dividend);
2067 SET_TOP(res);
2068 if (res == NULL)
2069 goto error;
2070 DISPATCH();
2071 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002072
Benjamin Petersonddd19492018-09-16 22:38:02 -07002073 case TARGET(BINARY_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002074 PyObject *right = POP();
2075 PyObject *left = TOP();
2076 PyObject *sum;
Victor Stinnerbd0a08e2020-10-01 18:57:37 +02002077 /* NOTE(vstinner): Please don't try to micro-optimize int+int on
Victor Stinnerd65f42a2016-10-20 12:18:10 +02002078 CPython using bytecode, it is simply worthless.
2079 See http://bugs.python.org/issue21955 and
2080 http://bugs.python.org/issue10044 for the discussion. In short,
2081 no patch shown any impact on a realistic benchmark, only a minor
2082 speedup on microbenchmarks. */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002083 if (PyUnicode_CheckExact(left) &&
2084 PyUnicode_CheckExact(right)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002085 sum = unicode_concatenate(tstate, left, right, f, next_instr);
Martin Panter95f53c12016-07-18 08:23:26 +00002086 /* unicode_concatenate consumed the ref to left */
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002087 }
2088 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002089 sum = PyNumber_Add(left, right);
2090 Py_DECREF(left);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002091 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002092 Py_DECREF(right);
2093 SET_TOP(sum);
2094 if (sum == NULL)
2095 goto error;
2096 DISPATCH();
2097 }
2098
Benjamin Petersonddd19492018-09-16 22:38:02 -07002099 case TARGET(BINARY_SUBTRACT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002100 PyObject *right = POP();
2101 PyObject *left = TOP();
2102 PyObject *diff = PyNumber_Subtract(left, right);
2103 Py_DECREF(right);
2104 Py_DECREF(left);
2105 SET_TOP(diff);
2106 if (diff == NULL)
2107 goto error;
2108 DISPATCH();
2109 }
2110
Benjamin Petersonddd19492018-09-16 22:38:02 -07002111 case TARGET(BINARY_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002112 PyObject *sub = POP();
2113 PyObject *container = TOP();
2114 PyObject *res = PyObject_GetItem(container, sub);
2115 Py_DECREF(container);
2116 Py_DECREF(sub);
2117 SET_TOP(res);
2118 if (res == NULL)
2119 goto error;
2120 DISPATCH();
2121 }
2122
Benjamin Petersonddd19492018-09-16 22:38:02 -07002123 case TARGET(BINARY_LSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002124 PyObject *right = POP();
2125 PyObject *left = TOP();
2126 PyObject *res = PyNumber_Lshift(left, right);
2127 Py_DECREF(left);
2128 Py_DECREF(right);
2129 SET_TOP(res);
2130 if (res == NULL)
2131 goto error;
2132 DISPATCH();
2133 }
2134
Benjamin Petersonddd19492018-09-16 22:38:02 -07002135 case TARGET(BINARY_RSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002136 PyObject *right = POP();
2137 PyObject *left = TOP();
2138 PyObject *res = PyNumber_Rshift(left, right);
2139 Py_DECREF(left);
2140 Py_DECREF(right);
2141 SET_TOP(res);
2142 if (res == NULL)
2143 goto error;
2144 DISPATCH();
2145 }
2146
Benjamin Petersonddd19492018-09-16 22:38:02 -07002147 case TARGET(BINARY_AND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002148 PyObject *right = POP();
2149 PyObject *left = TOP();
2150 PyObject *res = PyNumber_And(left, right);
2151 Py_DECREF(left);
2152 Py_DECREF(right);
2153 SET_TOP(res);
2154 if (res == NULL)
2155 goto error;
2156 DISPATCH();
2157 }
2158
Benjamin Petersonddd19492018-09-16 22:38:02 -07002159 case TARGET(BINARY_XOR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002160 PyObject *right = POP();
2161 PyObject *left = TOP();
2162 PyObject *res = PyNumber_Xor(left, right);
2163 Py_DECREF(left);
2164 Py_DECREF(right);
2165 SET_TOP(res);
2166 if (res == NULL)
2167 goto error;
2168 DISPATCH();
2169 }
2170
Benjamin Petersonddd19492018-09-16 22:38:02 -07002171 case TARGET(BINARY_OR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002172 PyObject *right = POP();
2173 PyObject *left = TOP();
2174 PyObject *res = PyNumber_Or(left, right);
2175 Py_DECREF(left);
2176 Py_DECREF(right);
2177 SET_TOP(res);
2178 if (res == NULL)
2179 goto error;
2180 DISPATCH();
2181 }
2182
Benjamin Petersonddd19492018-09-16 22:38:02 -07002183 case TARGET(LIST_APPEND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002184 PyObject *v = POP();
2185 PyObject *list = PEEK(oparg);
2186 int err;
2187 err = PyList_Append(list, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002189 if (err != 0)
2190 goto error;
2191 PREDICT(JUMP_ABSOLUTE);
2192 DISPATCH();
2193 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002194
Benjamin Petersonddd19492018-09-16 22:38:02 -07002195 case TARGET(SET_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002196 PyObject *v = POP();
Raymond Hettinger41862222016-10-15 19:03:06 -07002197 PyObject *set = PEEK(oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002198 int err;
2199 err = PySet_Add(set, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002201 if (err != 0)
2202 goto error;
2203 PREDICT(JUMP_ABSOLUTE);
2204 DISPATCH();
2205 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002206
Benjamin Petersonddd19492018-09-16 22:38:02 -07002207 case TARGET(INPLACE_POWER): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002208 PyObject *exp = POP();
2209 PyObject *base = TOP();
2210 PyObject *res = PyNumber_InPlacePower(base, exp, Py_None);
2211 Py_DECREF(base);
2212 Py_DECREF(exp);
2213 SET_TOP(res);
2214 if (res == NULL)
2215 goto error;
2216 DISPATCH();
2217 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002218
Benjamin Petersonddd19492018-09-16 22:38:02 -07002219 case TARGET(INPLACE_MULTIPLY): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002220 PyObject *right = POP();
2221 PyObject *left = TOP();
2222 PyObject *res = PyNumber_InPlaceMultiply(left, right);
2223 Py_DECREF(left);
2224 Py_DECREF(right);
2225 SET_TOP(res);
2226 if (res == NULL)
2227 goto error;
2228 DISPATCH();
2229 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002230
Benjamin Petersonddd19492018-09-16 22:38:02 -07002231 case TARGET(INPLACE_MATRIX_MULTIPLY): {
Benjamin Petersond51374e2014-04-09 23:55:56 -04002232 PyObject *right = POP();
2233 PyObject *left = TOP();
2234 PyObject *res = PyNumber_InPlaceMatrixMultiply(left, right);
2235 Py_DECREF(left);
2236 Py_DECREF(right);
2237 SET_TOP(res);
2238 if (res == NULL)
2239 goto error;
2240 DISPATCH();
2241 }
2242
Benjamin Petersonddd19492018-09-16 22:38:02 -07002243 case TARGET(INPLACE_TRUE_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002244 PyObject *divisor = POP();
2245 PyObject *dividend = TOP();
2246 PyObject *quotient = PyNumber_InPlaceTrueDivide(dividend, divisor);
2247 Py_DECREF(dividend);
2248 Py_DECREF(divisor);
2249 SET_TOP(quotient);
2250 if (quotient == NULL)
2251 goto error;
2252 DISPATCH();
2253 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002254
Benjamin Petersonddd19492018-09-16 22:38:02 -07002255 case TARGET(INPLACE_FLOOR_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002256 PyObject *divisor = POP();
2257 PyObject *dividend = TOP();
2258 PyObject *quotient = PyNumber_InPlaceFloorDivide(dividend, divisor);
2259 Py_DECREF(dividend);
2260 Py_DECREF(divisor);
2261 SET_TOP(quotient);
2262 if (quotient == NULL)
2263 goto error;
2264 DISPATCH();
2265 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002266
Benjamin Petersonddd19492018-09-16 22:38:02 -07002267 case TARGET(INPLACE_MODULO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002268 PyObject *right = POP();
2269 PyObject *left = TOP();
2270 PyObject *mod = PyNumber_InPlaceRemainder(left, right);
2271 Py_DECREF(left);
2272 Py_DECREF(right);
2273 SET_TOP(mod);
2274 if (mod == NULL)
2275 goto error;
2276 DISPATCH();
2277 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002278
Benjamin Petersonddd19492018-09-16 22:38:02 -07002279 case TARGET(INPLACE_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002280 PyObject *right = POP();
2281 PyObject *left = TOP();
2282 PyObject *sum;
2283 if (PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002284 sum = unicode_concatenate(tstate, left, right, f, next_instr);
Martin Panter95f53c12016-07-18 08:23:26 +00002285 /* unicode_concatenate consumed the ref to left */
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002286 }
2287 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002288 sum = PyNumber_InPlaceAdd(left, right);
2289 Py_DECREF(left);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002290 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002291 Py_DECREF(right);
2292 SET_TOP(sum);
2293 if (sum == NULL)
2294 goto error;
2295 DISPATCH();
2296 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002297
Benjamin Petersonddd19492018-09-16 22:38:02 -07002298 case TARGET(INPLACE_SUBTRACT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002299 PyObject *right = POP();
2300 PyObject *left = TOP();
2301 PyObject *diff = PyNumber_InPlaceSubtract(left, right);
2302 Py_DECREF(left);
2303 Py_DECREF(right);
2304 SET_TOP(diff);
2305 if (diff == NULL)
2306 goto error;
2307 DISPATCH();
2308 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002309
Benjamin Petersonddd19492018-09-16 22:38:02 -07002310 case TARGET(INPLACE_LSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002311 PyObject *right = POP();
2312 PyObject *left = TOP();
2313 PyObject *res = PyNumber_InPlaceLshift(left, right);
2314 Py_DECREF(left);
2315 Py_DECREF(right);
2316 SET_TOP(res);
2317 if (res == NULL)
2318 goto error;
2319 DISPATCH();
2320 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002321
Benjamin Petersonddd19492018-09-16 22:38:02 -07002322 case TARGET(INPLACE_RSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002323 PyObject *right = POP();
2324 PyObject *left = TOP();
2325 PyObject *res = PyNumber_InPlaceRshift(left, right);
2326 Py_DECREF(left);
2327 Py_DECREF(right);
2328 SET_TOP(res);
2329 if (res == NULL)
2330 goto error;
2331 DISPATCH();
2332 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002333
Benjamin Petersonddd19492018-09-16 22:38:02 -07002334 case TARGET(INPLACE_AND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002335 PyObject *right = POP();
2336 PyObject *left = TOP();
2337 PyObject *res = PyNumber_InPlaceAnd(left, right);
2338 Py_DECREF(left);
2339 Py_DECREF(right);
2340 SET_TOP(res);
2341 if (res == NULL)
2342 goto error;
2343 DISPATCH();
2344 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002345
Benjamin Petersonddd19492018-09-16 22:38:02 -07002346 case TARGET(INPLACE_XOR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002347 PyObject *right = POP();
2348 PyObject *left = TOP();
2349 PyObject *res = PyNumber_InPlaceXor(left, right);
2350 Py_DECREF(left);
2351 Py_DECREF(right);
2352 SET_TOP(res);
2353 if (res == NULL)
2354 goto error;
2355 DISPATCH();
2356 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002357
Benjamin Petersonddd19492018-09-16 22:38:02 -07002358 case TARGET(INPLACE_OR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002359 PyObject *right = POP();
2360 PyObject *left = TOP();
2361 PyObject *res = PyNumber_InPlaceOr(left, right);
2362 Py_DECREF(left);
2363 Py_DECREF(right);
2364 SET_TOP(res);
2365 if (res == NULL)
2366 goto error;
2367 DISPATCH();
2368 }
Thomas Wouters434d0822000-08-24 20:11:32 +00002369
Benjamin Petersonddd19492018-09-16 22:38:02 -07002370 case TARGET(STORE_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002371 PyObject *sub = TOP();
2372 PyObject *container = SECOND();
2373 PyObject *v = THIRD();
2374 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002375 STACK_SHRINK(3);
Martin Panter95f53c12016-07-18 08:23:26 +00002376 /* container[sub] = v */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002377 err = PyObject_SetItem(container, sub, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002379 Py_DECREF(container);
2380 Py_DECREF(sub);
2381 if (err != 0)
2382 goto error;
2383 DISPATCH();
2384 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002385
Benjamin Petersonddd19492018-09-16 22:38:02 -07002386 case TARGET(DELETE_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002387 PyObject *sub = TOP();
2388 PyObject *container = SECOND();
2389 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002390 STACK_SHRINK(2);
Martin Panter95f53c12016-07-18 08:23:26 +00002391 /* del container[sub] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002392 err = PyObject_DelItem(container, sub);
2393 Py_DECREF(container);
2394 Py_DECREF(sub);
2395 if (err != 0)
2396 goto error;
2397 DISPATCH();
2398 }
Barry Warsaw23c9ec82000-08-21 15:44:01 +00002399
Benjamin Petersonddd19492018-09-16 22:38:02 -07002400 case TARGET(PRINT_EXPR): {
Victor Stinnercab75e32013-11-06 22:38:37 +01002401 _Py_IDENTIFIER(displayhook);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002402 PyObject *value = POP();
Victor Stinnercab75e32013-11-06 22:38:37 +01002403 PyObject *hook = _PySys_GetObjectId(&PyId_displayhook);
Benjamin Petersonfe1bcb62012-10-12 11:40:01 -04002404 PyObject *res;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002405 if (hook == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002406 _PyErr_SetString(tstate, PyExc_RuntimeError,
2407 "lost sys.displayhook");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002408 Py_DECREF(value);
2409 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 }
Petr Viktorinffd97532020-02-11 17:46:57 +01002411 res = PyObject_CallOneArg(hook, value);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002412 Py_DECREF(value);
2413 if (res == NULL)
2414 goto error;
2415 Py_DECREF(res);
2416 DISPATCH();
2417 }
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +00002418
Benjamin Petersonddd19492018-09-16 22:38:02 -07002419 case TARGET(RAISE_VARARGS): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002420 PyObject *cause = NULL, *exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 switch (oparg) {
2422 case 2:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002423 cause = POP(); /* cause */
Stefan Krahf432a322017-08-21 13:09:59 +02002424 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 case 1:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002426 exc = POP(); /* exc */
Stefan Krahf432a322017-08-21 13:09:59 +02002427 /* fall through */
2428 case 0:
Victor Stinner09532fe2019-05-10 23:39:09 +02002429 if (do_raise(tstate, exc, cause)) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002430 goto exception_unwind;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 break;
2433 default:
Victor Stinner438a12d2019-05-24 17:01:38 +02002434 _PyErr_SetString(tstate, PyExc_SystemError,
2435 "bad RAISE_VARARGS oparg");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 break;
2437 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002438 goto error;
2439 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002440
Benjamin Petersonddd19492018-09-16 22:38:02 -07002441 case TARGET(RETURN_VALUE): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 retval = POP();
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002443 assert(f->f_iblock == 0);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002444 assert(EMPTY());
Mark Shannoncb9879b2020-07-17 11:44:23 +01002445 f->f_state = FRAME_RETURNED;
2446 f->f_stackdepth = 0;
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002447 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002448 }
Guido van Rossumdb3165e1993-10-18 17:06:59 +00002449
Benjamin Petersonddd19492018-09-16 22:38:02 -07002450 case TARGET(GET_AITER): {
Yury Selivanov6ef05902015-05-28 11:21:31 -04002451 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002452 PyObject *iter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002453 PyObject *obj = TOP();
2454 PyTypeObject *type = Py_TYPE(obj);
2455
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002456 if (type->tp_as_async != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002457 getter = type->tp_as_async->am_aiter;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002458 }
Yury Selivanov75445082015-05-11 22:57:16 -04002459
2460 if (getter != NULL) {
2461 iter = (*getter)(obj);
2462 Py_DECREF(obj);
2463 if (iter == NULL) {
2464 SET_TOP(NULL);
2465 goto error;
2466 }
2467 }
2468 else {
2469 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02002470 _PyErr_Format(tstate, PyExc_TypeError,
2471 "'async for' requires an object with "
2472 "__aiter__ method, got %.100s",
2473 type->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -04002474 Py_DECREF(obj);
2475 goto error;
2476 }
2477
Yury Selivanovfaa135a2017-10-06 02:08:57 -04002478 if (Py_TYPE(iter)->tp_as_async == NULL ||
2479 Py_TYPE(iter)->tp_as_async->am_anext == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002480
Yury Selivanov398ff912017-03-02 22:20:00 -05002481 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02002482 _PyErr_Format(tstate, PyExc_TypeError,
2483 "'async for' received an object from __aiter__ "
2484 "that does not implement __anext__: %.100s",
2485 Py_TYPE(iter)->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -04002486 Py_DECREF(iter);
2487 goto error;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002488 }
2489
Yury Selivanovfaa135a2017-10-06 02:08:57 -04002490 SET_TOP(iter);
Yury Selivanov75445082015-05-11 22:57:16 -04002491 DISPATCH();
2492 }
2493
Benjamin Petersonddd19492018-09-16 22:38:02 -07002494 case TARGET(GET_ANEXT): {
Yury Selivanov6ef05902015-05-28 11:21:31 -04002495 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002496 PyObject *next_iter = NULL;
2497 PyObject *awaitable = NULL;
2498 PyObject *aiter = TOP();
2499 PyTypeObject *type = Py_TYPE(aiter);
2500
Yury Selivanoveb636452016-09-08 22:01:51 -07002501 if (PyAsyncGen_CheckExact(aiter)) {
2502 awaitable = type->tp_as_async->am_anext(aiter);
2503 if (awaitable == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002504 goto error;
2505 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002506 } else {
2507 if (type->tp_as_async != NULL){
2508 getter = type->tp_as_async->am_anext;
2509 }
Yury Selivanov75445082015-05-11 22:57:16 -04002510
Yury Selivanoveb636452016-09-08 22:01:51 -07002511 if (getter != NULL) {
2512 next_iter = (*getter)(aiter);
2513 if (next_iter == NULL) {
2514 goto error;
2515 }
2516 }
2517 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02002518 _PyErr_Format(tstate, PyExc_TypeError,
2519 "'async for' requires an iterator with "
2520 "__anext__ method, got %.100s",
2521 type->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07002522 goto error;
2523 }
Yury Selivanov75445082015-05-11 22:57:16 -04002524
Yury Selivanoveb636452016-09-08 22:01:51 -07002525 awaitable = _PyCoro_GetAwaitableIter(next_iter);
2526 if (awaitable == NULL) {
Yury Selivanov398ff912017-03-02 22:20:00 -05002527 _PyErr_FormatFromCause(
Yury Selivanoveb636452016-09-08 22:01:51 -07002528 PyExc_TypeError,
2529 "'async for' received an invalid object "
2530 "from __anext__: %.100s",
2531 Py_TYPE(next_iter)->tp_name);
2532
2533 Py_DECREF(next_iter);
2534 goto error;
2535 } else {
2536 Py_DECREF(next_iter);
2537 }
2538 }
Yury Selivanov75445082015-05-11 22:57:16 -04002539
2540 PUSH(awaitable);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03002541 PREDICT(LOAD_CONST);
Yury Selivanov75445082015-05-11 22:57:16 -04002542 DISPATCH();
2543 }
2544
Benjamin Petersonddd19492018-09-16 22:38:02 -07002545 case TARGET(GET_AWAITABLE): {
2546 PREDICTED(GET_AWAITABLE);
Yury Selivanov75445082015-05-11 22:57:16 -04002547 PyObject *iterable = TOP();
Yury Selivanov5376ba92015-06-22 12:19:30 -04002548 PyObject *iter = _PyCoro_GetAwaitableIter(iterable);
Yury Selivanov75445082015-05-11 22:57:16 -04002549
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03002550 if (iter == NULL) {
Mark Shannonfee55262019-11-21 09:11:43 +00002551 int opcode_at_minus_3 = 0;
2552 if ((next_instr - first_instr) > 2) {
2553 opcode_at_minus_3 = _Py_OPCODE(next_instr[-3]);
2554 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002555 format_awaitable_error(tstate, Py_TYPE(iterable),
Mark Shannonfee55262019-11-21 09:11:43 +00002556 opcode_at_minus_3,
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03002557 _Py_OPCODE(next_instr[-2]));
2558 }
2559
Yury Selivanov75445082015-05-11 22:57:16 -04002560 Py_DECREF(iterable);
2561
Yury Selivanovc724bae2016-03-02 11:30:46 -05002562 if (iter != NULL && PyCoro_CheckExact(iter)) {
2563 PyObject *yf = _PyGen_yf((PyGenObject*)iter);
2564 if (yf != NULL) {
2565 /* `iter` is a coroutine object that is being
2566 awaited, `yf` is a pointer to the current awaitable
2567 being awaited on. */
2568 Py_DECREF(yf);
2569 Py_CLEAR(iter);
Victor Stinner438a12d2019-05-24 17:01:38 +02002570 _PyErr_SetString(tstate, PyExc_RuntimeError,
2571 "coroutine is being awaited already");
Yury Selivanovc724bae2016-03-02 11:30:46 -05002572 /* The code below jumps to `error` if `iter` is NULL. */
2573 }
2574 }
2575
Yury Selivanov75445082015-05-11 22:57:16 -04002576 SET_TOP(iter); /* Even if it's NULL */
2577
2578 if (iter == NULL) {
2579 goto error;
2580 }
2581
Serhiy Storchakada9c5132016-06-27 18:58:57 +03002582 PREDICT(LOAD_CONST);
Yury Selivanov75445082015-05-11 22:57:16 -04002583 DISPATCH();
2584 }
2585
Benjamin Petersonddd19492018-09-16 22:38:02 -07002586 case TARGET(YIELD_FROM): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002587 PyObject *v = POP();
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002588 PyObject *receiver = TOP();
Vladimir Matveev037245c2020-10-09 17:15:15 -07002589 PySendResult gen_status;
2590 if (tstate->c_tracefunc == NULL) {
2591 gen_status = PyIter_Send(receiver, v, &retval);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002592 } else {
Vladimir Matveev037245c2020-10-09 17:15:15 -07002593 _Py_IDENTIFIER(send);
2594 if (v == Py_None && PyIter_Check(receiver)) {
2595 retval = Py_TYPE(receiver)->tp_iternext(receiver);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002596 }
2597 else {
Vladimir Matveev037245c2020-10-09 17:15:15 -07002598 retval = _PyObject_CallMethodIdOneArg(receiver, &PyId_send, v);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002599 }
Vladimir Matveev2b053612020-09-18 18:38:38 -07002600 if (retval == NULL) {
2601 if (tstate->c_tracefunc != NULL
2602 && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
Mark Shannon8e1b4062021-03-05 14:45:50 +00002603 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, &trace_info);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002604 if (_PyGen_FetchStopIterationValue(&retval) == 0) {
2605 gen_status = PYGEN_RETURN;
2606 }
2607 else {
2608 gen_status = PYGEN_ERROR;
2609 }
2610 }
2611 else {
2612 gen_status = PYGEN_NEXT;
2613 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002614 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002615 Py_DECREF(v);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002616 if (gen_status == PYGEN_ERROR) {
2617 assert (retval == NULL);
2618 goto error;
2619 }
2620 if (gen_status == PYGEN_RETURN) {
2621 assert (retval != NULL);
2622
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002623 Py_DECREF(receiver);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002624 SET_TOP(retval);
2625 retval = NULL;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002626 DISPATCH();
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002627 }
Vladimir Matveev2b053612020-09-18 18:38:38 -07002628 assert (gen_status == PYGEN_NEXT);
Martin Panter95f53c12016-07-18 08:23:26 +00002629 /* receiver remains on stack, retval is value to be yielded */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002630 /* and repeat... */
Victor Stinnerf7d199f2016-11-24 22:33:01 +01002631 assert(f->f_lasti >= (int)sizeof(_Py_CODEUNIT));
Serhiy Storchakaab874002016-09-11 13:48:15 +03002632 f->f_lasti -= sizeof(_Py_CODEUNIT);
Mark Shannoncb9879b2020-07-17 11:44:23 +01002633 f->f_state = FRAME_SUSPENDED;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02002634 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002635 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002636 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002637
Benjamin Petersonddd19492018-09-16 22:38:02 -07002638 case TARGET(YIELD_VALUE): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 retval = POP();
Yury Selivanoveb636452016-09-08 22:01:51 -07002640
2641 if (co->co_flags & CO_ASYNC_GENERATOR) {
2642 PyObject *w = _PyAsyncGenValueWrapperNew(retval);
2643 Py_DECREF(retval);
2644 if (w == NULL) {
2645 retval = NULL;
2646 goto error;
2647 }
2648 retval = w;
2649 }
Mark Shannoncb9879b2020-07-17 11:44:23 +01002650 f->f_state = FRAME_SUSPENDED;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02002651 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002652 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002653 }
Tim Peters5ca576e2001-06-18 22:08:13 +00002654
Benjamin Petersonddd19492018-09-16 22:38:02 -07002655 case TARGET(POP_EXCEPT): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002656 PyObject *type, *value, *traceback;
2657 _PyErr_StackItem *exc_info;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002658 PyTryBlock *b = PyFrame_BlockPop(f);
2659 if (b->b_type != EXCEPT_HANDLER) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002660 _PyErr_SetString(tstate, PyExc_SystemError,
2661 "popped block is not an except handler");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002662 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002664 assert(STACK_LEVEL() >= (b)->b_level + 3 &&
2665 STACK_LEVEL() <= (b)->b_level + 4);
2666 exc_info = tstate->exc_info;
2667 type = exc_info->exc_type;
2668 value = exc_info->exc_value;
2669 traceback = exc_info->exc_traceback;
2670 exc_info->exc_type = POP();
2671 exc_info->exc_value = POP();
2672 exc_info->exc_traceback = POP();
2673 Py_XDECREF(type);
2674 Py_XDECREF(value);
2675 Py_XDECREF(traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002677 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002678
Benjamin Petersonddd19492018-09-16 22:38:02 -07002679 case TARGET(POP_BLOCK): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002680 PyFrame_BlockPop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002682 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002683
Mark Shannonfee55262019-11-21 09:11:43 +00002684 case TARGET(RERAISE): {
Mark Shannonbf353f32020-12-17 13:55:28 +00002685 assert(f->f_iblock > 0);
2686 if (oparg) {
2687 f->f_lasti = f->f_blockstack[f->f_iblock-1].b_handler;
2688 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002689 PyObject *exc = POP();
Mark Shannonfee55262019-11-21 09:11:43 +00002690 PyObject *val = POP();
2691 PyObject *tb = POP();
2692 assert(PyExceptionClass_Check(exc));
Victor Stinner61f4db82020-01-28 03:37:45 +01002693 _PyErr_Restore(tstate, exc, val, tb);
Mark Shannonfee55262019-11-21 09:11:43 +00002694 goto exception_unwind;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002695 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002696
Benjamin Petersonddd19492018-09-16 22:38:02 -07002697 case TARGET(END_ASYNC_FOR): {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002698 PyObject *exc = POP();
2699 assert(PyExceptionClass_Check(exc));
2700 if (PyErr_GivenExceptionMatches(exc, PyExc_StopAsyncIteration)) {
2701 PyTryBlock *b = PyFrame_BlockPop(f);
2702 assert(b->b_type == EXCEPT_HANDLER);
2703 Py_DECREF(exc);
2704 UNWIND_EXCEPT_HANDLER(b);
2705 Py_DECREF(POP());
2706 JUMPBY(oparg);
2707 FAST_DISPATCH();
2708 }
2709 else {
2710 PyObject *val = POP();
2711 PyObject *tb = POP();
Victor Stinner438a12d2019-05-24 17:01:38 +02002712 _PyErr_Restore(tstate, exc, val, tb);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002713 goto exception_unwind;
2714 }
2715 }
2716
Zackery Spytzce6a0702019-08-25 03:44:09 -06002717 case TARGET(LOAD_ASSERTION_ERROR): {
2718 PyObject *value = PyExc_AssertionError;
2719 Py_INCREF(value);
2720 PUSH(value);
2721 FAST_DISPATCH();
2722 }
2723
Benjamin Petersonddd19492018-09-16 22:38:02 -07002724 case TARGET(LOAD_BUILD_CLASS): {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002725 _Py_IDENTIFIER(__build_class__);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002726
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002727 PyObject *bc;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002728 if (PyDict_CheckExact(f->f_builtins)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002729 bc = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___build_class__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002730 if (bc == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002731 if (!_PyErr_Occurred(tstate)) {
2732 _PyErr_SetString(tstate, PyExc_NameError,
2733 "__build_class__ not found");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002734 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002735 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002736 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002737 Py_INCREF(bc);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002738 }
2739 else {
2740 PyObject *build_class_str = _PyUnicode_FromId(&PyId___build_class__);
2741 if (build_class_str == NULL)
Serhiy Storchaka70b72f02016-11-08 23:12:46 +02002742 goto error;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002743 bc = PyObject_GetItem(f->f_builtins, build_class_str);
2744 if (bc == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002745 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
2746 _PyErr_SetString(tstate, PyExc_NameError,
2747 "__build_class__ not found");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002748 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002749 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002751 PUSH(bc);
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002752 DISPATCH();
Victor Stinner3c1e4812012-03-26 22:10:51 +02002753 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002754
Benjamin Petersonddd19492018-09-16 22:38:02 -07002755 case TARGET(STORE_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002756 PyObject *name = GETITEM(names, oparg);
2757 PyObject *v = POP();
2758 PyObject *ns = f->f_locals;
2759 int err;
2760 if (ns == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002761 _PyErr_Format(tstate, PyExc_SystemError,
2762 "no locals found when storing %R", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002764 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002766 if (PyDict_CheckExact(ns))
2767 err = PyDict_SetItem(ns, name, v);
2768 else
2769 err = PyObject_SetItem(ns, name, v);
2770 Py_DECREF(v);
2771 if (err != 0)
2772 goto error;
2773 DISPATCH();
2774 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002775
Benjamin Petersonddd19492018-09-16 22:38:02 -07002776 case TARGET(DELETE_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002777 PyObject *name = GETITEM(names, oparg);
2778 PyObject *ns = f->f_locals;
2779 int err;
2780 if (ns == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002781 _PyErr_Format(tstate, PyExc_SystemError,
2782 "no locals when deleting %R", name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002783 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002785 err = PyObject_DelItem(ns, name);
2786 if (err != 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002787 format_exc_check_arg(tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002788 NAME_ERROR_MSG,
2789 name);
2790 goto error;
2791 }
2792 DISPATCH();
2793 }
Guido van Rossum04691fc1992-08-12 15:35:34 +00002794
Benjamin Petersonddd19492018-09-16 22:38:02 -07002795 case TARGET(UNPACK_SEQUENCE): {
2796 PREDICTED(UNPACK_SEQUENCE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002797 PyObject *seq = POP(), *item, **items;
2798 if (PyTuple_CheckExact(seq) &&
2799 PyTuple_GET_SIZE(seq) == oparg) {
2800 items = ((PyTupleObject *)seq)->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 while (oparg--) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002802 item = items[oparg];
2803 Py_INCREF(item);
2804 PUSH(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002806 } else if (PyList_CheckExact(seq) &&
2807 PyList_GET_SIZE(seq) == oparg) {
2808 items = ((PyListObject *)seq)->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 while (oparg--) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002810 item = items[oparg];
2811 Py_INCREF(item);
2812 PUSH(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002814 } else if (unpack_iterable(tstate, seq, oparg, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 stack_pointer + oparg)) {
costypetrisor8ed317f2018-07-31 20:55:14 +00002816 STACK_GROW(oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 } else {
2818 /* unpack_iterable() raised an exception */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002819 Py_DECREF(seq);
2820 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002822 Py_DECREF(seq);
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002823 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 }
Guido van Rossum0368b722007-05-11 16:50:42 +00002825
Benjamin Petersonddd19492018-09-16 22:38:02 -07002826 case TARGET(UNPACK_EX): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002827 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
2828 PyObject *seq = POP();
2829
Victor Stinner438a12d2019-05-24 17:01:38 +02002830 if (unpack_iterable(tstate, seq, oparg & 0xFF, oparg >> 8,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002831 stack_pointer + totalargs)) {
2832 stack_pointer += totalargs;
2833 } else {
2834 Py_DECREF(seq);
2835 goto error;
2836 }
2837 Py_DECREF(seq);
2838 DISPATCH();
2839 }
2840
Benjamin Petersonddd19492018-09-16 22:38:02 -07002841 case TARGET(STORE_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002842 PyObject *name = GETITEM(names, oparg);
2843 PyObject *owner = TOP();
2844 PyObject *v = SECOND();
2845 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002846 STACK_SHRINK(2);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002847 err = PyObject_SetAttr(owner, name, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002849 Py_DECREF(owner);
2850 if (err != 0)
2851 goto error;
2852 DISPATCH();
2853 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002854
Benjamin Petersonddd19492018-09-16 22:38:02 -07002855 case TARGET(DELETE_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002856 PyObject *name = GETITEM(names, oparg);
2857 PyObject *owner = POP();
2858 int err;
2859 err = PyObject_SetAttr(owner, name, (PyObject *)NULL);
2860 Py_DECREF(owner);
2861 if (err != 0)
2862 goto error;
2863 DISPATCH();
2864 }
2865
Benjamin Petersonddd19492018-09-16 22:38:02 -07002866 case TARGET(STORE_GLOBAL): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002867 PyObject *name = GETITEM(names, oparg);
2868 PyObject *v = POP();
2869 int err;
2870 err = PyDict_SetItem(f->f_globals, name, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002872 if (err != 0)
2873 goto error;
2874 DISPATCH();
2875 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002876
Benjamin Petersonddd19492018-09-16 22:38:02 -07002877 case TARGET(DELETE_GLOBAL): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002878 PyObject *name = GETITEM(names, oparg);
2879 int err;
2880 err = PyDict_DelItem(f->f_globals, name);
2881 if (err != 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002882 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2883 format_exc_check_arg(tstate, PyExc_NameError,
2884 NAME_ERROR_MSG, name);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002885 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002886 goto error;
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002887 }
2888 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002889 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002890
Benjamin Petersonddd19492018-09-16 22:38:02 -07002891 case TARGET(LOAD_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002892 PyObject *name = GETITEM(names, oparg);
2893 PyObject *locals = f->f_locals;
2894 PyObject *v;
2895 if (locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002896 _PyErr_Format(tstate, PyExc_SystemError,
2897 "no locals when loading %R", name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002898 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002900 if (PyDict_CheckExact(locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002901 v = PyDict_GetItemWithError(locals, name);
2902 if (v != NULL) {
2903 Py_INCREF(v);
2904 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002905 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002906 goto error;
2907 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 }
2909 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002910 v = PyObject_GetItem(locals, name);
Victor Stinnere20310f2015-11-05 13:56:58 +01002911 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002912 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
Benjamin Peterson92722792012-12-15 12:51:05 -05002913 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02002914 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 }
2916 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002917 if (v == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002918 v = PyDict_GetItemWithError(f->f_globals, name);
2919 if (v != NULL) {
2920 Py_INCREF(v);
2921 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002922 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002923 goto error;
2924 }
2925 else {
Victor Stinnerb0b22422012-04-19 00:57:45 +02002926 if (PyDict_CheckExact(f->f_builtins)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002927 v = PyDict_GetItemWithError(f->f_builtins, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002928 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002929 if (!_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002930 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02002931 tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002932 NAME_ERROR_MSG, name);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002933 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002934 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002935 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002936 Py_INCREF(v);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002937 }
2938 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002939 v = PyObject_GetItem(f->f_builtins, name);
2940 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002941 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Victor Stinnerb0b22422012-04-19 00:57:45 +02002942 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02002943 tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002944 NAME_ERROR_MSG, name);
Victor Stinner438a12d2019-05-24 17:01:38 +02002945 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002946 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002947 }
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002948 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002951 PUSH(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002953 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002954
Benjamin Petersonddd19492018-09-16 22:38:02 -07002955 case TARGET(LOAD_GLOBAL): {
Inada Naoki91234a12019-06-03 21:30:58 +09002956 PyObject *name;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002957 PyObject *v;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002958 if (PyDict_CheckExact(f->f_globals)
Victor Stinnerb4efc962015-11-20 09:24:02 +01002959 && PyDict_CheckExact(f->f_builtins))
2960 {
Inada Naoki91234a12019-06-03 21:30:58 +09002961 OPCACHE_CHECK();
2962 if (co_opcache != NULL && co_opcache->optimized > 0) {
2963 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2964
2965 if (lg->globals_ver ==
2966 ((PyDictObject *)f->f_globals)->ma_version_tag
2967 && lg->builtins_ver ==
2968 ((PyDictObject *)f->f_builtins)->ma_version_tag)
2969 {
2970 PyObject *ptr = lg->ptr;
2971 OPCACHE_STAT_GLOBAL_HIT();
2972 assert(ptr != NULL);
2973 Py_INCREF(ptr);
2974 PUSH(ptr);
2975 DISPATCH();
2976 }
2977 }
2978
2979 name = GETITEM(names, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002980 v = _PyDict_LoadGlobal((PyDictObject *)f->f_globals,
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002981 (PyDictObject *)f->f_builtins,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002982 name);
2983 if (v == NULL) {
Victor Stinnera4860542021-02-19 15:08:54 +01002984 if (!_PyErr_Occurred(tstate)) {
Victor Stinnerb4efc962015-11-20 09:24:02 +01002985 /* _PyDict_LoadGlobal() returns NULL without raising
2986 * an exception if the key doesn't exist */
Victor Stinner438a12d2019-05-24 17:01:38 +02002987 format_exc_check_arg(tstate, PyExc_NameError,
Ezio Melotti04a29552013-03-03 15:12:44 +02002988 NAME_ERROR_MSG, name);
Victor Stinnerb4efc962015-11-20 09:24:02 +01002989 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002990 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 }
Inada Naoki91234a12019-06-03 21:30:58 +09002992
2993 if (co_opcache != NULL) {
2994 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2995
2996 if (co_opcache->optimized == 0) {
2997 /* Wasn't optimized before. */
2998 OPCACHE_STAT_GLOBAL_OPT();
2999 } else {
3000 OPCACHE_STAT_GLOBAL_MISS();
3001 }
3002
3003 co_opcache->optimized = 1;
3004 lg->globals_ver =
3005 ((PyDictObject *)f->f_globals)->ma_version_tag;
3006 lg->builtins_ver =
3007 ((PyDictObject *)f->f_builtins)->ma_version_tag;
3008 lg->ptr = v; /* borrowed */
3009 }
3010
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003011 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003013 else {
3014 /* Slow-path if globals or builtins is not a dict */
Victor Stinnerb4efc962015-11-20 09:24:02 +01003015
3016 /* namespace 1: globals */
Inada Naoki91234a12019-06-03 21:30:58 +09003017 name = GETITEM(names, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003018 v = PyObject_GetItem(f->f_globals, name);
3019 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003020 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Victor Stinner60a1d3c2015-11-05 13:55:20 +01003021 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02003022 }
3023 _PyErr_Clear(tstate);
Victor Stinner60a1d3c2015-11-05 13:55:20 +01003024
Victor Stinnerb4efc962015-11-20 09:24:02 +01003025 /* namespace 2: builtins */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003026 v = PyObject_GetItem(f->f_builtins, name);
3027 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003028 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003029 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02003030 tstate, PyExc_NameError,
Ezio Melotti04a29552013-03-03 15:12:44 +02003031 NAME_ERROR_MSG, name);
Victor Stinner438a12d2019-05-24 17:01:38 +02003032 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003033 goto error;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003034 }
3035 }
3036 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003037 PUSH(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003039 }
Guido van Rossum681d79a1995-07-18 14:51:37 +00003040
Benjamin Petersonddd19492018-09-16 22:38:02 -07003041 case TARGET(DELETE_FAST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003042 PyObject *v = GETLOCAL(oparg);
3043 if (v != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 SETLOCAL(oparg, NULL);
3045 DISPATCH();
3046 }
3047 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02003048 tstate, PyExc_UnboundLocalError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 UNBOUNDLOCAL_ERROR_MSG,
3050 PyTuple_GetItem(co->co_varnames, oparg)
3051 );
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003052 goto error;
3053 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003054
Benjamin Petersonddd19492018-09-16 22:38:02 -07003055 case TARGET(DELETE_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003056 PyObject *cell = freevars[oparg];
Raymond Hettingerc32f9db2016-11-12 04:10:35 -05003057 PyObject *oldobj = PyCell_GET(cell);
3058 if (oldobj != NULL) {
3059 PyCell_SET(cell, NULL);
3060 Py_DECREF(oldobj);
Benjamin Peterson00ebe2c2010-09-10 22:02:31 +00003061 DISPATCH();
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003062 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003063 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003064 goto error;
3065 }
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003066
Benjamin Petersonddd19492018-09-16 22:38:02 -07003067 case TARGET(LOAD_CLOSURE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003068 PyObject *cell = freevars[oparg];
3069 Py_INCREF(cell);
3070 PUSH(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003072 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003073
Benjamin Petersonddd19492018-09-16 22:38:02 -07003074 case TARGET(LOAD_CLASSDEREF): {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003075 PyObject *name, *value, *locals = f->f_locals;
Victor Stinnerd3dfd0e2013-05-16 23:48:01 +02003076 Py_ssize_t idx;
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003077 assert(locals);
3078 assert(oparg >= PyTuple_GET_SIZE(co->co_cellvars));
3079 idx = oparg - PyTuple_GET_SIZE(co->co_cellvars);
3080 assert(idx >= 0 && idx < PyTuple_GET_SIZE(co->co_freevars));
3081 name = PyTuple_GET_ITEM(co->co_freevars, idx);
3082 if (PyDict_CheckExact(locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003083 value = PyDict_GetItemWithError(locals, name);
3084 if (value != NULL) {
3085 Py_INCREF(value);
3086 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003087 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003088 goto error;
3089 }
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003090 }
3091 else {
3092 value = PyObject_GetItem(locals, name);
Victor Stinnere20310f2015-11-05 13:56:58 +01003093 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003094 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003095 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02003096 }
3097 _PyErr_Clear(tstate);
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003098 }
3099 }
3100 if (!value) {
3101 PyObject *cell = freevars[oparg];
3102 value = PyCell_GET(cell);
3103 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003104 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003105 goto error;
3106 }
3107 Py_INCREF(value);
3108 }
3109 PUSH(value);
3110 DISPATCH();
3111 }
3112
Benjamin Petersonddd19492018-09-16 22:38:02 -07003113 case TARGET(LOAD_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003114 PyObject *cell = freevars[oparg];
3115 PyObject *value = PyCell_GET(cell);
3116 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003117 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003118 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003120 Py_INCREF(value);
3121 PUSH(value);
3122 DISPATCH();
3123 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003124
Benjamin Petersonddd19492018-09-16 22:38:02 -07003125 case TARGET(STORE_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003126 PyObject *v = POP();
3127 PyObject *cell = freevars[oparg];
Raymond Hettingerb2b15432016-11-11 04:32:11 -08003128 PyObject *oldobj = PyCell_GET(cell);
3129 PyCell_SET(cell, v);
3130 Py_XDECREF(oldobj);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003131 DISPATCH();
3132 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003133
Benjamin Petersonddd19492018-09-16 22:38:02 -07003134 case TARGET(BUILD_STRING): {
Serhiy Storchakaea525a22016-09-06 22:07:53 +03003135 PyObject *str;
3136 PyObject *empty = PyUnicode_New(0, 0);
3137 if (empty == NULL) {
3138 goto error;
3139 }
3140 str = _PyUnicode_JoinArray(empty, stack_pointer - oparg, oparg);
3141 Py_DECREF(empty);
3142 if (str == NULL)
3143 goto error;
3144 while (--oparg >= 0) {
3145 PyObject *item = POP();
3146 Py_DECREF(item);
3147 }
3148 PUSH(str);
3149 DISPATCH();
3150 }
3151
Benjamin Petersonddd19492018-09-16 22:38:02 -07003152 case TARGET(BUILD_TUPLE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003153 PyObject *tup = PyTuple_New(oparg);
3154 if (tup == NULL)
3155 goto error;
3156 while (--oparg >= 0) {
3157 PyObject *item = POP();
3158 PyTuple_SET_ITEM(tup, oparg, item);
3159 }
3160 PUSH(tup);
3161 DISPATCH();
3162 }
3163
Benjamin Petersonddd19492018-09-16 22:38:02 -07003164 case TARGET(BUILD_LIST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003165 PyObject *list = PyList_New(oparg);
3166 if (list == NULL)
3167 goto error;
3168 while (--oparg >= 0) {
3169 PyObject *item = POP();
3170 PyList_SET_ITEM(list, oparg, item);
3171 }
3172 PUSH(list);
3173 DISPATCH();
3174 }
3175
Mark Shannon13bc1392020-01-23 09:25:17 +00003176 case TARGET(LIST_TO_TUPLE): {
3177 PyObject *list = POP();
3178 PyObject *tuple = PyList_AsTuple(list);
3179 Py_DECREF(list);
3180 if (tuple == NULL) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003181 goto error;
Mark Shannon13bc1392020-01-23 09:25:17 +00003182 }
3183 PUSH(tuple);
3184 DISPATCH();
3185 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003186
Mark Shannon13bc1392020-01-23 09:25:17 +00003187 case TARGET(LIST_EXTEND): {
3188 PyObject *iterable = POP();
3189 PyObject *list = PEEK(oparg);
3190 PyObject *none_val = _PyList_Extend((PyListObject *)list, iterable);
3191 if (none_val == NULL) {
3192 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
Victor Stinnera102ed72020-02-07 02:24:48 +01003193 (Py_TYPE(iterable)->tp_iter == NULL && !PySequence_Check(iterable)))
Mark Shannon13bc1392020-01-23 09:25:17 +00003194 {
Victor Stinner61f4db82020-01-28 03:37:45 +01003195 _PyErr_Clear(tstate);
Mark Shannon13bc1392020-01-23 09:25:17 +00003196 _PyErr_Format(tstate, PyExc_TypeError,
3197 "Value after * must be an iterable, not %.200s",
3198 Py_TYPE(iterable)->tp_name);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003199 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003200 Py_DECREF(iterable);
3201 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003202 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003203 Py_DECREF(none_val);
3204 Py_DECREF(iterable);
3205 DISPATCH();
3206 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003207
Mark Shannon13bc1392020-01-23 09:25:17 +00003208 case TARGET(SET_UPDATE): {
3209 PyObject *iterable = POP();
3210 PyObject *set = PEEK(oparg);
3211 int err = _PySet_Update(set, iterable);
3212 Py_DECREF(iterable);
3213 if (err < 0) {
3214 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003215 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003216 DISPATCH();
3217 }
3218
Benjamin Petersonddd19492018-09-16 22:38:02 -07003219 case TARGET(BUILD_SET): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003220 PyObject *set = PySet_New(NULL);
3221 int err = 0;
Raymond Hettinger4c483ad2016-09-08 14:45:40 -07003222 int i;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003223 if (set == NULL)
3224 goto error;
Raymond Hettinger4c483ad2016-09-08 14:45:40 -07003225 for (i = oparg; i > 0; i--) {
3226 PyObject *item = PEEK(i);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003227 if (err == 0)
3228 err = PySet_Add(set, item);
3229 Py_DECREF(item);
3230 }
costypetrisor8ed317f2018-07-31 20:55:14 +00003231 STACK_SHRINK(oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003232 if (err != 0) {
3233 Py_DECREF(set);
3234 goto error;
3235 }
3236 PUSH(set);
3237 DISPATCH();
3238 }
3239
Benjamin Petersonddd19492018-09-16 22:38:02 -07003240 case TARGET(BUILD_MAP): {
Victor Stinner74319ae2016-08-25 00:04:09 +02003241 Py_ssize_t i;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003242 PyObject *map = _PyDict_NewPresized((Py_ssize_t)oparg);
3243 if (map == NULL)
3244 goto error;
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003245 for (i = oparg; i > 0; i--) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003246 int err;
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003247 PyObject *key = PEEK(2*i);
3248 PyObject *value = PEEK(2*i - 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003249 err = PyDict_SetItem(map, key, value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003250 if (err != 0) {
3251 Py_DECREF(map);
3252 goto error;
3253 }
3254 }
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003255
3256 while (oparg--) {
3257 Py_DECREF(POP());
3258 Py_DECREF(POP());
3259 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003260 PUSH(map);
3261 DISPATCH();
3262 }
3263
Benjamin Petersonddd19492018-09-16 22:38:02 -07003264 case TARGET(SETUP_ANNOTATIONS): {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003265 _Py_IDENTIFIER(__annotations__);
3266 int err;
3267 PyObject *ann_dict;
3268 if (f->f_locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003269 _PyErr_Format(tstate, PyExc_SystemError,
3270 "no locals found when setting up annotations");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003271 goto error;
3272 }
3273 /* check if __annotations__ in locals()... */
3274 if (PyDict_CheckExact(f->f_locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003275 ann_dict = _PyDict_GetItemIdWithError(f->f_locals,
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003276 &PyId___annotations__);
3277 if (ann_dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003278 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003279 goto error;
3280 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003281 /* ...if not, create a new one */
3282 ann_dict = PyDict_New();
3283 if (ann_dict == NULL) {
3284 goto error;
3285 }
3286 err = _PyDict_SetItemId(f->f_locals,
3287 &PyId___annotations__, ann_dict);
3288 Py_DECREF(ann_dict);
3289 if (err != 0) {
3290 goto error;
3291 }
3292 }
3293 }
3294 else {
3295 /* do the same if locals() is not a dict */
3296 PyObject *ann_str = _PyUnicode_FromId(&PyId___annotations__);
3297 if (ann_str == NULL) {
Serhiy Storchaka4678b2f2016-11-08 23:13:36 +02003298 goto error;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003299 }
3300 ann_dict = PyObject_GetItem(f->f_locals, ann_str);
3301 if (ann_dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003302 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003303 goto error;
3304 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003305 _PyErr_Clear(tstate);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003306 ann_dict = PyDict_New();
3307 if (ann_dict == NULL) {
3308 goto error;
3309 }
3310 err = PyObject_SetItem(f->f_locals, ann_str, ann_dict);
3311 Py_DECREF(ann_dict);
3312 if (err != 0) {
3313 goto error;
3314 }
3315 }
3316 else {
3317 Py_DECREF(ann_dict);
3318 }
3319 }
3320 DISPATCH();
3321 }
3322
Benjamin Petersonddd19492018-09-16 22:38:02 -07003323 case TARGET(BUILD_CONST_KEY_MAP): {
Victor Stinner74319ae2016-08-25 00:04:09 +02003324 Py_ssize_t i;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003325 PyObject *map;
3326 PyObject *keys = TOP();
3327 if (!PyTuple_CheckExact(keys) ||
3328 PyTuple_GET_SIZE(keys) != (Py_ssize_t)oparg) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003329 _PyErr_SetString(tstate, PyExc_SystemError,
3330 "bad BUILD_CONST_KEY_MAP keys argument");
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003331 goto error;
3332 }
3333 map = _PyDict_NewPresized((Py_ssize_t)oparg);
3334 if (map == NULL) {
3335 goto error;
3336 }
3337 for (i = oparg; i > 0; i--) {
3338 int err;
3339 PyObject *key = PyTuple_GET_ITEM(keys, oparg - i);
3340 PyObject *value = PEEK(i + 1);
3341 err = PyDict_SetItem(map, key, value);
3342 if (err != 0) {
3343 Py_DECREF(map);
3344 goto error;
3345 }
3346 }
3347
3348 Py_DECREF(POP());
3349 while (oparg--) {
3350 Py_DECREF(POP());
3351 }
3352 PUSH(map);
3353 DISPATCH();
3354 }
3355
Mark Shannon8a4cd702020-01-27 09:57:45 +00003356 case TARGET(DICT_UPDATE): {
3357 PyObject *update = POP();
3358 PyObject *dict = PEEK(oparg);
3359 if (PyDict_Update(dict, update) < 0) {
3360 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
3361 _PyErr_Format(tstate, PyExc_TypeError,
3362 "'%.200s' object is not a mapping",
Victor Stinnera102ed72020-02-07 02:24:48 +01003363 Py_TYPE(update)->tp_name);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003364 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003365 Py_DECREF(update);
3366 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003367 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003368 Py_DECREF(update);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003369 DISPATCH();
3370 }
3371
Mark Shannon8a4cd702020-01-27 09:57:45 +00003372 case TARGET(DICT_MERGE): {
3373 PyObject *update = POP();
3374 PyObject *dict = PEEK(oparg);
3375
3376 if (_PyDict_MergeEx(dict, update, 2) < 0) {
3377 format_kwargs_error(tstate, PEEK(2 + oparg), update);
3378 Py_DECREF(update);
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003379 goto error;
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003380 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003381 Py_DECREF(update);
Brandt Bucherf185a732019-09-28 17:12:49 -07003382 PREDICT(CALL_FUNCTION_EX);
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003383 DISPATCH();
3384 }
3385
Benjamin Petersonddd19492018-09-16 22:38:02 -07003386 case TARGET(MAP_ADD): {
Jörn Heisslerc8a35412019-06-22 16:40:55 +02003387 PyObject *value = TOP();
3388 PyObject *key = SECOND();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003389 PyObject *map;
3390 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00003391 STACK_SHRINK(2);
Raymond Hettinger41862222016-10-15 19:03:06 -07003392 map = PEEK(oparg); /* dict */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003393 assert(PyDict_CheckExact(map));
Martin Panter95f53c12016-07-18 08:23:26 +00003394 err = PyDict_SetItem(map, key, value); /* map[key] = value */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003395 Py_DECREF(value);
3396 Py_DECREF(key);
3397 if (err != 0)
3398 goto error;
3399 PREDICT(JUMP_ABSOLUTE);
3400 DISPATCH();
3401 }
3402
Benjamin Petersonddd19492018-09-16 22:38:02 -07003403 case TARGET(LOAD_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003404 PyObject *name = GETITEM(names, oparg);
3405 PyObject *owner = TOP();
Pablo Galindo109826c2020-10-20 06:22:44 +01003406
3407 PyTypeObject *type = Py_TYPE(owner);
3408 PyObject *res;
3409 PyObject **dictptr;
3410 PyObject *dict;
3411 _PyOpCodeOpt_LoadAttr *la;
3412
3413 OPCACHE_STAT_ATTR_TOTAL();
3414
3415 OPCACHE_CHECK();
3416 if (co_opcache != NULL && PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
3417 {
3418 if (co_opcache->optimized > 0) {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003419 // Fast path -- cache hit makes LOAD_ATTR ~30% faster.
Pablo Galindo109826c2020-10-20 06:22:44 +01003420 la = &co_opcache->u.la;
3421 if (la->type == type && la->tp_version_tag == type->tp_version_tag)
3422 {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003423 // Hint >= 0 is a dict index; hint == -1 is a dict miss.
3424 // Hint < -1 is an inverted slot offset: offset is strictly > 0,
3425 // so ~offset is strictly < -1 (assuming 2's complement).
3426 if (la->hint < -1) {
3427 // Even faster path -- slot hint.
3428 Py_ssize_t offset = ~la->hint;
3429 // fprintf(stderr, "Using hint for offset %zd\n", offset);
3430 char *addr = (char *)owner + offset;
3431 res = *(PyObject **)addr;
Pablo Galindo109826c2020-10-20 06:22:44 +01003432 if (res != NULL) {
Pablo Galindo109826c2020-10-20 06:22:44 +01003433 Py_INCREF(res);
3434 SET_TOP(res);
3435 Py_DECREF(owner);
Pablo Galindo109826c2020-10-20 06:22:44 +01003436 DISPATCH();
Pablo Galindo109826c2020-10-20 06:22:44 +01003437 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003438 // Else slot is NULL. Fall through to slow path to raise AttributeError(name).
3439 // Don't DEOPT, since the slot is still there.
Pablo Galindo109826c2020-10-20 06:22:44 +01003440 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003441 // Fast path for dict.
3442 assert(type->tp_dict != NULL);
3443 assert(type->tp_dictoffset > 0);
3444
3445 dictptr = (PyObject **) ((char *)owner + type->tp_dictoffset);
3446 dict = *dictptr;
3447 if (dict != NULL && PyDict_CheckExact(dict)) {
3448 Py_ssize_t hint = la->hint;
3449 Py_INCREF(dict);
3450 res = NULL;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003451 assert(!_PyErr_Occurred(tstate));
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003452 la->hint = _PyDict_GetItemHint((PyDictObject*)dict, name, hint, &res);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003453 if (res != NULL) {
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003454 assert(la->hint >= 0);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003455 if (la->hint == hint && hint >= 0) {
3456 // Our hint has helped -- cache hit.
3457 OPCACHE_STAT_ATTR_HIT();
3458 } else {
3459 // The hint we provided didn't work.
3460 // Maybe next time?
3461 OPCACHE_MAYBE_DEOPT_LOAD_ATTR();
3462 }
3463
3464 Py_INCREF(res);
3465 SET_TOP(res);
3466 Py_DECREF(owner);
3467 Py_DECREF(dict);
3468 DISPATCH();
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003469 }
3470 else {
3471 _PyErr_Clear(tstate);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003472 // This attribute can be missing sometimes;
3473 // we don't want to optimize this lookup.
3474 OPCACHE_DEOPT_LOAD_ATTR();
3475 Py_DECREF(dict);
3476 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003477 }
3478 else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003479 // There is no dict, or __dict__ doesn't satisfy PyDict_CheckExact.
3480 OPCACHE_DEOPT_LOAD_ATTR();
3481 }
Pablo Galindo109826c2020-10-20 06:22:44 +01003482 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003483 }
3484 else {
Pablo Galindo109826c2020-10-20 06:22:44 +01003485 // The type of the object has either been updated,
3486 // or is different. Maybe it will stabilize?
3487 OPCACHE_MAYBE_DEOPT_LOAD_ATTR();
3488 }
Pablo Galindo109826c2020-10-20 06:22:44 +01003489 OPCACHE_STAT_ATTR_MISS();
3490 }
3491
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003492 if (co_opcache != NULL && // co_opcache can be NULL after a DEOPT() call.
Pablo Galindo109826c2020-10-20 06:22:44 +01003493 type->tp_getattro == PyObject_GenericGetAttr)
3494 {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003495 if (type->tp_dict == NULL) {
3496 if (PyType_Ready(type) < 0) {
3497 Py_DECREF(owner);
3498 SET_TOP(NULL);
3499 goto error;
Pablo Galindo109826c2020-10-20 06:22:44 +01003500 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003501 }
3502 PyObject *descr = _PyType_Lookup(type, name);
3503 if (descr != NULL) {
3504 // We found an attribute with a data-like descriptor.
3505 PyTypeObject *dtype = Py_TYPE(descr);
3506 if (dtype == &PyMemberDescr_Type) { // It's a slot
3507 PyMemberDescrObject *member = (PyMemberDescrObject *)descr;
3508 struct PyMemberDef *dmem = member->d_member;
3509 if (dmem->type == T_OBJECT_EX) {
3510 Py_ssize_t offset = dmem->offset;
3511 assert(offset > 0); // 0 would be confused with dict hint == -1 (miss).
Pablo Galindo109826c2020-10-20 06:22:44 +01003512
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003513 if (co_opcache->optimized == 0) {
3514 // First time we optimize this opcode.
3515 OPCACHE_STAT_ATTR_OPT();
3516 co_opcache->optimized = OPCODE_CACHE_MAX_TRIES;
3517 // fprintf(stderr, "Setting hint for %s, offset %zd\n", dmem->name, offset);
3518 }
3519
3520 la = &co_opcache->u.la;
3521 la->type = type;
3522 la->tp_version_tag = type->tp_version_tag;
3523 la->hint = ~offset;
3524
3525 char *addr = (char *)owner + offset;
3526 res = *(PyObject **)addr;
Pablo Galindo109826c2020-10-20 06:22:44 +01003527 if (res != NULL) {
3528 Py_INCREF(res);
Pablo Galindo109826c2020-10-20 06:22:44 +01003529 Py_DECREF(owner);
3530 SET_TOP(res);
3531
Pablo Galindo109826c2020-10-20 06:22:44 +01003532 DISPATCH();
3533 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003534 // Else slot is NULL. Fall through to slow path to raise AttributeError(name).
Pablo Galindo109826c2020-10-20 06:22:44 +01003535 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003536 // Else it's a slot of a different type. We don't handle those.
3537 }
3538 // Else it's some other kind of descriptor that we don't handle.
3539 OPCACHE_DEOPT_LOAD_ATTR();
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003540 }
3541 else if (type->tp_dictoffset > 0) {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003542 // We found an instance with a __dict__.
3543 dictptr = (PyObject **) ((char *)owner + type->tp_dictoffset);
3544 dict = *dictptr;
3545
3546 if (dict != NULL && PyDict_CheckExact(dict)) {
3547 Py_INCREF(dict);
3548 res = NULL;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003549 assert(!_PyErr_Occurred(tstate));
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003550 Py_ssize_t hint = _PyDict_GetItemHint((PyDictObject*)dict, name, -1, &res);
3551 if (res != NULL) {
3552 Py_INCREF(res);
3553 Py_DECREF(dict);
3554 Py_DECREF(owner);
3555 SET_TOP(res);
3556
3557 if (co_opcache->optimized == 0) {
3558 // First time we optimize this opcode.
3559 OPCACHE_STAT_ATTR_OPT();
3560 co_opcache->optimized = OPCODE_CACHE_MAX_TRIES;
3561 }
3562
3563 la = &co_opcache->u.la;
3564 la->type = type;
3565 la->tp_version_tag = type->tp_version_tag;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003566 assert(hint >= 0);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003567 la->hint = hint;
3568
3569 DISPATCH();
3570 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003571 else {
3572 _PyErr_Clear(tstate);
3573 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003574 Py_DECREF(dict);
Pablo Galindo109826c2020-10-20 06:22:44 +01003575 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003576 // There is no dict, or __dict__ doesn't satisfy PyDict_CheckExact.
Pablo Galindo109826c2020-10-20 06:22:44 +01003577 OPCACHE_DEOPT_LOAD_ATTR();
3578 }
3579 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003580 // The object's class does not have a tp_dictoffset we can use.
Pablo Galindo109826c2020-10-20 06:22:44 +01003581 OPCACHE_DEOPT_LOAD_ATTR();
3582 }
3583 } else if (type->tp_getattro != PyObject_GenericGetAttr) {
3584 OPCACHE_DEOPT_LOAD_ATTR();
3585 }
3586 }
3587
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003588 // Slow path.
Pablo Galindo109826c2020-10-20 06:22:44 +01003589 res = PyObject_GetAttr(owner, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003590 Py_DECREF(owner);
3591 SET_TOP(res);
3592 if (res == NULL)
3593 goto error;
3594 DISPATCH();
3595 }
3596
Benjamin Petersonddd19492018-09-16 22:38:02 -07003597 case TARGET(COMPARE_OP): {
Mark Shannon9af0e472020-01-14 10:12:45 +00003598 assert(oparg <= Py_GE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003599 PyObject *right = POP();
3600 PyObject *left = TOP();
Mark Shannon9af0e472020-01-14 10:12:45 +00003601 PyObject *res = PyObject_RichCompare(left, right, oparg);
3602 SET_TOP(res);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003603 Py_DECREF(left);
3604 Py_DECREF(right);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003605 if (res == NULL)
3606 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 PREDICT(POP_JUMP_IF_FALSE);
3608 PREDICT(POP_JUMP_IF_TRUE);
3609 DISPATCH();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003610 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003611
Mark Shannon9af0e472020-01-14 10:12:45 +00003612 case TARGET(IS_OP): {
3613 PyObject *right = POP();
3614 PyObject *left = TOP();
3615 int res = (left == right)^oparg;
3616 PyObject *b = res ? Py_True : Py_False;
3617 Py_INCREF(b);
3618 SET_TOP(b);
3619 Py_DECREF(left);
3620 Py_DECREF(right);
3621 PREDICT(POP_JUMP_IF_FALSE);
3622 PREDICT(POP_JUMP_IF_TRUE);
3623 FAST_DISPATCH();
3624 }
3625
3626 case TARGET(CONTAINS_OP): {
3627 PyObject *right = POP();
3628 PyObject *left = POP();
3629 int res = PySequence_Contains(right, left);
3630 Py_DECREF(left);
3631 Py_DECREF(right);
3632 if (res < 0) {
3633 goto error;
3634 }
3635 PyObject *b = (res^oparg) ? Py_True : Py_False;
3636 Py_INCREF(b);
3637 PUSH(b);
3638 PREDICT(POP_JUMP_IF_FALSE);
3639 PREDICT(POP_JUMP_IF_TRUE);
3640 FAST_DISPATCH();
3641 }
3642
3643#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
3644 "BaseException is not allowed"
3645
3646 case TARGET(JUMP_IF_NOT_EXC_MATCH): {
3647 PyObject *right = POP();
3648 PyObject *left = POP();
3649 if (PyTuple_Check(right)) {
3650 Py_ssize_t i, length;
3651 length = PyTuple_GET_SIZE(right);
3652 for (i = 0; i < length; i++) {
3653 PyObject *exc = PyTuple_GET_ITEM(right, i);
3654 if (!PyExceptionClass_Check(exc)) {
3655 _PyErr_SetString(tstate, PyExc_TypeError,
3656 CANNOT_CATCH_MSG);
3657 Py_DECREF(left);
3658 Py_DECREF(right);
3659 goto error;
3660 }
3661 }
3662 }
3663 else {
3664 if (!PyExceptionClass_Check(right)) {
3665 _PyErr_SetString(tstate, PyExc_TypeError,
3666 CANNOT_CATCH_MSG);
3667 Py_DECREF(left);
3668 Py_DECREF(right);
3669 goto error;
3670 }
3671 }
3672 int res = PyErr_GivenExceptionMatches(left, right);
3673 Py_DECREF(left);
3674 Py_DECREF(right);
3675 if (res > 0) {
3676 /* Exception matches -- Do nothing */;
3677 }
3678 else if (res == 0) {
3679 JUMPTO(oparg);
3680 }
3681 else {
3682 goto error;
3683 }
3684 DISPATCH();
3685 }
3686
Benjamin Petersonddd19492018-09-16 22:38:02 -07003687 case TARGET(IMPORT_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003688 PyObject *name = GETITEM(names, oparg);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03003689 PyObject *fromlist = POP();
3690 PyObject *level = TOP();
3691 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02003692 res = import_name(tstate, f, name, fromlist, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03003693 Py_DECREF(level);
3694 Py_DECREF(fromlist);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003695 SET_TOP(res);
3696 if (res == NULL)
3697 goto error;
3698 DISPATCH();
3699 }
3700
Benjamin Petersonddd19492018-09-16 22:38:02 -07003701 case TARGET(IMPORT_STAR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003702 PyObject *from = POP(), *locals;
3703 int err;
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003704 if (PyFrame_FastToLocalsWithError(f) < 0) {
3705 Py_DECREF(from);
Victor Stinner41bb43a2013-10-29 01:19:37 +01003706 goto error;
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003707 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01003708
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003709 locals = f->f_locals;
3710 if (locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003711 _PyErr_SetString(tstate, PyExc_SystemError,
3712 "no locals found during 'import *'");
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003713 Py_DECREF(from);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003714 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003716 err = import_all_from(tstate, locals, from);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 PyFrame_LocalsToFast(f, 0);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003718 Py_DECREF(from);
3719 if (err != 0)
3720 goto error;
3721 DISPATCH();
3722 }
Guido van Rossum25831651993-05-19 14:50:45 +00003723
Benjamin Petersonddd19492018-09-16 22:38:02 -07003724 case TARGET(IMPORT_FROM): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003725 PyObject *name = GETITEM(names, oparg);
3726 PyObject *from = TOP();
3727 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02003728 res = import_from(tstate, from, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003729 PUSH(res);
3730 if (res == NULL)
3731 goto error;
3732 DISPATCH();
3733 }
Thomas Wouters52152252000-08-17 22:55:00 +00003734
Benjamin Petersonddd19492018-09-16 22:38:02 -07003735 case TARGET(JUMP_FORWARD): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 JUMPBY(oparg);
3737 FAST_DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003738 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003739
Benjamin Petersonddd19492018-09-16 22:38:02 -07003740 case TARGET(POP_JUMP_IF_FALSE): {
3741 PREDICTED(POP_JUMP_IF_FALSE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003742 PyObject *cond = POP();
3743 int err;
3744 if (cond == Py_True) {
3745 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 FAST_DISPATCH();
3747 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003748 if (cond == Py_False) {
3749 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 JUMPTO(oparg);
3751 FAST_DISPATCH();
3752 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003753 err = PyObject_IsTrue(cond);
3754 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 if (err > 0)
Adrian Wielgosik50c28502017-06-23 13:35:41 -07003756 ;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 else if (err == 0)
3758 JUMPTO(oparg);
3759 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003760 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003762 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003763
Benjamin Petersonddd19492018-09-16 22:38:02 -07003764 case TARGET(POP_JUMP_IF_TRUE): {
3765 PREDICTED(POP_JUMP_IF_TRUE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003766 PyObject *cond = POP();
3767 int err;
3768 if (cond == Py_False) {
3769 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 FAST_DISPATCH();
3771 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003772 if (cond == Py_True) {
3773 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 JUMPTO(oparg);
3775 FAST_DISPATCH();
3776 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003777 err = PyObject_IsTrue(cond);
3778 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 if (err > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 JUMPTO(oparg);
3781 }
3782 else if (err == 0)
3783 ;
3784 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003785 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003787 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003788
Benjamin Petersonddd19492018-09-16 22:38:02 -07003789 case TARGET(JUMP_IF_FALSE_OR_POP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003790 PyObject *cond = TOP();
3791 int err;
3792 if (cond == Py_True) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003793 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003794 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 FAST_DISPATCH();
3796 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003797 if (cond == Py_False) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 JUMPTO(oparg);
3799 FAST_DISPATCH();
3800 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003801 err = PyObject_IsTrue(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 if (err > 0) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003803 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003804 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 }
3806 else if (err == 0)
3807 JUMPTO(oparg);
3808 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003809 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003811 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003812
Benjamin Petersonddd19492018-09-16 22:38:02 -07003813 case TARGET(JUMP_IF_TRUE_OR_POP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003814 PyObject *cond = TOP();
3815 int err;
3816 if (cond == Py_False) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003817 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003818 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 FAST_DISPATCH();
3820 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003821 if (cond == Py_True) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 JUMPTO(oparg);
3823 FAST_DISPATCH();
3824 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003825 err = PyObject_IsTrue(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 if (err > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 JUMPTO(oparg);
3828 }
3829 else if (err == 0) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003830 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003831 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 }
3833 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003834 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003836 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003837
Benjamin Petersonddd19492018-09-16 22:38:02 -07003838 case TARGET(JUMP_ABSOLUTE): {
3839 PREDICTED(JUMP_ABSOLUTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 JUMPTO(oparg);
Guido van Rossum58da9312007-11-10 23:39:45 +00003841#if FAST_LOOPS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 /* Enabling this path speeds-up all while and for-loops by bypassing
3843 the per-loop checks for signals. By default, this should be turned-off
3844 because it prevents detection of a control-break in tight loops like
3845 "while 1: pass". Compile with this option turned-on when you need
3846 the speed-up and do not need break checking inside tight loops (ones
3847 that contain only instructions ending with FAST_DISPATCH).
3848 */
3849 FAST_DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00003850#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 DISPATCH();
Guido van Rossum58da9312007-11-10 23:39:45 +00003852#endif
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003853 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003854
Brandt Bucher145bf262021-02-26 14:51:55 -08003855 case TARGET(GET_LEN): {
3856 // PUSH(len(TOS))
3857 Py_ssize_t len_i = PyObject_Length(TOP());
3858 if (len_i < 0) {
3859 goto error;
3860 }
3861 PyObject *len_o = PyLong_FromSsize_t(len_i);
3862 if (len_o == NULL) {
3863 goto error;
3864 }
3865 PUSH(len_o);
3866 DISPATCH();
3867 }
3868
3869 case TARGET(MATCH_CLASS): {
3870 // Pop TOS. On success, set TOS to True and TOS1 to a tuple of
3871 // attributes. On failure, set TOS to False.
3872 PyObject *names = POP();
3873 PyObject *type = TOP();
3874 PyObject *subject = SECOND();
3875 assert(PyTuple_CheckExact(names));
3876 PyObject *attrs = match_class(tstate, subject, type, oparg, names);
3877 Py_DECREF(names);
3878 if (attrs) {
3879 // Success!
3880 assert(PyTuple_CheckExact(attrs));
3881 Py_DECREF(subject);
3882 SET_SECOND(attrs);
3883 }
3884 else if (_PyErr_Occurred(tstate)) {
3885 goto error;
3886 }
3887 Py_DECREF(type);
3888 SET_TOP(PyBool_FromLong(!!attrs));
3889 DISPATCH();
3890 }
3891
3892 case TARGET(MATCH_MAPPING): {
3893 // PUSH(isinstance(TOS, _collections_abc.Mapping))
3894 PyObject *subject = TOP();
3895 // Fast path for dicts:
3896 if (PyDict_Check(subject)) {
3897 Py_INCREF(Py_True);
3898 PUSH(Py_True);
3899 DISPATCH();
3900 }
3901 // Lazily import _collections_abc.Mapping, and keep it handy on the
3902 // PyInterpreterState struct (it gets cleaned up at exit):
3903 PyInterpreterState *interp = PyInterpreterState_Get();
3904 if (interp->map_abc == NULL) {
3905 PyObject *abc = PyImport_ImportModule("_collections_abc");
3906 if (abc == NULL) {
3907 goto error;
3908 }
3909 interp->map_abc = PyObject_GetAttrString(abc, "Mapping");
3910 if (interp->map_abc == NULL) {
3911 goto error;
3912 }
3913 }
3914 int match = PyObject_IsInstance(subject, interp->map_abc);
3915 if (match < 0) {
3916 goto error;
3917 }
3918 PUSH(PyBool_FromLong(match));
3919 DISPATCH();
3920 }
3921
3922 case TARGET(MATCH_SEQUENCE): {
3923 // PUSH(not isinstance(TOS, (bytearray, bytes, str))
3924 // and isinstance(TOS, _collections_abc.Sequence))
3925 PyObject *subject = TOP();
3926 // Fast path for lists and tuples:
3927 if (PyType_FastSubclass(Py_TYPE(subject),
3928 Py_TPFLAGS_LIST_SUBCLASS |
3929 Py_TPFLAGS_TUPLE_SUBCLASS))
3930 {
3931 Py_INCREF(Py_True);
3932 PUSH(Py_True);
3933 DISPATCH();
3934 }
3935 // Bail on some possible Sequences that we intentionally exclude:
3936 if (PyType_FastSubclass(Py_TYPE(subject),
3937 Py_TPFLAGS_BYTES_SUBCLASS |
3938 Py_TPFLAGS_UNICODE_SUBCLASS) ||
3939 PyByteArray_Check(subject))
3940 {
3941 Py_INCREF(Py_False);
3942 PUSH(Py_False);
3943 DISPATCH();
3944 }
3945 // Lazily import _collections_abc.Sequence, and keep it handy on the
3946 // PyInterpreterState struct (it gets cleaned up at exit):
3947 PyInterpreterState *interp = PyInterpreterState_Get();
3948 if (interp->seq_abc == NULL) {
3949 PyObject *abc = PyImport_ImportModule("_collections_abc");
3950 if (abc == NULL) {
3951 goto error;
3952 }
3953 interp->seq_abc = PyObject_GetAttrString(abc, "Sequence");
3954 if (interp->seq_abc == NULL) {
3955 goto error;
3956 }
3957 }
3958 int match = PyObject_IsInstance(subject, interp->seq_abc);
3959 if (match < 0) {
3960 goto error;
3961 }
3962 PUSH(PyBool_FromLong(match));
3963 DISPATCH();
3964 }
3965
3966 case TARGET(MATCH_KEYS): {
3967 // On successful match for all keys, PUSH(values) and PUSH(True).
3968 // Otherwise, PUSH(None) and PUSH(False).
3969 PyObject *keys = TOP();
3970 PyObject *subject = SECOND();
3971 PyObject *values_or_none = match_keys(tstate, subject, keys);
3972 if (values_or_none == NULL) {
3973 goto error;
3974 }
3975 PUSH(values_or_none);
3976 if (values_or_none == Py_None) {
3977 Py_INCREF(Py_False);
3978 PUSH(Py_False);
3979 DISPATCH();
3980 }
3981 assert(PyTuple_CheckExact(values_or_none));
3982 Py_INCREF(Py_True);
3983 PUSH(Py_True);
3984 DISPATCH();
3985 }
3986
3987 case TARGET(COPY_DICT_WITHOUT_KEYS): {
3988 // rest = dict(TOS1)
3989 // for key in TOS:
3990 // del rest[key]
3991 // SET_TOP(rest)
3992 PyObject *keys = TOP();
3993 PyObject *subject = SECOND();
3994 PyObject *rest = PyDict_New();
3995 if (rest == NULL || PyDict_Update(rest, subject)) {
3996 Py_XDECREF(rest);
3997 goto error;
3998 }
3999 // This may seem a bit inefficient, but keys is rarely big enough to
4000 // actually impact runtime.
4001 assert(PyTuple_CheckExact(keys));
4002 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(keys); i++) {
4003 if (PyDict_DelItem(rest, PyTuple_GET_ITEM(keys, i))) {
4004 Py_DECREF(rest);
4005 goto error;
4006 }
4007 }
4008 Py_DECREF(keys);
4009 SET_TOP(rest);
4010 DISPATCH();
4011 }
4012
Benjamin Petersonddd19492018-09-16 22:38:02 -07004013 case TARGET(GET_ITER): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 /* before: [obj]; after [getiter(obj)] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004015 PyObject *iterable = TOP();
Yury Selivanov5376ba92015-06-22 12:19:30 -04004016 PyObject *iter = PyObject_GetIter(iterable);
4017 Py_DECREF(iterable);
4018 SET_TOP(iter);
4019 if (iter == NULL)
4020 goto error;
4021 PREDICT(FOR_ITER);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004022 PREDICT(CALL_FUNCTION);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004023 DISPATCH();
4024 }
4025
Benjamin Petersonddd19492018-09-16 22:38:02 -07004026 case TARGET(GET_YIELD_FROM_ITER): {
Yury Selivanov5376ba92015-06-22 12:19:30 -04004027 /* before: [obj]; after [getiter(obj)] */
4028 PyObject *iterable = TOP();
Yury Selivanov75445082015-05-11 22:57:16 -04004029 PyObject *iter;
Yury Selivanov5376ba92015-06-22 12:19:30 -04004030 if (PyCoro_CheckExact(iterable)) {
4031 /* `iterable` is a coroutine */
4032 if (!(co->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))) {
4033 /* and it is used in a 'yield from' expression of a
4034 regular generator. */
4035 Py_DECREF(iterable);
4036 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02004037 _PyErr_SetString(tstate, PyExc_TypeError,
4038 "cannot 'yield from' a coroutine object "
4039 "in a non-coroutine generator");
Yury Selivanov5376ba92015-06-22 12:19:30 -04004040 goto error;
4041 }
4042 }
4043 else if (!PyGen_CheckExact(iterable)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004044 /* `iterable` is not a generator. */
4045 iter = PyObject_GetIter(iterable);
4046 Py_DECREF(iterable);
4047 SET_TOP(iter);
4048 if (iter == NULL)
4049 goto error;
4050 }
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004051 PREDICT(LOAD_CONST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004052 DISPATCH();
4053 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00004054
Benjamin Petersonddd19492018-09-16 22:38:02 -07004055 case TARGET(FOR_ITER): {
4056 PREDICTED(FOR_ITER);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 /* before: [iter]; after: [iter, iter()] *or* [] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004058 PyObject *iter = TOP();
Victor Stinnera102ed72020-02-07 02:24:48 +01004059 PyObject *next = (*Py_TYPE(iter)->tp_iternext)(iter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004060 if (next != NULL) {
4061 PUSH(next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 PREDICT(STORE_FAST);
4063 PREDICT(UNPACK_SEQUENCE);
4064 DISPATCH();
4065 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004066 if (_PyErr_Occurred(tstate)) {
4067 if (!_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004068 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02004069 }
4070 else if (tstate->c_tracefunc != NULL) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00004071 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, &trace_info);
Victor Stinner438a12d2019-05-24 17:01:38 +02004072 }
4073 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 }
4075 /* iterator ended normally */
costypetrisor8ed317f2018-07-31 20:55:14 +00004076 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004077 Py_DECREF(iter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 JUMPBY(oparg);
4079 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004080 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00004081
Benjamin Petersonddd19492018-09-16 22:38:02 -07004082 case TARGET(SETUP_FINALLY): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004083 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 STACK_LEVEL());
4085 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004086 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004087
Benjamin Petersonddd19492018-09-16 22:38:02 -07004088 case TARGET(BEFORE_ASYNC_WITH): {
Yury Selivanov75445082015-05-11 22:57:16 -04004089 _Py_IDENTIFIER(__aenter__);
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004090 _Py_IDENTIFIER(__aexit__);
Yury Selivanov75445082015-05-11 22:57:16 -04004091 PyObject *mgr = TOP();
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004092 PyObject *enter = special_lookup(tstate, mgr, &PyId___aenter__);
Yury Selivanov75445082015-05-11 22:57:16 -04004093 PyObject *res;
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004094 if (enter == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04004095 goto error;
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004096 }
4097 PyObject *exit = special_lookup(tstate, mgr, &PyId___aexit__);
4098 if (exit == NULL) {
4099 Py_DECREF(enter);
4100 goto error;
4101 }
Yury Selivanov75445082015-05-11 22:57:16 -04004102 SET_TOP(exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004103 Py_DECREF(mgr);
Victor Stinnerf17c3de2016-12-06 18:46:19 +01004104 res = _PyObject_CallNoArg(enter);
Yury Selivanov75445082015-05-11 22:57:16 -04004105 Py_DECREF(enter);
4106 if (res == NULL)
4107 goto error;
4108 PUSH(res);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004109 PREDICT(GET_AWAITABLE);
Yury Selivanov75445082015-05-11 22:57:16 -04004110 DISPATCH();
4111 }
4112
Benjamin Petersonddd19492018-09-16 22:38:02 -07004113 case TARGET(SETUP_ASYNC_WITH): {
Yury Selivanov75445082015-05-11 22:57:16 -04004114 PyObject *res = POP();
4115 /* Setup the finally block before pushing the result
4116 of __aenter__ on the stack. */
4117 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
4118 STACK_LEVEL());
4119 PUSH(res);
4120 DISPATCH();
4121 }
4122
Benjamin Petersonddd19492018-09-16 22:38:02 -07004123 case TARGET(SETUP_WITH): {
Benjamin Petersonce798522012-01-22 11:24:29 -05004124 _Py_IDENTIFIER(__enter__);
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004125 _Py_IDENTIFIER(__exit__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004126 PyObject *mgr = TOP();
Victor Stinner438a12d2019-05-24 17:01:38 +02004127 PyObject *enter = special_lookup(tstate, mgr, &PyId___enter__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004128 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02004129 if (enter == NULL) {
Raymond Hettingera3fec152016-11-21 17:24:23 -08004130 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02004131 }
4132 PyObject *exit = special_lookup(tstate, mgr, &PyId___exit__);
Raymond Hettinger64e2f9a2016-11-22 11:50:40 -08004133 if (exit == NULL) {
4134 Py_DECREF(enter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004135 goto error;
Raymond Hettinger64e2f9a2016-11-22 11:50:40 -08004136 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004137 SET_TOP(exit);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004138 Py_DECREF(mgr);
Victor Stinnerf17c3de2016-12-06 18:46:19 +01004139 res = _PyObject_CallNoArg(enter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004140 Py_DECREF(enter);
4141 if (res == NULL)
4142 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 /* Setup the finally block before pushing the result
4144 of __enter__ on the stack. */
4145 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
4146 STACK_LEVEL());
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004147
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004148 PUSH(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 DISPATCH();
4150 }
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004151
Mark Shannonfee55262019-11-21 09:11:43 +00004152 case TARGET(WITH_EXCEPT_START): {
4153 /* At the top of the stack are 7 values:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 - (TOP, SECOND, THIRD) = exc_info()
Mark Shannonfee55262019-11-21 09:11:43 +00004155 - (FOURTH, FIFTH, SIXTH) = previous exception for EXCEPT_HANDLER
4156 - SEVENTH: the context.__exit__ bound method
4157 We call SEVENTH(TOP, SECOND, THIRD).
4158 Then we push again the TOP exception and the __exit__
4159 return value.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 PyObject *exit_func;
Victor Stinner842cfff2016-12-01 14:45:31 +01004162 PyObject *exc, *val, *tb, *res;
4163
Victor Stinner842cfff2016-12-01 14:45:31 +01004164 exc = TOP();
Mark Shannonfee55262019-11-21 09:11:43 +00004165 val = SECOND();
4166 tb = THIRD();
4167 assert(exc != Py_None);
4168 assert(!PyLong_Check(exc));
4169 exit_func = PEEK(7);
Jeroen Demeyer469d1a72019-07-03 12:52:21 +02004170 PyObject *stack[4] = {NULL, exc, val, tb};
Petr Viktorinffd97532020-02-11 17:46:57 +01004171 res = PyObject_Vectorcall(exit_func, stack + 1,
Jeroen Demeyer469d1a72019-07-03 12:52:21 +02004172 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004173 if (res == NULL)
4174 goto error;
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00004175
Yury Selivanov75445082015-05-11 22:57:16 -04004176 PUSH(res);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004177 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00004179
Benjamin Petersonddd19492018-09-16 22:38:02 -07004180 case TARGET(LOAD_METHOD): {
Andreyb021ba52019-04-29 14:33:26 +10004181 /* Designed to work in tandem with CALL_METHOD. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004182 PyObject *name = GETITEM(names, oparg);
4183 PyObject *obj = TOP();
4184 PyObject *meth = NULL;
4185
4186 int meth_found = _PyObject_GetMethod(obj, name, &meth);
4187
Yury Selivanovf2392132016-12-13 19:03:51 -05004188 if (meth == NULL) {
4189 /* Most likely attribute wasn't found. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004190 goto error;
4191 }
4192
4193 if (meth_found) {
INADA Naoki015bce62017-01-16 17:23:30 +09004194 /* We can bypass temporary bound method object.
4195 meth is unbound method and obj is self.
Victor Stinnera8cb5152017-01-18 14:12:51 +01004196
INADA Naoki015bce62017-01-16 17:23:30 +09004197 meth | self | arg1 | ... | argN
4198 */
4199 SET_TOP(meth);
4200 PUSH(obj); // self
Yury Selivanovf2392132016-12-13 19:03:51 -05004201 }
4202 else {
INADA Naoki015bce62017-01-16 17:23:30 +09004203 /* meth is not an unbound method (but a regular attr, or
4204 something was returned by a descriptor protocol). Set
4205 the second element of the stack to NULL, to signal
Yury Selivanovf2392132016-12-13 19:03:51 -05004206 CALL_METHOD that it's not a method call.
INADA Naoki015bce62017-01-16 17:23:30 +09004207
4208 NULL | meth | arg1 | ... | argN
Yury Selivanovf2392132016-12-13 19:03:51 -05004209 */
INADA Naoki015bce62017-01-16 17:23:30 +09004210 SET_TOP(NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004211 Py_DECREF(obj);
INADA Naoki015bce62017-01-16 17:23:30 +09004212 PUSH(meth);
Yury Selivanovf2392132016-12-13 19:03:51 -05004213 }
4214 DISPATCH();
4215 }
4216
Benjamin Petersonddd19492018-09-16 22:38:02 -07004217 case TARGET(CALL_METHOD): {
Yury Selivanovf2392132016-12-13 19:03:51 -05004218 /* Designed to work in tamdem with LOAD_METHOD. */
INADA Naoki015bce62017-01-16 17:23:30 +09004219 PyObject **sp, *res, *meth;
Yury Selivanovf2392132016-12-13 19:03:51 -05004220
4221 sp = stack_pointer;
4222
INADA Naoki015bce62017-01-16 17:23:30 +09004223 meth = PEEK(oparg + 2);
4224 if (meth == NULL) {
4225 /* `meth` is NULL when LOAD_METHOD thinks that it's not
4226 a method call.
Yury Selivanovf2392132016-12-13 19:03:51 -05004227
4228 Stack layout:
4229
INADA Naoki015bce62017-01-16 17:23:30 +09004230 ... | NULL | callable | arg1 | ... | argN
4231 ^- TOP()
4232 ^- (-oparg)
4233 ^- (-oparg-1)
4234 ^- (-oparg-2)
Yury Selivanovf2392132016-12-13 19:03:51 -05004235
Ville Skyttä49b27342017-08-03 09:00:59 +03004236 `callable` will be POPed by call_function.
INADA Naoki015bce62017-01-16 17:23:30 +09004237 NULL will will be POPed manually later.
Yury Selivanovf2392132016-12-13 19:03:51 -05004238 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00004239 res = call_function(tstate, &trace_info, &sp, oparg, NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004240 stack_pointer = sp;
INADA Naoki015bce62017-01-16 17:23:30 +09004241 (void)POP(); /* POP the NULL. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004242 }
4243 else {
4244 /* This is a method call. Stack layout:
4245
INADA Naoki015bce62017-01-16 17:23:30 +09004246 ... | method | self | arg1 | ... | argN
Yury Selivanovf2392132016-12-13 19:03:51 -05004247 ^- TOP()
4248 ^- (-oparg)
INADA Naoki015bce62017-01-16 17:23:30 +09004249 ^- (-oparg-1)
4250 ^- (-oparg-2)
Yury Selivanovf2392132016-12-13 19:03:51 -05004251
INADA Naoki015bce62017-01-16 17:23:30 +09004252 `self` and `method` will be POPed by call_function.
Yury Selivanovf2392132016-12-13 19:03:51 -05004253 We'll be passing `oparg + 1` to call_function, to
INADA Naoki015bce62017-01-16 17:23:30 +09004254 make it accept the `self` as a first argument.
Yury Selivanovf2392132016-12-13 19:03:51 -05004255 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00004256 res = call_function(tstate, &trace_info, &sp, oparg + 1, NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004257 stack_pointer = sp;
4258 }
4259
4260 PUSH(res);
4261 if (res == NULL)
4262 goto error;
4263 DISPATCH();
4264 }
4265
Benjamin Petersonddd19492018-09-16 22:38:02 -07004266 case TARGET(CALL_FUNCTION): {
4267 PREDICTED(CALL_FUNCTION);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004268 PyObject **sp, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 sp = stack_pointer;
Mark Shannon8e1b4062021-03-05 14:45:50 +00004270 res = call_function(tstate, &trace_info, &sp, oparg, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 stack_pointer = sp;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004272 PUSH(res);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004273 if (res == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004274 goto error;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004275 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004276 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004278
Benjamin Petersonddd19492018-09-16 22:38:02 -07004279 case TARGET(CALL_FUNCTION_KW): {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004280 PyObject **sp, *res, *names;
4281
4282 names = POP();
Jeroen Demeyer05677862019-08-16 12:41:27 +02004283 assert(PyTuple_Check(names));
4284 assert(PyTuple_GET_SIZE(names) <= oparg);
4285 /* We assume without checking that names contains only strings */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 sp = stack_pointer;
Mark Shannon8e1b4062021-03-05 14:45:50 +00004287 res = call_function(tstate, &trace_info, &sp, oparg, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 stack_pointer = sp;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004289 PUSH(res);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004290 Py_DECREF(names);
4291
4292 if (res == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004293 goto error;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004294 }
4295 DISPATCH();
4296 }
4297
Benjamin Petersonddd19492018-09-16 22:38:02 -07004298 case TARGET(CALL_FUNCTION_EX): {
Brandt Bucherf185a732019-09-28 17:12:49 -07004299 PREDICTED(CALL_FUNCTION_EX);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004300 PyObject *func, *callargs, *kwargs = NULL, *result;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004301 if (oparg & 0x01) {
4302 kwargs = POP();
Serhiy Storchakab7281052016-09-12 00:52:40 +03004303 if (!PyDict_CheckExact(kwargs)) {
4304 PyObject *d = PyDict_New();
4305 if (d == NULL)
4306 goto error;
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02004307 if (_PyDict_MergeEx(d, kwargs, 2) < 0) {
Serhiy Storchakab7281052016-09-12 00:52:40 +03004308 Py_DECREF(d);
Victor Stinner438a12d2019-05-24 17:01:38 +02004309 format_kwargs_error(tstate, SECOND(), kwargs);
Victor Stinnereece2222016-09-12 11:16:37 +02004310 Py_DECREF(kwargs);
Serhiy Storchakab7281052016-09-12 00:52:40 +03004311 goto error;
4312 }
4313 Py_DECREF(kwargs);
4314 kwargs = d;
4315 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004316 assert(PyDict_CheckExact(kwargs));
4317 }
4318 callargs = POP();
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004319 func = TOP();
Serhiy Storchaka63dc5482016-09-22 19:41:20 +03004320 if (!PyTuple_CheckExact(callargs)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02004321 if (check_args_iterable(tstate, func, callargs) < 0) {
Victor Stinnereece2222016-09-12 11:16:37 +02004322 Py_DECREF(callargs);
Serhiy Storchakab7281052016-09-12 00:52:40 +03004323 goto error;
4324 }
4325 Py_SETREF(callargs, PySequence_Tuple(callargs));
4326 if (callargs == NULL) {
4327 goto error;
4328 }
4329 }
Serhiy Storchaka63dc5482016-09-22 19:41:20 +03004330 assert(PyTuple_CheckExact(callargs));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004331
Mark Shannon8e1b4062021-03-05 14:45:50 +00004332 result = do_call_core(tstate, &trace_info, func, callargs, kwargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004333 Py_DECREF(func);
4334 Py_DECREF(callargs);
4335 Py_XDECREF(kwargs);
4336
4337 SET_TOP(result);
4338 if (result == NULL) {
4339 goto error;
4340 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004341 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004343
Benjamin Petersonddd19492018-09-16 22:38:02 -07004344 case TARGET(MAKE_FUNCTION): {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004345 PyObject *qualname = POP();
4346 PyObject *codeobj = POP();
4347 PyFunctionObject *func = (PyFunctionObject *)
4348 PyFunction_NewWithQualName(codeobj, f->f_globals, qualname);
Guido van Rossum4f72a782006-10-27 23:31:49 +00004349
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004350 Py_DECREF(codeobj);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004351 Py_DECREF(qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004352 if (func == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004353 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 }
Neal Norwitzc1505362006-12-28 06:47:50 +00004355
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004356 if (oparg & 0x08) {
4357 assert(PyTuple_CheckExact(TOP()));
Mark Shannond6c33fb2021-01-29 13:24:55 +00004358 func->func_closure = POP();
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004359 }
4360 if (oparg & 0x04) {
Yurii Karabas73019792020-11-25 12:43:18 +02004361 assert(PyTuple_CheckExact(TOP()));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004362 func->func_annotations = POP();
4363 }
4364 if (oparg & 0x02) {
4365 assert(PyDict_CheckExact(TOP()));
4366 func->func_kwdefaults = POP();
4367 }
4368 if (oparg & 0x01) {
4369 assert(PyTuple_CheckExact(TOP()));
4370 func->func_defaults = POP();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 }
Neal Norwitzc1505362006-12-28 06:47:50 +00004372
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004373 PUSH((PyObject *)func);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004374 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004376
Benjamin Petersonddd19492018-09-16 22:38:02 -07004377 case TARGET(BUILD_SLICE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004378 PyObject *start, *stop, *step, *slice;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (oparg == 3)
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004380 step = POP();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004382 step = NULL;
4383 stop = POP();
4384 start = TOP();
4385 slice = PySlice_New(start, stop, step);
4386 Py_DECREF(start);
4387 Py_DECREF(stop);
4388 Py_XDECREF(step);
4389 SET_TOP(slice);
4390 if (slice == NULL)
4391 goto error;
4392 DISPATCH();
4393 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004394
Benjamin Petersonddd19492018-09-16 22:38:02 -07004395 case TARGET(FORMAT_VALUE): {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004396 /* Handles f-string value formatting. */
4397 PyObject *result;
4398 PyObject *fmt_spec;
4399 PyObject *value;
4400 PyObject *(*conv_fn)(PyObject *);
4401 int which_conversion = oparg & FVC_MASK;
4402 int have_fmt_spec = (oparg & FVS_MASK) == FVS_HAVE_SPEC;
4403
4404 fmt_spec = have_fmt_spec ? POP() : NULL;
Eric V. Smith135d5f42016-02-05 18:23:08 -05004405 value = POP();
Eric V. Smitha78c7952015-11-03 12:45:05 -05004406
4407 /* See if any conversion is specified. */
4408 switch (which_conversion) {
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004409 case FVC_NONE: conv_fn = NULL; break;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004410 case FVC_STR: conv_fn = PyObject_Str; break;
4411 case FVC_REPR: conv_fn = PyObject_Repr; break;
4412 case FVC_ASCII: conv_fn = PyObject_ASCII; break;
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004413 default:
Victor Stinner438a12d2019-05-24 17:01:38 +02004414 _PyErr_Format(tstate, PyExc_SystemError,
4415 "unexpected conversion flag %d",
4416 which_conversion);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004417 goto error;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004418 }
4419
4420 /* If there's a conversion function, call it and replace
4421 value with that result. Otherwise, just use value,
4422 without conversion. */
Eric V. Smitheb588a12016-02-05 18:26:20 -05004423 if (conv_fn != NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004424 result = conv_fn(value);
4425 Py_DECREF(value);
Eric V. Smitheb588a12016-02-05 18:26:20 -05004426 if (result == NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004427 Py_XDECREF(fmt_spec);
4428 goto error;
4429 }
4430 value = result;
4431 }
4432
4433 /* If value is a unicode object, and there's no fmt_spec,
4434 then we know the result of format(value) is value
4435 itself. In that case, skip calling format(). I plan to
4436 move this optimization in to PyObject_Format()
4437 itself. */
4438 if (PyUnicode_CheckExact(value) && fmt_spec == NULL) {
4439 /* Do nothing, just transfer ownership to result. */
4440 result = value;
4441 } else {
4442 /* Actually call format(). */
4443 result = PyObject_Format(value, fmt_spec);
4444 Py_DECREF(value);
4445 Py_XDECREF(fmt_spec);
Eric V. Smitheb588a12016-02-05 18:26:20 -05004446 if (result == NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004447 goto error;
Eric V. Smitheb588a12016-02-05 18:26:20 -05004448 }
Eric V. Smitha78c7952015-11-03 12:45:05 -05004449 }
4450
Eric V. Smith135d5f42016-02-05 18:23:08 -05004451 PUSH(result);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004452 DISPATCH();
4453 }
4454
Benjamin Petersonddd19492018-09-16 22:38:02 -07004455 case TARGET(EXTENDED_ARG): {
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03004456 int oldoparg = oparg;
4457 NEXTOPARG();
4458 oparg |= oldoparg << 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 goto dispatch_opcode;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004460 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004461
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004462
Antoine Pitrou042b1282010-08-13 21:15:58 +00004463#if USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 _unknown_opcode:
Antoine Pitroub52ec782009-01-25 16:34:23 +00004465#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 default:
4467 fprintf(stderr,
4468 "XXX lineno: %d, opcode: %d\n",
4469 PyFrame_GetLineNumber(f),
4470 opcode);
Victor Stinner438a12d2019-05-24 17:01:38 +02004471 _PyErr_SetString(tstate, PyExc_SystemError, "unknown opcode");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004472 goto error;
Guido van Rossum04691fc1992-08-12 15:35:34 +00004473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 } /* switch */
Guido van Rossum374a9221991-04-04 10:40:29 +00004475
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004476 /* This should never be reached. Every opcode should end with DISPATCH()
4477 or goto error. */
Barry Warsawb2e57942017-09-14 18:13:16 -07004478 Py_UNREACHABLE();
Guido van Rossumac7be682001-01-17 15:42:30 +00004479
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004480error:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004481 /* Double-check exception status. */
Victor Stinner365b6932013-07-12 00:11:58 +02004482#ifdef NDEBUG
Victor Stinner438a12d2019-05-24 17:01:38 +02004483 if (!_PyErr_Occurred(tstate)) {
4484 _PyErr_SetString(tstate, PyExc_SystemError,
4485 "error return without exception set");
4486 }
Victor Stinner365b6932013-07-12 00:11:58 +02004487#else
Victor Stinner438a12d2019-05-24 17:01:38 +02004488 assert(_PyErr_Occurred(tstate));
Victor Stinner365b6932013-07-12 00:11:58 +02004489#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00004490
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004491 /* Log traceback info. */
4492 PyTraceBack_Here(f);
Guido van Rossumac7be682001-01-17 15:42:30 +00004493
Mark Shannoncb9879b2020-07-17 11:44:23 +01004494 if (tstate->c_tracefunc != NULL) {
4495 /* Make sure state is set to FRAME_EXECUTING for tracing */
4496 assert(f->f_state == FRAME_EXECUTING);
4497 f->f_state = FRAME_UNWINDING;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01004498 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004499 tstate, f, &trace_info);
Mark Shannoncb9879b2020-07-17 11:44:23 +01004500 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004501exception_unwind:
Mark Shannoncb9879b2020-07-17 11:44:23 +01004502 f->f_state = FRAME_UNWINDING;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004503 /* Unwind stacks if an exception occurred */
4504 while (f->f_iblock > 0) {
4505 /* Pop the current block. */
4506 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (b->b_type == EXCEPT_HANDLER) {
4509 UNWIND_EXCEPT_HANDLER(b);
4510 continue;
4511 }
4512 UNWIND_BLOCK(b);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004513 if (b->b_type == SETUP_FINALLY) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 PyObject *exc, *val, *tb;
4515 int handler = b->b_handler;
Mark Shannonae3087c2017-10-22 22:41:51 +01004516 _PyErr_StackItem *exc_info = tstate->exc_info;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 /* Beware, this invalidates all b->b_* fields */
Mark Shannonbf353f32020-12-17 13:55:28 +00004518 PyFrame_BlockSetup(f, EXCEPT_HANDLER, f->f_lasti, STACK_LEVEL());
Mark Shannonae3087c2017-10-22 22:41:51 +01004519 PUSH(exc_info->exc_traceback);
4520 PUSH(exc_info->exc_value);
4521 if (exc_info->exc_type != NULL) {
4522 PUSH(exc_info->exc_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 }
4524 else {
4525 Py_INCREF(Py_None);
4526 PUSH(Py_None);
4527 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004528 _PyErr_Fetch(tstate, &exc, &val, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 /* Make the raw exception data
4530 available to the handler,
4531 so a program can emulate the
4532 Python main loop. */
Victor Stinner438a12d2019-05-24 17:01:38 +02004533 _PyErr_NormalizeException(tstate, &exc, &val, &tb);
Victor Stinner7eab0d02013-07-15 21:16:27 +02004534 if (tb != NULL)
4535 PyException_SetTraceback(val, tb);
4536 else
4537 PyException_SetTraceback(val, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 Py_INCREF(exc);
Mark Shannonae3087c2017-10-22 22:41:51 +01004539 exc_info->exc_type = exc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 Py_INCREF(val);
Mark Shannonae3087c2017-10-22 22:41:51 +01004541 exc_info->exc_value = val;
4542 exc_info->exc_traceback = tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 if (tb == NULL)
4544 tb = Py_None;
4545 Py_INCREF(tb);
4546 PUSH(tb);
4547 PUSH(val);
4548 PUSH(exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 JUMPTO(handler);
Victor Stinnerdab84232020-03-17 18:56:44 +01004550 if (_Py_TracingPossible(ceval2)) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00004551 trace_info.instr_prev = INT_MAX;
Mark Shannonfee55262019-11-21 09:11:43 +00004552 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004553 /* Resume normal execution */
Mark Shannoncb9879b2020-07-17 11:44:23 +01004554 f->f_state = FRAME_EXECUTING;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004555 goto main_loop;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 }
4557 } /* unwind stack */
Guido van Rossum374a9221991-04-04 10:40:29 +00004558
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004559 /* End the loop as we still have an error */
4560 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 } /* main loop */
Guido van Rossumac7be682001-01-17 15:42:30 +00004562
Pablo Galindof00828a2019-05-09 16:52:02 +01004563 assert(retval == NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02004564 assert(_PyErr_Occurred(tstate));
Pablo Galindof00828a2019-05-09 16:52:02 +01004565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 /* Pop remaining stack entries. */
4567 while (!EMPTY()) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004568 PyObject *o = POP();
4569 Py_XDECREF(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 }
Mark Shannoncb9879b2020-07-17 11:44:23 +01004571 f->f_stackdepth = 0;
4572 f->f_state = FRAME_RAISED;
Mark Shannone7c9f4a2020-01-13 12:51:26 +00004573exiting:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 if (tstate->use_tracing) {
Benjamin Peterson51f46162013-01-23 08:38:47 -05004575 if (tstate->c_tracefunc) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004576 if (call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004577 tstate, f, &trace_info, PyTrace_RETURN, retval)) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004578 Py_CLEAR(retval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 }
4580 }
4581 if (tstate->c_profilefunc) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004582 if (call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004583 tstate, f, &trace_info, PyTrace_RETURN, retval)) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004584 Py_CLEAR(retval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 }
4586 }
4587 }
Guido van Rossuma4240131997-01-21 21:18:36 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 /* pop frame */
Thomas Woutersce272b62007-09-19 21:19:28 +00004590exit_eval_frame:
Łukasz Langaa785c872016-09-09 17:37:37 -07004591 if (PyDTrace_FUNCTION_RETURN_ENABLED())
4592 dtrace_function_return(f);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01004593 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 tstate->frame = f->f_back;
Guido van Rossumac7be682001-01-17 15:42:30 +00004595
Victor Stinner0b72b232020-03-12 23:18:39 +01004596 return _Py_CheckFunctionResult(tstate, NULL, retval, __func__);
Guido van Rossum374a9221991-04-04 10:40:29 +00004597}
4598
Benjamin Petersonb204a422011-06-05 22:04:07 -05004599static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004600format_missing(PyThreadState *tstate, const char *kind,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004601 PyCodeObject *co, PyObject *names, PyObject *qualname)
Benjamin Petersone109c702011-06-24 09:37:26 -05004602{
4603 int err;
4604 Py_ssize_t len = PyList_GET_SIZE(names);
4605 PyObject *name_str, *comma, *tail, *tmp;
4606
4607 assert(PyList_CheckExact(names));
4608 assert(len >= 1);
4609 /* Deal with the joys of natural language. */
4610 switch (len) {
4611 case 1:
4612 name_str = PyList_GET_ITEM(names, 0);
4613 Py_INCREF(name_str);
4614 break;
4615 case 2:
4616 name_str = PyUnicode_FromFormat("%U and %U",
4617 PyList_GET_ITEM(names, len - 2),
4618 PyList_GET_ITEM(names, len - 1));
4619 break;
4620 default:
4621 tail = PyUnicode_FromFormat(", %U, and %U",
4622 PyList_GET_ITEM(names, len - 2),
4623 PyList_GET_ITEM(names, len - 1));
Benjamin Petersond1ab6082012-06-01 11:18:22 -07004624 if (tail == NULL)
4625 return;
Benjamin Petersone109c702011-06-24 09:37:26 -05004626 /* Chop off the last two objects in the list. This shouldn't actually
4627 fail, but we can't be too careful. */
4628 err = PyList_SetSlice(names, len - 2, len, NULL);
4629 if (err == -1) {
4630 Py_DECREF(tail);
4631 return;
4632 }
4633 /* Stitch everything up into a nice comma-separated list. */
4634 comma = PyUnicode_FromString(", ");
4635 if (comma == NULL) {
4636 Py_DECREF(tail);
4637 return;
4638 }
4639 tmp = PyUnicode_Join(comma, names);
4640 Py_DECREF(comma);
4641 if (tmp == NULL) {
4642 Py_DECREF(tail);
4643 return;
4644 }
4645 name_str = PyUnicode_Concat(tmp, tail);
4646 Py_DECREF(tmp);
4647 Py_DECREF(tail);
4648 break;
4649 }
4650 if (name_str == NULL)
4651 return;
Victor Stinner438a12d2019-05-24 17:01:38 +02004652 _PyErr_Format(tstate, PyExc_TypeError,
4653 "%U() missing %i required %s argument%s: %U",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004654 qualname,
Victor Stinner438a12d2019-05-24 17:01:38 +02004655 len,
4656 kind,
4657 len == 1 ? "" : "s",
4658 name_str);
Benjamin Petersone109c702011-06-24 09:37:26 -05004659 Py_DECREF(name_str);
4660}
4661
4662static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004663missing_arguments(PyThreadState *tstate, PyCodeObject *co,
4664 Py_ssize_t missing, Py_ssize_t defcount,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004665 PyObject **fastlocals, PyObject *qualname)
Benjamin Petersone109c702011-06-24 09:37:26 -05004666{
Victor Stinner74319ae2016-08-25 00:04:09 +02004667 Py_ssize_t i, j = 0;
4668 Py_ssize_t start, end;
4669 int positional = (defcount != -1);
Benjamin Petersone109c702011-06-24 09:37:26 -05004670 const char *kind = positional ? "positional" : "keyword-only";
4671 PyObject *missing_names;
4672
4673 /* Compute the names of the arguments that are missing. */
4674 missing_names = PyList_New(missing);
4675 if (missing_names == NULL)
4676 return;
4677 if (positional) {
4678 start = 0;
Pablo Galindocd74e662019-06-01 18:08:04 +01004679 end = co->co_argcount - defcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05004680 }
4681 else {
Pablo Galindocd74e662019-06-01 18:08:04 +01004682 start = co->co_argcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05004683 end = start + co->co_kwonlyargcount;
4684 }
4685 for (i = start; i < end; i++) {
4686 if (GETLOCAL(i) == NULL) {
4687 PyObject *raw = PyTuple_GET_ITEM(co->co_varnames, i);
4688 PyObject *name = PyObject_Repr(raw);
4689 if (name == NULL) {
4690 Py_DECREF(missing_names);
4691 return;
4692 }
4693 PyList_SET_ITEM(missing_names, j++, name);
4694 }
4695 }
4696 assert(j == missing);
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004697 format_missing(tstate, kind, co, missing_names, qualname);
Benjamin Petersone109c702011-06-24 09:37:26 -05004698 Py_DECREF(missing_names);
4699}
4700
4701static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004702too_many_positional(PyThreadState *tstate, PyCodeObject *co,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004703 Py_ssize_t given, PyObject *defaults,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004704 PyObject **fastlocals, PyObject *qualname)
Benjamin Petersonb204a422011-06-05 22:04:07 -05004705{
4706 int plural;
Victor Stinner74319ae2016-08-25 00:04:09 +02004707 Py_ssize_t kwonly_given = 0;
4708 Py_ssize_t i;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004709 PyObject *sig, *kwonly_sig;
Victor Stinner74319ae2016-08-25 00:04:09 +02004710 Py_ssize_t co_argcount = co->co_argcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004711
Benjamin Petersone109c702011-06-24 09:37:26 -05004712 assert((co->co_flags & CO_VARARGS) == 0);
4713 /* Count missing keyword-only args. */
Pablo Galindocd74e662019-06-01 18:08:04 +01004714 for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
Victor Stinner74319ae2016-08-25 00:04:09 +02004715 if (GETLOCAL(i) != NULL) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004716 kwonly_given++;
Victor Stinner74319ae2016-08-25 00:04:09 +02004717 }
4718 }
Mark Shannond6c33fb2021-01-29 13:24:55 +00004719 Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
Benjamin Petersone109c702011-06-24 09:37:26 -05004720 if (defcount) {
Pablo Galindocd74e662019-06-01 18:08:04 +01004721 Py_ssize_t atleast = co_argcount - defcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004722 plural = 1;
Pablo Galindocd74e662019-06-01 18:08:04 +01004723 sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004724 }
4725 else {
Pablo Galindocd74e662019-06-01 18:08:04 +01004726 plural = (co_argcount != 1);
4727 sig = PyUnicode_FromFormat("%zd", co_argcount);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004728 }
4729 if (sig == NULL)
4730 return;
4731 if (kwonly_given) {
Victor Stinner74319ae2016-08-25 00:04:09 +02004732 const char *format = " positional argument%s (and %zd keyword-only argument%s)";
4733 kwonly_sig = PyUnicode_FromFormat(format,
4734 given != 1 ? "s" : "",
4735 kwonly_given,
4736 kwonly_given != 1 ? "s" : "");
Benjamin Petersonb204a422011-06-05 22:04:07 -05004737 if (kwonly_sig == NULL) {
4738 Py_DECREF(sig);
4739 return;
4740 }
4741 }
4742 else {
4743 /* This will not fail. */
4744 kwonly_sig = PyUnicode_FromString("");
Benjamin Petersone109c702011-06-24 09:37:26 -05004745 assert(kwonly_sig != NULL);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004746 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004747 _PyErr_Format(tstate, PyExc_TypeError,
4748 "%U() takes %U positional argument%s but %zd%U %s given",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004749 qualname,
Victor Stinner438a12d2019-05-24 17:01:38 +02004750 sig,
4751 plural ? "s" : "",
4752 given,
4753 kwonly_sig,
4754 given == 1 && !kwonly_given ? "was" : "were");
Benjamin Petersonb204a422011-06-05 22:04:07 -05004755 Py_DECREF(sig);
4756 Py_DECREF(kwonly_sig);
4757}
4758
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004759static int
Victor Stinner438a12d2019-05-24 17:01:38 +02004760positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
Mark Shannon0332e562021-02-01 10:42:03 +00004761 Py_ssize_t kwcount, PyObject* kwnames,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004762 PyObject *qualname)
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004763{
4764 int posonly_conflicts = 0;
4765 PyObject* posonly_names = PyList_New(0);
4766
4767 for(int k=0; k < co->co_posonlyargcount; k++){
4768 PyObject* posonly_name = PyTuple_GET_ITEM(co->co_varnames, k);
4769
4770 for (int k2=0; k2<kwcount; k2++){
4771 /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
Mark Shannon0332e562021-02-01 10:42:03 +00004772 PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004773 if (kwname == posonly_name){
4774 if(PyList_Append(posonly_names, kwname) != 0) {
4775 goto fail;
4776 }
4777 posonly_conflicts++;
4778 continue;
4779 }
4780
4781 int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
4782
4783 if ( cmp > 0) {
4784 if(PyList_Append(posonly_names, kwname) != 0) {
4785 goto fail;
4786 }
4787 posonly_conflicts++;
4788 } else if (cmp < 0) {
4789 goto fail;
4790 }
4791
4792 }
4793 }
4794 if (posonly_conflicts) {
4795 PyObject* comma = PyUnicode_FromString(", ");
4796 if (comma == NULL) {
4797 goto fail;
4798 }
4799 PyObject* error_names = PyUnicode_Join(comma, posonly_names);
4800 Py_DECREF(comma);
4801 if (error_names == NULL) {
4802 goto fail;
4803 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004804 _PyErr_Format(tstate, PyExc_TypeError,
4805 "%U() got some positional-only arguments passed"
4806 " as keyword arguments: '%U'",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004807 qualname, error_names);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004808 Py_DECREF(error_names);
4809 goto fail;
4810 }
4811
4812 Py_DECREF(posonly_names);
4813 return 0;
4814
4815fail:
4816 Py_XDECREF(posonly_names);
4817 return 1;
4818
4819}
4820
Skip Montanaro786ea6b2004-03-01 15:44:05 +00004821
Mark Shannon0332e562021-02-01 10:42:03 +00004822PyFrameObject *
4823_PyEval_MakeFrameVector(PyThreadState *tstate,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004824 PyFrameConstructor *con, PyObject *locals,
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02004825 PyObject *const *args, Py_ssize_t argcount,
Mark Shannon0332e562021-02-01 10:42:03 +00004826 PyObject *kwnames)
Tim Peters5ca576e2001-06-18 22:08:13 +00004827{
Victor Stinnerda2914d2020-03-20 09:29:08 +01004828 assert(is_tstate_valid(tstate));
Victor Stinnerb5e170f2019-11-16 01:03:22 +01004829
Mark Shannond6c33fb2021-01-29 13:24:55 +00004830 PyCodeObject *co = (PyCodeObject*)con->fc_code;
4831 assert(con->fc_defaults == NULL || PyTuple_CheckExact(con->fc_defaults));
Pablo Galindocd74e662019-06-01 18:08:04 +01004832 const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
Tim Peters5ca576e2001-06-18 22:08:13 +00004833
Victor Stinnerc7020012016-08-16 23:40:29 +02004834 /* Create the frame */
Mark Shannon0332e562021-02-01 10:42:03 +00004835 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, con, locals);
Victor Stinnerc7020012016-08-16 23:40:29 +02004836 if (f == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 return NULL;
Victor Stinnerc7020012016-08-16 23:40:29 +02004838 }
Victor Stinner232dda62020-06-04 15:19:02 +02004839 PyObject **fastlocals = f->f_localsplus;
4840 PyObject **freevars = f->f_localsplus + co->co_nlocals;
Tim Peters5ca576e2001-06-18 22:08:13 +00004841
Victor Stinnerc7020012016-08-16 23:40:29 +02004842 /* Create a dictionary for keyword parameters (**kwags) */
Victor Stinner232dda62020-06-04 15:19:02 +02004843 PyObject *kwdict;
4844 Py_ssize_t i;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004845 if (co->co_flags & CO_VARKEYWORDS) {
4846 kwdict = PyDict_New();
4847 if (kwdict == NULL)
4848 goto fail;
4849 i = total_args;
Victor Stinnerc7020012016-08-16 23:40:29 +02004850 if (co->co_flags & CO_VARARGS) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004851 i++;
Victor Stinnerc7020012016-08-16 23:40:29 +02004852 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004853 SETLOCAL(i, kwdict);
4854 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004855 else {
4856 kwdict = NULL;
4857 }
4858
Pablo Galindocd74e662019-06-01 18:08:04 +01004859 /* Copy all positional arguments into local variables */
Victor Stinner232dda62020-06-04 15:19:02 +02004860 Py_ssize_t j, n;
Pablo Galindocd74e662019-06-01 18:08:04 +01004861 if (argcount > co->co_argcount) {
4862 n = co->co_argcount;
Victor Stinnerc7020012016-08-16 23:40:29 +02004863 }
4864 else {
4865 n = argcount;
4866 }
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004867 for (j = 0; j < n; j++) {
Victor Stinner232dda62020-06-04 15:19:02 +02004868 PyObject *x = args[j];
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004869 Py_INCREF(x);
4870 SETLOCAL(j, x);
4871 }
4872
Victor Stinnerc7020012016-08-16 23:40:29 +02004873 /* Pack other positional arguments into the *args argument */
Benjamin Petersonb204a422011-06-05 22:04:07 -05004874 if (co->co_flags & CO_VARARGS) {
Victor Stinner232dda62020-06-04 15:19:02 +02004875 PyObject *u = _PyTuple_FromArray(args + n, argcount - n);
Victor Stinnerc7020012016-08-16 23:40:29 +02004876 if (u == NULL) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004877 goto fail;
Victor Stinnerc7020012016-08-16 23:40:29 +02004878 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004879 SETLOCAL(total_args, u);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004880 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004881
Mark Shannon0332e562021-02-01 10:42:03 +00004882 /* Handle keyword arguments */
4883 if (kwnames != NULL) {
4884 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
4885 for (i = 0; i < kwcount; i++) {
4886 PyObject **co_varnames;
4887 PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
4888 PyObject *value = args[i+argcount];
4889 Py_ssize_t j;
Victor Stinnerc7020012016-08-16 23:40:29 +02004890
Mark Shannon0332e562021-02-01 10:42:03 +00004891 if (keyword == NULL || !PyUnicode_Check(keyword)) {
4892 _PyErr_Format(tstate, PyExc_TypeError,
4893 "%U() keywords must be strings",
Mark Shannond6c33fb2021-01-29 13:24:55 +00004894 con->fc_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 goto fail;
Victor Stinner6fea7f72016-08-22 23:17:30 +02004896 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004897
Mark Shannon0332e562021-02-01 10:42:03 +00004898 /* Speed hack: do raw pointer compares. As names are
4899 normally interned this should almost always hit. */
4900 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
4901 for (j = co->co_posonlyargcount; j < total_args; j++) {
4902 PyObject *varname = co_varnames[j];
4903 if (varname == keyword) {
4904 goto kw_found;
4905 }
4906 }
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004907
Mark Shannon0332e562021-02-01 10:42:03 +00004908 /* Slow fallback, just in case */
4909 for (j = co->co_posonlyargcount; j < total_args; j++) {
4910 PyObject *varname = co_varnames[j];
4911 int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
4912 if (cmp > 0) {
4913 goto kw_found;
4914 }
4915 else if (cmp < 0) {
4916 goto fail;
4917 }
4918 }
4919
4920 assert(j >= total_args);
4921 if (kwdict == NULL) {
4922
4923 if (co->co_posonlyargcount
4924 && positional_only_passed_as_keyword(tstate, co,
4925 kwcount, kwnames,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004926 con->fc_qualname))
Mark Shannon0332e562021-02-01 10:42:03 +00004927 {
4928 goto fail;
4929 }
4930
4931 _PyErr_Format(tstate, PyExc_TypeError,
4932 "%U() got an unexpected keyword argument '%S'",
4933 con->fc_qualname, keyword);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004934 goto fail;
4935 }
4936
Mark Shannon0332e562021-02-01 10:42:03 +00004937 if (PyDict_SetItem(kwdict, keyword, value) == -1) {
4938 goto fail;
4939 }
4940 continue;
Victor Stinnerc7020012016-08-16 23:40:29 +02004941
Mark Shannon0332e562021-02-01 10:42:03 +00004942 kw_found:
4943 if (GETLOCAL(j) != NULL) {
4944 _PyErr_Format(tstate, PyExc_TypeError,
4945 "%U() got multiple values for argument '%S'",
Mark Shannond6c33fb2021-01-29 13:24:55 +00004946 con->fc_qualname, keyword);
Mark Shannon0332e562021-02-01 10:42:03 +00004947 goto fail;
4948 }
4949 Py_INCREF(value);
4950 SETLOCAL(j, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004953
4954 /* Check the number of positional arguments */
Pablo Galindocd74e662019-06-01 18:08:04 +01004955 if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00004956 too_many_positional(tstate, co, argcount, con->fc_defaults, fastlocals,
4957 con->fc_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 goto fail;
4959 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004960
4961 /* Add missing positional arguments (copy default values from defs) */
Pablo Galindocd74e662019-06-01 18:08:04 +01004962 if (argcount < co->co_argcount) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00004963 Py_ssize_t defcount = con->fc_defaults == NULL ? 0 : PyTuple_GET_SIZE(con->fc_defaults);
Pablo Galindocd74e662019-06-01 18:08:04 +01004964 Py_ssize_t m = co->co_argcount - defcount;
Victor Stinner17061a92016-08-16 23:39:42 +02004965 Py_ssize_t missing = 0;
4966 for (i = argcount; i < m; i++) {
4967 if (GETLOCAL(i) == NULL) {
Benjamin Petersone109c702011-06-24 09:37:26 -05004968 missing++;
Victor Stinner17061a92016-08-16 23:39:42 +02004969 }
4970 }
Benjamin Petersone109c702011-06-24 09:37:26 -05004971 if (missing) {
Victor Stinner232dda62020-06-04 15:19:02 +02004972 missing_arguments(tstate, co, missing, defcount, fastlocals,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004973 con->fc_qualname);
Benjamin Petersone109c702011-06-24 09:37:26 -05004974 goto fail;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004975 }
4976 if (n > m)
4977 i = n - m;
4978 else
4979 i = 0;
Mark Shannond6c33fb2021-01-29 13:24:55 +00004980 if (defcount) {
4981 PyObject **defs = &PyTuple_GET_ITEM(con->fc_defaults, 0);
4982 for (; i < defcount; i++) {
4983 if (GETLOCAL(m+i) == NULL) {
4984 PyObject *def = defs[i];
4985 Py_INCREF(def);
4986 SETLOCAL(m+i, def);
4987 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004988 }
4989 }
4990 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004991
4992 /* Add missing keyword arguments (copy default values from kwdefs) */
Benjamin Petersonb204a422011-06-05 22:04:07 -05004993 if (co->co_kwonlyargcount > 0) {
Victor Stinner17061a92016-08-16 23:39:42 +02004994 Py_ssize_t missing = 0;
Pablo Galindocd74e662019-06-01 18:08:04 +01004995 for (i = co->co_argcount; i < total_args; i++) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004996 if (GETLOCAL(i) != NULL)
4997 continue;
Victor Stinner232dda62020-06-04 15:19:02 +02004998 PyObject *varname = PyTuple_GET_ITEM(co->co_varnames, i);
Mark Shannond6c33fb2021-01-29 13:24:55 +00004999 if (con->fc_kwdefaults != NULL) {
5000 PyObject *def = PyDict_GetItemWithError(con->fc_kwdefaults, varname);
Benjamin Petersonb204a422011-06-05 22:04:07 -05005001 if (def) {
5002 Py_INCREF(def);
5003 SETLOCAL(i, def);
5004 continue;
5005 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005006 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02005007 goto fail;
5008 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05005009 }
Benjamin Petersone109c702011-06-24 09:37:26 -05005010 missing++;
5011 }
5012 if (missing) {
Victor Stinner232dda62020-06-04 15:19:02 +02005013 missing_arguments(tstate, co, missing, -1, fastlocals,
Mark Shannond6c33fb2021-01-29 13:24:55 +00005014 con->fc_qualname);
Benjamin Petersonb204a422011-06-05 22:04:07 -05005015 goto fail;
5016 }
5017 }
5018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 /* Allocate and initialize storage for cell vars, and copy free
Benjamin Peterson90037602011-06-25 22:54:45 -05005020 vars into frame. */
5021 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 PyObject *c;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +02005023 Py_ssize_t arg;
Benjamin Peterson90037602011-06-25 22:54:45 -05005024 /* Possibly account for the cell variable being an argument. */
5025 if (co->co_cell2arg != NULL &&
Guido van Rossum6832c812013-05-10 08:47:42 -07005026 (arg = co->co_cell2arg[i]) != CO_CELL_NOT_AN_ARG) {
Benjamin Peterson90037602011-06-25 22:54:45 -05005027 c = PyCell_New(GETLOCAL(arg));
Benjamin Peterson159ae412013-05-12 18:16:06 -05005028 /* Clear the local copy. */
5029 SETLOCAL(arg, NULL);
Guido van Rossum6832c812013-05-10 08:47:42 -07005030 }
5031 else {
Benjamin Peterson90037602011-06-25 22:54:45 -05005032 c = PyCell_New(NULL);
Guido van Rossum6832c812013-05-10 08:47:42 -07005033 }
Benjamin Peterson159ae412013-05-12 18:16:06 -05005034 if (c == NULL)
5035 goto fail;
Benjamin Peterson90037602011-06-25 22:54:45 -05005036 SETLOCAL(co->co_nlocals + i, c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 }
Victor Stinnerc7020012016-08-16 23:40:29 +02005038
5039 /* Copy closure variables to free variables */
Benjamin Peterson90037602011-06-25 22:54:45 -05005040 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00005041 PyObject *o = PyTuple_GET_ITEM(con->fc_closure, i);
Benjamin Peterson90037602011-06-25 22:54:45 -05005042 Py_INCREF(o);
5043 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 }
Tim Peters5ca576e2001-06-18 22:08:13 +00005045
Mark Shannon0332e562021-02-01 10:42:03 +00005046 return f;
Tim Peters5ca576e2001-06-18 22:08:13 +00005047
Thomas Woutersce272b62007-09-19 21:19:28 +00005048fail: /* Jump here from prelude on failure */
Tim Peters5ca576e2001-06-18 22:08:13 +00005049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 /* decref'ing the frame can cause __del__ methods to get invoked,
5051 which can call back into Python. While we're done with the
5052 current Python frame (f), the associated C stack is still in use,
5053 so recursion_depth must be boosted for the duration.
5054 */
INADA Naoki5a625d02016-12-24 20:19:08 +09005055 if (Py_REFCNT(f) > 1) {
5056 Py_DECREF(f);
5057 _PyObject_GC_TRACK(f);
5058 }
5059 else {
5060 ++tstate->recursion_depth;
5061 Py_DECREF(f);
5062 --tstate->recursion_depth;
5063 }
Mark Shannon0332e562021-02-01 10:42:03 +00005064 return NULL;
5065}
5066
5067static PyObject *
5068make_coro(PyFrameConstructor *con, PyFrameObject *f)
5069{
5070 assert (((PyCodeObject *)con->fc_code)->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR));
5071 PyObject *gen;
5072 int is_coro = ((PyCodeObject *)con->fc_code)->co_flags & CO_COROUTINE;
5073
5074 /* Don't need to keep the reference to f_back, it will be set
5075 * when the generator is resumed. */
5076 Py_CLEAR(f->f_back);
5077
5078 /* Create a new generator that owns the ready to run frame
5079 * and return that as the value. */
5080 if (is_coro) {
5081 gen = PyCoro_New(f, con->fc_name, con->fc_qualname);
5082 } else if (((PyCodeObject *)con->fc_code)->co_flags & CO_ASYNC_GENERATOR) {
5083 gen = PyAsyncGen_New(f, con->fc_name, con->fc_qualname);
5084 } else {
5085 gen = PyGen_NewWithQualName(f, con->fc_name, con->fc_qualname);
5086 }
5087 if (gen == NULL) {
5088 return NULL;
5089 }
5090
5091 _PyObject_GC_TRACK(f);
5092
5093 return gen;
5094}
5095
5096PyObject *
5097_PyEval_Vector(PyThreadState *tstate, PyFrameConstructor *con,
5098 PyObject *locals,
5099 PyObject* const* args, size_t argcount,
5100 PyObject *kwnames)
5101{
5102 PyFrameObject *f = _PyEval_MakeFrameVector(
5103 tstate, con, locals, args, argcount, kwnames);
5104 if (f == NULL) {
5105 return NULL;
5106 }
5107 if (((PyCodeObject *)con->fc_code)->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
5108 return make_coro(con, f);
5109 }
5110 PyObject *retval = _PyEval_EvalFrame(tstate, f, 0);
5111
5112 /* decref'ing the frame can cause __del__ methods to get invoked,
5113 which can call back into Python. While we're done with the
5114 current Python frame (f), the associated C stack is still in use,
5115 so recursion_depth must be boosted for the duration.
5116 */
5117 if (Py_REFCNT(f) > 1) {
5118 Py_DECREF(f);
5119 _PyObject_GC_TRACK(f);
5120 }
5121 else {
5122 ++tstate->recursion_depth;
5123 Py_DECREF(f);
5124 --tstate->recursion_depth;
5125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 return retval;
Tim Peters5ca576e2001-06-18 22:08:13 +00005127}
5128
Mark Shannond6c33fb2021-01-29 13:24:55 +00005129/* Legacy API */
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005130PyObject *
Mark Shannon0332e562021-02-01 10:42:03 +00005131PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
5132 PyObject *const *args, int argcount,
5133 PyObject *const *kws, int kwcount,
5134 PyObject *const *defs, int defcount,
5135 PyObject *kwdefs, PyObject *closure)
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005136{
Victor Stinner46496f92021-02-20 15:17:18 +01005137 PyThreadState *tstate = _PyThreadState_GET();
Mark Shannon0332e562021-02-01 10:42:03 +00005138 PyObject *res;
Mark Shannond6c33fb2021-01-29 13:24:55 +00005139 PyObject *defaults = _PyTuple_FromArray(defs, defcount);
5140 if (defaults == NULL) {
5141 return NULL;
5142 }
Victor Stinner46496f92021-02-20 15:17:18 +01005143 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals);
Mark Shannond6c33fb2021-01-29 13:24:55 +00005144 if (builtins == NULL) {
5145 Py_DECREF(defaults);
5146 return NULL;
5147 }
Dong-hee Na3cf08332021-02-14 15:54:39 +09005148 assert ((((PyCodeObject *)_co)->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == 0);
Mark Shannon0332e562021-02-01 10:42:03 +00005149 if (locals == NULL) {
5150 locals = globals;
5151 }
5152 PyObject *kwnames;
5153 PyObject *const *allargs;
5154 PyObject **newargs;
5155 if (kwcount == 0) {
5156 allargs = args;
5157 kwnames = NULL;
5158 }
5159 else {
5160 kwnames = PyTuple_New(kwcount);
5161 if (kwnames == NULL) {
5162 res = NULL;
5163 goto fail;
5164 }
5165 newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
5166 if (newargs == NULL) {
5167 res = NULL;
5168 Py_DECREF(kwnames);
5169 goto fail;
5170 }
5171 for (int i = 0; i < argcount; i++) {
5172 newargs[i] = args[i];
5173 }
5174 for (int i = 0; i < kwcount; i++) {
5175 Py_INCREF(kws[2*i]);
5176 PyTuple_SET_ITEM(kwnames, i, kws[2*i]);
5177 newargs[argcount+i] = kws[2*i+1];
5178 }
5179 allargs = newargs;
5180 }
5181 PyObject **kwargs = PyMem_Malloc(sizeof(PyObject *)*kwcount);
5182 if (kwargs == NULL) {
5183 res = NULL;
5184 Py_DECREF(kwnames);
5185 goto fail;
5186 }
5187 for (int i = 0; i < kwcount; i++) {
5188 Py_INCREF(kws[2*i]);
5189 PyTuple_SET_ITEM(kwnames, i, kws[2*i]);
5190 kwargs[i] = kws[2*i+1];
5191 }
Mark Shannond6c33fb2021-01-29 13:24:55 +00005192 PyFrameConstructor constr = {
5193 .fc_globals = globals,
5194 .fc_builtins = builtins,
Mark Shannon0332e562021-02-01 10:42:03 +00005195 .fc_name = ((PyCodeObject *)_co)->co_name,
5196 .fc_qualname = ((PyCodeObject *)_co)->co_name,
Mark Shannond6c33fb2021-01-29 13:24:55 +00005197 .fc_code = _co,
5198 .fc_defaults = defaults,
5199 .fc_kwdefaults = kwdefs,
5200 .fc_closure = closure
5201 };
Mark Shannon0332e562021-02-01 10:42:03 +00005202 res = _PyEval_Vector(tstate, &constr, locals,
Victor Stinner44085a32021-02-18 19:20:16 +01005203 allargs, argcount,
5204 kwnames);
Mark Shannon0332e562021-02-01 10:42:03 +00005205 if (kwcount) {
5206 Py_DECREF(kwnames);
5207 PyMem_Free(newargs);
5208 }
5209fail:
Mark Shannond6c33fb2021-01-29 13:24:55 +00005210 Py_DECREF(defaults);
5211 Py_DECREF(builtins);
5212 return res;
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005213}
5214
Tim Peters5ca576e2001-06-18 22:08:13 +00005215
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005216static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02005217special_lookup(PyThreadState *tstate, PyObject *o, _Py_Identifier *id)
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005220 res = _PyObject_LookupSpecial(o, id);
Victor Stinner438a12d2019-05-24 17:01:38 +02005221 if (res == NULL && !_PyErr_Occurred(tstate)) {
Victor Stinner4804b5b2020-05-12 01:43:38 +02005222 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(id));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 return NULL;
5224 }
5225 return res;
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005226}
5227
5228
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005229/* Logic for the raise statement (too complicated for inlining).
5230 This *consumes* a reference count to each of its arguments. */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005231static int
Victor Stinner09532fe2019-05-10 23:39:09 +02005232do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005234 PyObject *type = NULL, *value = NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00005235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 if (exc == NULL) {
5237 /* Reraise */
Mark Shannonae3087c2017-10-22 22:41:51 +01005238 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 PyObject *tb;
Mark Shannonae3087c2017-10-22 22:41:51 +01005240 type = exc_info->exc_type;
5241 value = exc_info->exc_value;
5242 tb = exc_info->exc_traceback;
Victor Stinnereec93312016-08-18 18:13:10 +02005243 if (type == Py_None || type == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005244 _PyErr_SetString(tstate, PyExc_RuntimeError,
5245 "No active exception to reraise");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005246 return 0;
5247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 Py_XINCREF(type);
5249 Py_XINCREF(value);
5250 Py_XINCREF(tb);
Victor Stinner438a12d2019-05-24 17:01:38 +02005251 _PyErr_Restore(tstate, type, value, tb);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005252 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 }
Guido van Rossumac7be682001-01-17 15:42:30 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 /* We support the following forms of raise:
5256 raise
Collin Winter828f04a2007-08-31 00:04:24 +00005257 raise <instance>
5258 raise <type> */
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 if (PyExceptionClass_Check(exc)) {
5261 type = exc;
Victor Stinnera5ed5f02016-12-06 18:45:50 +01005262 value = _PyObject_CallNoArg(exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 if (value == NULL)
5264 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05005265 if (!PyExceptionInstance_Check(value)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005266 _PyErr_Format(tstate, PyExc_TypeError,
5267 "calling %R should have returned an instance of "
5268 "BaseException, not %R",
5269 type, Py_TYPE(value));
5270 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05005271 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 }
5273 else if (PyExceptionInstance_Check(exc)) {
5274 value = exc;
5275 type = PyExceptionInstance_Class(exc);
5276 Py_INCREF(type);
5277 }
5278 else {
5279 /* Not something you can raise. You get an exception
5280 anyway, just not what you specified :-) */
5281 Py_DECREF(exc);
Victor Stinner438a12d2019-05-24 17:01:38 +02005282 _PyErr_SetString(tstate, PyExc_TypeError,
5283 "exceptions must derive from BaseException");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 goto raise_error;
5285 }
Collin Winter828f04a2007-08-31 00:04:24 +00005286
Serhiy Storchakac0191582016-09-27 11:37:10 +03005287 assert(type != NULL);
5288 assert(value != NULL);
5289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 if (cause) {
5291 PyObject *fixed_cause;
5292 if (PyExceptionClass_Check(cause)) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01005293 fixed_cause = _PyObject_CallNoArg(cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 if (fixed_cause == NULL)
5295 goto raise_error;
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005296 Py_DECREF(cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005298 else if (PyExceptionInstance_Check(cause)) {
5299 fixed_cause = cause;
5300 }
5301 else if (cause == Py_None) {
5302 Py_DECREF(cause);
5303 fixed_cause = NULL;
5304 }
5305 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005306 _PyErr_SetString(tstate, PyExc_TypeError,
5307 "exception causes must derive from "
5308 "BaseException");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 goto raise_error;
5310 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005311 PyException_SetCause(value, fixed_cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 }
Collin Winter828f04a2007-08-31 00:04:24 +00005313
Victor Stinner438a12d2019-05-24 17:01:38 +02005314 _PyErr_SetObject(tstate, type, value);
Victor Stinner61f4db82020-01-28 03:37:45 +01005315 /* _PyErr_SetObject incref's its arguments */
Serhiy Storchakac0191582016-09-27 11:37:10 +03005316 Py_DECREF(value);
5317 Py_DECREF(type);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005318 return 0;
Collin Winter828f04a2007-08-31 00:04:24 +00005319
5320raise_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 Py_XDECREF(value);
5322 Py_XDECREF(type);
5323 Py_XDECREF(cause);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005324 return 0;
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005325}
5326
Tim Petersd6d010b2001-06-21 02:49:55 +00005327/* Iterate v argcnt times and store the results on the stack (via decreasing
Guido van Rossum0368b722007-05-11 16:50:42 +00005328 sp). Return 1 for success, 0 if error.
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00005329
Guido van Rossum0368b722007-05-11 16:50:42 +00005330 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
5331 with a variable target.
5332*/
Tim Petersd6d010b2001-06-21 02:49:55 +00005333
Barry Warsawe42b18f1997-08-25 22:13:04 +00005334static int
Victor Stinner438a12d2019-05-24 17:01:38 +02005335unpack_iterable(PyThreadState *tstate, PyObject *v,
5336 int argcnt, int argcntafter, PyObject **sp)
Barry Warsawe42b18f1997-08-25 22:13:04 +00005337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 int i = 0, j = 0;
5339 Py_ssize_t ll = 0;
5340 PyObject *it; /* iter(v) */
5341 PyObject *w;
5342 PyObject *l = NULL; /* variable list */
Guido van Rossumac7be682001-01-17 15:42:30 +00005343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 assert(v != NULL);
Tim Petersd6d010b2001-06-21 02:49:55 +00005345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 it = PyObject_GetIter(v);
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005347 if (it == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005348 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
Victor Stinnera102ed72020-02-07 02:24:48 +01005349 Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005350 {
Victor Stinner438a12d2019-05-24 17:01:38 +02005351 _PyErr_Format(tstate, PyExc_TypeError,
5352 "cannot unpack non-iterable %.200s object",
Victor Stinnera102ed72020-02-07 02:24:48 +01005353 Py_TYPE(v)->tp_name);
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005354 }
5355 return 0;
5356 }
Tim Petersd6d010b2001-06-21 02:49:55 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 for (; i < argcnt; i++) {
5359 w = PyIter_Next(it);
5360 if (w == NULL) {
5361 /* Iterator done, via error or exhaustion. */
Victor Stinner438a12d2019-05-24 17:01:38 +02005362 if (!_PyErr_Occurred(tstate)) {
R David Murray4171bbe2015-04-15 17:08:45 -04005363 if (argcntafter == -1) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005364 _PyErr_Format(tstate, PyExc_ValueError,
5365 "not enough values to unpack "
5366 "(expected %d, got %d)",
5367 argcnt, i);
R David Murray4171bbe2015-04-15 17:08:45 -04005368 }
5369 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005370 _PyErr_Format(tstate, PyExc_ValueError,
5371 "not enough values to unpack "
5372 "(expected at least %d, got %d)",
5373 argcnt + argcntafter, i);
R David Murray4171bbe2015-04-15 17:08:45 -04005374 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 }
5376 goto Error;
5377 }
5378 *--sp = w;
5379 }
Tim Petersd6d010b2001-06-21 02:49:55 +00005380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 if (argcntafter == -1) {
5382 /* We better have exhausted the iterator now. */
5383 w = PyIter_Next(it);
5384 if (w == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005385 if (_PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 goto Error;
5387 Py_DECREF(it);
5388 return 1;
5389 }
5390 Py_DECREF(w);
Victor Stinner438a12d2019-05-24 17:01:38 +02005391 _PyErr_Format(tstate, PyExc_ValueError,
5392 "too many values to unpack (expected %d)",
5393 argcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 goto Error;
5395 }
Guido van Rossum0368b722007-05-11 16:50:42 +00005396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 l = PySequence_List(it);
5398 if (l == NULL)
5399 goto Error;
5400 *--sp = l;
5401 i++;
Guido van Rossum0368b722007-05-11 16:50:42 +00005402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 ll = PyList_GET_SIZE(l);
5404 if (ll < argcntafter) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005405 _PyErr_Format(tstate, PyExc_ValueError,
R David Murray4171bbe2015-04-15 17:08:45 -04005406 "not enough values to unpack (expected at least %d, got %zd)",
5407 argcnt + argcntafter, argcnt + ll);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 goto Error;
5409 }
Guido van Rossum0368b722007-05-11 16:50:42 +00005410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 /* Pop the "after-variable" args off the list. */
5412 for (j = argcntafter; j > 0; j--, i++) {
5413 *--sp = PyList_GET_ITEM(l, ll - j);
5414 }
5415 /* Resize the list. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005416 Py_SET_SIZE(l, ll - argcntafter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 Py_DECREF(it);
5418 return 1;
Guido van Rossum0368b722007-05-11 16:50:42 +00005419
Tim Petersd6d010b2001-06-21 02:49:55 +00005420Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 for (; i > 0; i--, sp++)
5422 Py_DECREF(*sp);
5423 Py_XDECREF(it);
5424 return 0;
Barry Warsawe42b18f1997-08-25 22:13:04 +00005425}
5426
5427
Guido van Rossum96a42c81992-01-12 02:29:51 +00005428#ifdef LLTRACE
Guido van Rossum3f5da241990-12-20 15:06:42 +00005429static int
Victor Stinner438a12d2019-05-24 17:01:38 +02005430prtrace(PyThreadState *tstate, PyObject *v, const char *str)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 printf("%s ", str);
Victor Stinner438a12d2019-05-24 17:01:38 +02005433 if (PyObject_Print(v, stdout, 0) != 0) {
5434 /* Don't know what else to do */
5435 _PyErr_Clear(tstate);
5436 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 printf("\n");
5438 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005439}
Guido van Rossum3f5da241990-12-20 15:06:42 +00005440#endif
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005441
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005442static void
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005443call_exc_trace(Py_tracefunc func, PyObject *self,
Mark Shannon86433452021-01-07 16:49:02 +00005444 PyThreadState *tstate,
5445 PyFrameObject *f,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005446 PyTraceInfo *trace_info)
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005447{
Victor Stinneraaa8ed82013-07-10 13:57:55 +02005448 PyObject *type, *value, *traceback, *orig_traceback, *arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 int err;
Victor Stinner438a12d2019-05-24 17:01:38 +02005450 _PyErr_Fetch(tstate, &type, &value, &orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 if (value == NULL) {
5452 value = Py_None;
5453 Py_INCREF(value);
5454 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005455 _PyErr_NormalizeException(tstate, &type, &value, &orig_traceback);
Antoine Pitrou89335212013-11-23 14:05:23 +01005456 traceback = (orig_traceback != NULL) ? orig_traceback : Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 arg = PyTuple_Pack(3, type, value, traceback);
5458 if (arg == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005459 _PyErr_Restore(tstate, type, value, orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 return;
5461 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00005462 err = call_trace(func, self, tstate, f, trace_info, PyTrace_EXCEPTION, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 Py_DECREF(arg);
Victor Stinner438a12d2019-05-24 17:01:38 +02005464 if (err == 0) {
5465 _PyErr_Restore(tstate, type, value, orig_traceback);
5466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 else {
5468 Py_XDECREF(type);
5469 Py_XDECREF(value);
Victor Stinneraaa8ed82013-07-10 13:57:55 +02005470 Py_XDECREF(orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 }
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005472}
5473
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +00005474static int
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005475call_trace_protected(Py_tracefunc func, PyObject *obj,
5476 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005477 PyTraceInfo *trace_info,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 int what, PyObject *arg)
Fred Drake4ec5d562001-10-04 19:26:43 +00005479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 PyObject *type, *value, *traceback;
5481 int err;
Victor Stinner438a12d2019-05-24 17:01:38 +02005482 _PyErr_Fetch(tstate, &type, &value, &traceback);
Mark Shannon8e1b4062021-03-05 14:45:50 +00005483 err = call_trace(func, obj, tstate, frame, trace_info, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 if (err == 0)
5485 {
Victor Stinner438a12d2019-05-24 17:01:38 +02005486 _PyErr_Restore(tstate, type, value, traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 return 0;
5488 }
5489 else {
5490 Py_XDECREF(type);
5491 Py_XDECREF(value);
5492 Py_XDECREF(traceback);
5493 return -1;
5494 }
Fred Drake4ec5d562001-10-04 19:26:43 +00005495}
5496
Mark Shannon8e1b4062021-03-05 14:45:50 +00005497static void
5498initialize_trace_info(PyTraceInfo *trace_info, PyFrameObject *frame)
5499{
5500 if (trace_info->code != frame->f_code) {
5501 trace_info->code = frame->f_code;
5502 trace_info->instr_prev = -1;
5503 _PyCode_InitAddressRange(frame->f_code, &trace_info->bounds);
5504 }
5505}
5506
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005507static int
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005508call_trace(Py_tracefunc func, PyObject *obj,
5509 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005510 PyTraceInfo *trace_info,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 int what, PyObject *arg)
Guido van Rossum96a42c81992-01-12 02:29:51 +00005512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 int result;
5514 if (tstate->tracing)
5515 return 0;
5516 tstate->tracing++;
5517 tstate->use_tracing = 0;
Mark Shannon86433452021-01-07 16:49:02 +00005518 if (frame->f_lasti < 0) {
5519 frame->f_lineno = frame->f_code->co_firstlineno;
5520 }
5521 else {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005522 initialize_trace_info(trace_info, frame);
5523 frame->f_lineno = _PyCode_CheckLineNumber(frame->f_lasti, &trace_info->bounds);
Mark Shannon86433452021-01-07 16:49:02 +00005524 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 result = func(obj, frame, what, arg);
Mark Shannon86433452021-01-07 16:49:02 +00005526 frame->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
5528 || (tstate->c_profilefunc != NULL));
5529 tstate->tracing--;
5530 return result;
Guido van Rossum96a42c81992-01-12 02:29:51 +00005531}
5532
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005533PyObject *
5534_PyEval_CallTracing(PyObject *func, PyObject *args)
5535{
Victor Stinner50b48572018-11-01 01:51:40 +01005536 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 int save_tracing = tstate->tracing;
5538 int save_use_tracing = tstate->use_tracing;
5539 PyObject *result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 tstate->tracing = 0;
5542 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
5543 || (tstate->c_profilefunc != NULL));
5544 result = PyObject_Call(func, args, NULL);
5545 tstate->tracing = save_tracing;
5546 tstate->use_tracing = save_use_tracing;
5547 return result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005548}
5549
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005550/* See Objects/lnotab_notes.txt for a description of how tracing works. */
Michael W. Hudson006c7522002-11-08 13:08:46 +00005551static int
Tim Peters8a5c3c72004-04-05 19:36:21 +00005552maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005553 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005554 PyTraceInfo *trace_info)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00005555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 int result = 0;
Michael W. Hudson006c7522002-11-08 13:08:46 +00005557
Nick Coghlan5a851672017-09-08 10:14:16 +10005558 /* If the last instruction falls at the start of a line or if it
5559 represents a jump backwards, update the frame's line number and
5560 then call the trace function if we're tracing source lines.
5561 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00005562 initialize_trace_info(trace_info, frame);
5563 int lastline = trace_info->bounds.ar_line;
5564 int line = _PyCode_CheckLineNumber(frame->f_lasti, &trace_info->bounds);
Mark Shannonee9f98d2021-01-05 12:04:10 +00005565 if (line != -1 && frame->f_trace_lines) {
5566 /* Trace backward edges or first instruction of a new line */
Mark Shannon8e1b4062021-03-05 14:45:50 +00005567 if (frame->f_lasti < trace_info->instr_prev ||
5568 (line != lastline && frame->f_lasti == trace_info->bounds.ar_start))
Mark Shannonee9f98d2021-01-05 12:04:10 +00005569 {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005570 result = call_trace(func, obj, tstate, frame, trace_info, PyTrace_LINE, Py_None);
Nick Coghlan5a851672017-09-08 10:14:16 +10005571 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 }
George King20faa682017-10-18 17:44:22 -07005573 /* Always emit an opcode event if we're tracing all opcodes. */
5574 if (frame->f_trace_opcodes) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005575 result = call_trace(func, obj, tstate, frame, trace_info, PyTrace_OPCODE, Py_None);
George King20faa682017-10-18 17:44:22 -07005576 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00005577 trace_info->instr_prev = frame->f_lasti;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 return result;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00005579}
5580
Victor Stinner309d7cc2020-03-13 16:39:12 +01005581int
5582_PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
5583{
Victor Stinnerda2914d2020-03-20 09:29:08 +01005584 assert(is_tstate_valid(tstate));
Victor Stinner309d7cc2020-03-13 16:39:12 +01005585 /* The caller must hold the GIL */
5586 assert(PyGILState_Check());
5587
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005588 /* Call _PySys_Audit() in the context of the current thread state,
Victor Stinner309d7cc2020-03-13 16:39:12 +01005589 even if tstate is not the current thread state. */
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005590 PyThreadState *current_tstate = _PyThreadState_GET();
5591 if (_PySys_Audit(current_tstate, "sys.setprofile", NULL) < 0) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01005592 return -1;
5593 }
5594
5595 PyObject *profileobj = tstate->c_profileobj;
5596
5597 tstate->c_profilefunc = NULL;
5598 tstate->c_profileobj = NULL;
5599 /* Must make sure that tracing is not ignored if 'profileobj' is freed */
5600 tstate->use_tracing = tstate->c_tracefunc != NULL;
5601 Py_XDECREF(profileobj);
5602
5603 Py_XINCREF(arg);
5604 tstate->c_profileobj = arg;
5605 tstate->c_profilefunc = func;
5606
5607 /* Flag that tracing or profiling is turned on */
5608 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
5609 return 0;
5610}
5611
Fred Drake5755ce62001-06-27 19:19:46 +00005612void
5613PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
Fred Draked0838392001-06-16 21:02:31 +00005614{
Victor Stinner309d7cc2020-03-13 16:39:12 +01005615 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerf6a58502020-03-16 17:41:44 +01005616 if (_PyEval_SetProfile(tstate, func, arg) < 0) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005617 /* Log _PySys_Audit() error */
Victor Stinnerf6a58502020-03-16 17:41:44 +01005618 _PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL);
5619 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01005620}
5621
5622int
5623_PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
5624{
Victor Stinnerda2914d2020-03-20 09:29:08 +01005625 assert(is_tstate_valid(tstate));
Victor Stinner309d7cc2020-03-13 16:39:12 +01005626 /* The caller must hold the GIL */
5627 assert(PyGILState_Check());
5628
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005629 /* Call _PySys_Audit() in the context of the current thread state,
Victor Stinner309d7cc2020-03-13 16:39:12 +01005630 even if tstate is not the current thread state. */
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005631 PyThreadState *current_tstate = _PyThreadState_GET();
5632 if (_PySys_Audit(current_tstate, "sys.settrace", NULL) < 0) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01005633 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005634 }
5635
Victor Stinnerda2914d2020-03-20 09:29:08 +01005636 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinner309d7cc2020-03-13 16:39:12 +01005637 PyObject *traceobj = tstate->c_traceobj;
Victor Stinnerda2914d2020-03-20 09:29:08 +01005638 ceval2->tracing_possible += (func != NULL) - (tstate->c_tracefunc != NULL);
Victor Stinner309d7cc2020-03-13 16:39:12 +01005639
5640 tstate->c_tracefunc = NULL;
5641 tstate->c_traceobj = NULL;
5642 /* Must make sure that profiling is not ignored if 'traceobj' is freed */
5643 tstate->use_tracing = (tstate->c_profilefunc != NULL);
5644 Py_XDECREF(traceobj);
5645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 Py_XINCREF(arg);
Victor Stinner309d7cc2020-03-13 16:39:12 +01005647 tstate->c_traceobj = arg;
5648 tstate->c_tracefunc = func;
5649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 /* Flag that tracing or profiling is turned on */
Victor Stinner309d7cc2020-03-13 16:39:12 +01005651 tstate->use_tracing = ((func != NULL)
5652 || (tstate->c_profilefunc != NULL));
5653
5654 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00005655}
5656
5657void
5658PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
5659{
Victor Stinner309d7cc2020-03-13 16:39:12 +01005660 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerf6a58502020-03-16 17:41:44 +01005661 if (_PyEval_SetTrace(tstate, func, arg) < 0) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005662 /* Log _PySys_Audit() error */
Victor Stinnerf6a58502020-03-16 17:41:44 +01005663 _PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL);
5664 }
Fred Draked0838392001-06-16 21:02:31 +00005665}
5666
Victor Stinner309d7cc2020-03-13 16:39:12 +01005667
Yury Selivanov75445082015-05-11 22:57:16 -04005668void
Victor Stinner838f2642019-06-13 22:41:23 +02005669_PyEval_SetCoroutineOriginTrackingDepth(PyThreadState *tstate, int new_depth)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005670{
5671 assert(new_depth >= 0);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005672 tstate->coroutine_origin_tracking_depth = new_depth;
5673}
5674
5675int
5676_PyEval_GetCoroutineOriginTrackingDepth(void)
5677{
Victor Stinner50b48572018-11-01 01:51:40 +01005678 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005679 return tstate->coroutine_origin_tracking_depth;
5680}
5681
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005682int
Yury Selivanoveb636452016-09-08 22:01:51 -07005683_PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
5684{
Victor Stinner50b48572018-11-01 01:51:40 +01005685 PyThreadState *tstate = _PyThreadState_GET();
Steve Dowerb82e17e2019-05-23 08:45:22 -07005686
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005687 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005688 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005689 }
5690
Yury Selivanoveb636452016-09-08 22:01:51 -07005691 Py_XINCREF(firstiter);
5692 Py_XSETREF(tstate->async_gen_firstiter, firstiter);
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005693 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07005694}
5695
5696PyObject *
5697_PyEval_GetAsyncGenFirstiter(void)
5698{
Victor Stinner50b48572018-11-01 01:51:40 +01005699 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07005700 return tstate->async_gen_firstiter;
5701}
5702
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005703int
Yury Selivanoveb636452016-09-08 22:01:51 -07005704_PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
5705{
Victor Stinner50b48572018-11-01 01:51:40 +01005706 PyThreadState *tstate = _PyThreadState_GET();
Steve Dowerb82e17e2019-05-23 08:45:22 -07005707
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005708 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005709 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005710 }
5711
Yury Selivanoveb636452016-09-08 22:01:51 -07005712 Py_XINCREF(finalizer);
5713 Py_XSETREF(tstate->async_gen_finalizer, finalizer);
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005714 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07005715}
5716
5717PyObject *
5718_PyEval_GetAsyncGenFinalizer(void)
5719{
Victor Stinner50b48572018-11-01 01:51:40 +01005720 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07005721 return tstate->async_gen_finalizer;
5722}
5723
Victor Stinner438a12d2019-05-24 17:01:38 +02005724PyFrameObject *
5725PyEval_GetFrame(void)
5726{
5727 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005728 return tstate->frame;
Victor Stinner438a12d2019-05-24 17:01:38 +02005729}
5730
Guido van Rossumb209a111997-04-29 18:18:01 +00005731PyObject *
Victor Stinner46496f92021-02-20 15:17:18 +01005732_PyEval_GetBuiltins(PyThreadState *tstate)
5733{
5734 PyFrameObject *frame = tstate->frame;
5735 if (frame != NULL) {
5736 return frame->f_builtins;
5737 }
5738 return tstate->interp->builtins;
5739}
5740
5741PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005742PyEval_GetBuiltins(void)
Guido van Rossum6135a871995-01-09 17:53:26 +00005743{
Victor Stinner438a12d2019-05-24 17:01:38 +02005744 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner46496f92021-02-20 15:17:18 +01005745 return _PyEval_GetBuiltins(tstate);
Guido van Rossum6135a871995-01-09 17:53:26 +00005746}
5747
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005748/* Convenience function to get a builtin from its name */
5749PyObject *
5750_PyEval_GetBuiltinId(_Py_Identifier *name)
5751{
Victor Stinner438a12d2019-05-24 17:01:38 +02005752 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005753 PyObject *attr = _PyDict_GetItemIdWithError(PyEval_GetBuiltins(), name);
5754 if (attr) {
5755 Py_INCREF(attr);
5756 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005757 else if (!_PyErr_Occurred(tstate)) {
5758 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(name));
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005759 }
5760 return attr;
5761}
5762
Guido van Rossumb209a111997-04-29 18:18:01 +00005763PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005764PyEval_GetLocals(void)
Guido van Rossum5b722181993-03-30 17:46:03 +00005765{
Victor Stinner438a12d2019-05-24 17:01:38 +02005766 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005767 PyFrameObject *current_frame = tstate->frame;
Victor Stinner41bb43a2013-10-29 01:19:37 +01005768 if (current_frame == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005769 _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 return NULL;
Victor Stinner41bb43a2013-10-29 01:19:37 +01005771 }
5772
Victor Stinner438a12d2019-05-24 17:01:38 +02005773 if (PyFrame_FastToLocalsWithError(current_frame) < 0) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01005774 return NULL;
Victor Stinner438a12d2019-05-24 17:01:38 +02005775 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01005776
5777 assert(current_frame->f_locals != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005778 return current_frame->f_locals;
Guido van Rossum5b722181993-03-30 17:46:03 +00005779}
5780
Guido van Rossumb209a111997-04-29 18:18:01 +00005781PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005782PyEval_GetGlobals(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +00005783{
Victor Stinner438a12d2019-05-24 17:01:38 +02005784 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005785 PyFrameObject *current_frame = tstate->frame;
Victor Stinner438a12d2019-05-24 17:01:38 +02005786 if (current_frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 return NULL;
Victor Stinner438a12d2019-05-24 17:01:38 +02005788 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01005789
5790 assert(current_frame->f_globals != NULL);
5791 return current_frame->f_globals;
Guido van Rossum3f5da241990-12-20 15:06:42 +00005792}
5793
Guido van Rossum6135a871995-01-09 17:53:26 +00005794int
Tim Peters5ba58662001-07-16 02:29:45 +00005795PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Jeremy Hylton061d1062001-03-22 02:32:48 +00005796{
Victor Stinner438a12d2019-05-24 17:01:38 +02005797 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005798 PyFrameObject *current_frame = tstate->frame;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 int result = cf->cf_flags != 0;
Tim Peters5ba58662001-07-16 02:29:45 +00005800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 if (current_frame != NULL) {
5802 const int codeflags = current_frame->f_code->co_flags;
5803 const int compilerflags = codeflags & PyCF_MASK;
5804 if (compilerflags) {
5805 result = 1;
5806 cf->cf_flags |= compilerflags;
5807 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00005808#if 0 /* future keyword */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 if (codeflags & CO_GENERATOR_ALLOWED) {
5810 result = 1;
5811 cf->cf_flags |= CO_GENERATOR_ALLOWED;
5812 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00005813#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 }
5815 return result;
Jeremy Hylton061d1062001-03-22 02:32:48 +00005816}
5817
Guido van Rossum3f5da241990-12-20 15:06:42 +00005818
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00005819const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005820PyEval_GetFuncName(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00005821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 if (PyMethod_Check(func))
5823 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
5824 else if (PyFunction_Check(func))
Serhiy Storchaka06515832016-11-20 09:13:07 +02005825 return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 else if (PyCFunction_Check(func))
5827 return ((PyCFunctionObject*)func)->m_ml->ml_name;
5828 else
Victor Stinnera102ed72020-02-07 02:24:48 +01005829 return Py_TYPE(func)->tp_name;
Jeremy Hylton512a2372001-04-11 13:52:29 +00005830}
5831
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00005832const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005833PyEval_GetFuncDesc(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00005834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 if (PyMethod_Check(func))
5836 return "()";
5837 else if (PyFunction_Check(func))
5838 return "()";
5839 else if (PyCFunction_Check(func))
5840 return "()";
5841 else
5842 return " object";
Jeremy Hylton512a2372001-04-11 13:52:29 +00005843}
5844
Armin Rigo1c2d7e52005-09-20 18:34:01 +00005845#define C_TRACE(x, call) \
Nicholas Bastind858a772004-06-25 23:31:06 +00005846if (tstate->use_tracing && tstate->c_profilefunc) { \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005847 if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005848 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005849 PyTrace_C_CALL, func)) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 x = NULL; \
5851 } \
5852 else { \
5853 x = call; \
5854 if (tstate->c_profilefunc != NULL) { \
5855 if (x == NULL) { \
5856 call_trace_protected(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_EXCEPTION, func); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005860 /* XXX should pass (type, value, tb) */ \
5861 } else { \
5862 if (call_trace(tstate->c_profilefunc, \
5863 tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005864 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005865 PyTrace_C_RETURN, func)) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 Py_DECREF(x); \
5867 x = NULL; \
5868 } \
5869 } \
5870 } \
5871 } \
Nicholas Bastind858a772004-06-25 23:31:06 +00005872} else { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 x = call; \
5874 }
Nicholas Bastinc69ebe82004-03-24 21:57:10 +00005875
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005876
5877static PyObject *
5878trace_call_function(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005879 PyTraceInfo *trace_info,
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005880 PyObject *func,
5881 PyObject **args, Py_ssize_t nargs,
5882 PyObject *kwnames)
5883{
5884 PyObject *x;
scoder4c9ea092020-05-12 16:12:41 +02005885 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005886 C_TRACE(x, PyObject_Vectorcall(func, args, nargs, kwnames));
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005887 return x;
5888 }
Andy Lesterdffe4c02020-03-04 07:15:20 -06005889 else if (Py_IS_TYPE(func, &PyMethodDescr_Type) && nargs > 0) {
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005890 /* We need to create a temporary bound method as argument
5891 for profiling.
5892
5893 If nargs == 0, then this cannot work because we have no
5894 "self". In any case, the call itself would raise
5895 TypeError (foo needs an argument), so we just skip
5896 profiling. */
5897 PyObject *self = args[0];
5898 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5899 if (func == NULL) {
5900 return NULL;
5901 }
Petr Viktorinffd97532020-02-11 17:46:57 +01005902 C_TRACE(x, PyObject_Vectorcall(func,
Jeroen Demeyer0d722f32019-07-05 14:48:24 +02005903 args+1, nargs-1,
5904 kwnames));
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005905 Py_DECREF(func);
5906 return x;
5907 }
Petr Viktorinffd97532020-02-11 17:46:57 +01005908 return PyObject_Vectorcall(func, args, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005909}
5910
Victor Stinner415c5102017-01-11 00:54:57 +01005911/* Issue #29227: Inline call_function() into _PyEval_EvalFrameDefault()
5912 to reduce the stack consumption. */
5913Py_LOCAL_INLINE(PyObject *) _Py_HOT_FUNCTION
Mark Shannon86433452021-01-07 16:49:02 +00005914call_function(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005915 PyTraceInfo *trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00005916 PyObject ***pp_stack,
5917 Py_ssize_t oparg,
5918 PyObject *kwnames)
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005919{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005920 PyObject **pfunc = (*pp_stack) - oparg - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 PyObject *func = *pfunc;
5922 PyObject *x, *w;
Victor Stinnerd8735722016-09-09 12:36:44 -07005923 Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
5924 Py_ssize_t nargs = oparg - nkwargs;
INADA Naoki5566bbb2017-02-03 07:43:03 +09005925 PyObject **stack = (*pp_stack) - nargs - nkwargs;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005926
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005927 if (tstate->use_tracing) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005928 x = trace_call_function(tstate, trace_info, func, stack, nargs, kwnames);
INADA Naoki5566bbb2017-02-03 07:43:03 +09005929 }
Victor Stinner4a7cc882015-03-06 23:35:27 +01005930 else {
Petr Viktorinffd97532020-02-11 17:46:57 +01005931 x = PyObject_Vectorcall(func, stack, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 }
Tim Peters8a5c3c72004-04-05 19:36:21 +00005933
Victor Stinner438a12d2019-05-24 17:01:38 +02005934 assert((x != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005935
Victor Stinnerc22bfaa2017-02-12 19:27:05 +01005936 /* Clear the stack of the function object. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005937 while ((*pp_stack) > pfunc) {
5938 w = EXT_POP(*pp_stack);
5939 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 }
Victor Stinnerace47d72013-07-18 01:41:08 +02005941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 return x;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005943}
5944
Jeremy Hylton52820442001-01-03 23:52:36 +00005945static PyObject *
Mark Shannon86433452021-01-07 16:49:02 +00005946do_call_core(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005947 PyTraceInfo *trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00005948 PyObject *func,
5949 PyObject *callargs,
5950 PyObject *kwdict)
Jeremy Hylton52820442001-01-03 23:52:36 +00005951{
jdemeyere89de732018-09-19 12:06:20 +02005952 PyObject *result;
5953
scoder4c9ea092020-05-12 16:12:41 +02005954 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
Jeroen Demeyer7a6873c2019-09-11 13:01:01 +02005955 C_TRACE(result, PyObject_Call(func, callargs, kwdict));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005956 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 }
Andy Lesterdffe4c02020-03-04 07:15:20 -06005958 else if (Py_IS_TYPE(func, &PyMethodDescr_Type)) {
jdemeyere89de732018-09-19 12:06:20 +02005959 Py_ssize_t nargs = PyTuple_GET_SIZE(callargs);
5960 if (nargs > 0 && tstate->use_tracing) {
5961 /* We need to create a temporary bound method as argument
5962 for profiling.
5963
5964 If nargs == 0, then this cannot work because we have no
5965 "self". In any case, the call itself would raise
5966 TypeError (foo needs an argument), so we just skip
5967 profiling. */
5968 PyObject *self = PyTuple_GET_ITEM(callargs, 0);
5969 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5970 if (func == NULL) {
5971 return NULL;
5972 }
5973
Victor Stinner4d231bc2019-11-14 13:36:21 +01005974 C_TRACE(result, _PyObject_FastCallDictTstate(
5975 tstate, func,
5976 &_PyTuple_ITEMS(callargs)[1],
5977 nargs - 1,
5978 kwdict));
jdemeyere89de732018-09-19 12:06:20 +02005979 Py_DECREF(func);
5980 return result;
5981 }
Victor Stinner74319ae2016-08-25 00:04:09 +02005982 }
jdemeyere89de732018-09-19 12:06:20 +02005983 return PyObject_Call(func, callargs, kwdict);
Jeremy Hylton52820442001-01-03 23:52:36 +00005984}
5985
Serhiy Storchaka483405b2015-02-17 10:14:30 +02005986/* Extract a slice index from a PyLong or an object with the
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005987 nb_index slot defined, and store in *pi.
5988 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
Xiang Zhang2ddf5a12017-05-10 18:19:41 +08005989 and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
Martin v. Löwisdde99d22006-02-17 15:57:41 +00005990 Return 0 on error, 1 on success.
Tim Peterscb479e72001-12-16 19:11:44 +00005991*/
Guido van Rossum20c6add2000-05-08 14:06:50 +00005992int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005993_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005994{
Victor Stinner438a12d2019-05-24 17:01:38 +02005995 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03005996 if (v != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005997 Py_ssize_t x;
Victor Stinnera15e2602020-04-08 02:01:56 +02005998 if (_PyIndex_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 x = PyNumber_AsSsize_t(v, NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02006000 if (x == -1 && _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 return 0;
6002 }
6003 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006004 _PyErr_SetString(tstate, PyExc_TypeError,
6005 "slice indices must be integers or "
6006 "None or have an __index__ method");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 return 0;
6008 }
6009 *pi = x;
6010 }
6011 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00006012}
6013
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006014int
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006015_PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006016{
Victor Stinner438a12d2019-05-24 17:01:38 +02006017 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006018 Py_ssize_t x;
Victor Stinnera15e2602020-04-08 02:01:56 +02006019 if (_PyIndex_Check(v)) {
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006020 x = PyNumber_AsSsize_t(v, NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02006021 if (x == -1 && _PyErr_Occurred(tstate))
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006022 return 0;
6023 }
6024 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006025 _PyErr_SetString(tstate, PyExc_TypeError,
6026 "slice indices must be integers or "
6027 "have an __index__ method");
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006028 return 0;
6029 }
6030 *pi = x;
6031 return 1;
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006032}
6033
Thomas Wouters52152252000-08-17 22:55:00 +00006034static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006035import_name(PyThreadState *tstate, PyFrameObject *f,
6036 PyObject *name, PyObject *fromlist, PyObject *level)
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006037{
6038 _Py_IDENTIFIER(__import__);
Victor Stinnerdf142fd2016-08-20 00:44:42 +02006039 PyObject *import_func, *res;
6040 PyObject* stack[5];
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006041
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006042 import_func = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___import__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006043 if (import_func == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006044 if (!_PyErr_Occurred(tstate)) {
6045 _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006046 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006047 return NULL;
6048 }
6049
6050 /* Fast path for not overloaded __import__. */
Victor Stinner438a12d2019-05-24 17:01:38 +02006051 if (import_func == tstate->interp->import_func) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006052 int ilevel = _PyLong_AsInt(level);
Victor Stinner438a12d2019-05-24 17:01:38 +02006053 if (ilevel == -1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006054 return NULL;
6055 }
6056 res = PyImport_ImportModuleLevelObject(
6057 name,
6058 f->f_globals,
6059 f->f_locals == NULL ? Py_None : f->f_locals,
6060 fromlist,
6061 ilevel);
6062 return res;
6063 }
6064
6065 Py_INCREF(import_func);
Victor Stinnerdf142fd2016-08-20 00:44:42 +02006066
6067 stack[0] = name;
6068 stack[1] = f->f_globals;
6069 stack[2] = f->f_locals == NULL ? Py_None : f->f_locals;
6070 stack[3] = fromlist;
6071 stack[4] = level;
Victor Stinner559bb6a2016-08-22 22:48:54 +02006072 res = _PyObject_FastCall(import_func, stack, 5);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006073 Py_DECREF(import_func);
6074 return res;
6075}
6076
6077static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006078import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
Guido van Rossume9736fc1990-11-18 17:33:06 +00006079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006080 PyObject *x;
Xiang Zhang4830f582017-03-21 11:13:42 +08006081 PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg;
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00006082
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006083 if (_PyObject_LookupAttr(v, name, &x) != 0) {
Antoine Pitrou0373a102014-10-13 20:19:45 +02006084 return x;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006085 }
Antoine Pitrou0373a102014-10-13 20:19:45 +02006086 /* Issue #17636: in case this failed because of a circular relative
6087 import, try to fallback on reading the module directly from
6088 sys.modules. */
Antoine Pitrou0373a102014-10-13 20:19:45 +02006089 pkgname = _PyObject_GetAttrId(v, &PyId___name__);
Brett Cannon3008bc02015-08-11 18:01:31 -07006090 if (pkgname == NULL) {
6091 goto error;
6092 }
Oren Milman6db70332017-09-19 14:23:01 +03006093 if (!PyUnicode_Check(pkgname)) {
6094 Py_CLEAR(pkgname);
6095 goto error;
6096 }
Antoine Pitrou0373a102014-10-13 20:19:45 +02006097 fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
Brett Cannon3008bc02015-08-11 18:01:31 -07006098 if (fullmodname == NULL) {
Xiang Zhang4830f582017-03-21 11:13:42 +08006099 Py_DECREF(pkgname);
Antoine Pitrou0373a102014-10-13 20:19:45 +02006100 return NULL;
Brett Cannon3008bc02015-08-11 18:01:31 -07006101 }
Eric Snow3f9eee62017-09-15 16:35:20 -06006102 x = PyImport_GetModule(fullmodname);
Antoine Pitrou0373a102014-10-13 20:19:45 +02006103 Py_DECREF(fullmodname);
Victor Stinner438a12d2019-05-24 17:01:38 +02006104 if (x == NULL && !_PyErr_Occurred(tstate)) {
Brett Cannon3008bc02015-08-11 18:01:31 -07006105 goto error;
6106 }
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006107 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006108 return x;
Brett Cannon3008bc02015-08-11 18:01:31 -07006109 error:
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006110 pkgpath = PyModule_GetFilenameObject(v);
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006111 if (pkgname == NULL) {
6112 pkgname_or_unknown = PyUnicode_FromString("<unknown module name>");
6113 if (pkgname_or_unknown == NULL) {
6114 Py_XDECREF(pkgpath);
6115 return NULL;
6116 }
6117 } else {
6118 pkgname_or_unknown = pkgname;
6119 }
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006120
6121 if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006122 _PyErr_Clear(tstate);
Xiang Zhang4830f582017-03-21 11:13:42 +08006123 errmsg = PyUnicode_FromFormat(
6124 "cannot import name %R from %R (unknown location)",
6125 name, pkgname_or_unknown
6126 );
Stefan Krah027b09c2019-03-25 21:50:58 +01006127 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
Xiang Zhang4830f582017-03-21 11:13:42 +08006128 PyErr_SetImportError(errmsg, pkgname, NULL);
6129 }
6130 else {
Anthony Sottile65366bc2019-09-09 08:17:50 -07006131 _Py_IDENTIFIER(__spec__);
6132 PyObject *spec = _PyObject_GetAttrId(v, &PyId___spec__);
Anthony Sottile65366bc2019-09-09 08:17:50 -07006133 const char *fmt =
6134 _PyModuleSpec_IsInitializing(spec) ?
6135 "cannot import name %R from partially initialized module %R "
6136 "(most likely due to a circular import) (%S)" :
6137 "cannot import name %R from %R (%S)";
6138 Py_XDECREF(spec);
6139
6140 errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
Stefan Krah027b09c2019-03-25 21:50:58 +01006141 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
Xiang Zhang4830f582017-03-21 11:13:42 +08006142 PyErr_SetImportError(errmsg, pkgname, pkgpath);
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006143 }
6144
Xiang Zhang4830f582017-03-21 11:13:42 +08006145 Py_XDECREF(errmsg);
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006146 Py_XDECREF(pkgname_or_unknown);
6147 Py_XDECREF(pkgpath);
Brett Cannon3008bc02015-08-11 18:01:31 -07006148 return NULL;
Thomas Wouters52152252000-08-17 22:55:00 +00006149}
Guido van Rossumac7be682001-01-17 15:42:30 +00006150
Thomas Wouters52152252000-08-17 22:55:00 +00006151static int
Victor Stinner438a12d2019-05-24 17:01:38 +02006152import_all_from(PyThreadState *tstate, PyObject *locals, PyObject *v)
Thomas Wouters52152252000-08-17 22:55:00 +00006153{
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02006154 _Py_IDENTIFIER(__all__);
6155 _Py_IDENTIFIER(__dict__);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006156 PyObject *all, *dict, *name, *value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006157 int skip_leading_underscores = 0;
6158 int pos, err;
Thomas Wouters52152252000-08-17 22:55:00 +00006159
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006160 if (_PyObject_LookupAttrId(v, &PyId___all__, &all) < 0) {
6161 return -1; /* Unexpected error */
6162 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006163 if (all == NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006164 if (_PyObject_LookupAttrId(v, &PyId___dict__, &dict) < 0) {
6165 return -1;
6166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006167 if (dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006168 _PyErr_SetString(tstate, PyExc_ImportError,
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006169 "from-import-* object has no __dict__ and no __all__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006170 return -1;
6171 }
6172 all = PyMapping_Keys(dict);
6173 Py_DECREF(dict);
6174 if (all == NULL)
6175 return -1;
6176 skip_leading_underscores = 1;
6177 }
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00006178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006179 for (pos = 0, err = 0; ; pos++) {
6180 name = PySequence_GetItem(all, pos);
6181 if (name == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006182 if (!_PyErr_ExceptionMatches(tstate, PyExc_IndexError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006183 err = -1;
Victor Stinner438a12d2019-05-24 17:01:38 +02006184 }
6185 else {
6186 _PyErr_Clear(tstate);
6187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006188 break;
6189 }
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006190 if (!PyUnicode_Check(name)) {
6191 PyObject *modname = _PyObject_GetAttrId(v, &PyId___name__);
6192 if (modname == NULL) {
6193 Py_DECREF(name);
6194 err = -1;
6195 break;
6196 }
6197 if (!PyUnicode_Check(modname)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006198 _PyErr_Format(tstate, PyExc_TypeError,
6199 "module __name__ must be a string, not %.100s",
6200 Py_TYPE(modname)->tp_name);
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006201 }
6202 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006203 _PyErr_Format(tstate, PyExc_TypeError,
6204 "%s in %U.%s must be str, not %.100s",
6205 skip_leading_underscores ? "Key" : "Item",
6206 modname,
6207 skip_leading_underscores ? "__dict__" : "__all__",
6208 Py_TYPE(name)->tp_name);
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006209 }
6210 Py_DECREF(modname);
6211 Py_DECREF(name);
6212 err = -1;
6213 break;
6214 }
6215 if (skip_leading_underscores) {
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03006216 if (PyUnicode_READY(name) == -1) {
6217 Py_DECREF(name);
6218 err = -1;
6219 break;
6220 }
6221 if (PyUnicode_READ_CHAR(name, 0) == '_') {
6222 Py_DECREF(name);
6223 continue;
6224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006225 }
6226 value = PyObject_GetAttr(v, name);
6227 if (value == NULL)
6228 err = -1;
6229 else if (PyDict_CheckExact(locals))
6230 err = PyDict_SetItem(locals, name, value);
6231 else
6232 err = PyObject_SetItem(locals, name, value);
6233 Py_DECREF(name);
6234 Py_XDECREF(value);
6235 if (err != 0)
6236 break;
6237 }
6238 Py_DECREF(all);
6239 return err;
Guido van Rossume9736fc1990-11-18 17:33:06 +00006240}
6241
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006242static int
Victor Stinner438a12d2019-05-24 17:01:38 +02006243check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006244{
Victor Stinnera102ed72020-02-07 02:24:48 +01006245 if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006246 /* check_args_iterable() may be called with a live exception:
6247 * clear it to prevent calling _PyObject_FunctionStr() with an
6248 * exception set. */
Victor Stinner61f4db82020-01-28 03:37:45 +01006249 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006250 PyObject *funcstr = _PyObject_FunctionStr(func);
6251 if (funcstr != NULL) {
6252 _PyErr_Format(tstate, PyExc_TypeError,
6253 "%U argument after * must be an iterable, not %.200s",
6254 funcstr, Py_TYPE(args)->tp_name);
6255 Py_DECREF(funcstr);
6256 }
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006257 return -1;
6258 }
6259 return 0;
6260}
6261
6262static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006263format_kwargs_error(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006264{
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006265 /* _PyDict_MergeEx raises attribute
6266 * error (percolated from an attempt
6267 * to get 'keys' attribute) instead of
6268 * a type error if its second argument
6269 * is not a mapping.
6270 */
Victor Stinner438a12d2019-05-24 17:01:38 +02006271 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Victor Stinner61f4db82020-01-28 03:37:45 +01006272 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006273 PyObject *funcstr = _PyObject_FunctionStr(func);
6274 if (funcstr != NULL) {
6275 _PyErr_Format(
6276 tstate, PyExc_TypeError,
6277 "%U argument after ** must be a mapping, not %.200s",
6278 funcstr, Py_TYPE(kwargs)->tp_name);
6279 Py_DECREF(funcstr);
6280 }
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006281 }
Victor Stinner438a12d2019-05-24 17:01:38 +02006282 else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006283 PyObject *exc, *val, *tb;
Victor Stinner438a12d2019-05-24 17:01:38 +02006284 _PyErr_Fetch(tstate, &exc, &val, &tb);
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006285 if (val && PyTuple_Check(val) && PyTuple_GET_SIZE(val) == 1) {
Victor Stinner61f4db82020-01-28 03:37:45 +01006286 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006287 PyObject *funcstr = _PyObject_FunctionStr(func);
6288 if (funcstr != NULL) {
6289 PyObject *key = PyTuple_GET_ITEM(val, 0);
6290 _PyErr_Format(
6291 tstate, PyExc_TypeError,
6292 "%U got multiple values for keyword argument '%S'",
6293 funcstr, key);
6294 Py_DECREF(funcstr);
6295 }
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006296 Py_XDECREF(exc);
6297 Py_XDECREF(val);
6298 Py_XDECREF(tb);
6299 }
6300 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006301 _PyErr_Restore(tstate, exc, val, tb);
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006302 }
6303 }
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006304}
6305
Guido van Rossumac7be682001-01-17 15:42:30 +00006306static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006307format_exc_check_arg(PyThreadState *tstate, PyObject *exc,
6308 const char *format_str, PyObject *obj)
Paul Prescode68140d2000-08-30 20:25:01 +00006309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006310 const char *obj_str;
Paul Prescode68140d2000-08-30 20:25:01 +00006311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006312 if (!obj)
6313 return;
Paul Prescode68140d2000-08-30 20:25:01 +00006314
Serhiy Storchaka06515832016-11-20 09:13:07 +02006315 obj_str = PyUnicode_AsUTF8(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006316 if (!obj_str)
6317 return;
Paul Prescode68140d2000-08-30 20:25:01 +00006318
Victor Stinner438a12d2019-05-24 17:01:38 +02006319 _PyErr_Format(tstate, exc, format_str, obj_str);
Paul Prescode68140d2000-08-30 20:25:01 +00006320}
Guido van Rossum950361c1997-01-24 13:49:28 +00006321
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006322static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006323format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006324{
6325 PyObject *name;
6326 /* Don't stomp existing exception */
Victor Stinner438a12d2019-05-24 17:01:38 +02006327 if (_PyErr_Occurred(tstate))
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006328 return;
6329 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
6330 name = PyTuple_GET_ITEM(co->co_cellvars,
6331 oparg);
Victor Stinner438a12d2019-05-24 17:01:38 +02006332 format_exc_check_arg(tstate,
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006333 PyExc_UnboundLocalError,
6334 UNBOUNDLOCAL_ERROR_MSG,
6335 name);
6336 } else {
6337 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
6338 PyTuple_GET_SIZE(co->co_cellvars));
Victor Stinner438a12d2019-05-24 17:01:38 +02006339 format_exc_check_arg(tstate, PyExc_NameError,
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006340 UNBOUNDFREE_ERROR_MSG, name);
6341 }
6342}
6343
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006344static void
Mark Shannonfee55262019-11-21 09:11:43 +00006345format_awaitable_error(PyThreadState *tstate, PyTypeObject *type, int prevprevopcode, int prevopcode)
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006346{
6347 if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
6348 if (prevopcode == BEFORE_ASYNC_WITH) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006349 _PyErr_Format(tstate, PyExc_TypeError,
6350 "'async with' received an object from __aenter__ "
6351 "that does not implement __await__: %.100s",
6352 type->tp_name);
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006353 }
Mark Shannonfee55262019-11-21 09:11:43 +00006354 else if (prevopcode == WITH_EXCEPT_START || (prevopcode == CALL_FUNCTION && prevprevopcode == DUP_TOP)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006355 _PyErr_Format(tstate, PyExc_TypeError,
6356 "'async with' received an object from __aexit__ "
6357 "that does not implement __await__: %.100s",
6358 type->tp_name);
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006359 }
6360 }
6361}
6362
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006363static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006364unicode_concatenate(PyThreadState *tstate, PyObject *v, PyObject *w,
Serhiy Storchakaab874002016-09-11 13:48:15 +03006365 PyFrameObject *f, const _Py_CODEUNIT *next_instr)
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006366{
6367 PyObject *res;
6368 if (Py_REFCNT(v) == 2) {
6369 /* In the common case, there are 2 references to the value
6370 * stored in 'variable' when the += is performed: one on the
6371 * value stack (in 'v') and one still stored in the
6372 * 'variable'. We try to delete the variable now to reduce
6373 * the refcnt to 1.
6374 */
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006375 int opcode, oparg;
6376 NEXTOPARG();
6377 switch (opcode) {
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006378 case STORE_FAST:
6379 {
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006380 PyObject **fastlocals = f->f_localsplus;
6381 if (GETLOCAL(oparg) == v)
6382 SETLOCAL(oparg, NULL);
6383 break;
6384 }
6385 case STORE_DEREF:
6386 {
6387 PyObject **freevars = (f->f_localsplus +
6388 f->f_code->co_nlocals);
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006389 PyObject *c = freevars[oparg];
Raymond Hettingerc32f9db2016-11-12 04:10:35 -05006390 if (PyCell_GET(c) == v) {
6391 PyCell_SET(c, NULL);
6392 Py_DECREF(v);
6393 }
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006394 break;
6395 }
6396 case STORE_NAME:
6397 {
6398 PyObject *names = f->f_code->co_names;
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006399 PyObject *name = GETITEM(names, oparg);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006400 PyObject *locals = f->f_locals;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006401 if (locals && PyDict_CheckExact(locals)) {
6402 PyObject *w = PyDict_GetItemWithError(locals, name);
6403 if ((w == v && PyDict_DelItem(locals, name) != 0) ||
Victor Stinner438a12d2019-05-24 17:01:38 +02006404 (w == NULL && _PyErr_Occurred(tstate)))
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006405 {
6406 Py_DECREF(v);
6407 return NULL;
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006408 }
6409 }
6410 break;
6411 }
6412 }
6413 }
6414 res = v;
6415 PyUnicode_Append(&res, w);
6416 return res;
6417}
6418
Guido van Rossum950361c1997-01-24 13:49:28 +00006419#ifdef DYNAMIC_EXECUTION_PROFILE
6420
Skip Montanarof118cb12001-10-15 20:51:38 +00006421static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00006422getarray(long a[256])
Guido van Rossum950361c1997-01-24 13:49:28 +00006423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006424 int i;
6425 PyObject *l = PyList_New(256);
6426 if (l == NULL) return NULL;
6427 for (i = 0; i < 256; i++) {
6428 PyObject *x = PyLong_FromLong(a[i]);
6429 if (x == NULL) {
6430 Py_DECREF(l);
6431 return NULL;
6432 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07006433 PyList_SET_ITEM(l, i, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006434 }
6435 for (i = 0; i < 256; i++)
6436 a[i] = 0;
6437 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00006438}
6439
6440PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00006441_Py_GetDXProfile(PyObject *self, PyObject *args)
Guido van Rossum950361c1997-01-24 13:49:28 +00006442{
6443#ifndef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006444 return getarray(dxp);
Guido van Rossum950361c1997-01-24 13:49:28 +00006445#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006446 int i;
6447 PyObject *l = PyList_New(257);
6448 if (l == NULL) return NULL;
6449 for (i = 0; i < 257; i++) {
6450 PyObject *x = getarray(dxpairs[i]);
6451 if (x == NULL) {
6452 Py_DECREF(l);
6453 return NULL;
6454 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07006455 PyList_SET_ITEM(l, i, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006456 }
6457 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00006458#endif
6459}
6460
6461#endif
Brett Cannon5c4de282016-09-07 11:16:41 -07006462
6463Py_ssize_t
6464_PyEval_RequestCodeExtraIndex(freefunc free)
6465{
Victor Stinner81a7be32020-04-14 15:14:01 +02006466 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannon5c4de282016-09-07 11:16:41 -07006467 Py_ssize_t new_index;
6468
Dino Viehlandf3cffd22017-06-21 14:44:36 -07006469 if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
Brett Cannon5c4de282016-09-07 11:16:41 -07006470 return -1;
6471 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -07006472 new_index = interp->co_extra_user_count++;
6473 interp->co_extra_freefuncs[new_index] = free;
Brett Cannon5c4de282016-09-07 11:16:41 -07006474 return new_index;
6475}
Łukasz Langaa785c872016-09-09 17:37:37 -07006476
6477static void
6478dtrace_function_entry(PyFrameObject *f)
6479{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006480 const char *filename;
6481 const char *funcname;
Łukasz Langaa785c872016-09-09 17:37:37 -07006482 int lineno;
6483
Victor Stinner6d86a232020-04-29 00:56:58 +02006484 PyCodeObject *code = f->f_code;
6485 filename = PyUnicode_AsUTF8(code->co_filename);
6486 funcname = PyUnicode_AsUTF8(code->co_name);
6487 lineno = PyCode_Addr2Line(code, f->f_lasti);
Łukasz Langaa785c872016-09-09 17:37:37 -07006488
Andy Lestere6be9b52020-02-11 20:28:35 -06006489 PyDTrace_FUNCTION_ENTRY(filename, funcname, lineno);
Łukasz Langaa785c872016-09-09 17:37:37 -07006490}
6491
6492static void
6493dtrace_function_return(PyFrameObject *f)
6494{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006495 const char *filename;
6496 const char *funcname;
Łukasz Langaa785c872016-09-09 17:37:37 -07006497 int lineno;
6498
Victor Stinner6d86a232020-04-29 00:56:58 +02006499 PyCodeObject *code = f->f_code;
6500 filename = PyUnicode_AsUTF8(code->co_filename);
6501 funcname = PyUnicode_AsUTF8(code->co_name);
6502 lineno = PyCode_Addr2Line(code, f->f_lasti);
Łukasz Langaa785c872016-09-09 17:37:37 -07006503
Andy Lestere6be9b52020-02-11 20:28:35 -06006504 PyDTrace_FUNCTION_RETURN(filename, funcname, lineno);
Łukasz Langaa785c872016-09-09 17:37:37 -07006505}
6506
6507/* DTrace equivalent of maybe_call_line_trace. */
6508static void
6509maybe_dtrace_line(PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00006510 PyTraceInfo *trace_info)
Łukasz Langaa785c872016-09-09 17:37:37 -07006511{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006512 const char *co_filename, *co_name;
Łukasz Langaa785c872016-09-09 17:37:37 -07006513
6514 /* If the last instruction executed isn't in the current
6515 instruction window, reset the window.
6516 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00006517 initialize_trace_info(trace_info, frame);
6518 int line = _PyCode_CheckLineNumber(frame->f_lasti, &trace_info->bounds);
Łukasz Langaa785c872016-09-09 17:37:37 -07006519 /* If the last instruction falls at the start of a line or if
6520 it represents a jump backwards, update the frame's line
6521 number and call the trace function. */
Mark Shannon8e1b4062021-03-05 14:45:50 +00006522 if (line != frame->f_lineno || frame->f_lasti < trace_info->instr_prev) {
Mark Shannon877df852020-11-12 09:43:29 +00006523 if (line != -1) {
6524 frame->f_lineno = line;
6525 co_filename = PyUnicode_AsUTF8(frame->f_code->co_filename);
6526 if (!co_filename)
6527 co_filename = "?";
6528 co_name = PyUnicode_AsUTF8(frame->f_code->co_name);
6529 if (!co_name)
6530 co_name = "?";
6531 PyDTrace_LINE(co_filename, co_name, line);
6532 }
Łukasz Langaa785c872016-09-09 17:37:37 -07006533 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00006534 trace_info->instr_prev = frame->f_lasti;
Łukasz Langaa785c872016-09-09 17:37:37 -07006535}
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006536
6537
6538/* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
6539 for the limited API. */
6540
6541#undef Py_EnterRecursiveCall
6542
6543int Py_EnterRecursiveCall(const char *where)
6544{
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006545 return _Py_EnterRecursiveCall_inline(where);
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006546}
6547
6548#undef Py_LeaveRecursiveCall
6549
6550void Py_LeaveRecursiveCall(void)
6551{
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006552 _Py_LeaveRecursiveCall_inline();
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006553}