blob: c12116044b54e81e1e02e077eca8816a4eb499e6 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Execute compiled code */
Guido van Rossum10dc2e81990-11-18 17:27:39 +00002
Guido van Rossum681d79a1995-07-18 14:51:37 +00003/* XXX TO DO:
Guido van Rossum681d79a1995-07-18 14:51:37 +00004 XXX speed up searching for keywords by using a dictionary
Guido van Rossum681d79a1995-07-18 14:51:37 +00005 XXX document it!
6 */
7
Thomas Wouters477c8d52006-05-27 19:21:47 +00008/* enable more aggressive intra-module optimizations, where available */
db3l131d5512021-03-03 22:09:48 -05009/* affects both release and debug builds - see bpo-43271 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010#define PY_LOCAL_AGGRESSIVE
11
Guido van Rossumb209a111997-04-29 18:18:01 +000012#include "Python.h"
Victor Stinnere560f902020-04-14 18:30:41 +020013#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinner384621c2020-06-22 17:27:35 +020014#include "pycore_call.h" // _PyObject_FastCallDictTstate()
15#include "pycore_ceval.h" // _PyEval_SignalAsyncExc()
16#include "pycore_code.h" // _PyCode_InitOpcache()
17#include "pycore_initconfig.h" // _PyStatus_OK()
18#include "pycore_object.h" // _PyObject_GC_TRACK()
19#include "pycore_pyerrors.h" // _PyErr_Fetch()
20#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere560f902020-04-14 18:30:41 +020021#include "pycore_pymem.h" // _PyMem_IsPtrFreed()
22#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner384621c2020-06-22 17:27:35 +020023#include "pycore_sysmodule.h" // _PySys_Audit()
24#include "pycore_tuple.h" // _PyTuple_ITEMS()
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "code.h"
Benjamin Peterson025e9eb2015-05-05 20:16:41 -040027#include "dictobject.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000028#include "frameobject.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "opcode.h"
Łukasz Langaa785c872016-09-09 17:37:37 -070030#include "pydtrace.h"
Benjamin Peterson025e9eb2015-05-05 20:16:41 -040031#include "setobject.h"
Guido van Rossum5c5a9382021-01-29 18:02:29 -080032#include "structmember.h" // struct PyMemberDef, T_OFFSET_EX
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033
Guido van Rossumc6004111993-11-05 10:22:19 +000034#include <ctype.h>
35
Mark Shannon8e1b4062021-03-05 14:45:50 +000036typedef struct {
37 PyCodeObject *code; // The code object for the bounds. May be NULL.
38 int instr_prev; // Only valid if code != NULL.
39 PyCodeAddressRange bounds; // Only valid if code != NULL.
40} PyTraceInfo;
41
42
Guido van Rossum408027e1996-12-30 16:17:54 +000043#ifdef Py_DEBUG
Guido van Rossum96a42c81992-01-12 02:29:51 +000044/* For debugging the interpreter: */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045#define LLTRACE 1 /* Low-level trace feature */
46#define CHECKEXC 1 /* Double-check exception checking */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000047#endif
48
Victor Stinner5c75f372019-04-17 23:02:26 +020049#if !defined(Py_BUILD_CORE)
50# error "ceval.c must be build with Py_BUILD_CORE define for best performance"
51#endif
52
Hai Shi46874c22020-01-30 17:20:25 -060053_Py_IDENTIFIER(__name__);
Guido van Rossum5b722181993-03-30 17:46:03 +000054
Guido van Rossum374a9221991-04-04 10:40:29 +000055/* Forward declarations */
Victor Stinner09532fe2019-05-10 23:39:09 +020056Py_LOCAL_INLINE(PyObject *) call_function(
Mark Shannon8e1b4062021-03-05 14:45:50 +000057 PyThreadState *tstate, PyTraceInfo *, PyObject ***pp_stack,
Victor Stinner09532fe2019-05-10 23:39:09 +020058 Py_ssize_t oparg, PyObject *kwnames);
59static PyObject * do_call_core(
Mark Shannon8e1b4062021-03-05 14:45:50 +000060 PyThreadState *tstate, PyTraceInfo *, PyObject *func,
Victor Stinner09532fe2019-05-10 23:39:09 +020061 PyObject *callargs, PyObject *kwdict);
Jeremy Hylton52820442001-01-03 23:52:36 +000062
Guido van Rossum0a066c01992-03-27 17:29:15 +000063#ifdef LLTRACE
Guido van Rossumc2e20742006-02-27 22:32:47 +000064static int lltrace;
Victor Stinner438a12d2019-05-24 17:01:38 +020065static int prtrace(PyThreadState *, PyObject *, const char *);
Guido van Rossum0a066c01992-03-27 17:29:15 +000066#endif
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +010067static int call_trace(Py_tracefunc, PyObject *,
68 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000069 PyTraceInfo *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 int, PyObject *);
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +000071static int call_trace_protected(Py_tracefunc, PyObject *,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +010072 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000073 PyTraceInfo *,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +010074 int, PyObject *);
75static void call_exc_trace(Py_tracefunc, PyObject *,
Mark Shannon86433452021-01-07 16:49:02 +000076 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000077 PyTraceInfo *trace_info);
Tim Peters8a5c3c72004-04-05 19:36:21 +000078static int maybe_call_line_trace(Py_tracefunc, PyObject *,
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079 PyThreadState *, PyFrameObject *,
Mark Shannon8e1b4062021-03-05 14:45:50 +000080 PyTraceInfo *);
81static void maybe_dtrace_line(PyFrameObject *, PyTraceInfo *);
Łukasz Langaa785c872016-09-09 17:37:37 -070082static void dtrace_function_entry(PyFrameObject *);
83static void dtrace_function_return(PyFrameObject *);
Michael W. Hudsondd32a912002-08-15 14:59:02 +000084
Victor Stinner438a12d2019-05-24 17:01:38 +020085static PyObject * import_name(PyThreadState *, PyFrameObject *,
86 PyObject *, PyObject *, PyObject *);
87static PyObject * import_from(PyThreadState *, PyObject *, PyObject *);
88static int import_all_from(PyThreadState *, PyObject *, PyObject *);
89static void format_exc_check_arg(PyThreadState *, PyObject *, const char *, PyObject *);
90static void format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
91static PyObject * unicode_concatenate(PyThreadState *, PyObject *, PyObject *,
Serhiy Storchakaab874002016-09-11 13:48:15 +030092 PyFrameObject *, const _Py_CODEUNIT *);
Victor Stinner438a12d2019-05-24 17:01:38 +020093static PyObject * special_lookup(PyThreadState *, PyObject *, _Py_Identifier *);
94static int check_args_iterable(PyThreadState *, PyObject *func, PyObject *vararg);
95static void format_kwargs_error(PyThreadState *, PyObject *func, PyObject *kwargs);
Mark Shannonfee55262019-11-21 09:11:43 +000096static void format_awaitable_error(PyThreadState *, PyTypeObject *, int, int);
Guido van Rossum374a9221991-04-04 10:40:29 +000097
Paul Prescode68140d2000-08-30 20:25:01 +000098#define NAME_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 "name '%.200s' is not defined"
Paul Prescode68140d2000-08-30 20:25:01 +0000100#define UNBOUNDLOCAL_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 "local variable '%.200s' referenced before assignment"
Jeremy Hyltonc76770c2001-04-13 16:51:46 +0000102#define UNBOUNDFREE_ERROR_MSG \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 "free variable '%.200s' referenced before assignment" \
104 " in enclosing scope"
Guido van Rossum374a9221991-04-04 10:40:29 +0000105
Guido van Rossum950361c1997-01-24 13:49:28 +0000106/* Dynamic execution profile */
107#ifdef DYNAMIC_EXECUTION_PROFILE
108#ifdef DXPAIRS
109static long dxpairs[257][256];
110#define dxp dxpairs[256]
111#else
112static long dxp[256];
113#endif
114#endif
115
Inada Naoki91234a12019-06-03 21:30:58 +0900116/* per opcode cache */
Pablo Galindoaf5fa132021-02-28 22:41:09 +0000117static int opcache_min_runs = 1024; /* create opcache when code executed this many times */
Pablo Galindo109826c2020-10-20 06:22:44 +0100118#define OPCODE_CACHE_MAX_TRIES 20
Inada Naoki91234a12019-06-03 21:30:58 +0900119#define OPCACHE_STATS 0 /* Enable stats */
120
Pablo Galindoaf5fa132021-02-28 22:41:09 +0000121// This function allows to deactivate the opcode cache. As different cache mechanisms may hold
122// references, this can mess with the reference leak detector functionality so the cache needs
123// to be deactivated in such scenarios to avoid false positives. See bpo-3714 for more information.
124void
125_PyEval_DeactivateOpCache(void)
126{
127 opcache_min_runs = 0;
128}
129
Inada Naoki91234a12019-06-03 21:30:58 +0900130#if OPCACHE_STATS
131static size_t opcache_code_objects = 0;
132static size_t opcache_code_objects_extra_mem = 0;
133
134static size_t opcache_global_opts = 0;
135static size_t opcache_global_hits = 0;
136static size_t opcache_global_misses = 0;
Pablo Galindo109826c2020-10-20 06:22:44 +0100137
138static size_t opcache_attr_opts = 0;
139static size_t opcache_attr_hits = 0;
140static size_t opcache_attr_misses = 0;
141static size_t opcache_attr_deopts = 0;
142static size_t opcache_attr_total = 0;
Inada Naoki91234a12019-06-03 21:30:58 +0900143#endif
144
Victor Stinner5a3a71d2020-03-19 17:40:12 +0100145
Victor Stinnerda2914d2020-03-20 09:29:08 +0100146#ifndef NDEBUG
147/* Ensure that tstate is valid: sanity check for PyEval_AcquireThread() and
148 PyEval_RestoreThread(). Detect if tstate memory was freed. It can happen
149 when a thread continues to run after Python finalization, especially
150 daemon threads. */
151static int
152is_tstate_valid(PyThreadState *tstate)
153{
154 assert(!_PyMem_IsPtrFreed(tstate));
155 assert(!_PyMem_IsPtrFreed(tstate->interp));
156 return 1;
157}
158#endif
159
160
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000161/* This can set eval_breaker to 0 even though gil_drop_request became
162 1. We believe this is all right because the eval loop will release
163 the GIL eventually anyway. */
Victor Stinnerda2914d2020-03-20 09:29:08 +0100164static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200165COMPUTE_EVAL_BREAKER(PyInterpreterState *interp,
Victor Stinner299b8c62020-05-05 17:40:18 +0200166 struct _ceval_runtime_state *ceval,
167 struct _ceval_state *ceval2)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100168{
Victor Stinner299b8c62020-05-05 17:40:18 +0200169 _Py_atomic_store_relaxed(&ceval2->eval_breaker,
170 _Py_atomic_load_relaxed(&ceval2->gil_drop_request)
Victor Stinner0b1e3302020-05-05 16:14:31 +0200171 | (_Py_atomic_load_relaxed(&ceval->signals_pending)
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200172 && _Py_ThreadCanHandleSignals(interp))
Victor Stinner299b8c62020-05-05 17:40:18 +0200173 | (_Py_atomic_load_relaxed(&ceval2->pending.calls_to_do)
Victor Stinnerd8316882020-03-20 14:50:35 +0100174 && _Py_ThreadCanHandlePendingCalls())
Victor Stinner299b8c62020-05-05 17:40:18 +0200175 | ceval2->pending.async_exc);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100176}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000177
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000178
Victor Stinnerda2914d2020-03-20 09:29:08 +0100179static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200180SET_GIL_DROP_REQUEST(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100181{
Victor Stinner299b8c62020-05-05 17:40:18 +0200182 struct _ceval_state *ceval2 = &interp->ceval;
183 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 1);
184 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100185}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000186
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000187
Victor Stinnerda2914d2020-03-20 09:29:08 +0100188static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200189RESET_GIL_DROP_REQUEST(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100190{
Victor Stinner299b8c62020-05-05 17:40:18 +0200191 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
192 struct _ceval_state *ceval2 = &interp->ceval;
193 _Py_atomic_store_relaxed(&ceval2->gil_drop_request, 0);
194 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100195}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000196
Eric Snowfdf282d2019-01-11 14:26:55 -0700197
Victor Stinnerda2914d2020-03-20 09:29:08 +0100198static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200199SIGNAL_PENDING_CALLS(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100200{
Victor Stinner299b8c62020-05-05 17:40:18 +0200201 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
202 struct _ceval_state *ceval2 = &interp->ceval;
203 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 1);
204 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100205}
Eric Snowfdf282d2019-01-11 14:26:55 -0700206
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000207
Victor Stinnerda2914d2020-03-20 09:29:08 +0100208static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200209UNSIGNAL_PENDING_CALLS(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100210{
Victor Stinner299b8c62020-05-05 17:40:18 +0200211 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
212 struct _ceval_state *ceval2 = &interp->ceval;
213 _Py_atomic_store_relaxed(&ceval2->pending.calls_to_do, 0);
214 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100215}
216
217
218static inline void
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100219SIGNAL_PENDING_SIGNALS(PyInterpreterState *interp, int force)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100220{
Victor Stinner299b8c62020-05-05 17:40:18 +0200221 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
222 struct _ceval_state *ceval2 = &interp->ceval;
Victor Stinner0b1e3302020-05-05 16:14:31 +0200223 _Py_atomic_store_relaxed(&ceval->signals_pending, 1);
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100224 if (force) {
225 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
226 }
227 else {
228 /* eval_breaker is not set to 1 if thread_can_handle_signals() is false */
229 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
230 }
Victor Stinnerda2914d2020-03-20 09:29:08 +0100231}
232
233
234static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200235UNSIGNAL_PENDING_SIGNALS(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100236{
Victor Stinner299b8c62020-05-05 17:40:18 +0200237 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
238 struct _ceval_state *ceval2 = &interp->ceval;
Victor Stinner0b1e3302020-05-05 16:14:31 +0200239 _Py_atomic_store_relaxed(&ceval->signals_pending, 0);
Victor Stinner299b8c62020-05-05 17:40:18 +0200240 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100241}
242
243
244static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200245SIGNAL_ASYNC_EXC(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100246{
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200247 struct _ceval_state *ceval2 = &interp->ceval;
Victor Stinnerda2914d2020-03-20 09:29:08 +0100248 ceval2->pending.async_exc = 1;
249 _Py_atomic_store_relaxed(&ceval2->eval_breaker, 1);
250}
251
252
253static inline void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200254UNSIGNAL_ASYNC_EXC(PyInterpreterState *interp)
Victor Stinnerda2914d2020-03-20 09:29:08 +0100255{
Victor Stinner299b8c62020-05-05 17:40:18 +0200256 struct _ceval_runtime_state *ceval = &interp->runtime->ceval;
257 struct _ceval_state *ceval2 = &interp->ceval;
258 ceval2->pending.async_exc = 0;
259 COMPUTE_EVAL_BREAKER(interp, ceval, ceval2);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100260}
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000261
262
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000263#ifdef HAVE_ERRNO_H
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000264#include <errno.h>
Guido van Rossum2571cc81999-04-07 16:07:23 +0000265#endif
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000266#include "ceval_gil.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000267
Victor Stinner3026cad2020-06-01 16:02:40 +0200268void _Py_NO_RETURN
269_Py_FatalError_TstateNULL(const char *func)
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100270{
Victor Stinner3026cad2020-06-01 16:02:40 +0200271 _Py_FatalErrorFunc(func,
272 "the function must be called with the GIL held, "
273 "but the GIL is released "
274 "(the current Python thread state is NULL)");
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100275}
276
Victor Stinner7be4e352020-05-05 20:27:47 +0200277#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
278int
279_PyEval_ThreadsInitialized(PyInterpreterState *interp)
280{
281 return gil_created(&interp->ceval.gil);
282}
283
284int
285PyEval_ThreadsInitialized(void)
286{
287 // Fatal error if there is no current interpreter
288 PyInterpreterState *interp = PyInterpreterState_Get();
289 return _PyEval_ThreadsInitialized(interp);
290}
291#else
Tim Peters7f468f22004-10-11 02:40:51 +0000292int
Victor Stinner175a7042020-03-10 00:37:48 +0100293_PyEval_ThreadsInitialized(_PyRuntimeState *runtime)
294{
295 return gil_created(&runtime->ceval.gil);
296}
297
298int
Tim Peters7f468f22004-10-11 02:40:51 +0000299PyEval_ThreadsInitialized(void)
300{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100301 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner175a7042020-03-10 00:37:48 +0100302 return _PyEval_ThreadsInitialized(runtime);
Tim Peters7f468f22004-10-11 02:40:51 +0000303}
Victor Stinner7be4e352020-05-05 20:27:47 +0200304#endif
Tim Peters7f468f22004-10-11 02:40:51 +0000305
Victor Stinner111e4ee2020-03-09 21:24:14 +0100306PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200307_PyEval_InitGIL(PyThreadState *tstate)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000308{
Victor Stinner7be4e352020-05-05 20:27:47 +0200309#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner101bf692021-02-19 13:33:31 +0100310 if (!_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200311 /* Currently, the GIL is shared by all interpreters,
312 and only the main interpreter is responsible to create
313 and destroy it. */
314 return _PyStatus_OK();
Victor Stinner111e4ee2020-03-09 21:24:14 +0100315 }
Victor Stinner7be4e352020-05-05 20:27:47 +0200316#endif
Victor Stinner111e4ee2020-03-09 21:24:14 +0100317
Victor Stinner7be4e352020-05-05 20:27:47 +0200318#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
319 struct _gil_runtime_state *gil = &tstate->interp->ceval.gil;
320#else
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200321 struct _gil_runtime_state *gil = &tstate->interp->runtime->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200322#endif
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200323 assert(!gil_created(gil));
Victor Stinner85f5a692020-03-09 22:12:04 +0100324
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200325 PyThread_init_thread();
326 create_gil(gil);
327
328 take_gil(tstate);
329
330 assert(gil_created(gil));
Victor Stinner111e4ee2020-03-09 21:24:14 +0100331 return _PyStatus_OK();
332}
333
334void
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100335_PyEval_FiniGIL(PyInterpreterState *interp)
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200336{
Victor Stinner7be4e352020-05-05 20:27:47 +0200337#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100338 if (!_Py_IsMainInterpreter(interp)) {
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200339 /* Currently, the GIL is shared by all interpreters,
340 and only the main interpreter is responsible to create
341 and destroy it. */
342 return;
343 }
Victor Stinner7be4e352020-05-05 20:27:47 +0200344#endif
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200345
Victor Stinner7be4e352020-05-05 20:27:47 +0200346#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100347 struct _gil_runtime_state *gil = &interp->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200348#else
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100349 struct _gil_runtime_state *gil = &interp->runtime->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200350#endif
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200351 if (!gil_created(gil)) {
352 /* First Py_InitializeFromConfig() call: the GIL doesn't exist
353 yet: do nothing. */
354 return;
355 }
356
357 destroy_gil(gil);
358 assert(!gil_created(gil));
359}
360
361void
Victor Stinner111e4ee2020-03-09 21:24:14 +0100362PyEval_InitThreads(void)
363{
Victor Stinnerb4698ec2020-03-10 01:28:54 +0100364 /* Do nothing: kept for backward compatibility */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000365}
Guido van Rossumff4949e1992-08-05 19:58:53 +0000366
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000367void
Inada Naoki91234a12019-06-03 21:30:58 +0900368_PyEval_Fini(void)
369{
370#if OPCACHE_STATS
371 fprintf(stderr, "-- Opcode cache number of objects = %zd\n",
372 opcache_code_objects);
373
374 fprintf(stderr, "-- Opcode cache total extra mem = %zd\n",
375 opcache_code_objects_extra_mem);
376
377 fprintf(stderr, "\n");
378
379 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL hits = %zd (%d%%)\n",
380 opcache_global_hits,
381 (int) (100.0 * opcache_global_hits /
382 (opcache_global_hits + opcache_global_misses)));
383
384 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL misses = %zd (%d%%)\n",
385 opcache_global_misses,
386 (int) (100.0 * opcache_global_misses /
387 (opcache_global_hits + opcache_global_misses)));
388
389 fprintf(stderr, "-- Opcode cache LOAD_GLOBAL opts = %zd\n",
390 opcache_global_opts);
391
392 fprintf(stderr, "\n");
Pablo Galindo109826c2020-10-20 06:22:44 +0100393
394 fprintf(stderr, "-- Opcode cache LOAD_ATTR hits = %zd (%d%%)\n",
395 opcache_attr_hits,
396 (int) (100.0 * opcache_attr_hits /
397 opcache_attr_total));
398
399 fprintf(stderr, "-- Opcode cache LOAD_ATTR misses = %zd (%d%%)\n",
400 opcache_attr_misses,
401 (int) (100.0 * opcache_attr_misses /
402 opcache_attr_total));
403
404 fprintf(stderr, "-- Opcode cache LOAD_ATTR opts = %zd\n",
405 opcache_attr_opts);
406
407 fprintf(stderr, "-- Opcode cache LOAD_ATTR deopts = %zd\n",
408 opcache_attr_deopts);
409
410 fprintf(stderr, "-- Opcode cache LOAD_ATTR total = %zd\n",
411 opcache_attr_total);
Inada Naoki91234a12019-06-03 21:30:58 +0900412#endif
413}
414
415void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000416PyEval_AcquireLock(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000417{
Victor Stinner09532fe2019-05-10 23:39:09 +0200418 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner09532fe2019-05-10 23:39:09 +0200419 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner3026cad2020-06-01 16:02:40 +0200420 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100421
Victor Stinner85f5a692020-03-09 22:12:04 +0100422 take_gil(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000423}
424
425void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000426PyEval_ReleaseLock(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000427{
Victor Stinner09532fe2019-05-10 23:39:09 +0200428 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnere225beb2019-06-03 18:14:24 +0200429 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 /* This function must succeed when the current thread state is NULL.
Victor Stinner50b48572018-11-01 01:51:40 +0100431 We therefore avoid PyThreadState_Get() which dumps a fatal error
Victor Stinnerda2914d2020-03-20 09:29:08 +0100432 in debug mode. */
Victor Stinner299b8c62020-05-05 17:40:18 +0200433 struct _ceval_runtime_state *ceval = &runtime->ceval;
434 struct _ceval_state *ceval2 = &tstate->interp->ceval;
435 drop_gil(ceval, ceval2, tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000436}
437
438void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100439_PyEval_ReleaseLock(PyThreadState *tstate)
440{
441 struct _ceval_runtime_state *ceval = &tstate->interp->runtime->ceval;
Victor Stinner0b1e3302020-05-05 16:14:31 +0200442 struct _ceval_state *ceval2 = &tstate->interp->ceval;
443 drop_gil(ceval, ceval2, tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100444}
445
446void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000447PyEval_AcquireThread(PyThreadState *tstate)
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000448{
Victor Stinner3026cad2020-06-01 16:02:40 +0200449 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100450
Victor Stinner85f5a692020-03-09 22:12:04 +0100451 take_gil(tstate);
Victor Stinnere225beb2019-06-03 18:14:24 +0200452
Victor Stinner85f5a692020-03-09 22:12:04 +0100453 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinnere838a932020-05-05 19:56:48 +0200454#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
455 (void)_PyThreadState_Swap(gilstate, tstate);
456#else
Victor Stinner85f5a692020-03-09 22:12:04 +0100457 if (_PyThreadState_Swap(gilstate, tstate) != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100458 Py_FatalError("non-NULL old thread state");
Victor Stinner09532fe2019-05-10 23:39:09 +0200459 }
Victor Stinnere838a932020-05-05 19:56:48 +0200460#endif
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000461}
462
463void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000464PyEval_ReleaseThread(PyThreadState *tstate)
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000465{
Victor Stinnerda2914d2020-03-20 09:29:08 +0100466 assert(is_tstate_valid(tstate));
Victor Stinner09532fe2019-05-10 23:39:09 +0200467
Victor Stinner01b1cc12019-11-20 02:27:56 +0100468 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner09532fe2019-05-10 23:39:09 +0200469 PyThreadState *new_tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
470 if (new_tstate != tstate) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100471 Py_FatalError("wrong thread state");
Victor Stinner09532fe2019-05-10 23:39:09 +0200472 }
Victor Stinner0b1e3302020-05-05 16:14:31 +0200473 struct _ceval_runtime_state *ceval = &runtime->ceval;
474 struct _ceval_state *ceval2 = &tstate->interp->ceval;
475 drop_gil(ceval, ceval2, tstate);
Guido van Rossum9cc8a201997-07-19 19:55:50 +0000476}
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000477
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900478#ifdef HAVE_FORK
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200479/* This function is called from PyOS_AfterFork_Child to destroy all threads
Victor Stinner26881c82020-06-02 15:51:37 +0200480 which are not running in the child process, and clear internal locks
481 which might be held by those threads. */
482PyStatus
Victor Stinner317bab02020-06-02 18:44:54 +0200483_PyEval_ReInitThreads(PyThreadState *tstate)
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000484{
Victor Stinner317bab02020-06-02 18:44:54 +0200485 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner7be4e352020-05-05 20:27:47 +0200486
487#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
488 struct _gil_runtime_state *gil = &tstate->interp->ceval.gil;
489#else
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100490 struct _gil_runtime_state *gil = &runtime->ceval.gil;
Victor Stinner7be4e352020-05-05 20:27:47 +0200491#endif
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100492 if (!gil_created(gil)) {
Victor Stinner26881c82020-06-02 15:51:37 +0200493 return _PyStatus_OK();
Victor Stinner09532fe2019-05-10 23:39:09 +0200494 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100495 recreate_gil(gil);
Victor Stinner85f5a692020-03-09 22:12:04 +0100496
497 take_gil(tstate);
Eric Snow8479a342019-03-08 23:44:33 -0700498
Victor Stinner50e6e992020-03-19 02:41:21 +0100499 struct _pending_calls *pending = &tstate->interp->ceval.pending;
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900500 if (_PyThread_at_fork_reinit(&pending->lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200501 return _PyStatus_ERR("Can't reinitialize pending calls lock");
Eric Snow8479a342019-03-08 23:44:33 -0700502 }
Jesse Nollera8513972008-07-17 16:49:17 +0000503
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200504 /* Destroy all threads except the current one */
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100505 _PyThreadState_DeleteExcept(runtime, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200506 return _PyStatus_OK();
Guido van Rossumfee3a2d2000-08-27 17:34:07 +0000507}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900508#endif
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000509
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000510/* This function is used to signal that async exceptions are waiting to be
Zackery Spytzeef05962018-09-29 10:07:11 -0600511 raised. */
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000512
513void
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100514_PyEval_SignalAsyncExc(PyInterpreterState *interp)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000515{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100516 SIGNAL_ASYNC_EXC(interp);
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000517}
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000518
Guido van Rossum2fca21f71997-07-18 23:56:58 +0000519PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000520PyEval_SaveThread(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000521{
Victor Stinner09532fe2019-05-10 23:39:09 +0200522 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnere838a932020-05-05 19:56:48 +0200523#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
524 PyThreadState *old_tstate = _PyThreadState_GET();
525 PyThreadState *tstate = _PyThreadState_Swap(&runtime->gilstate, old_tstate);
526#else
Victor Stinner09532fe2019-05-10 23:39:09 +0200527 PyThreadState *tstate = _PyThreadState_Swap(&runtime->gilstate, NULL);
Victor Stinnere838a932020-05-05 19:56:48 +0200528#endif
Victor Stinner3026cad2020-06-01 16:02:40 +0200529 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnerda2914d2020-03-20 09:29:08 +0100530
Victor Stinner0b1e3302020-05-05 16:14:31 +0200531 struct _ceval_runtime_state *ceval = &runtime->ceval;
532 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinner7be4e352020-05-05 20:27:47 +0200533#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
534 assert(gil_created(&ceval2->gil));
535#else
Victor Stinnere225beb2019-06-03 18:14:24 +0200536 assert(gil_created(&ceval->gil));
Victor Stinner7be4e352020-05-05 20:27:47 +0200537#endif
Victor Stinner0b1e3302020-05-05 16:14:31 +0200538 drop_gil(ceval, ceval2, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return tstate;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000540}
541
542void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000543PyEval_RestoreThread(PyThreadState *tstate)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000544{
Victor Stinner3026cad2020-06-01 16:02:40 +0200545 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnereb4e2ae2020-03-08 11:57:45 +0100546
Victor Stinner85f5a692020-03-09 22:12:04 +0100547 take_gil(tstate);
Victor Stinner17c68b82020-01-30 12:20:48 +0100548
Victor Stinner85f5a692020-03-09 22:12:04 +0100549 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
550 _PyThreadState_Swap(gilstate, tstate);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000551}
552
553
Guido van Rossuma9672091994-09-14 13:31:22 +0000554/* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
555 signal handlers or Mac I/O completion routines) can schedule calls
556 to a function to be called synchronously.
557 The synchronous function is called with one void* argument.
558 It should return 0 for success or -1 for failure -- failure should
559 be accompanied by an exception.
560
561 If registry succeeds, the registry function returns 0; if it fails
562 (e.g. due to too many pending calls) it returns -1 (without setting
563 an exception condition).
564
565 Note that because registry may occur from within signal handlers,
566 or other asynchronous events, calling malloc() is unsafe!
567
Guido van Rossuma9672091994-09-14 13:31:22 +0000568 Any thread can schedule pending calls, but only the main thread
569 will execute them.
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000570 There is no facility to schedule calls to a particular thread, but
571 that should be easy to change, should that ever be required. In
572 that case, the static variables here should go into the python
573 threadstate.
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000574*/
Guido van Rossuma9672091994-09-14 13:31:22 +0000575
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200576void
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200577_PyEval_SignalReceived(PyInterpreterState *interp)
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200578{
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100579#ifdef MS_WINDOWS
580 // bpo-42296: On Windows, _PyEval_SignalReceived() is called from a signal
581 // handler which can run in a thread different than the Python thread, in
582 // which case _Py_ThreadCanHandleSignals() is wrong. Ignore
583 // _Py_ThreadCanHandleSignals() and always set eval_breaker to 1.
584 //
585 // The next eval_frame_handle_pending() call will call
586 // _Py_ThreadCanHandleSignals() to recompute eval_breaker.
587 int force = 1;
588#else
589 int force = 0;
590#endif
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200591 /* bpo-30703: Function called when the C signal handler of Python gets a
Victor Stinner50e6e992020-03-19 02:41:21 +0100592 signal. We cannot queue a callback using _PyEval_AddPendingCall() since
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200593 that function is not async-signal-safe. */
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100594 SIGNAL_PENDING_SIGNALS(interp, force);
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200595}
596
Eric Snow5be45a62019-03-08 22:47:07 -0700597/* Push one item onto the queue while holding the lock. */
598static int
Victor Stinnere225beb2019-06-03 18:14:24 +0200599_push_pending_call(struct _pending_calls *pending,
Eric Snow842a2f02019-03-15 15:47:51 -0600600 int (*func)(void *), void *arg)
Eric Snow5be45a62019-03-08 22:47:07 -0700601{
Eric Snow842a2f02019-03-15 15:47:51 -0600602 int i = pending->last;
Eric Snow5be45a62019-03-08 22:47:07 -0700603 int j = (i + 1) % NPENDINGCALLS;
Eric Snow842a2f02019-03-15 15:47:51 -0600604 if (j == pending->first) {
Eric Snow5be45a62019-03-08 22:47:07 -0700605 return -1; /* Queue full */
606 }
Eric Snow842a2f02019-03-15 15:47:51 -0600607 pending->calls[i].func = func;
608 pending->calls[i].arg = arg;
609 pending->last = j;
Eric Snow5be45a62019-03-08 22:47:07 -0700610 return 0;
611}
612
613/* Pop one item off the queue while holding the lock. */
614static void
Victor Stinnere225beb2019-06-03 18:14:24 +0200615_pop_pending_call(struct _pending_calls *pending,
Eric Snow842a2f02019-03-15 15:47:51 -0600616 int (**func)(void *), void **arg)
Eric Snow5be45a62019-03-08 22:47:07 -0700617{
Eric Snow842a2f02019-03-15 15:47:51 -0600618 int i = pending->first;
619 if (i == pending->last) {
Eric Snow5be45a62019-03-08 22:47:07 -0700620 return; /* Queue empty */
621 }
622
Eric Snow842a2f02019-03-15 15:47:51 -0600623 *func = pending->calls[i].func;
624 *arg = pending->calls[i].arg;
625 pending->first = (i + 1) % NPENDINGCALLS;
Eric Snow5be45a62019-03-08 22:47:07 -0700626}
627
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200628/* This implementation is thread-safe. It allows
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000629 scheduling to be made from any thread, and even from an executing
630 callback.
631 */
632
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000633int
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200634_PyEval_AddPendingCall(PyInterpreterState *interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200635 int (*func)(void *), void *arg)
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000636{
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200637 struct _pending_calls *pending = &interp->ceval.pending;
Eric Snow842a2f02019-03-15 15:47:51 -0600638
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200639 /* Ensure that _PyEval_InitPendingCalls() was called
640 and that _PyEval_FiniPendingCalls() is not called yet. */
641 assert(pending->lock != NULL);
642
Eric Snow842a2f02019-03-15 15:47:51 -0600643 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
Victor Stinnere225beb2019-06-03 18:14:24 +0200644 int result = _push_pending_call(pending, func, arg);
Eric Snow842a2f02019-03-15 15:47:51 -0600645 PyThread_release_lock(pending->lock);
Eric Snow5be45a62019-03-08 22:47:07 -0700646
Victor Stinnere225beb2019-06-03 18:14:24 +0200647 /* signal main loop */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200648 SIGNAL_PENDING_CALLS(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 return result;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000650}
651
Victor Stinner09532fe2019-05-10 23:39:09 +0200652int
653Py_AddPendingCall(int (*func)(void *), void *arg)
654{
Victor Stinner50e6e992020-03-19 02:41:21 +0100655 /* Best-effort to support subinterpreters and calls with the GIL released.
656
657 First attempt _PyThreadState_GET() since it supports subinterpreters.
658
659 If the GIL is released, _PyThreadState_GET() returns NULL . In this
660 case, use PyGILState_GetThisThreadState() which works even if the GIL
661 is released.
662
663 Sadly, PyGILState_GetThisThreadState() doesn't support subinterpreters:
664 see bpo-10915 and bpo-15751.
665
Victor Stinner8849e592020-03-18 19:28:53 +0100666 Py_AddPendingCall() doesn't require the caller to hold the GIL. */
Victor Stinner50e6e992020-03-19 02:41:21 +0100667 PyThreadState *tstate = _PyThreadState_GET();
668 if (tstate == NULL) {
669 tstate = PyGILState_GetThisThreadState();
670 }
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200671
672 PyInterpreterState *interp;
673 if (tstate != NULL) {
674 interp = tstate->interp;
675 }
676 else {
677 /* Last resort: use the main interpreter */
678 interp = _PyRuntime.interpreters.main;
679 }
680 return _PyEval_AddPendingCall(interp, func, arg);
Victor Stinner09532fe2019-05-10 23:39:09 +0200681}
682
Eric Snowfdf282d2019-01-11 14:26:55 -0700683static int
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100684handle_signals(PyThreadState *tstate)
Eric Snowfdf282d2019-01-11 14:26:55 -0700685{
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200686 assert(is_tstate_valid(tstate));
687 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Eric Snow64d6cc82019-02-23 15:40:43 -0700688 return 0;
689 }
Eric Snowfdf282d2019-01-11 14:26:55 -0700690
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200691 UNSIGNAL_PENDING_SIGNALS(tstate->interp);
Victor Stinner72818982020-03-26 22:28:11 +0100692 if (_PyErr_CheckSignalsTstate(tstate) < 0) {
693 /* On failure, re-schedule a call to handle_signals(). */
Victor Stinnerd96a7a82020-11-13 14:44:42 +0100694 SIGNAL_PENDING_SIGNALS(tstate->interp, 0);
Eric Snowfdf282d2019-01-11 14:26:55 -0700695 return -1;
696 }
697 return 0;
698}
699
700static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100701make_pending_calls(PyInterpreterState *interp)
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000702{
Victor Stinnerd8316882020-03-20 14:50:35 +0100703 /* only execute pending calls on main thread */
704 if (!_Py_ThreadCanHandlePendingCalls()) {
Victor Stinnere225beb2019-06-03 18:14:24 +0200705 return 0;
706 }
707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 /* don't perform recursive pending calls */
Victor Stinnerda2914d2020-03-20 09:29:08 +0100709 static int busy = 0;
Eric Snowfdf282d2019-01-11 14:26:55 -0700710 if (busy) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 return 0;
Eric Snowfdf282d2019-01-11 14:26:55 -0700712 }
Charles-François Natalif23339a2011-07-23 18:15:43 +0200713 busy = 1;
Victor Stinnerda2914d2020-03-20 09:29:08 +0100714
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200715 /* unsignal before starting to call callbacks, so that any callback
716 added in-between re-signals */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100717 UNSIGNAL_PENDING_CALLS(interp);
Eric Snowfdf282d2019-01-11 14:26:55 -0700718 int res = 0;
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 /* perform a bounded number of calls, in case of recursion */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100721 struct _pending_calls *pending = &interp->ceval.pending;
Eric Snowfdf282d2019-01-11 14:26:55 -0700722 for (int i=0; i<NPENDINGCALLS; i++) {
Eric Snow5be45a62019-03-08 22:47:07 -0700723 int (*func)(void *) = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 void *arg = NULL;
725
726 /* pop one item off the queue while holding the lock */
Eric Snow842a2f02019-03-15 15:47:51 -0600727 PyThread_acquire_lock(pending->lock, WAIT_LOCK);
Victor Stinnere225beb2019-06-03 18:14:24 +0200728 _pop_pending_call(pending, &func, &arg);
Eric Snow842a2f02019-03-15 15:47:51 -0600729 PyThread_release_lock(pending->lock);
Eric Snow5be45a62019-03-08 22:47:07 -0700730
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100731 /* having released the lock, perform the callback */
Eric Snow5be45a62019-03-08 22:47:07 -0700732 if (func == NULL) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100733 break;
Eric Snow5be45a62019-03-08 22:47:07 -0700734 }
Eric Snowfdf282d2019-01-11 14:26:55 -0700735 res = func(arg);
736 if (res) {
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200737 goto error;
738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200740
Charles-François Natalif23339a2011-07-23 18:15:43 +0200741 busy = 0;
Eric Snowfdf282d2019-01-11 14:26:55 -0700742 return res;
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200743
744error:
745 busy = 0;
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100746 SIGNAL_PENDING_CALLS(interp);
Eric Snowfdf282d2019-01-11 14:26:55 -0700747 return res;
748}
749
Eric Snow842a2f02019-03-15 15:47:51 -0600750void
Victor Stinner2b1df452020-01-13 18:46:59 +0100751_Py_FinishPendingCalls(PyThreadState *tstate)
Eric Snow842a2f02019-03-15 15:47:51 -0600752{
Eric Snow842a2f02019-03-15 15:47:51 -0600753 assert(PyGILState_Check());
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100754 assert(is_tstate_valid(tstate));
Eric Snow842a2f02019-03-15 15:47:51 -0600755
Victor Stinner50e6e992020-03-19 02:41:21 +0100756 struct _pending_calls *pending = &tstate->interp->ceval.pending;
Victor Stinner09532fe2019-05-10 23:39:09 +0200757
Eric Snow842a2f02019-03-15 15:47:51 -0600758 if (!_Py_atomic_load_relaxed(&(pending->calls_to_do))) {
759 return;
760 }
761
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100762 if (make_pending_calls(tstate->interp) < 0) {
Victor Stinnere225beb2019-06-03 18:14:24 +0200763 PyObject *exc, *val, *tb;
764 _PyErr_Fetch(tstate, &exc, &val, &tb);
765 PyErr_BadInternalCall();
766 _PyErr_ChainExceptions(exc, val, tb);
767 _PyErr_Print(tstate);
Eric Snow842a2f02019-03-15 15:47:51 -0600768 }
769}
770
Eric Snowfdf282d2019-01-11 14:26:55 -0700771/* Py_MakePendingCalls() is a simple wrapper for the sake
772 of backward-compatibility. */
773int
774Py_MakePendingCalls(void)
775{
776 assert(PyGILState_Check());
777
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100778 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100779 assert(is_tstate_valid(tstate));
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100780
Eric Snowfdf282d2019-01-11 14:26:55 -0700781 /* Python signal handler doesn't really queue a callback: it only signals
782 that a signal was received, see _PyEval_SignalReceived(). */
Victor Stinnerd7fabc12020-03-18 01:56:21 +0100783 int res = handle_signals(tstate);
Eric Snowfdf282d2019-01-11 14:26:55 -0700784 if (res != 0) {
785 return res;
786 }
787
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100788 res = make_pending_calls(tstate->interp);
Eric Snowb75b1a352019-04-12 10:20:10 -0600789 if (res != 0) {
790 return res;
791 }
792
793 return 0;
Benjamin Petersone5bf3832009-01-17 23:43:58 +0000794}
795
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000796/* The interpreter's recursion limit */
797
Hye-Shik Changb6fa2812005-04-04 15:49:02 +0000798#ifndef Py_DEFAULT_RECURSION_LIMIT
Victor Stinner19c3ac92020-09-23 14:04:57 +0200799# define Py_DEFAULT_RECURSION_LIMIT 1000
Hye-Shik Changb6fa2812005-04-04 15:49:02 +0000800#endif
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600801
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600802void
Victor Stinnerdab84232020-03-17 18:56:44 +0100803_PyEval_InitRuntimeState(struct _ceval_runtime_state *ceval)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600804{
Victor Stinner7be4e352020-05-05 20:27:47 +0200805#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinnerdab84232020-03-17 18:56:44 +0100806 _gil_initialize(&ceval->gil);
Victor Stinner7be4e352020-05-05 20:27:47 +0200807#endif
Victor Stinnerdab84232020-03-17 18:56:44 +0100808}
809
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200810int
Victor Stinnerdab84232020-03-17 18:56:44 +0100811_PyEval_InitState(struct _ceval_state *ceval)
812{
Victor Stinner4e30ed32020-05-05 16:52:52 +0200813 ceval->recursion_limit = Py_DEFAULT_RECURSION_LIMIT;
814
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200815 struct _pending_calls *pending = &ceval->pending;
816 assert(pending->lock == NULL);
817
818 pending->lock = PyThread_allocate_lock();
819 if (pending->lock == NULL) {
820 return -1;
821 }
Victor Stinner7be4e352020-05-05 20:27:47 +0200822
823#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
824 _gil_initialize(&ceval->gil);
825#endif
826
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200827 return 0;
828}
829
830void
831_PyEval_FiniState(struct _ceval_state *ceval)
832{
833 struct _pending_calls *pending = &ceval->pending;
834 if (pending->lock != NULL) {
835 PyThread_free_lock(pending->lock);
836 pending->lock = NULL;
837 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600838}
839
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000840int
841Py_GetRecursionLimit(void)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000842{
Victor Stinner1bcc32f2020-06-10 20:08:26 +0200843 PyInterpreterState *interp = _PyInterpreterState_GET();
844 return interp->ceval.recursion_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000845}
846
Vladimir Marangozov7bd25be2000-09-01 11:07:19 +0000847void
848Py_SetRecursionLimit(int new_limit)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000849{
Victor Stinner4e30ed32020-05-05 16:52:52 +0200850 PyThreadState *tstate = _PyThreadState_GET();
851 tstate->interp->ceval.recursion_limit = new_limit;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000852}
853
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100854/* The function _Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
Victor Stinner19c3ac92020-09-23 14:04:57 +0200855 if the recursion_depth reaches recursion_limit.
856 If USE_STACKCHECK, the macro decrements recursion_limit
Armin Rigo2b3eb402003-10-28 12:05:48 +0000857 to guarantee that _Py_CheckRecursiveCall() is regularly called.
858 Without USE_STACKCHECK, there is no need for this. */
859int
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100860_Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
Armin Rigo2b3eb402003-10-28 12:05:48 +0000861{
Victor Stinner4e30ed32020-05-05 16:52:52 +0200862 int recursion_limit = tstate->interp->ceval.recursion_limit;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000863
864#ifdef USE_STACKCHECK
pdox18967932017-10-25 23:03:01 -0700865 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (PyOS_CheckStack()) {
867 --tstate->recursion_depth;
Victor Stinner438a12d2019-05-24 17:01:38 +0200868 _PyErr_SetString(tstate, PyExc_MemoryError, "Stack overflow");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 return -1;
870 }
pdox18967932017-10-25 23:03:01 -0700871#endif
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000872 if (tstate->recursion_headroom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (tstate->recursion_depth > recursion_limit + 50) {
874 /* Overflowing while handling an overflow. Give up. */
875 Py_FatalError("Cannot recover from stack overflow.");
876 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 }
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000878 else {
879 if (tstate->recursion_depth > recursion_limit) {
880 tstate->recursion_headroom++;
881 _PyErr_Format(tstate, PyExc_RecursionError,
882 "maximum recursion depth exceeded%s",
883 where);
884 tstate->recursion_headroom--;
885 --tstate->recursion_depth;
886 return -1;
887 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 }
889 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000890}
891
Brandt Bucher145bf262021-02-26 14:51:55 -0800892
893// PEP 634: Structural Pattern Matching
894
895
896// Return a tuple of values corresponding to keys, with error checks for
897// duplicate/missing keys.
898static PyObject*
899match_keys(PyThreadState *tstate, PyObject *map, PyObject *keys)
900{
901 assert(PyTuple_CheckExact(keys));
902 Py_ssize_t nkeys = PyTuple_GET_SIZE(keys);
903 if (!nkeys) {
904 // No keys means no items.
905 return PyTuple_New(0);
906 }
907 PyObject *seen = NULL;
908 PyObject *dummy = NULL;
909 PyObject *values = NULL;
910 // We use the two argument form of map.get(key, default) for two reasons:
911 // - Atomically check for a key and get its value without error handling.
912 // - Don't cause key creation or resizing in dict subclasses like
913 // collections.defaultdict that define __missing__ (or similar).
914 _Py_IDENTIFIER(get);
915 PyObject *get = _PyObject_GetAttrId(map, &PyId_get);
916 if (get == NULL) {
917 goto fail;
918 }
919 seen = PySet_New(NULL);
920 if (seen == NULL) {
921 goto fail;
922 }
923 // dummy = object()
924 dummy = _PyObject_CallNoArg((PyObject *)&PyBaseObject_Type);
925 if (dummy == NULL) {
926 goto fail;
927 }
928 values = PyList_New(0);
929 if (values == NULL) {
930 goto fail;
931 }
932 for (Py_ssize_t i = 0; i < nkeys; i++) {
933 PyObject *key = PyTuple_GET_ITEM(keys, i);
934 if (PySet_Contains(seen, key) || PySet_Add(seen, key)) {
935 if (!_PyErr_Occurred(tstate)) {
936 // Seen it before!
937 _PyErr_Format(tstate, PyExc_ValueError,
938 "mapping pattern checks duplicate key (%R)", key);
939 }
940 goto fail;
941 }
942 PyObject *value = PyObject_CallFunctionObjArgs(get, key, dummy, NULL);
943 if (value == NULL) {
944 goto fail;
945 }
946 if (value == dummy) {
947 // key not in map!
948 Py_DECREF(value);
949 Py_DECREF(values);
950 // Return None:
951 Py_INCREF(Py_None);
952 values = Py_None;
953 goto done;
954 }
955 PyList_Append(values, value);
956 Py_DECREF(value);
957 }
958 Py_SETREF(values, PyList_AsTuple(values));
959 // Success:
960done:
961 Py_DECREF(get);
962 Py_DECREF(seen);
963 Py_DECREF(dummy);
964 return values;
965fail:
966 Py_XDECREF(get);
967 Py_XDECREF(seen);
968 Py_XDECREF(dummy);
969 Py_XDECREF(values);
970 return NULL;
971}
972
973// Extract a named attribute from the subject, with additional bookkeeping to
974// raise TypeErrors for repeated lookups. On failure, return NULL (with no
975// error set). Use _PyErr_Occurred(tstate) to disambiguate.
976static PyObject*
977match_class_attr(PyThreadState *tstate, PyObject *subject, PyObject *type,
978 PyObject *name, PyObject *seen)
979{
980 assert(PyUnicode_CheckExact(name));
981 assert(PySet_CheckExact(seen));
982 if (PySet_Contains(seen, name) || PySet_Add(seen, name)) {
983 if (!_PyErr_Occurred(tstate)) {
984 // Seen it before!
985 _PyErr_Format(tstate, PyExc_TypeError,
986 "%s() got multiple sub-patterns for attribute %R",
987 ((PyTypeObject*)type)->tp_name, name);
988 }
989 return NULL;
990 }
991 PyObject *attr = PyObject_GetAttr(subject, name);
992 if (attr == NULL && _PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
993 _PyErr_Clear(tstate);
994 }
995 return attr;
996}
997
998// On success (match), return a tuple of extracted attributes. On failure (no
999// match), return NULL. Use _PyErr_Occurred(tstate) to disambiguate.
1000static PyObject*
1001match_class(PyThreadState *tstate, PyObject *subject, PyObject *type,
1002 Py_ssize_t nargs, PyObject *kwargs)
1003{
1004 if (!PyType_Check(type)) {
1005 const char *e = "called match pattern must be a type";
1006 _PyErr_Format(tstate, PyExc_TypeError, e);
1007 return NULL;
1008 }
1009 assert(PyTuple_CheckExact(kwargs));
1010 // First, an isinstance check:
1011 if (PyObject_IsInstance(subject, type) <= 0) {
1012 return NULL;
1013 }
1014 // So far so good:
1015 PyObject *seen = PySet_New(NULL);
1016 if (seen == NULL) {
1017 return NULL;
1018 }
1019 PyObject *attrs = PyList_New(0);
1020 if (attrs == NULL) {
1021 Py_DECREF(seen);
1022 return NULL;
1023 }
1024 // NOTE: From this point on, goto fail on failure:
1025 PyObject *match_args = NULL;
1026 // First, the positional subpatterns:
1027 if (nargs) {
1028 int match_self = 0;
1029 match_args = PyObject_GetAttrString(type, "__match_args__");
1030 if (match_args) {
Brandt Bucher145bf262021-02-26 14:51:55 -08001031 if (!PyTuple_CheckExact(match_args)) {
Brandt Bucherf84d5a12021-04-05 19:17:08 -07001032 const char *e = "%s.__match_args__ must be a tuple (got %s)";
Brandt Bucher145bf262021-02-26 14:51:55 -08001033 _PyErr_Format(tstate, PyExc_TypeError, e,
1034 ((PyTypeObject *)type)->tp_name,
1035 Py_TYPE(match_args)->tp_name);
1036 goto fail;
1037 }
1038 }
1039 else if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
1040 _PyErr_Clear(tstate);
1041 // _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
1042 // define __match_args__. This is natural behavior for subclasses:
1043 // it's as if __match_args__ is some "magic" value that is lost as
1044 // soon as they redefine it.
1045 match_args = PyTuple_New(0);
1046 match_self = PyType_HasFeature((PyTypeObject*)type,
1047 _Py_TPFLAGS_MATCH_SELF);
1048 }
1049 else {
1050 goto fail;
1051 }
1052 assert(PyTuple_CheckExact(match_args));
1053 Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
1054 if (allowed < nargs) {
1055 const char *plural = (allowed == 1) ? "" : "s";
1056 _PyErr_Format(tstate, PyExc_TypeError,
1057 "%s() accepts %d positional sub-pattern%s (%d given)",
1058 ((PyTypeObject*)type)->tp_name,
1059 allowed, plural, nargs);
1060 goto fail;
1061 }
1062 if (match_self) {
1063 // Easy. Copy the subject itself, and move on to kwargs.
1064 PyList_Append(attrs, subject);
1065 }
1066 else {
1067 for (Py_ssize_t i = 0; i < nargs; i++) {
1068 PyObject *name = PyTuple_GET_ITEM(match_args, i);
1069 if (!PyUnicode_CheckExact(name)) {
1070 _PyErr_Format(tstate, PyExc_TypeError,
1071 "__match_args__ elements must be strings "
1072 "(got %s)", Py_TYPE(name)->tp_name);
1073 goto fail;
1074 }
1075 PyObject *attr = match_class_attr(tstate, subject, type, name,
1076 seen);
1077 if (attr == NULL) {
1078 goto fail;
1079 }
1080 PyList_Append(attrs, attr);
1081 Py_DECREF(attr);
1082 }
1083 }
1084 Py_CLEAR(match_args);
1085 }
1086 // Finally, the keyword subpatterns:
1087 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
1088 PyObject *name = PyTuple_GET_ITEM(kwargs, i);
1089 PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
1090 if (attr == NULL) {
1091 goto fail;
1092 }
1093 PyList_Append(attrs, attr);
1094 Py_DECREF(attr);
1095 }
1096 Py_SETREF(attrs, PyList_AsTuple(attrs));
1097 Py_DECREF(seen);
1098 return attrs;
1099fail:
1100 // We really don't care whether an error was raised or not... that's our
1101 // caller's problem. All we know is that the match failed.
1102 Py_XDECREF(match_args);
1103 Py_DECREF(seen);
1104 Py_DECREF(attrs);
1105 return NULL;
1106}
1107
1108
Victor Stinner09532fe2019-05-10 23:39:09 +02001109static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
Victor Stinner438a12d2019-05-24 17:01:38 +02001110static int unpack_iterable(PyThreadState *, PyObject *, int, int, PyObject **);
Guido van Rossum1aa14831997-01-21 05:34:20 +00001111
Victor Stinnere225beb2019-06-03 18:14:24 +02001112#define _Py_TracingPossible(ceval) ((ceval)->tracing_possible)
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001113
Guido van Rossum374a9221991-04-04 10:40:29 +00001114
Guido van Rossumb209a111997-04-29 18:18:01 +00001115PyObject *
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001116PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001117{
Victor Stinner46496f92021-02-20 15:17:18 +01001118 PyThreadState *tstate = PyThreadState_GET();
Mark Shannon0332e562021-02-01 10:42:03 +00001119 if (locals == NULL) {
1120 locals = globals;
1121 }
Victor Stinnerfc980e02021-03-18 14:51:24 +01001122 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Mark Shannon0332e562021-02-01 10:42:03 +00001123 if (builtins == NULL) {
1124 return NULL;
1125 }
1126 PyFrameConstructor desc = {
1127 .fc_globals = globals,
1128 .fc_builtins = builtins,
1129 .fc_name = ((PyCodeObject *)co)->co_name,
1130 .fc_qualname = ((PyCodeObject *)co)->co_name,
1131 .fc_code = co,
1132 .fc_defaults = NULL,
1133 .fc_kwdefaults = NULL,
1134 .fc_closure = NULL
1135 };
Victor Stinner46496f92021-02-20 15:17:18 +01001136 return _PyEval_Vector(tstate, &desc, locals, NULL, 0, NULL);
Guido van Rossum681d79a1995-07-18 14:51:37 +00001137}
1138
1139
1140/* Interpreter main loop */
1141
Martin v. Löwis8d97e332004-06-27 15:43:12 +00001142PyObject *
Victor Stinnerb9e68122019-11-14 12:20:46 +01001143PyEval_EvalFrame(PyFrameObject *f)
1144{
Victor Stinner0b72b232020-03-12 23:18:39 +01001145 /* Function kept for backward compatibility */
Victor Stinnerb9e68122019-11-14 12:20:46 +01001146 PyThreadState *tstate = _PyThreadState_GET();
1147 return _PyEval_EvalFrame(tstate, f, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00001148}
1149
1150PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001151PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Guido van Rossum374a9221991-04-04 10:40:29 +00001152{
Victor Stinnerb9e68122019-11-14 12:20:46 +01001153 PyThreadState *tstate = _PyThreadState_GET();
1154 return _PyEval_EvalFrame(tstate, f, throwflag);
Brett Cannon3cebf932016-09-05 15:33:46 -07001155}
1156
Victor Stinnerda2914d2020-03-20 09:29:08 +01001157
1158/* Handle signals, pending calls, GIL drop request
1159 and asynchronous exception */
1160static int
1161eval_frame_handle_pending(PyThreadState *tstate)
1162{
Victor Stinnerda2914d2020-03-20 09:29:08 +01001163 _PyRuntimeState * const runtime = &_PyRuntime;
1164 struct _ceval_runtime_state *ceval = &runtime->ceval;
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001165
1166 /* Pending signals */
Victor Stinner299b8c62020-05-05 17:40:18 +02001167 if (_Py_atomic_load_relaxed(&ceval->signals_pending)) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001168 if (handle_signals(tstate) != 0) {
1169 return -1;
1170 }
1171 }
1172
1173 /* Pending calls */
Victor Stinner299b8c62020-05-05 17:40:18 +02001174 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinnerda2914d2020-03-20 09:29:08 +01001175 if (_Py_atomic_load_relaxed(&ceval2->pending.calls_to_do)) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001176 if (make_pending_calls(tstate->interp) != 0) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001177 return -1;
1178 }
1179 }
1180
1181 /* GIL drop request */
Victor Stinner0b1e3302020-05-05 16:14:31 +02001182 if (_Py_atomic_load_relaxed(&ceval2->gil_drop_request)) {
Victor Stinnerda2914d2020-03-20 09:29:08 +01001183 /* Give another thread a chance */
1184 if (_PyThreadState_Swap(&runtime->gilstate, NULL) != tstate) {
1185 Py_FatalError("tstate mix-up");
1186 }
Victor Stinner0b1e3302020-05-05 16:14:31 +02001187 drop_gil(ceval, ceval2, tstate);
Victor Stinnerda2914d2020-03-20 09:29:08 +01001188
1189 /* Other threads may run now */
1190
1191 take_gil(tstate);
1192
Victor Stinnere838a932020-05-05 19:56:48 +02001193#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1194 (void)_PyThreadState_Swap(&runtime->gilstate, tstate);
1195#else
Victor Stinnerda2914d2020-03-20 09:29:08 +01001196 if (_PyThreadState_Swap(&runtime->gilstate, tstate) != NULL) {
1197 Py_FatalError("orphan tstate");
1198 }
Victor Stinnere838a932020-05-05 19:56:48 +02001199#endif
Victor Stinnerda2914d2020-03-20 09:29:08 +01001200 }
1201
1202 /* Check for asynchronous exception. */
1203 if (tstate->async_exc != NULL) {
1204 PyObject *exc = tstate->async_exc;
1205 tstate->async_exc = NULL;
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001206 UNSIGNAL_ASYNC_EXC(tstate->interp);
Victor Stinnerda2914d2020-03-20 09:29:08 +01001207 _PyErr_SetNone(tstate, exc);
1208 Py_DECREF(exc);
1209 return -1;
1210 }
1211
Victor Stinnerd96a7a82020-11-13 14:44:42 +01001212#ifdef MS_WINDOWS
1213 // bpo-42296: On Windows, _PyEval_SignalReceived() can be called in a
1214 // different thread than the Python thread, in which case
1215 // _Py_ThreadCanHandleSignals() is wrong. Recompute eval_breaker in the
1216 // current Python thread with the correct _Py_ThreadCanHandleSignals()
1217 // value. It prevents to interrupt the eval loop at every instruction if
1218 // the current Python thread cannot handle signals (if
1219 // _Py_ThreadCanHandleSignals() is false).
1220 COMPUTE_EVAL_BREAKER(tstate->interp, ceval, ceval2);
1221#endif
1222
Victor Stinnerda2914d2020-03-20 09:29:08 +01001223 return 0;
1224}
1225
Victor Stinner3c1e4812012-03-26 22:10:51 +02001226
Antoine Pitroub52ec782009-01-25 16:34:23 +00001227/* Computed GOTOs, or
1228 the-optimization-commonly-but-improperly-known-as-"threaded code"
1229 using gcc's labels-as-values extension
1230 (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).
1231
1232 The traditional bytecode evaluation loop uses a "switch" statement, which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 decent compilers will optimize as a single indirect branch instruction
Antoine Pitroub52ec782009-01-25 16:34:23 +00001234 combined with a lookup table of jump addresses. However, since the
1235 indirect jump instruction is shared by all opcodes, the CPU will have a
1236 hard time making the right prediction for where to jump next (actually,
1237 it will be always wrong except in the uncommon case of a sequence of
1238 several identical opcodes).
1239
1240 "Threaded code" in contrast, uses an explicit jump table and an explicit
1241 indirect jump instruction at the end of each opcode. Since the jump
1242 instruction is at a different address for each opcode, the CPU will make a
1243 separate prediction for each of these instructions, which is equivalent to
1244 predicting the second opcode of each opcode pair. These predictions have
1245 a much better chance to turn out valid, especially in small bytecode loops.
1246
1247 A mispredicted branch on a modern CPU flushes the whole pipeline and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 can cost several CPU cycles (depending on the pipeline depth),
Antoine Pitroub52ec782009-01-25 16:34:23 +00001249 and potentially many more instructions (depending on the pipeline width).
1250 A correctly predicted branch, however, is nearly free.
1251
1252 At the time of this writing, the "threaded code" version is up to 15-20%
1253 faster than the normal "switch" version, depending on the compiler and the
1254 CPU architecture.
1255
1256 We disable the optimization if DYNAMIC_EXECUTION_PROFILE is defined,
1257 because it would render the measurements invalid.
1258
1259
1260 NOTE: care must be taken that the compiler doesn't try to "optimize" the
1261 indirect jumps by sharing them between all opcodes. Such optimizations
1262 can be disabled on gcc by using the -fno-gcse flag (or possibly
1263 -fno-crossjumping).
1264*/
1265
Mark Shannon28d28e02021-04-08 11:22:55 +01001266/* Use macros rather than inline functions, to make it as clear as possible
1267 * to the C compiler that the tracing check is a simple test then branch.
1268 * We want to be sure that the compiler knows this before it generates
1269 * the CFG.
1270 */
1271#ifdef LLTRACE
1272#define OR_LLTRACE || lltrace
1273#else
1274#define OR_LLTRACE
1275#endif
1276
1277#ifdef WITH_DTRACE
1278#define OR_DTRACE_LINE || PyDTrace_LINE_ENABLED()
1279#else
1280#define OR_DTRACE_LINE
1281#endif
1282
Antoine Pitrou042b1282010-08-13 21:15:58 +00001283#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitroub52ec782009-01-25 16:34:23 +00001284#undef USE_COMPUTED_GOTOS
Antoine Pitrou042b1282010-08-13 21:15:58 +00001285#define USE_COMPUTED_GOTOS 0
Antoine Pitroub52ec782009-01-25 16:34:23 +00001286#endif
1287
Antoine Pitrou042b1282010-08-13 21:15:58 +00001288#ifdef HAVE_COMPUTED_GOTOS
1289 #ifndef USE_COMPUTED_GOTOS
1290 #define USE_COMPUTED_GOTOS 1
1291 #endif
1292#else
1293 #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
1294 #error "Computed gotos are not supported on this compiler."
1295 #endif
1296 #undef USE_COMPUTED_GOTOS
1297 #define USE_COMPUTED_GOTOS 0
1298#endif
1299
1300#if USE_COMPUTED_GOTOS
Mark Shannon28d28e02021-04-08 11:22:55 +01001301#define TARGET(op) op: TARGET_##op
1302#define DISPATCH_GOTO() goto *opcode_targets[opcode]
Antoine Pitroub52ec782009-01-25 16:34:23 +00001303#else
Benjamin Petersonddd19492018-09-16 22:38:02 -07001304#define TARGET(op) op
Mark Shannon28d28e02021-04-08 11:22:55 +01001305#define DISPATCH_GOTO() goto dispatch_opcode
Antoine Pitroub52ec782009-01-25 16:34:23 +00001306#endif
1307
Mark Shannon28d28e02021-04-08 11:22:55 +01001308#define DISPATCH() \
1309 { \
1310 if (_Py_TracingPossible(ceval2) OR_DTRACE_LINE OR_LLTRACE) { \
1311 goto tracing_dispatch; \
1312 } \
1313 f->f_lasti = INSTR_OFFSET(); \
1314 NEXTOPARG(); \
1315 DISPATCH_GOTO(); \
1316 }
1317
Mark Shannon4958f5d2021-03-24 17:56:12 +00001318#define CHECK_EVAL_BREAKER() \
1319 if (_Py_atomic_load_relaxed(eval_breaker)) { \
1320 continue; \
1321 }
1322
Antoine Pitroub52ec782009-01-25 16:34:23 +00001323
Neal Norwitza81d2202002-07-14 00:27:26 +00001324/* Tuple access macros */
1325
1326#ifndef Py_DEBUG
1327#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
1328#else
1329#define GETITEM(v, i) PyTuple_GetItem((v), (i))
1330#endif
1331
Guido van Rossum374a9221991-04-04 10:40:29 +00001332/* Code access macros */
1333
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001334/* The integer overflow is checked by an assertion below. */
Mark Shannonfcb55c02021-04-01 16:00:31 +01001335#define INSTR_OFFSET() ((int)(next_instr - first_instr))
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001336#define NEXTOPARG() do { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001337 _Py_CODEUNIT word = *next_instr; \
1338 opcode = _Py_OPCODE(word); \
1339 oparg = _Py_OPARG(word); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001340 next_instr++; \
1341 } while (0)
Mark Shannonfcb55c02021-04-01 16:00:31 +01001342#define JUMPTO(x) (next_instr = first_instr + (x))
1343#define JUMPBY(x) (next_instr += (x))
Guido van Rossum374a9221991-04-04 10:40:29 +00001344
Raymond Hettingerf606f872003-03-16 03:11:04 +00001345/* OpCode prediction macros
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Some opcodes tend to come in pairs thus making it possible to
1347 predict the second code when the first is run. For example,
Serhiy Storchakada9c5132016-06-27 18:58:57 +03001348 COMPARE_OP is often followed by POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 Verifying the prediction costs a single high-speed test of a register
1351 variable against a constant. If the pairing was good, then the
1352 processor's own internal branch predication has a high likelihood of
1353 success, resulting in a nearly zero-overhead transition to the
1354 next opcode. A successful prediction saves a trip through the eval-loop
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001355 including its unpredictable switch-case branch. Combined with the
1356 processor's internal branch prediction, a successful PREDICT has the
1357 effect of making the two opcodes run as if they were a single new opcode
1358 with the bodies combined.
Raymond Hettingerf606f872003-03-16 03:11:04 +00001359
Georg Brandl86b2fb92008-07-16 03:43:04 +00001360 If collecting opcode statistics, your choices are to either keep the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 predictions turned-on and interpret the results as if some opcodes
1362 had been combined or turn-off predictions so that the opcode frequency
1363 counter updates for both opcodes.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001364
1365 Opcode prediction is disabled with threaded code, since the latter allows
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 the CPU to record separate branch prediction information for each
1367 opcode.
Antoine Pitroub52ec782009-01-25 16:34:23 +00001368
Raymond Hettingerf606f872003-03-16 03:11:04 +00001369*/
1370
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001371#define PREDICT_ID(op) PRED_##op
1372
Antoine Pitrou042b1282010-08-13 21:15:58 +00001373#if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001374#define PREDICT(op) if (0) goto PREDICT_ID(op)
Raymond Hettingera7216982004-02-08 19:59:27 +00001375#else
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001376#define PREDICT(op) \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001377 do { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001378 _Py_CODEUNIT word = *next_instr; \
1379 opcode = _Py_OPCODE(word); \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001380 if (opcode == op) { \
Serhiy Storchakaab874002016-09-11 13:48:15 +03001381 oparg = _Py_OPARG(word); \
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001382 next_instr++; \
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001383 goto PREDICT_ID(op); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001384 } \
1385 } while(0)
Antoine Pitroub52ec782009-01-25 16:34:23 +00001386#endif
Denis Chernikovbaf29b22020-02-21 12:17:50 +03001387#define PREDICTED(op) PREDICT_ID(op):
Antoine Pitroub52ec782009-01-25 16:34:23 +00001388
Raymond Hettingerf606f872003-03-16 03:11:04 +00001389
Guido van Rossum374a9221991-04-04 10:40:29 +00001390/* Stack manipulation macros */
1391
Martin v. Löwis18e16552006-02-15 17:27:45 +00001392/* The stack can grow at most MAXINT deep, as co_nlocals and
1393 co_stacksize are ints. */
Stefan Krahb7e10102010-06-23 18:42:39 +00001394#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
1395#define EMPTY() (STACK_LEVEL() == 0)
1396#define TOP() (stack_pointer[-1])
1397#define SECOND() (stack_pointer[-2])
1398#define THIRD() (stack_pointer[-3])
1399#define FOURTH() (stack_pointer[-4])
1400#define PEEK(n) (stack_pointer[-(n)])
1401#define SET_TOP(v) (stack_pointer[-1] = (v))
1402#define SET_SECOND(v) (stack_pointer[-2] = (v))
1403#define SET_THIRD(v) (stack_pointer[-3] = (v))
1404#define SET_FOURTH(v) (stack_pointer[-4] = (v))
Stefan Krahb7e10102010-06-23 18:42:39 +00001405#define BASIC_STACKADJ(n) (stack_pointer += n)
1406#define BASIC_PUSH(v) (*stack_pointer++ = (v))
1407#define BASIC_POP() (*--stack_pointer)
Guido van Rossum374a9221991-04-04 10:40:29 +00001408
Guido van Rossum96a42c81992-01-12 02:29:51 +00001409#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410#define PUSH(v) { (void)(BASIC_PUSH(v), \
Victor Stinner438a12d2019-05-24 17:01:38 +02001411 lltrace && prtrace(tstate, TOP(), "push")); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001412 assert(STACK_LEVEL() <= co->co_stacksize); }
Victor Stinner438a12d2019-05-24 17:01:38 +02001413#define POP() ((void)(lltrace && prtrace(tstate, TOP(), "pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001414 BASIC_POP())
costypetrisor8ed317f2018-07-31 20:55:14 +00001415#define STACK_GROW(n) do { \
1416 assert(n >= 0); \
1417 (void)(BASIC_STACKADJ(n), \
Victor Stinner438a12d2019-05-24 17:01:38 +02001418 lltrace && prtrace(tstate, TOP(), "stackadj")); \
costypetrisor8ed317f2018-07-31 20:55:14 +00001419 assert(STACK_LEVEL() <= co->co_stacksize); \
1420 } while (0)
1421#define STACK_SHRINK(n) do { \
1422 assert(n >= 0); \
Victor Stinner438a12d2019-05-24 17:01:38 +02001423 (void)(lltrace && prtrace(tstate, TOP(), "stackadj")); \
costypetrisor8ed317f2018-07-31 20:55:14 +00001424 (void)(BASIC_STACKADJ(-n)); \
1425 assert(STACK_LEVEL() <= co->co_stacksize); \
1426 } while (0)
Christian Heimes0449f632007-12-15 01:27:15 +00001427#define EXT_POP(STACK_POINTER) ((void)(lltrace && \
Victor Stinner438a12d2019-05-24 17:01:38 +02001428 prtrace(tstate, (STACK_POINTER)[-1], "ext_pop")), \
Stefan Krahb7e10102010-06-23 18:42:39 +00001429 *--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001430#else
Stefan Krahb7e10102010-06-23 18:42:39 +00001431#define PUSH(v) BASIC_PUSH(v)
1432#define POP() BASIC_POP()
costypetrisor8ed317f2018-07-31 20:55:14 +00001433#define STACK_GROW(n) BASIC_STACKADJ(n)
1434#define STACK_SHRINK(n) BASIC_STACKADJ(-n)
Guido van Rossumc2e20742006-02-27 22:32:47 +00001435#define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
Guido van Rossum374a9221991-04-04 10:40:29 +00001436#endif
1437
Guido van Rossum681d79a1995-07-18 14:51:37 +00001438/* Local variable macros */
1439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440#define GETLOCAL(i) (fastlocals[i])
Guido van Rossumcfbf1a32002-03-28 20:17:52 +00001441
1442/* The SETLOCAL() macro must not DECREF the local variable in-place and
1443 then store the new value; it must copy the old value to a temporary
1444 value, then store the new value, and then DECREF the temporary value.
1445 This is because it is possible that during the DECREF the frame is
1446 accessed by other code (e.g. a __del__ method or gc.collect()) and the
1447 variable would be pointing to already-freed memory. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
Stefan Krahb7e10102010-06-23 18:42:39 +00001449 GETLOCAL(i) = value; \
1450 Py_XDECREF(tmp); } while (0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00001451
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001452
1453#define UNWIND_BLOCK(b) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 while (STACK_LEVEL() > (b)->b_level) { \
1455 PyObject *v = POP(); \
1456 Py_XDECREF(v); \
1457 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001458
1459#define UNWIND_EXCEPT_HANDLER(b) \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001460 do { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 PyObject *type, *value, *traceback; \
Mark Shannonae3087c2017-10-22 22:41:51 +01001462 _PyErr_StackItem *exc_info; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 assert(STACK_LEVEL() >= (b)->b_level + 3); \
1464 while (STACK_LEVEL() > (b)->b_level + 3) { \
1465 value = POP(); \
1466 Py_XDECREF(value); \
1467 } \
Mark Shannonae3087c2017-10-22 22:41:51 +01001468 exc_info = tstate->exc_info; \
1469 type = exc_info->exc_type; \
1470 value = exc_info->exc_value; \
1471 traceback = exc_info->exc_traceback; \
1472 exc_info->exc_type = POP(); \
1473 exc_info->exc_value = POP(); \
1474 exc_info->exc_traceback = POP(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 Py_XDECREF(type); \
1476 Py_XDECREF(value); \
1477 Py_XDECREF(traceback); \
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001478 } while(0)
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001479
Inada Naoki91234a12019-06-03 21:30:58 +09001480 /* macros for opcode cache */
1481#define OPCACHE_CHECK() \
1482 do { \
1483 co_opcache = NULL; \
1484 if (co->co_opcache != NULL) { \
Pablo Galindo109826c2020-10-20 06:22:44 +01001485 unsigned char co_opcache_offset = \
Inada Naoki91234a12019-06-03 21:30:58 +09001486 co->co_opcache_map[next_instr - first_instr]; \
Pablo Galindo109826c2020-10-20 06:22:44 +01001487 if (co_opcache_offset > 0) { \
1488 assert(co_opcache_offset <= co->co_opcache_size); \
1489 co_opcache = &co->co_opcache[co_opcache_offset - 1]; \
Inada Naoki91234a12019-06-03 21:30:58 +09001490 assert(co_opcache != NULL); \
Inada Naoki91234a12019-06-03 21:30:58 +09001491 } \
1492 } \
1493 } while (0)
1494
Pablo Galindo109826c2020-10-20 06:22:44 +01001495#define OPCACHE_DEOPT() \
1496 do { \
1497 if (co_opcache != NULL) { \
1498 co_opcache->optimized = -1; \
1499 unsigned char co_opcache_offset = \
1500 co->co_opcache_map[next_instr - first_instr]; \
1501 assert(co_opcache_offset <= co->co_opcache_size); \
1502 co->co_opcache_map[co_opcache_offset] = 0; \
1503 co_opcache = NULL; \
1504 } \
1505 } while (0)
1506
1507#define OPCACHE_DEOPT_LOAD_ATTR() \
1508 do { \
1509 if (co_opcache != NULL) { \
1510 OPCACHE_STAT_ATTR_DEOPT(); \
1511 OPCACHE_DEOPT(); \
1512 } \
1513 } while (0)
1514
1515#define OPCACHE_MAYBE_DEOPT_LOAD_ATTR() \
1516 do { \
1517 if (co_opcache != NULL && --co_opcache->optimized <= 0) { \
1518 OPCACHE_DEOPT_LOAD_ATTR(); \
1519 } \
1520 } while (0)
1521
Inada Naoki91234a12019-06-03 21:30:58 +09001522#if OPCACHE_STATS
1523
1524#define OPCACHE_STAT_GLOBAL_HIT() \
1525 do { \
1526 if (co->co_opcache != NULL) opcache_global_hits++; \
1527 } while (0)
1528
1529#define OPCACHE_STAT_GLOBAL_MISS() \
1530 do { \
1531 if (co->co_opcache != NULL) opcache_global_misses++; \
1532 } while (0)
1533
1534#define OPCACHE_STAT_GLOBAL_OPT() \
1535 do { \
1536 if (co->co_opcache != NULL) opcache_global_opts++; \
1537 } while (0)
1538
Pablo Galindo109826c2020-10-20 06:22:44 +01001539#define OPCACHE_STAT_ATTR_HIT() \
1540 do { \
1541 if (co->co_opcache != NULL) opcache_attr_hits++; \
1542 } while (0)
1543
1544#define OPCACHE_STAT_ATTR_MISS() \
1545 do { \
1546 if (co->co_opcache != NULL) opcache_attr_misses++; \
1547 } while (0)
1548
1549#define OPCACHE_STAT_ATTR_OPT() \
1550 do { \
1551 if (co->co_opcache!= NULL) opcache_attr_opts++; \
1552 } while (0)
1553
1554#define OPCACHE_STAT_ATTR_DEOPT() \
1555 do { \
1556 if (co->co_opcache != NULL) opcache_attr_deopts++; \
1557 } while (0)
1558
1559#define OPCACHE_STAT_ATTR_TOTAL() \
1560 do { \
1561 if (co->co_opcache != NULL) opcache_attr_total++; \
1562 } while (0)
1563
Inada Naoki91234a12019-06-03 21:30:58 +09001564#else /* OPCACHE_STATS */
1565
1566#define OPCACHE_STAT_GLOBAL_HIT()
1567#define OPCACHE_STAT_GLOBAL_MISS()
1568#define OPCACHE_STAT_GLOBAL_OPT()
1569
Pablo Galindo109826c2020-10-20 06:22:44 +01001570#define OPCACHE_STAT_ATTR_HIT()
1571#define OPCACHE_STAT_ATTR_MISS()
1572#define OPCACHE_STAT_ATTR_OPT()
1573#define OPCACHE_STAT_ATTR_DEOPT()
1574#define OPCACHE_STAT_ATTR_TOTAL()
1575
Inada Naoki91234a12019-06-03 21:30:58 +09001576#endif
1577
Mark Shannond41bddd2021-03-25 12:00:30 +00001578
1579PyObject* _Py_HOT_FUNCTION
1580_PyEval_EvalFrameDefault(PyThreadState *tstate, PyFrameObject *f, int throwflag)
1581{
1582 _Py_EnsureTstateNotNULL(tstate);
1583
1584#if USE_COMPUTED_GOTOS
1585/* Import the static jump table */
1586#include "opcode_targets.h"
1587#endif
1588
1589#ifdef DXPAIRS
1590 int lastopcode = 0;
1591#endif
1592 PyObject **stack_pointer; /* Next free slot in value stack */
1593 const _Py_CODEUNIT *next_instr;
1594 int opcode; /* Current opcode */
1595 int oparg; /* Current opcode argument, if any */
1596 PyObject **fastlocals, **freevars;
1597 PyObject *retval = NULL; /* Return value */
1598 struct _ceval_state * const ceval2 = &tstate->interp->ceval;
1599 _Py_atomic_int * const eval_breaker = &ceval2->eval_breaker;
1600 PyCodeObject *co;
1601
Mark Shannond41bddd2021-03-25 12:00:30 +00001602 const _Py_CODEUNIT *first_instr;
1603 PyObject *names;
1604 PyObject *consts;
1605 _PyOpcache *co_opcache;
1606
1607#ifdef LLTRACE
1608 _Py_IDENTIFIER(__ltrace__);
1609#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +00001610
Victor Stinnerbe434dc2019-11-05 00:51:22 +01001611 if (_Py_EnterRecursiveCall(tstate, "")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01001613 }
Guido van Rossum8861b741996-07-30 16:49:37 +00001614
Mark Shannon8e1b4062021-03-05 14:45:50 +00001615 PyTraceInfo trace_info;
Mark Shannon28d28e02021-04-08 11:22:55 +01001616 /* Mark trace_info as uninitialized */
Mark Shannon8e1b4062021-03-05 14:45:50 +00001617 trace_info.code = NULL;
1618
1619 /* push frame */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 tstate->frame = f;
Mark Shannon86433452021-01-07 16:49:02 +00001621 co = f->f_code;
Tim Peters5ca576e2001-06-18 22:08:13 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (tstate->use_tracing) {
1624 if (tstate->c_tracefunc != NULL) {
1625 /* tstate->c_tracefunc, if defined, is a
1626 function that will be called on *every* entry
1627 to a code block. Its return value, if not
1628 None, is a function that will be called at
1629 the start of each executed line of code.
1630 (Actually, the function must return itself
1631 in order to continue tracing.) The trace
1632 functions are called with three arguments:
1633 a pointer to the current frame, a string
1634 indicating why the function is called, and
1635 an argument which depends on the situation.
1636 The global trace function is also called
1637 whenever an exception is detected. */
1638 if (call_trace_protected(tstate->c_tracefunc,
1639 tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001640 tstate, f, &trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00001641 PyTrace_CALL, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* Trace function raised an error */
1643 goto exit_eval_frame;
1644 }
1645 }
1646 if (tstate->c_profilefunc != NULL) {
1647 /* Similar for c_profilefunc, except it needn't
1648 return itself and isn't called for "line" events */
1649 if (call_trace_protected(tstate->c_profilefunc,
1650 tstate->c_profileobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001651 tstate, f, &trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00001652 PyTrace_CALL, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 /* Profile function raised an error */
1654 goto exit_eval_frame;
1655 }
1656 }
1657 }
Neil Schemenauer6c0f2002001-09-04 19:03:35 +00001658
Łukasz Langaa785c872016-09-09 17:37:37 -07001659 if (PyDTrace_FUNCTION_ENTRY_ENABLED())
1660 dtrace_function_entry(f);
1661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 names = co->co_names;
1663 consts = co->co_consts;
1664 fastlocals = f->f_localsplus;
1665 freevars = f->f_localsplus + co->co_nlocals;
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03001666 assert(PyBytes_Check(co->co_code));
1667 assert(PyBytes_GET_SIZE(co->co_code) <= INT_MAX);
Serhiy Storchakaab874002016-09-11 13:48:15 +03001668 assert(PyBytes_GET_SIZE(co->co_code) % sizeof(_Py_CODEUNIT) == 0);
1669 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(co->co_code), sizeof(_Py_CODEUNIT)));
1670 first_instr = (_Py_CODEUNIT *) PyBytes_AS_STRING(co->co_code);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001671 /*
1672 f->f_lasti refers to the index of the last instruction,
1673 unless it's -1 in which case next_instr should be first_instr.
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001674
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001675 YIELD_FROM sets f_lasti to itself, in order to repeatedly yield
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05001676 multiple values.
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 When the PREDICT() macros are enabled, some opcode pairs follow in
1679 direct succession without updating f->f_lasti. A successful
1680 prediction effectively links the two codes together as if they
1681 were a single new opcode; accordingly,f->f_lasti will point to
1682 the first code in the pair (for instance, GET_ITER followed by
1683 FOR_ITER is effectively a single opcode and f->f_lasti will point
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001684 to the beginning of the combined pair.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 */
Serhiy Storchakaab874002016-09-11 13:48:15 +03001686 assert(f->f_lasti >= -1);
Mark Shannonfcb55c02021-04-01 16:00:31 +01001687 next_instr = first_instr + f->f_lasti + 1;
Mark Shannoncb9879b2020-07-17 11:44:23 +01001688 stack_pointer = f->f_valuestack + f->f_stackdepth;
1689 /* Set f->f_stackdepth to -1.
1690 * Update when returning or calling trace function.
1691 Having f_stackdepth <= 0 ensures that invalid
1692 values are not visible to the cycle GC.
1693 We choose -1 rather than 0 to assist debugging.
1694 */
1695 f->f_stackdepth = -1;
1696 f->f_state = FRAME_EXECUTING;
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001697
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001698 if (co->co_opcache_flag < opcache_min_runs) {
Inada Naoki91234a12019-06-03 21:30:58 +09001699 co->co_opcache_flag++;
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001700 if (co->co_opcache_flag == opcache_min_runs) {
Inada Naoki91234a12019-06-03 21:30:58 +09001701 if (_PyCode_InitOpcache(co) < 0) {
Victor Stinner25104942020-04-24 02:43:18 +02001702 goto exit_eval_frame;
Inada Naoki91234a12019-06-03 21:30:58 +09001703 }
1704#if OPCACHE_STATS
1705 opcache_code_objects_extra_mem +=
1706 PyBytes_Size(co->co_code) / sizeof(_Py_CODEUNIT) +
1707 sizeof(_PyOpcache) * co->co_opcache_size;
1708 opcache_code_objects++;
1709#endif
1710 }
1711 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00001712
Tim Peters5ca576e2001-06-18 22:08:13 +00001713#ifdef LLTRACE
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001714 {
1715 int r = _PyDict_ContainsId(f->f_globals, &PyId___ltrace__);
1716 if (r < 0) {
1717 goto exit_eval_frame;
1718 }
1719 lltrace = r;
1720 }
Tim Peters5ca576e2001-06-18 22:08:13 +00001721#endif
Guido van Rossumac7be682001-01-17 15:42:30 +00001722
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001723 if (throwflag) { /* support for generator.throw() */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001724 goto error;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001725 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001726
Victor Stinnerace47d72013-07-18 01:41:08 +02001727#ifdef Py_DEBUG
Victor Stinner0b72b232020-03-12 23:18:39 +01001728 /* _PyEval_EvalFrameDefault() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +01001729 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +00001730 caller loses its exception */
Victor Stinner438a12d2019-05-24 17:01:38 +02001731 assert(!_PyErr_Occurred(tstate));
Victor Stinnerace47d72013-07-18 01:41:08 +02001732#endif
1733
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001734main_loop:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 for (;;) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 assert(stack_pointer >= f->f_valuestack); /* else underflow */
1737 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
Victor Stinner438a12d2019-05-24 17:01:38 +02001738 assert(!_PyErr_Occurred(tstate));
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 /* Do periodic things. Doing this every time through
1741 the loop would add too much overhead, so we do it
1742 only every Nth instruction. We also do it if
Chris Jerdonek4a12d122020-05-14 19:25:45 -07001743 ``pending.calls_to_do'' is set, i.e. when an asynchronous
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 event needs attention (e.g. a signal handler or
1745 async I/O handler); see Py_AddPendingCall() and
1746 Py_MakePendingCalls() above. */
Guido van Rossumac7be682001-01-17 15:42:30 +00001747
Eric Snow7bda9de2019-03-08 17:25:54 -07001748 if (_Py_atomic_load_relaxed(eval_breaker)) {
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001749 opcode = _Py_OPCODE(*next_instr);
Mark Shannon28d28e02021-04-08 11:22:55 +01001750 if (opcode != SETUP_FINALLY &&
1751 opcode != SETUP_WITH &&
1752 opcode != BEFORE_ASYNC_WITH &&
1753 opcode != YIELD_FROM) {
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001754 /* Few cases where we skip running signal handlers and other
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07001755 pending calls:
Serhiy Storchaka3f4d90d2018-07-09 15:40:14 +03001756 - If we're about to enter the 'with:'. It will prevent
1757 emitting a resource warning in the common idiom
1758 'with open(path) as file:'.
1759 - If we're about to enter the 'async with:'.
1760 - If we're about to enter the 'try:' of a try/finally (not
Nathaniel J. Smithab4413a2017-05-17 13:33:23 -07001761 *very* useful, but might help in some cases and it's
1762 traditional)
1763 - If we're resuming a chain of nested 'yield from' or
1764 'await' calls, then each frame is parked with YIELD_FROM
1765 as its next opcode. If the user hit control-C we want to
1766 wait until we've reached the innermost frame before
1767 running the signal handler and raising KeyboardInterrupt
1768 (see bpo-30039).
1769 */
Mark Shannon28d28e02021-04-08 11:22:55 +01001770 if (eval_frame_handle_pending(tstate) != 0) {
1771 goto error;
1772 }
1773 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001775
Mark Shannon28d28e02021-04-08 11:22:55 +01001776 tracing_dispatch:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 f->f_lasti = INSTR_OFFSET();
Mark Shannon28d28e02021-04-08 11:22:55 +01001778 NEXTOPARG();
Guido van Rossumac7be682001-01-17 15:42:30 +00001779
Łukasz Langaa785c872016-09-09 17:37:37 -07001780 if (PyDTrace_LINE_ENABLED())
Mark Shannon8e1b4062021-03-05 14:45:50 +00001781 maybe_dtrace_line(f, &trace_info);
Łukasz Langaa785c872016-09-09 17:37:37 -07001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 /* line-by-line tracing support */
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001784
Victor Stinnerdab84232020-03-17 18:56:44 +01001785 if (_Py_TracingPossible(ceval2) &&
Benjamin Peterson51f46162013-01-23 08:38:47 -05001786 tstate->c_tracefunc != NULL && !tstate->tracing) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001787 int err;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02001788 /* see maybe_call_line_trace()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 for expository comments */
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02001790 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Tim Peters8a5c3c72004-04-05 19:36:21 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 err = maybe_call_line_trace(tstate->c_tracefunc,
1793 tstate->c_traceobj,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01001794 tstate, f,
Mark Shannon8e1b4062021-03-05 14:45:50 +00001795 &trace_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Reload possibly changed frame fields */
1797 JUMPTO(f->f_lasti);
Mark Shannoncb9879b2020-07-17 11:44:23 +01001798 stack_pointer = f->f_valuestack+f->f_stackdepth;
1799 f->f_stackdepth = -1;
Mark Shannon28d28e02021-04-08 11:22:55 +01001800 if (err) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 /* trace function raised an exception */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001802 goto error;
Mark Shannon28d28e02021-04-08 11:22:55 +01001803 }
1804 NEXTOPARG();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 }
Michael W. Hudson019a78e2002-11-08 12:53:11 +00001806
Guido van Rossum96a42c81992-01-12 02:29:51 +00001807#ifdef LLTRACE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 /* Instruction tracing */
Guido van Rossumac7be682001-01-17 15:42:30 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 if (lltrace) {
1811 if (HAS_ARG(opcode)) {
1812 printf("%d: %d, %d\n",
1813 f->f_lasti, opcode, oparg);
1814 }
1815 else {
1816 printf("%d: %d\n",
1817 f->f_lasti, opcode);
1818 }
1819 }
Guido van Rossum374a9221991-04-04 10:40:29 +00001820#endif
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001821
Mark Shannon28d28e02021-04-08 11:22:55 +01001822 dispatch_opcode:
1823#ifdef DYNAMIC_EXECUTION_PROFILE
1824#ifdef DXPAIRS
1825 dxpairs[lastopcode][opcode]++;
1826 lastopcode = opcode;
1827#endif
1828 dxp[opcode]++;
1829#endif
1830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 switch (opcode) {
Guido van Rossumac7be682001-01-17 15:42:30 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 /* BEWARE!
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001834 It is essential that any operation that fails must goto error
Mark Shannon28d28e02021-04-08 11:22:55 +01001835 and that all operation that succeed call DISPATCH() ! */
Guido van Rossumac7be682001-01-17 15:42:30 +00001836
Benjamin Petersonddd19492018-09-16 22:38:02 -07001837 case TARGET(NOP): {
Mark Shannon4958f5d2021-03-24 17:56:12 +00001838 DISPATCH();
Benjamin Petersonddd19492018-09-16 22:38:02 -07001839 }
Raymond Hettinger9c18e812004-06-21 16:31:15 +00001840
Benjamin Petersonddd19492018-09-16 22:38:02 -07001841 case TARGET(LOAD_FAST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001842 PyObject *value = GETLOCAL(oparg);
1843 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02001844 format_exc_check_arg(tstate, PyExc_UnboundLocalError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001845 UNBOUNDLOCAL_ERROR_MSG,
1846 PyTuple_GetItem(co->co_varnames, oparg));
1847 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001849 Py_INCREF(value);
1850 PUSH(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001851 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001852 }
1853
Benjamin Petersonddd19492018-09-16 22:38:02 -07001854 case TARGET(LOAD_CONST): {
1855 PREDICTED(LOAD_CONST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001856 PyObject *value = GETITEM(consts, oparg);
1857 Py_INCREF(value);
1858 PUSH(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001859 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001860 }
Neil Schemenauer63543862002-02-17 19:10:14 +00001861
Benjamin Petersonddd19492018-09-16 22:38:02 -07001862 case TARGET(STORE_FAST): {
1863 PREDICTED(STORE_FAST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001864 PyObject *value = POP();
1865 SETLOCAL(oparg, value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001866 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001867 }
Neil Schemenauer63543862002-02-17 19:10:14 +00001868
Benjamin Petersonddd19492018-09-16 22:38:02 -07001869 case TARGET(POP_TOP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001870 PyObject *value = POP();
1871 Py_DECREF(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001872 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001873 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001874
Benjamin Petersonddd19492018-09-16 22:38:02 -07001875 case TARGET(ROT_TWO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001876 PyObject *top = TOP();
1877 PyObject *second = SECOND();
1878 SET_TOP(second);
1879 SET_SECOND(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001880 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001881 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001882
Benjamin Petersonddd19492018-09-16 22:38:02 -07001883 case TARGET(ROT_THREE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001884 PyObject *top = TOP();
1885 PyObject *second = SECOND();
1886 PyObject *third = THIRD();
1887 SET_TOP(second);
1888 SET_SECOND(third);
1889 SET_THIRD(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001890 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001891 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001892
Benjamin Petersonddd19492018-09-16 22:38:02 -07001893 case TARGET(ROT_FOUR): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001894 PyObject *top = TOP();
1895 PyObject *second = SECOND();
1896 PyObject *third = THIRD();
1897 PyObject *fourth = FOURTH();
1898 SET_TOP(second);
1899 SET_SECOND(third);
1900 SET_THIRD(fourth);
1901 SET_FOURTH(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001902 DISPATCH();
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001903 }
1904
Benjamin Petersonddd19492018-09-16 22:38:02 -07001905 case TARGET(DUP_TOP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001906 PyObject *top = TOP();
1907 Py_INCREF(top);
1908 PUSH(top);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001909 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001910 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001911
Benjamin Petersonddd19492018-09-16 22:38:02 -07001912 case TARGET(DUP_TOP_TWO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001913 PyObject *top = TOP();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001914 PyObject *second = SECOND();
Benjamin Petersonf208df32012-10-12 11:37:56 -04001915 Py_INCREF(top);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001916 Py_INCREF(second);
costypetrisor8ed317f2018-07-31 20:55:14 +00001917 STACK_GROW(2);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001918 SET_TOP(top);
1919 SET_SECOND(second);
Mark Shannon4958f5d2021-03-24 17:56:12 +00001920 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001921 }
Thomas Wouters434d0822000-08-24 20:11:32 +00001922
Benjamin Petersonddd19492018-09-16 22:38:02 -07001923 case TARGET(UNARY_POSITIVE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001924 PyObject *value = TOP();
1925 PyObject *res = PyNumber_Positive(value);
1926 Py_DECREF(value);
1927 SET_TOP(res);
1928 if (res == NULL)
1929 goto error;
1930 DISPATCH();
1931 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001932
Benjamin Petersonddd19492018-09-16 22:38:02 -07001933 case TARGET(UNARY_NEGATIVE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001934 PyObject *value = TOP();
1935 PyObject *res = PyNumber_Negative(value);
1936 Py_DECREF(value);
1937 SET_TOP(res);
1938 if (res == NULL)
1939 goto error;
1940 DISPATCH();
1941 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001942
Benjamin Petersonddd19492018-09-16 22:38:02 -07001943 case TARGET(UNARY_NOT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001944 PyObject *value = TOP();
1945 int err = PyObject_IsTrue(value);
1946 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (err == 0) {
1948 Py_INCREF(Py_True);
1949 SET_TOP(Py_True);
1950 DISPATCH();
1951 }
1952 else if (err > 0) {
1953 Py_INCREF(Py_False);
1954 SET_TOP(Py_False);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 DISPATCH();
1956 }
costypetrisor8ed317f2018-07-31 20:55:14 +00001957 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001958 goto error;
1959 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001960
Benjamin Petersonddd19492018-09-16 22:38:02 -07001961 case TARGET(UNARY_INVERT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001962 PyObject *value = TOP();
1963 PyObject *res = PyNumber_Invert(value);
1964 Py_DECREF(value);
1965 SET_TOP(res);
1966 if (res == NULL)
1967 goto error;
1968 DISPATCH();
1969 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001970
Benjamin Petersonddd19492018-09-16 22:38:02 -07001971 case TARGET(BINARY_POWER): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001972 PyObject *exp = POP();
1973 PyObject *base = TOP();
1974 PyObject *res = PyNumber_Power(base, exp, Py_None);
1975 Py_DECREF(base);
1976 Py_DECREF(exp);
1977 SET_TOP(res);
1978 if (res == NULL)
1979 goto error;
1980 DISPATCH();
1981 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001982
Benjamin Petersonddd19492018-09-16 22:38:02 -07001983 case TARGET(BINARY_MULTIPLY): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04001984 PyObject *right = POP();
1985 PyObject *left = TOP();
1986 PyObject *res = PyNumber_Multiply(left, right);
1987 Py_DECREF(left);
1988 Py_DECREF(right);
1989 SET_TOP(res);
1990 if (res == NULL)
1991 goto error;
1992 DISPATCH();
1993 }
Guido van Rossumac7be682001-01-17 15:42:30 +00001994
Benjamin Petersonddd19492018-09-16 22:38:02 -07001995 case TARGET(BINARY_MATRIX_MULTIPLY): {
Benjamin Petersond51374e2014-04-09 23:55:56 -04001996 PyObject *right = POP();
1997 PyObject *left = TOP();
1998 PyObject *res = PyNumber_MatrixMultiply(left, right);
1999 Py_DECREF(left);
2000 Py_DECREF(right);
2001 SET_TOP(res);
2002 if (res == NULL)
2003 goto error;
2004 DISPATCH();
2005 }
2006
Benjamin Petersonddd19492018-09-16 22:38:02 -07002007 case TARGET(BINARY_TRUE_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002008 PyObject *divisor = POP();
2009 PyObject *dividend = TOP();
2010 PyObject *quotient = PyNumber_TrueDivide(dividend, divisor);
2011 Py_DECREF(dividend);
2012 Py_DECREF(divisor);
2013 SET_TOP(quotient);
2014 if (quotient == NULL)
2015 goto error;
2016 DISPATCH();
2017 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002018
Benjamin Petersonddd19492018-09-16 22:38:02 -07002019 case TARGET(BINARY_FLOOR_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002020 PyObject *divisor = POP();
2021 PyObject *dividend = TOP();
2022 PyObject *quotient = PyNumber_FloorDivide(dividend, divisor);
2023 Py_DECREF(dividend);
2024 Py_DECREF(divisor);
2025 SET_TOP(quotient);
2026 if (quotient == NULL)
2027 goto error;
2028 DISPATCH();
2029 }
Guido van Rossum4668b002001-08-08 05:00:18 +00002030
Benjamin Petersonddd19492018-09-16 22:38:02 -07002031 case TARGET(BINARY_MODULO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002032 PyObject *divisor = POP();
2033 PyObject *dividend = TOP();
Martijn Pietersd7e64332017-02-23 13:38:04 +00002034 PyObject *res;
2035 if (PyUnicode_CheckExact(dividend) && (
2036 !PyUnicode_Check(divisor) || PyUnicode_CheckExact(divisor))) {
2037 // fast path; string formatting, but not if the RHS is a str subclass
2038 // (see issue28598)
2039 res = PyUnicode_Format(dividend, divisor);
2040 } else {
2041 res = PyNumber_Remainder(dividend, divisor);
2042 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002043 Py_DECREF(divisor);
2044 Py_DECREF(dividend);
2045 SET_TOP(res);
2046 if (res == NULL)
2047 goto error;
2048 DISPATCH();
2049 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002050
Benjamin Petersonddd19492018-09-16 22:38:02 -07002051 case TARGET(BINARY_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002052 PyObject *right = POP();
2053 PyObject *left = TOP();
2054 PyObject *sum;
Victor Stinnerbd0a08e2020-10-01 18:57:37 +02002055 /* NOTE(vstinner): Please don't try to micro-optimize int+int on
Victor Stinnerd65f42a2016-10-20 12:18:10 +02002056 CPython using bytecode, it is simply worthless.
2057 See http://bugs.python.org/issue21955 and
2058 http://bugs.python.org/issue10044 for the discussion. In short,
2059 no patch shown any impact on a realistic benchmark, only a minor
2060 speedup on microbenchmarks. */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002061 if (PyUnicode_CheckExact(left) &&
2062 PyUnicode_CheckExact(right)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002063 sum = unicode_concatenate(tstate, left, right, f, next_instr);
Martin Panter95f53c12016-07-18 08:23:26 +00002064 /* unicode_concatenate consumed the ref to left */
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002065 }
2066 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002067 sum = PyNumber_Add(left, right);
2068 Py_DECREF(left);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002069 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002070 Py_DECREF(right);
2071 SET_TOP(sum);
2072 if (sum == NULL)
2073 goto error;
2074 DISPATCH();
2075 }
2076
Benjamin Petersonddd19492018-09-16 22:38:02 -07002077 case TARGET(BINARY_SUBTRACT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002078 PyObject *right = POP();
2079 PyObject *left = TOP();
2080 PyObject *diff = PyNumber_Subtract(left, right);
2081 Py_DECREF(right);
2082 Py_DECREF(left);
2083 SET_TOP(diff);
2084 if (diff == NULL)
2085 goto error;
2086 DISPATCH();
2087 }
2088
Benjamin Petersonddd19492018-09-16 22:38:02 -07002089 case TARGET(BINARY_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002090 PyObject *sub = POP();
2091 PyObject *container = TOP();
2092 PyObject *res = PyObject_GetItem(container, sub);
2093 Py_DECREF(container);
2094 Py_DECREF(sub);
2095 SET_TOP(res);
2096 if (res == NULL)
2097 goto error;
2098 DISPATCH();
2099 }
2100
Benjamin Petersonddd19492018-09-16 22:38:02 -07002101 case TARGET(BINARY_LSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002102 PyObject *right = POP();
2103 PyObject *left = TOP();
2104 PyObject *res = PyNumber_Lshift(left, right);
2105 Py_DECREF(left);
2106 Py_DECREF(right);
2107 SET_TOP(res);
2108 if (res == NULL)
2109 goto error;
2110 DISPATCH();
2111 }
2112
Benjamin Petersonddd19492018-09-16 22:38:02 -07002113 case TARGET(BINARY_RSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002114 PyObject *right = POP();
2115 PyObject *left = TOP();
2116 PyObject *res = PyNumber_Rshift(left, right);
2117 Py_DECREF(left);
2118 Py_DECREF(right);
2119 SET_TOP(res);
2120 if (res == NULL)
2121 goto error;
2122 DISPATCH();
2123 }
2124
Benjamin Petersonddd19492018-09-16 22:38:02 -07002125 case TARGET(BINARY_AND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002126 PyObject *right = POP();
2127 PyObject *left = TOP();
2128 PyObject *res = PyNumber_And(left, right);
2129 Py_DECREF(left);
2130 Py_DECREF(right);
2131 SET_TOP(res);
2132 if (res == NULL)
2133 goto error;
2134 DISPATCH();
2135 }
2136
Benjamin Petersonddd19492018-09-16 22:38:02 -07002137 case TARGET(BINARY_XOR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002138 PyObject *right = POP();
2139 PyObject *left = TOP();
2140 PyObject *res = PyNumber_Xor(left, right);
2141 Py_DECREF(left);
2142 Py_DECREF(right);
2143 SET_TOP(res);
2144 if (res == NULL)
2145 goto error;
2146 DISPATCH();
2147 }
2148
Benjamin Petersonddd19492018-09-16 22:38:02 -07002149 case TARGET(BINARY_OR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002150 PyObject *right = POP();
2151 PyObject *left = TOP();
2152 PyObject *res = PyNumber_Or(left, right);
2153 Py_DECREF(left);
2154 Py_DECREF(right);
2155 SET_TOP(res);
2156 if (res == NULL)
2157 goto error;
2158 DISPATCH();
2159 }
2160
Benjamin Petersonddd19492018-09-16 22:38:02 -07002161 case TARGET(LIST_APPEND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002162 PyObject *v = POP();
2163 PyObject *list = PEEK(oparg);
2164 int err;
2165 err = PyList_Append(list, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002167 if (err != 0)
2168 goto error;
2169 PREDICT(JUMP_ABSOLUTE);
2170 DISPATCH();
2171 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002172
Benjamin Petersonddd19492018-09-16 22:38:02 -07002173 case TARGET(SET_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002174 PyObject *v = POP();
Raymond Hettinger41862222016-10-15 19:03:06 -07002175 PyObject *set = PEEK(oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002176 int err;
2177 err = PySet_Add(set, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002179 if (err != 0)
2180 goto error;
2181 PREDICT(JUMP_ABSOLUTE);
2182 DISPATCH();
2183 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002184
Benjamin Petersonddd19492018-09-16 22:38:02 -07002185 case TARGET(INPLACE_POWER): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002186 PyObject *exp = POP();
2187 PyObject *base = TOP();
2188 PyObject *res = PyNumber_InPlacePower(base, exp, Py_None);
2189 Py_DECREF(base);
2190 Py_DECREF(exp);
2191 SET_TOP(res);
2192 if (res == NULL)
2193 goto error;
2194 DISPATCH();
2195 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002196
Benjamin Petersonddd19492018-09-16 22:38:02 -07002197 case TARGET(INPLACE_MULTIPLY): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002198 PyObject *right = POP();
2199 PyObject *left = TOP();
2200 PyObject *res = PyNumber_InPlaceMultiply(left, right);
2201 Py_DECREF(left);
2202 Py_DECREF(right);
2203 SET_TOP(res);
2204 if (res == NULL)
2205 goto error;
2206 DISPATCH();
2207 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002208
Benjamin Petersonddd19492018-09-16 22:38:02 -07002209 case TARGET(INPLACE_MATRIX_MULTIPLY): {
Benjamin Petersond51374e2014-04-09 23:55:56 -04002210 PyObject *right = POP();
2211 PyObject *left = TOP();
2212 PyObject *res = PyNumber_InPlaceMatrixMultiply(left, right);
2213 Py_DECREF(left);
2214 Py_DECREF(right);
2215 SET_TOP(res);
2216 if (res == NULL)
2217 goto error;
2218 DISPATCH();
2219 }
2220
Benjamin Petersonddd19492018-09-16 22:38:02 -07002221 case TARGET(INPLACE_TRUE_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002222 PyObject *divisor = POP();
2223 PyObject *dividend = TOP();
2224 PyObject *quotient = PyNumber_InPlaceTrueDivide(dividend, divisor);
2225 Py_DECREF(dividend);
2226 Py_DECREF(divisor);
2227 SET_TOP(quotient);
2228 if (quotient == NULL)
2229 goto error;
2230 DISPATCH();
2231 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002232
Benjamin Petersonddd19492018-09-16 22:38:02 -07002233 case TARGET(INPLACE_FLOOR_DIVIDE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002234 PyObject *divisor = POP();
2235 PyObject *dividend = TOP();
2236 PyObject *quotient = PyNumber_InPlaceFloorDivide(dividend, divisor);
2237 Py_DECREF(dividend);
2238 Py_DECREF(divisor);
2239 SET_TOP(quotient);
2240 if (quotient == NULL)
2241 goto error;
2242 DISPATCH();
2243 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002244
Benjamin Petersonddd19492018-09-16 22:38:02 -07002245 case TARGET(INPLACE_MODULO): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002246 PyObject *right = POP();
2247 PyObject *left = TOP();
2248 PyObject *mod = PyNumber_InPlaceRemainder(left, right);
2249 Py_DECREF(left);
2250 Py_DECREF(right);
2251 SET_TOP(mod);
2252 if (mod == NULL)
2253 goto error;
2254 DISPATCH();
2255 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002256
Benjamin Petersonddd19492018-09-16 22:38:02 -07002257 case TARGET(INPLACE_ADD): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002258 PyObject *right = POP();
2259 PyObject *left = TOP();
2260 PyObject *sum;
2261 if (PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002262 sum = unicode_concatenate(tstate, left, right, f, next_instr);
Martin Panter95f53c12016-07-18 08:23:26 +00002263 /* unicode_concatenate consumed the ref to left */
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002264 }
2265 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002266 sum = PyNumber_InPlaceAdd(left, right);
2267 Py_DECREF(left);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02002268 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002269 Py_DECREF(right);
2270 SET_TOP(sum);
2271 if (sum == NULL)
2272 goto error;
2273 DISPATCH();
2274 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002275
Benjamin Petersonddd19492018-09-16 22:38:02 -07002276 case TARGET(INPLACE_SUBTRACT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002277 PyObject *right = POP();
2278 PyObject *left = TOP();
2279 PyObject *diff = PyNumber_InPlaceSubtract(left, right);
2280 Py_DECREF(left);
2281 Py_DECREF(right);
2282 SET_TOP(diff);
2283 if (diff == NULL)
2284 goto error;
2285 DISPATCH();
2286 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002287
Benjamin Petersonddd19492018-09-16 22:38:02 -07002288 case TARGET(INPLACE_LSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002289 PyObject *right = POP();
2290 PyObject *left = TOP();
2291 PyObject *res = PyNumber_InPlaceLshift(left, right);
2292 Py_DECREF(left);
2293 Py_DECREF(right);
2294 SET_TOP(res);
2295 if (res == NULL)
2296 goto error;
2297 DISPATCH();
2298 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002299
Benjamin Petersonddd19492018-09-16 22:38:02 -07002300 case TARGET(INPLACE_RSHIFT): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002301 PyObject *right = POP();
2302 PyObject *left = TOP();
2303 PyObject *res = PyNumber_InPlaceRshift(left, right);
2304 Py_DECREF(left);
2305 Py_DECREF(right);
2306 SET_TOP(res);
2307 if (res == NULL)
2308 goto error;
2309 DISPATCH();
2310 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002311
Benjamin Petersonddd19492018-09-16 22:38:02 -07002312 case TARGET(INPLACE_AND): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002313 PyObject *right = POP();
2314 PyObject *left = TOP();
2315 PyObject *res = PyNumber_InPlaceAnd(left, right);
2316 Py_DECREF(left);
2317 Py_DECREF(right);
2318 SET_TOP(res);
2319 if (res == NULL)
2320 goto error;
2321 DISPATCH();
2322 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002323
Benjamin Petersonddd19492018-09-16 22:38:02 -07002324 case TARGET(INPLACE_XOR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002325 PyObject *right = POP();
2326 PyObject *left = TOP();
2327 PyObject *res = PyNumber_InPlaceXor(left, right);
2328 Py_DECREF(left);
2329 Py_DECREF(right);
2330 SET_TOP(res);
2331 if (res == NULL)
2332 goto error;
2333 DISPATCH();
2334 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002335
Benjamin Petersonddd19492018-09-16 22:38:02 -07002336 case TARGET(INPLACE_OR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002337 PyObject *right = POP();
2338 PyObject *left = TOP();
2339 PyObject *res = PyNumber_InPlaceOr(left, right);
2340 Py_DECREF(left);
2341 Py_DECREF(right);
2342 SET_TOP(res);
2343 if (res == NULL)
2344 goto error;
2345 DISPATCH();
2346 }
Thomas Wouters434d0822000-08-24 20:11:32 +00002347
Benjamin Petersonddd19492018-09-16 22:38:02 -07002348 case TARGET(STORE_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002349 PyObject *sub = TOP();
2350 PyObject *container = SECOND();
2351 PyObject *v = THIRD();
2352 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002353 STACK_SHRINK(3);
Martin Panter95f53c12016-07-18 08:23:26 +00002354 /* container[sub] = v */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002355 err = PyObject_SetItem(container, sub, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002357 Py_DECREF(container);
2358 Py_DECREF(sub);
2359 if (err != 0)
2360 goto error;
2361 DISPATCH();
2362 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002363
Benjamin Petersonddd19492018-09-16 22:38:02 -07002364 case TARGET(DELETE_SUBSCR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002365 PyObject *sub = TOP();
2366 PyObject *container = SECOND();
2367 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002368 STACK_SHRINK(2);
Martin Panter95f53c12016-07-18 08:23:26 +00002369 /* del container[sub] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002370 err = PyObject_DelItem(container, sub);
2371 Py_DECREF(container);
2372 Py_DECREF(sub);
2373 if (err != 0)
2374 goto error;
2375 DISPATCH();
2376 }
Barry Warsaw23c9ec82000-08-21 15:44:01 +00002377
Benjamin Petersonddd19492018-09-16 22:38:02 -07002378 case TARGET(PRINT_EXPR): {
Victor Stinnercab75e32013-11-06 22:38:37 +01002379 _Py_IDENTIFIER(displayhook);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002380 PyObject *value = POP();
Victor Stinnercab75e32013-11-06 22:38:37 +01002381 PyObject *hook = _PySys_GetObjectId(&PyId_displayhook);
Benjamin Petersonfe1bcb62012-10-12 11:40:01 -04002382 PyObject *res;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002383 if (hook == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002384 _PyErr_SetString(tstate, PyExc_RuntimeError,
2385 "lost sys.displayhook");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002386 Py_DECREF(value);
2387 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 }
Petr Viktorinffd97532020-02-11 17:46:57 +01002389 res = PyObject_CallOneArg(hook, value);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002390 Py_DECREF(value);
2391 if (res == NULL)
2392 goto error;
2393 Py_DECREF(res);
2394 DISPATCH();
2395 }
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +00002396
Benjamin Petersonddd19492018-09-16 22:38:02 -07002397 case TARGET(RAISE_VARARGS): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002398 PyObject *cause = NULL, *exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 switch (oparg) {
2400 case 2:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002401 cause = POP(); /* cause */
Stefan Krahf432a322017-08-21 13:09:59 +02002402 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 case 1:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002404 exc = POP(); /* exc */
Stefan Krahf432a322017-08-21 13:09:59 +02002405 /* fall through */
2406 case 0:
Victor Stinner09532fe2019-05-10 23:39:09 +02002407 if (do_raise(tstate, exc, cause)) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002408 goto exception_unwind;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 break;
2411 default:
Victor Stinner438a12d2019-05-24 17:01:38 +02002412 _PyErr_SetString(tstate, PyExc_SystemError,
2413 "bad RAISE_VARARGS oparg");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 break;
2415 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002416 goto error;
2417 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002418
Benjamin Petersonddd19492018-09-16 22:38:02 -07002419 case TARGET(RETURN_VALUE): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 retval = POP();
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002421 assert(f->f_iblock == 0);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002422 assert(EMPTY());
Mark Shannoncb9879b2020-07-17 11:44:23 +01002423 f->f_state = FRAME_RETURNED;
2424 f->f_stackdepth = 0;
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002425 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002426 }
Guido van Rossumdb3165e1993-10-18 17:06:59 +00002427
Benjamin Petersonddd19492018-09-16 22:38:02 -07002428 case TARGET(GET_AITER): {
Yury Selivanov6ef05902015-05-28 11:21:31 -04002429 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002430 PyObject *iter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002431 PyObject *obj = TOP();
2432 PyTypeObject *type = Py_TYPE(obj);
2433
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002434 if (type->tp_as_async != NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002435 getter = type->tp_as_async->am_aiter;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002436 }
Yury Selivanov75445082015-05-11 22:57:16 -04002437
2438 if (getter != NULL) {
2439 iter = (*getter)(obj);
2440 Py_DECREF(obj);
2441 if (iter == NULL) {
2442 SET_TOP(NULL);
2443 goto error;
2444 }
2445 }
2446 else {
2447 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02002448 _PyErr_Format(tstate, PyExc_TypeError,
2449 "'async for' requires an object with "
2450 "__aiter__ method, got %.100s",
2451 type->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -04002452 Py_DECREF(obj);
2453 goto error;
2454 }
2455
Yury Selivanovfaa135a2017-10-06 02:08:57 -04002456 if (Py_TYPE(iter)->tp_as_async == NULL ||
2457 Py_TYPE(iter)->tp_as_async->am_anext == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002458
Yury Selivanov398ff912017-03-02 22:20:00 -05002459 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02002460 _PyErr_Format(tstate, PyExc_TypeError,
2461 "'async for' received an object from __aiter__ "
2462 "that does not implement __anext__: %.100s",
2463 Py_TYPE(iter)->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -04002464 Py_DECREF(iter);
2465 goto error;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04002466 }
2467
Yury Selivanovfaa135a2017-10-06 02:08:57 -04002468 SET_TOP(iter);
Yury Selivanov75445082015-05-11 22:57:16 -04002469 DISPATCH();
2470 }
2471
Benjamin Petersonddd19492018-09-16 22:38:02 -07002472 case TARGET(GET_ANEXT): {
Yury Selivanov6ef05902015-05-28 11:21:31 -04002473 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002474 PyObject *next_iter = NULL;
2475 PyObject *awaitable = NULL;
2476 PyObject *aiter = TOP();
2477 PyTypeObject *type = Py_TYPE(aiter);
2478
Yury Selivanoveb636452016-09-08 22:01:51 -07002479 if (PyAsyncGen_CheckExact(aiter)) {
2480 awaitable = type->tp_as_async->am_anext(aiter);
2481 if (awaitable == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002482 goto error;
2483 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002484 } else {
2485 if (type->tp_as_async != NULL){
2486 getter = type->tp_as_async->am_anext;
2487 }
Yury Selivanov75445082015-05-11 22:57:16 -04002488
Yury Selivanoveb636452016-09-08 22:01:51 -07002489 if (getter != NULL) {
2490 next_iter = (*getter)(aiter);
2491 if (next_iter == NULL) {
2492 goto error;
2493 }
2494 }
2495 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02002496 _PyErr_Format(tstate, PyExc_TypeError,
2497 "'async for' requires an iterator with "
2498 "__anext__ method, got %.100s",
2499 type->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07002500 goto error;
2501 }
Yury Selivanov75445082015-05-11 22:57:16 -04002502
Yury Selivanoveb636452016-09-08 22:01:51 -07002503 awaitable = _PyCoro_GetAwaitableIter(next_iter);
2504 if (awaitable == NULL) {
Yury Selivanov398ff912017-03-02 22:20:00 -05002505 _PyErr_FormatFromCause(
Yury Selivanoveb636452016-09-08 22:01:51 -07002506 PyExc_TypeError,
2507 "'async for' received an invalid object "
2508 "from __anext__: %.100s",
2509 Py_TYPE(next_iter)->tp_name);
2510
2511 Py_DECREF(next_iter);
2512 goto error;
2513 } else {
2514 Py_DECREF(next_iter);
2515 }
2516 }
Yury Selivanov75445082015-05-11 22:57:16 -04002517
2518 PUSH(awaitable);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03002519 PREDICT(LOAD_CONST);
Yury Selivanov75445082015-05-11 22:57:16 -04002520 DISPATCH();
2521 }
2522
Benjamin Petersonddd19492018-09-16 22:38:02 -07002523 case TARGET(GET_AWAITABLE): {
2524 PREDICTED(GET_AWAITABLE);
Yury Selivanov75445082015-05-11 22:57:16 -04002525 PyObject *iterable = TOP();
Yury Selivanov5376ba92015-06-22 12:19:30 -04002526 PyObject *iter = _PyCoro_GetAwaitableIter(iterable);
Yury Selivanov75445082015-05-11 22:57:16 -04002527
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03002528 if (iter == NULL) {
Mark Shannonfee55262019-11-21 09:11:43 +00002529 int opcode_at_minus_3 = 0;
2530 if ((next_instr - first_instr) > 2) {
2531 opcode_at_minus_3 = _Py_OPCODE(next_instr[-3]);
2532 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002533 format_awaitable_error(tstate, Py_TYPE(iterable),
Mark Shannonfee55262019-11-21 09:11:43 +00002534 opcode_at_minus_3,
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03002535 _Py_OPCODE(next_instr[-2]));
2536 }
2537
Yury Selivanov75445082015-05-11 22:57:16 -04002538 Py_DECREF(iterable);
2539
Yury Selivanovc724bae2016-03-02 11:30:46 -05002540 if (iter != NULL && PyCoro_CheckExact(iter)) {
2541 PyObject *yf = _PyGen_yf((PyGenObject*)iter);
2542 if (yf != NULL) {
2543 /* `iter` is a coroutine object that is being
2544 awaited, `yf` is a pointer to the current awaitable
2545 being awaited on. */
2546 Py_DECREF(yf);
2547 Py_CLEAR(iter);
Victor Stinner438a12d2019-05-24 17:01:38 +02002548 _PyErr_SetString(tstate, PyExc_RuntimeError,
2549 "coroutine is being awaited already");
Yury Selivanovc724bae2016-03-02 11:30:46 -05002550 /* The code below jumps to `error` if `iter` is NULL. */
2551 }
2552 }
2553
Yury Selivanov75445082015-05-11 22:57:16 -04002554 SET_TOP(iter); /* Even if it's NULL */
2555
2556 if (iter == NULL) {
2557 goto error;
2558 }
2559
Serhiy Storchakada9c5132016-06-27 18:58:57 +03002560 PREDICT(LOAD_CONST);
Yury Selivanov75445082015-05-11 22:57:16 -04002561 DISPATCH();
2562 }
2563
Benjamin Petersonddd19492018-09-16 22:38:02 -07002564 case TARGET(YIELD_FROM): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002565 PyObject *v = POP();
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002566 PyObject *receiver = TOP();
Vladimir Matveev037245c2020-10-09 17:15:15 -07002567 PySendResult gen_status;
2568 if (tstate->c_tracefunc == NULL) {
2569 gen_status = PyIter_Send(receiver, v, &retval);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002570 } else {
Vladimir Matveev037245c2020-10-09 17:15:15 -07002571 _Py_IDENTIFIER(send);
Victor Stinner09bbebe2021-04-11 00:17:39 +02002572 if (Py_IsNone(v) && PyIter_Check(receiver)) {
Vladimir Matveev037245c2020-10-09 17:15:15 -07002573 retval = Py_TYPE(receiver)->tp_iternext(receiver);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002574 }
2575 else {
Vladimir Matveev037245c2020-10-09 17:15:15 -07002576 retval = _PyObject_CallMethodIdOneArg(receiver, &PyId_send, v);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002577 }
Vladimir Matveev2b053612020-09-18 18:38:38 -07002578 if (retval == NULL) {
2579 if (tstate->c_tracefunc != NULL
2580 && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
Mark Shannon8e1b4062021-03-05 14:45:50 +00002581 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, &trace_info);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002582 if (_PyGen_FetchStopIterationValue(&retval) == 0) {
2583 gen_status = PYGEN_RETURN;
2584 }
2585 else {
2586 gen_status = PYGEN_ERROR;
2587 }
2588 }
2589 else {
2590 gen_status = PYGEN_NEXT;
2591 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002592 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002593 Py_DECREF(v);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002594 if (gen_status == PYGEN_ERROR) {
2595 assert (retval == NULL);
2596 goto error;
2597 }
2598 if (gen_status == PYGEN_RETURN) {
2599 assert (retval != NULL);
2600
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002601 Py_DECREF(receiver);
Vladimir Matveev2b053612020-09-18 18:38:38 -07002602 SET_TOP(retval);
2603 retval = NULL;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002604 DISPATCH();
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002605 }
Vladimir Matveev2b053612020-09-18 18:38:38 -07002606 assert (gen_status == PYGEN_NEXT);
Martin Panter95f53c12016-07-18 08:23:26 +00002607 /* receiver remains on stack, retval is value to be yielded */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05002608 /* and repeat... */
Mark Shannonfcb55c02021-04-01 16:00:31 +01002609 assert(f->f_lasti > 0);
2610 f->f_lasti -= 1;
Mark Shannoncb9879b2020-07-17 11:44:23 +01002611 f->f_state = FRAME_SUSPENDED;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02002612 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002613 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002614 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002615
Benjamin Petersonddd19492018-09-16 22:38:02 -07002616 case TARGET(YIELD_VALUE): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 retval = POP();
Yury Selivanoveb636452016-09-08 22:01:51 -07002618
2619 if (co->co_flags & CO_ASYNC_GENERATOR) {
2620 PyObject *w = _PyAsyncGenValueWrapperNew(retval);
2621 Py_DECREF(retval);
2622 if (w == NULL) {
2623 retval = NULL;
2624 goto error;
2625 }
2626 retval = w;
2627 }
Mark Shannoncb9879b2020-07-17 11:44:23 +01002628 f->f_state = FRAME_SUSPENDED;
Victor Stinnerb7d8d8d2020-09-23 14:07:16 +02002629 f->f_stackdepth = (int)(stack_pointer - f->f_valuestack);
Mark Shannone7c9f4a2020-01-13 12:51:26 +00002630 goto exiting;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002631 }
Tim Peters5ca576e2001-06-18 22:08:13 +00002632
Mark Shannonb37181e2021-04-06 11:48:59 +01002633 case TARGET(GEN_START): {
2634 PyObject *none = POP();
2635 Py_DECREF(none);
Victor Stinner09bbebe2021-04-11 00:17:39 +02002636 if (!Py_IsNone(none)) {
Mark Shannonb37181e2021-04-06 11:48:59 +01002637 if (oparg > 2) {
2638 _PyErr_SetString(tstate, PyExc_SystemError,
2639 "Illegal kind for GEN_START");
2640 }
2641 else {
2642 static const char *gen_kind[3] = {
2643 "generator",
2644 "coroutine",
2645 "async generator"
2646 };
2647 _PyErr_Format(tstate, PyExc_TypeError,
2648 "can't send non-None value to a "
2649 "just-started %s",
2650 gen_kind[oparg]);
2651 }
2652 goto error;
2653 }
2654 DISPATCH();
2655 }
2656
Benjamin Petersonddd19492018-09-16 22:38:02 -07002657 case TARGET(POP_EXCEPT): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002658 PyObject *type, *value, *traceback;
2659 _PyErr_StackItem *exc_info;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002660 PyTryBlock *b = PyFrame_BlockPop(f);
2661 if (b->b_type != EXCEPT_HANDLER) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002662 _PyErr_SetString(tstate, PyExc_SystemError,
2663 "popped block is not an except handler");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002664 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002666 assert(STACK_LEVEL() >= (b)->b_level + 3 &&
2667 STACK_LEVEL() <= (b)->b_level + 4);
2668 exc_info = tstate->exc_info;
2669 type = exc_info->exc_type;
2670 value = exc_info->exc_value;
2671 traceback = exc_info->exc_traceback;
2672 exc_info->exc_type = POP();
2673 exc_info->exc_value = POP();
2674 exc_info->exc_traceback = POP();
2675 Py_XDECREF(type);
2676 Py_XDECREF(value);
2677 Py_XDECREF(traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002679 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002680
Benjamin Petersonddd19492018-09-16 22:38:02 -07002681 case TARGET(POP_BLOCK): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002682 PyFrame_BlockPop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002684 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002685
Mark Shannonfee55262019-11-21 09:11:43 +00002686 case TARGET(RERAISE): {
Mark Shannonbf353f32020-12-17 13:55:28 +00002687 assert(f->f_iblock > 0);
2688 if (oparg) {
2689 f->f_lasti = f->f_blockstack[f->f_iblock-1].b_handler;
2690 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002691 PyObject *exc = POP();
Mark Shannonfee55262019-11-21 09:11:43 +00002692 PyObject *val = POP();
2693 PyObject *tb = POP();
2694 assert(PyExceptionClass_Check(exc));
Victor Stinner61f4db82020-01-28 03:37:45 +01002695 _PyErr_Restore(tstate, exc, val, tb);
Mark Shannonfee55262019-11-21 09:11:43 +00002696 goto exception_unwind;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002697 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002698
Benjamin Petersonddd19492018-09-16 22:38:02 -07002699 case TARGET(END_ASYNC_FOR): {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002700 PyObject *exc = POP();
2701 assert(PyExceptionClass_Check(exc));
2702 if (PyErr_GivenExceptionMatches(exc, PyExc_StopAsyncIteration)) {
2703 PyTryBlock *b = PyFrame_BlockPop(f);
2704 assert(b->b_type == EXCEPT_HANDLER);
2705 Py_DECREF(exc);
2706 UNWIND_EXCEPT_HANDLER(b);
2707 Py_DECREF(POP());
2708 JUMPBY(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00002709 DISPATCH();
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002710 }
2711 else {
2712 PyObject *val = POP();
2713 PyObject *tb = POP();
Victor Stinner438a12d2019-05-24 17:01:38 +02002714 _PyErr_Restore(tstate, exc, val, tb);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002715 goto exception_unwind;
2716 }
2717 }
2718
Zackery Spytzce6a0702019-08-25 03:44:09 -06002719 case TARGET(LOAD_ASSERTION_ERROR): {
2720 PyObject *value = PyExc_AssertionError;
2721 Py_INCREF(value);
2722 PUSH(value);
Mark Shannon4958f5d2021-03-24 17:56:12 +00002723 DISPATCH();
Zackery Spytzce6a0702019-08-25 03:44:09 -06002724 }
2725
Benjamin Petersonddd19492018-09-16 22:38:02 -07002726 case TARGET(LOAD_BUILD_CLASS): {
Victor Stinner3c1e4812012-03-26 22:10:51 +02002727 _Py_IDENTIFIER(__build_class__);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002728
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002729 PyObject *bc;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002730 if (PyDict_CheckExact(f->f_builtins)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002731 bc = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___build_class__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002732 if (bc == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002733 if (!_PyErr_Occurred(tstate)) {
2734 _PyErr_SetString(tstate, PyExc_NameError,
2735 "__build_class__ not found");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002736 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002737 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002738 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002739 Py_INCREF(bc);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002740 }
2741 else {
2742 PyObject *build_class_str = _PyUnicode_FromId(&PyId___build_class__);
2743 if (build_class_str == NULL)
Serhiy Storchaka70b72f02016-11-08 23:12:46 +02002744 goto error;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002745 bc = PyObject_GetItem(f->f_builtins, build_class_str);
2746 if (bc == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002747 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
2748 _PyErr_SetString(tstate, PyExc_NameError,
2749 "__build_class__ not found");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002750 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002753 PUSH(bc);
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002754 DISPATCH();
Victor Stinner3c1e4812012-03-26 22:10:51 +02002755 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002756
Benjamin Petersonddd19492018-09-16 22:38:02 -07002757 case TARGET(STORE_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002758 PyObject *name = GETITEM(names, oparg);
2759 PyObject *v = POP();
2760 PyObject *ns = f->f_locals;
2761 int err;
2762 if (ns == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002763 _PyErr_Format(tstate, PyExc_SystemError,
2764 "no locals found when storing %R", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002766 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002768 if (PyDict_CheckExact(ns))
2769 err = PyDict_SetItem(ns, name, v);
2770 else
2771 err = PyObject_SetItem(ns, name, v);
2772 Py_DECREF(v);
2773 if (err != 0)
2774 goto error;
2775 DISPATCH();
2776 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002777
Benjamin Petersonddd19492018-09-16 22:38:02 -07002778 case TARGET(DELETE_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002779 PyObject *name = GETITEM(names, oparg);
2780 PyObject *ns = f->f_locals;
2781 int err;
2782 if (ns == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002783 _PyErr_Format(tstate, PyExc_SystemError,
2784 "no locals when deleting %R", name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002785 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002787 err = PyObject_DelItem(ns, name);
2788 if (err != 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002789 format_exc_check_arg(tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002790 NAME_ERROR_MSG,
2791 name);
2792 goto error;
2793 }
2794 DISPATCH();
2795 }
Guido van Rossum04691fc1992-08-12 15:35:34 +00002796
Benjamin Petersonddd19492018-09-16 22:38:02 -07002797 case TARGET(UNPACK_SEQUENCE): {
2798 PREDICTED(UNPACK_SEQUENCE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002799 PyObject *seq = POP(), *item, **items;
2800 if (PyTuple_CheckExact(seq) &&
2801 PyTuple_GET_SIZE(seq) == oparg) {
2802 items = ((PyTupleObject *)seq)->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 while (oparg--) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002804 item = items[oparg];
2805 Py_INCREF(item);
2806 PUSH(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002808 } else if (PyList_CheckExact(seq) &&
2809 PyList_GET_SIZE(seq) == oparg) {
2810 items = ((PyListObject *)seq)->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 while (oparg--) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002812 item = items[oparg];
2813 Py_INCREF(item);
2814 PUSH(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002816 } else if (unpack_iterable(tstate, seq, oparg, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 stack_pointer + oparg)) {
costypetrisor8ed317f2018-07-31 20:55:14 +00002818 STACK_GROW(oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 } else {
2820 /* unpack_iterable() raised an exception */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002821 Py_DECREF(seq);
2822 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002824 Py_DECREF(seq);
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002825 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 }
Guido van Rossum0368b722007-05-11 16:50:42 +00002827
Benjamin Petersonddd19492018-09-16 22:38:02 -07002828 case TARGET(UNPACK_EX): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002829 int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
2830 PyObject *seq = POP();
2831
Victor Stinner438a12d2019-05-24 17:01:38 +02002832 if (unpack_iterable(tstate, seq, oparg & 0xFF, oparg >> 8,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002833 stack_pointer + totalargs)) {
2834 stack_pointer += totalargs;
2835 } else {
2836 Py_DECREF(seq);
2837 goto error;
2838 }
2839 Py_DECREF(seq);
2840 DISPATCH();
2841 }
2842
Benjamin Petersonddd19492018-09-16 22:38:02 -07002843 case TARGET(STORE_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002844 PyObject *name = GETITEM(names, oparg);
2845 PyObject *owner = TOP();
2846 PyObject *v = SECOND();
2847 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00002848 STACK_SHRINK(2);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002849 err = PyObject_SetAttr(owner, name, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002851 Py_DECREF(owner);
2852 if (err != 0)
2853 goto error;
2854 DISPATCH();
2855 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002856
Benjamin Petersonddd19492018-09-16 22:38:02 -07002857 case TARGET(DELETE_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002858 PyObject *name = GETITEM(names, oparg);
2859 PyObject *owner = POP();
2860 int err;
2861 err = PyObject_SetAttr(owner, name, (PyObject *)NULL);
2862 Py_DECREF(owner);
2863 if (err != 0)
2864 goto error;
2865 DISPATCH();
2866 }
2867
Benjamin Petersonddd19492018-09-16 22:38:02 -07002868 case TARGET(STORE_GLOBAL): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002869 PyObject *name = GETITEM(names, oparg);
2870 PyObject *v = POP();
2871 int err;
2872 err = PyDict_SetItem(f->f_globals, name, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 Py_DECREF(v);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002874 if (err != 0)
2875 goto error;
2876 DISPATCH();
2877 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002878
Benjamin Petersonddd19492018-09-16 22:38:02 -07002879 case TARGET(DELETE_GLOBAL): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002880 PyObject *name = GETITEM(names, oparg);
2881 int err;
2882 err = PyDict_DelItem(f->f_globals, name);
2883 if (err != 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002884 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2885 format_exc_check_arg(tstate, PyExc_NameError,
2886 NAME_ERROR_MSG, name);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002887 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002888 goto error;
Benjamin Peterson00f86f22012-10-10 14:10:33 -04002889 }
2890 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002891 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002892
Benjamin Petersonddd19492018-09-16 22:38:02 -07002893 case TARGET(LOAD_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002894 PyObject *name = GETITEM(names, oparg);
2895 PyObject *locals = f->f_locals;
2896 PyObject *v;
2897 if (locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002898 _PyErr_Format(tstate, PyExc_SystemError,
2899 "no locals when loading %R", name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002900 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002902 if (PyDict_CheckExact(locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002903 v = PyDict_GetItemWithError(locals, name);
2904 if (v != NULL) {
2905 Py_INCREF(v);
2906 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002907 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002908 goto error;
2909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 }
2911 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002912 v = PyObject_GetItem(locals, name);
Victor Stinnere20310f2015-11-05 13:56:58 +01002913 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002914 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError))
Benjamin Peterson92722792012-12-15 12:51:05 -05002915 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02002916 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 }
2918 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002919 if (v == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002920 v = PyDict_GetItemWithError(f->f_globals, name);
2921 if (v != NULL) {
2922 Py_INCREF(v);
2923 }
Victor Stinner438a12d2019-05-24 17:01:38 +02002924 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002925 goto error;
2926 }
2927 else {
Victor Stinnerb0b22422012-04-19 00:57:45 +02002928 if (PyDict_CheckExact(f->f_builtins)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002929 v = PyDict_GetItemWithError(f->f_builtins, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002930 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002931 if (!_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002932 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02002933 tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002934 NAME_ERROR_MSG, name);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002935 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002936 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002937 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002938 Py_INCREF(v);
Victor Stinnerb0b22422012-04-19 00:57:45 +02002939 }
2940 else {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002941 v = PyObject_GetItem(f->f_builtins, name);
2942 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02002943 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Victor Stinnerb0b22422012-04-19 00:57:45 +02002944 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02002945 tstate, PyExc_NameError,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002946 NAME_ERROR_MSG, name);
Victor Stinner438a12d2019-05-24 17:01:38 +02002947 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002948 goto error;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002949 }
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002953 PUSH(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002955 }
Guido van Rossumac7be682001-01-17 15:42:30 +00002956
Benjamin Petersonddd19492018-09-16 22:38:02 -07002957 case TARGET(LOAD_GLOBAL): {
Inada Naoki91234a12019-06-03 21:30:58 +09002958 PyObject *name;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002959 PyObject *v;
Victor Stinnerb0b22422012-04-19 00:57:45 +02002960 if (PyDict_CheckExact(f->f_globals)
Victor Stinnerb4efc962015-11-20 09:24:02 +01002961 && PyDict_CheckExact(f->f_builtins))
2962 {
Inada Naoki91234a12019-06-03 21:30:58 +09002963 OPCACHE_CHECK();
2964 if (co_opcache != NULL && co_opcache->optimized > 0) {
2965 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2966
2967 if (lg->globals_ver ==
2968 ((PyDictObject *)f->f_globals)->ma_version_tag
2969 && lg->builtins_ver ==
2970 ((PyDictObject *)f->f_builtins)->ma_version_tag)
2971 {
2972 PyObject *ptr = lg->ptr;
2973 OPCACHE_STAT_GLOBAL_HIT();
2974 assert(ptr != NULL);
2975 Py_INCREF(ptr);
2976 PUSH(ptr);
2977 DISPATCH();
2978 }
2979 }
2980
2981 name = GETITEM(names, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002982 v = _PyDict_LoadGlobal((PyDictObject *)f->f_globals,
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002983 (PyDictObject *)f->f_builtins,
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002984 name);
2985 if (v == NULL) {
Victor Stinnera4860542021-02-19 15:08:54 +01002986 if (!_PyErr_Occurred(tstate)) {
Victor Stinnerb4efc962015-11-20 09:24:02 +01002987 /* _PyDict_LoadGlobal() returns NULL without raising
2988 * an exception if the key doesn't exist */
Victor Stinner438a12d2019-05-24 17:01:38 +02002989 format_exc_check_arg(tstate, PyExc_NameError,
Ezio Melotti04a29552013-03-03 15:12:44 +02002990 NAME_ERROR_MSG, name);
Victor Stinnerb4efc962015-11-20 09:24:02 +01002991 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04002992 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 }
Inada Naoki91234a12019-06-03 21:30:58 +09002994
2995 if (co_opcache != NULL) {
2996 _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;
2997
2998 if (co_opcache->optimized == 0) {
2999 /* Wasn't optimized before. */
3000 OPCACHE_STAT_GLOBAL_OPT();
3001 } else {
3002 OPCACHE_STAT_GLOBAL_MISS();
3003 }
3004
3005 co_opcache->optimized = 1;
3006 lg->globals_ver =
3007 ((PyDictObject *)f->f_globals)->ma_version_tag;
3008 lg->builtins_ver =
3009 ((PyDictObject *)f->f_builtins)->ma_version_tag;
3010 lg->ptr = v; /* borrowed */
3011 }
3012
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003013 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003015 else {
3016 /* Slow-path if globals or builtins is not a dict */
Victor Stinnerb4efc962015-11-20 09:24:02 +01003017
3018 /* namespace 1: globals */
Inada Naoki91234a12019-06-03 21:30:58 +09003019 name = GETITEM(names, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003020 v = PyObject_GetItem(f->f_globals, name);
3021 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003022 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Victor Stinner60a1d3c2015-11-05 13:55:20 +01003023 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02003024 }
3025 _PyErr_Clear(tstate);
Victor Stinner60a1d3c2015-11-05 13:55:20 +01003026
Victor Stinnerb4efc962015-11-20 09:24:02 +01003027 /* namespace 2: builtins */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003028 v = PyObject_GetItem(f->f_builtins, name);
3029 if (v == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003030 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003031 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02003032 tstate, PyExc_NameError,
Ezio Melotti04a29552013-03-03 15:12:44 +02003033 NAME_ERROR_MSG, name);
Victor Stinner438a12d2019-05-24 17:01:38 +02003034 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003035 goto error;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003036 }
3037 }
3038 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003039 PUSH(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003041 }
Guido van Rossum681d79a1995-07-18 14:51:37 +00003042
Benjamin Petersonddd19492018-09-16 22:38:02 -07003043 case TARGET(DELETE_FAST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003044 PyObject *v = GETLOCAL(oparg);
3045 if (v != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 SETLOCAL(oparg, NULL);
3047 DISPATCH();
3048 }
3049 format_exc_check_arg(
Victor Stinner438a12d2019-05-24 17:01:38 +02003050 tstate, PyExc_UnboundLocalError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 UNBOUNDLOCAL_ERROR_MSG,
3052 PyTuple_GetItem(co->co_varnames, oparg)
3053 );
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003054 goto error;
3055 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003056
Benjamin Petersonddd19492018-09-16 22:38:02 -07003057 case TARGET(DELETE_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003058 PyObject *cell = freevars[oparg];
Raymond Hettingerc32f9db2016-11-12 04:10:35 -05003059 PyObject *oldobj = PyCell_GET(cell);
3060 if (oldobj != NULL) {
3061 PyCell_SET(cell, NULL);
3062 Py_DECREF(oldobj);
Benjamin Peterson00ebe2c2010-09-10 22:02:31 +00003063 DISPATCH();
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003064 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003065 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003066 goto error;
3067 }
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003068
Benjamin Petersonddd19492018-09-16 22:38:02 -07003069 case TARGET(LOAD_CLOSURE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003070 PyObject *cell = freevars[oparg];
3071 Py_INCREF(cell);
3072 PUSH(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003074 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003075
Benjamin Petersonddd19492018-09-16 22:38:02 -07003076 case TARGET(LOAD_CLASSDEREF): {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003077 PyObject *name, *value, *locals = f->f_locals;
Victor Stinnerd3dfd0e2013-05-16 23:48:01 +02003078 Py_ssize_t idx;
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003079 assert(locals);
3080 assert(oparg >= PyTuple_GET_SIZE(co->co_cellvars));
3081 idx = oparg - PyTuple_GET_SIZE(co->co_cellvars);
3082 assert(idx >= 0 && idx < PyTuple_GET_SIZE(co->co_freevars));
3083 name = PyTuple_GET_ITEM(co->co_freevars, idx);
3084 if (PyDict_CheckExact(locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003085 value = PyDict_GetItemWithError(locals, name);
3086 if (value != NULL) {
3087 Py_INCREF(value);
3088 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003089 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003090 goto error;
3091 }
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003092 }
3093 else {
3094 value = PyObject_GetItem(locals, name);
Victor Stinnere20310f2015-11-05 13:56:58 +01003095 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003096 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003097 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02003098 }
3099 _PyErr_Clear(tstate);
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003100 }
3101 }
3102 if (!value) {
3103 PyObject *cell = freevars[oparg];
3104 value = PyCell_GET(cell);
3105 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003106 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003107 goto error;
3108 }
3109 Py_INCREF(value);
3110 }
3111 PUSH(value);
3112 DISPATCH();
3113 }
3114
Benjamin Petersonddd19492018-09-16 22:38:02 -07003115 case TARGET(LOAD_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003116 PyObject *cell = freevars[oparg];
3117 PyObject *value = PyCell_GET(cell);
3118 if (value == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003119 format_exc_unbound(tstate, co, oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003120 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003122 Py_INCREF(value);
3123 PUSH(value);
3124 DISPATCH();
3125 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003126
Benjamin Petersonddd19492018-09-16 22:38:02 -07003127 case TARGET(STORE_DEREF): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003128 PyObject *v = POP();
3129 PyObject *cell = freevars[oparg];
Raymond Hettingerb2b15432016-11-11 04:32:11 -08003130 PyObject *oldobj = PyCell_GET(cell);
3131 PyCell_SET(cell, v);
3132 Py_XDECREF(oldobj);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003133 DISPATCH();
3134 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003135
Benjamin Petersonddd19492018-09-16 22:38:02 -07003136 case TARGET(BUILD_STRING): {
Serhiy Storchakaea525a22016-09-06 22:07:53 +03003137 PyObject *str;
3138 PyObject *empty = PyUnicode_New(0, 0);
3139 if (empty == NULL) {
3140 goto error;
3141 }
3142 str = _PyUnicode_JoinArray(empty, stack_pointer - oparg, oparg);
3143 Py_DECREF(empty);
3144 if (str == NULL)
3145 goto error;
3146 while (--oparg >= 0) {
3147 PyObject *item = POP();
3148 Py_DECREF(item);
3149 }
3150 PUSH(str);
3151 DISPATCH();
3152 }
3153
Benjamin Petersonddd19492018-09-16 22:38:02 -07003154 case TARGET(BUILD_TUPLE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003155 PyObject *tup = PyTuple_New(oparg);
3156 if (tup == NULL)
3157 goto error;
3158 while (--oparg >= 0) {
3159 PyObject *item = POP();
3160 PyTuple_SET_ITEM(tup, oparg, item);
3161 }
3162 PUSH(tup);
3163 DISPATCH();
3164 }
3165
Benjamin Petersonddd19492018-09-16 22:38:02 -07003166 case TARGET(BUILD_LIST): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003167 PyObject *list = PyList_New(oparg);
3168 if (list == NULL)
3169 goto error;
3170 while (--oparg >= 0) {
3171 PyObject *item = POP();
3172 PyList_SET_ITEM(list, oparg, item);
3173 }
3174 PUSH(list);
3175 DISPATCH();
3176 }
3177
Mark Shannon13bc1392020-01-23 09:25:17 +00003178 case TARGET(LIST_TO_TUPLE): {
3179 PyObject *list = POP();
3180 PyObject *tuple = PyList_AsTuple(list);
3181 Py_DECREF(list);
3182 if (tuple == NULL) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003183 goto error;
Mark Shannon13bc1392020-01-23 09:25:17 +00003184 }
3185 PUSH(tuple);
3186 DISPATCH();
3187 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003188
Mark Shannon13bc1392020-01-23 09:25:17 +00003189 case TARGET(LIST_EXTEND): {
3190 PyObject *iterable = POP();
3191 PyObject *list = PEEK(oparg);
3192 PyObject *none_val = _PyList_Extend((PyListObject *)list, iterable);
3193 if (none_val == NULL) {
3194 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
Victor Stinnera102ed72020-02-07 02:24:48 +01003195 (Py_TYPE(iterable)->tp_iter == NULL && !PySequence_Check(iterable)))
Mark Shannon13bc1392020-01-23 09:25:17 +00003196 {
Victor Stinner61f4db82020-01-28 03:37:45 +01003197 _PyErr_Clear(tstate);
Mark Shannon13bc1392020-01-23 09:25:17 +00003198 _PyErr_Format(tstate, PyExc_TypeError,
3199 "Value after * must be an iterable, not %.200s",
3200 Py_TYPE(iterable)->tp_name);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003201 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003202 Py_DECREF(iterable);
3203 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003204 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003205 Py_DECREF(none_val);
3206 Py_DECREF(iterable);
3207 DISPATCH();
3208 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003209
Mark Shannon13bc1392020-01-23 09:25:17 +00003210 case TARGET(SET_UPDATE): {
3211 PyObject *iterable = POP();
3212 PyObject *set = PEEK(oparg);
3213 int err = _PySet_Update(set, iterable);
3214 Py_DECREF(iterable);
3215 if (err < 0) {
3216 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003217 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003218 DISPATCH();
3219 }
3220
Benjamin Petersonddd19492018-09-16 22:38:02 -07003221 case TARGET(BUILD_SET): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003222 PyObject *set = PySet_New(NULL);
3223 int err = 0;
Raymond Hettinger4c483ad2016-09-08 14:45:40 -07003224 int i;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003225 if (set == NULL)
3226 goto error;
Raymond Hettinger4c483ad2016-09-08 14:45:40 -07003227 for (i = oparg; i > 0; i--) {
3228 PyObject *item = PEEK(i);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003229 if (err == 0)
3230 err = PySet_Add(set, item);
3231 Py_DECREF(item);
3232 }
costypetrisor8ed317f2018-07-31 20:55:14 +00003233 STACK_SHRINK(oparg);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003234 if (err != 0) {
3235 Py_DECREF(set);
3236 goto error;
3237 }
3238 PUSH(set);
3239 DISPATCH();
3240 }
3241
Benjamin Petersonddd19492018-09-16 22:38:02 -07003242 case TARGET(BUILD_MAP): {
Victor Stinner74319ae2016-08-25 00:04:09 +02003243 Py_ssize_t i;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003244 PyObject *map = _PyDict_NewPresized((Py_ssize_t)oparg);
3245 if (map == NULL)
3246 goto error;
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003247 for (i = oparg; i > 0; i--) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003248 int err;
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003249 PyObject *key = PEEK(2*i);
3250 PyObject *value = PEEK(2*i - 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003251 err = PyDict_SetItem(map, key, value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003252 if (err != 0) {
3253 Py_DECREF(map);
3254 goto error;
3255 }
3256 }
Benjamin Petersond5d77aa2015-07-05 10:37:25 -05003257
3258 while (oparg--) {
3259 Py_DECREF(POP());
3260 Py_DECREF(POP());
3261 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003262 PUSH(map);
3263 DISPATCH();
3264 }
3265
Benjamin Petersonddd19492018-09-16 22:38:02 -07003266 case TARGET(SETUP_ANNOTATIONS): {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003267 _Py_IDENTIFIER(__annotations__);
3268 int err;
3269 PyObject *ann_dict;
3270 if (f->f_locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003271 _PyErr_Format(tstate, PyExc_SystemError,
3272 "no locals found when setting up annotations");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003273 goto error;
3274 }
3275 /* check if __annotations__ in locals()... */
3276 if (PyDict_CheckExact(f->f_locals)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003277 ann_dict = _PyDict_GetItemIdWithError(f->f_locals,
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003278 &PyId___annotations__);
3279 if (ann_dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003280 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02003281 goto error;
3282 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003283 /* ...if not, create a new one */
3284 ann_dict = PyDict_New();
3285 if (ann_dict == NULL) {
3286 goto error;
3287 }
3288 err = _PyDict_SetItemId(f->f_locals,
3289 &PyId___annotations__, ann_dict);
3290 Py_DECREF(ann_dict);
3291 if (err != 0) {
3292 goto error;
3293 }
3294 }
3295 }
3296 else {
3297 /* do the same if locals() is not a dict */
3298 PyObject *ann_str = _PyUnicode_FromId(&PyId___annotations__);
3299 if (ann_str == NULL) {
Serhiy Storchaka4678b2f2016-11-08 23:13:36 +02003300 goto error;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003301 }
3302 ann_dict = PyObject_GetItem(f->f_locals, ann_str);
3303 if (ann_dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003304 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003305 goto error;
3306 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003307 _PyErr_Clear(tstate);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003308 ann_dict = PyDict_New();
3309 if (ann_dict == NULL) {
3310 goto error;
3311 }
3312 err = PyObject_SetItem(f->f_locals, ann_str, ann_dict);
3313 Py_DECREF(ann_dict);
3314 if (err != 0) {
3315 goto error;
3316 }
3317 }
3318 else {
3319 Py_DECREF(ann_dict);
3320 }
3321 }
3322 DISPATCH();
3323 }
3324
Benjamin Petersonddd19492018-09-16 22:38:02 -07003325 case TARGET(BUILD_CONST_KEY_MAP): {
Victor Stinner74319ae2016-08-25 00:04:09 +02003326 Py_ssize_t i;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003327 PyObject *map;
3328 PyObject *keys = TOP();
3329 if (!PyTuple_CheckExact(keys) ||
3330 PyTuple_GET_SIZE(keys) != (Py_ssize_t)oparg) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003331 _PyErr_SetString(tstate, PyExc_SystemError,
3332 "bad BUILD_CONST_KEY_MAP keys argument");
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003333 goto error;
3334 }
3335 map = _PyDict_NewPresized((Py_ssize_t)oparg);
3336 if (map == NULL) {
3337 goto error;
3338 }
3339 for (i = oparg; i > 0; i--) {
3340 int err;
3341 PyObject *key = PyTuple_GET_ITEM(keys, oparg - i);
3342 PyObject *value = PEEK(i + 1);
3343 err = PyDict_SetItem(map, key, value);
3344 if (err != 0) {
3345 Py_DECREF(map);
3346 goto error;
3347 }
3348 }
3349
3350 Py_DECREF(POP());
3351 while (oparg--) {
3352 Py_DECREF(POP());
3353 }
3354 PUSH(map);
3355 DISPATCH();
3356 }
3357
Mark Shannon8a4cd702020-01-27 09:57:45 +00003358 case TARGET(DICT_UPDATE): {
3359 PyObject *update = POP();
3360 PyObject *dict = PEEK(oparg);
3361 if (PyDict_Update(dict, update) < 0) {
3362 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
3363 _PyErr_Format(tstate, PyExc_TypeError,
3364 "'%.200s' object is not a mapping",
Victor Stinnera102ed72020-02-07 02:24:48 +01003365 Py_TYPE(update)->tp_name);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003366 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003367 Py_DECREF(update);
3368 goto error;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003369 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003370 Py_DECREF(update);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003371 DISPATCH();
3372 }
3373
Mark Shannon8a4cd702020-01-27 09:57:45 +00003374 case TARGET(DICT_MERGE): {
3375 PyObject *update = POP();
3376 PyObject *dict = PEEK(oparg);
3377
3378 if (_PyDict_MergeEx(dict, update, 2) < 0) {
3379 format_kwargs_error(tstate, PEEK(2 + oparg), update);
3380 Py_DECREF(update);
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003381 goto error;
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003382 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003383 Py_DECREF(update);
Brandt Bucherf185a732019-09-28 17:12:49 -07003384 PREDICT(CALL_FUNCTION_EX);
Serhiy Storchakae036ef82016-10-02 11:06:43 +03003385 DISPATCH();
3386 }
3387
Benjamin Petersonddd19492018-09-16 22:38:02 -07003388 case TARGET(MAP_ADD): {
Jörn Heisslerc8a35412019-06-22 16:40:55 +02003389 PyObject *value = TOP();
3390 PyObject *key = SECOND();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003391 PyObject *map;
3392 int err;
costypetrisor8ed317f2018-07-31 20:55:14 +00003393 STACK_SHRINK(2);
Raymond Hettinger41862222016-10-15 19:03:06 -07003394 map = PEEK(oparg); /* dict */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003395 assert(PyDict_CheckExact(map));
Martin Panter95f53c12016-07-18 08:23:26 +00003396 err = PyDict_SetItem(map, key, value); /* map[key] = value */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003397 Py_DECREF(value);
3398 Py_DECREF(key);
3399 if (err != 0)
3400 goto error;
3401 PREDICT(JUMP_ABSOLUTE);
3402 DISPATCH();
3403 }
3404
Benjamin Petersonddd19492018-09-16 22:38:02 -07003405 case TARGET(LOAD_ATTR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003406 PyObject *name = GETITEM(names, oparg);
3407 PyObject *owner = TOP();
Pablo Galindo109826c2020-10-20 06:22:44 +01003408
3409 PyTypeObject *type = Py_TYPE(owner);
3410 PyObject *res;
3411 PyObject **dictptr;
3412 PyObject *dict;
3413 _PyOpCodeOpt_LoadAttr *la;
3414
3415 OPCACHE_STAT_ATTR_TOTAL();
3416
3417 OPCACHE_CHECK();
3418 if (co_opcache != NULL && PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
3419 {
3420 if (co_opcache->optimized > 0) {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003421 // Fast path -- cache hit makes LOAD_ATTR ~30% faster.
Pablo Galindo109826c2020-10-20 06:22:44 +01003422 la = &co_opcache->u.la;
3423 if (la->type == type && la->tp_version_tag == type->tp_version_tag)
3424 {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003425 // Hint >= 0 is a dict index; hint == -1 is a dict miss.
3426 // Hint < -1 is an inverted slot offset: offset is strictly > 0,
3427 // so ~offset is strictly < -1 (assuming 2's complement).
3428 if (la->hint < -1) {
3429 // Even faster path -- slot hint.
3430 Py_ssize_t offset = ~la->hint;
3431 // fprintf(stderr, "Using hint for offset %zd\n", offset);
3432 char *addr = (char *)owner + offset;
3433 res = *(PyObject **)addr;
Pablo Galindo109826c2020-10-20 06:22:44 +01003434 if (res != NULL) {
Pablo Galindo109826c2020-10-20 06:22:44 +01003435 Py_INCREF(res);
3436 SET_TOP(res);
3437 Py_DECREF(owner);
Pablo Galindo109826c2020-10-20 06:22:44 +01003438 DISPATCH();
Pablo Galindo109826c2020-10-20 06:22:44 +01003439 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003440 // Else slot is NULL. Fall through to slow path to raise AttributeError(name).
3441 // Don't DEOPT, since the slot is still there.
Pablo Galindo109826c2020-10-20 06:22:44 +01003442 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003443 // Fast path for dict.
3444 assert(type->tp_dict != NULL);
3445 assert(type->tp_dictoffset > 0);
3446
3447 dictptr = (PyObject **) ((char *)owner + type->tp_dictoffset);
3448 dict = *dictptr;
3449 if (dict != NULL && PyDict_CheckExact(dict)) {
3450 Py_ssize_t hint = la->hint;
3451 Py_INCREF(dict);
3452 res = NULL;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003453 assert(!_PyErr_Occurred(tstate));
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003454 la->hint = _PyDict_GetItemHint((PyDictObject*)dict, name, hint, &res);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003455 if (res != NULL) {
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003456 assert(la->hint >= 0);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003457 if (la->hint == hint && hint >= 0) {
3458 // Our hint has helped -- cache hit.
3459 OPCACHE_STAT_ATTR_HIT();
3460 } else {
3461 // The hint we provided didn't work.
3462 // Maybe next time?
3463 OPCACHE_MAYBE_DEOPT_LOAD_ATTR();
3464 }
3465
3466 Py_INCREF(res);
3467 SET_TOP(res);
3468 Py_DECREF(owner);
3469 Py_DECREF(dict);
3470 DISPATCH();
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003471 }
3472 else {
3473 _PyErr_Clear(tstate);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003474 // This attribute can be missing sometimes;
3475 // we don't want to optimize this lookup.
3476 OPCACHE_DEOPT_LOAD_ATTR();
3477 Py_DECREF(dict);
3478 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003479 }
3480 else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003481 // There is no dict, or __dict__ doesn't satisfy PyDict_CheckExact.
3482 OPCACHE_DEOPT_LOAD_ATTR();
3483 }
Pablo Galindo109826c2020-10-20 06:22:44 +01003484 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003485 }
3486 else {
Pablo Galindo109826c2020-10-20 06:22:44 +01003487 // The type of the object has either been updated,
3488 // or is different. Maybe it will stabilize?
3489 OPCACHE_MAYBE_DEOPT_LOAD_ATTR();
3490 }
Pablo Galindo109826c2020-10-20 06:22:44 +01003491 OPCACHE_STAT_ATTR_MISS();
3492 }
3493
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003494 if (co_opcache != NULL && // co_opcache can be NULL after a DEOPT() call.
Pablo Galindo109826c2020-10-20 06:22:44 +01003495 type->tp_getattro == PyObject_GenericGetAttr)
3496 {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003497 if (type->tp_dict == NULL) {
3498 if (PyType_Ready(type) < 0) {
3499 Py_DECREF(owner);
3500 SET_TOP(NULL);
3501 goto error;
Pablo Galindo109826c2020-10-20 06:22:44 +01003502 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003503 }
3504 PyObject *descr = _PyType_Lookup(type, name);
3505 if (descr != NULL) {
3506 // We found an attribute with a data-like descriptor.
3507 PyTypeObject *dtype = Py_TYPE(descr);
3508 if (dtype == &PyMemberDescr_Type) { // It's a slot
3509 PyMemberDescrObject *member = (PyMemberDescrObject *)descr;
3510 struct PyMemberDef *dmem = member->d_member;
3511 if (dmem->type == T_OBJECT_EX) {
3512 Py_ssize_t offset = dmem->offset;
3513 assert(offset > 0); // 0 would be confused with dict hint == -1 (miss).
Pablo Galindo109826c2020-10-20 06:22:44 +01003514
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003515 if (co_opcache->optimized == 0) {
3516 // First time we optimize this opcode.
3517 OPCACHE_STAT_ATTR_OPT();
3518 co_opcache->optimized = OPCODE_CACHE_MAX_TRIES;
3519 // fprintf(stderr, "Setting hint for %s, offset %zd\n", dmem->name, offset);
3520 }
3521
3522 la = &co_opcache->u.la;
3523 la->type = type;
3524 la->tp_version_tag = type->tp_version_tag;
3525 la->hint = ~offset;
3526
3527 char *addr = (char *)owner + offset;
3528 res = *(PyObject **)addr;
Pablo Galindo109826c2020-10-20 06:22:44 +01003529 if (res != NULL) {
3530 Py_INCREF(res);
Pablo Galindo109826c2020-10-20 06:22:44 +01003531 Py_DECREF(owner);
3532 SET_TOP(res);
3533
Pablo Galindo109826c2020-10-20 06:22:44 +01003534 DISPATCH();
3535 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003536 // Else slot is NULL. Fall through to slow path to raise AttributeError(name).
Pablo Galindo109826c2020-10-20 06:22:44 +01003537 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003538 // Else it's a slot of a different type. We don't handle those.
3539 }
3540 // Else it's some other kind of descriptor that we don't handle.
3541 OPCACHE_DEOPT_LOAD_ATTR();
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003542 }
3543 else if (type->tp_dictoffset > 0) {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003544 // We found an instance with a __dict__.
3545 dictptr = (PyObject **) ((char *)owner + type->tp_dictoffset);
3546 dict = *dictptr;
3547
3548 if (dict != NULL && PyDict_CheckExact(dict)) {
3549 Py_INCREF(dict);
3550 res = NULL;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003551 assert(!_PyErr_Occurred(tstate));
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003552 Py_ssize_t hint = _PyDict_GetItemHint((PyDictObject*)dict, name, -1, &res);
3553 if (res != NULL) {
3554 Py_INCREF(res);
3555 Py_DECREF(dict);
3556 Py_DECREF(owner);
3557 SET_TOP(res);
3558
3559 if (co_opcache->optimized == 0) {
3560 // First time we optimize this opcode.
3561 OPCACHE_STAT_ATTR_OPT();
3562 co_opcache->optimized = OPCODE_CACHE_MAX_TRIES;
3563 }
3564
3565 la = &co_opcache->u.la;
3566 la->type = type;
3567 la->tp_version_tag = type->tp_version_tag;
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003568 assert(hint >= 0);
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003569 la->hint = hint;
3570
3571 DISPATCH();
3572 }
Victor Stinnerd5fc9982021-02-21 12:02:04 +01003573 else {
3574 _PyErr_Clear(tstate);
3575 }
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003576 Py_DECREF(dict);
Pablo Galindo109826c2020-10-20 06:22:44 +01003577 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003578 // There is no dict, or __dict__ doesn't satisfy PyDict_CheckExact.
Pablo Galindo109826c2020-10-20 06:22:44 +01003579 OPCACHE_DEOPT_LOAD_ATTR();
3580 }
3581 } else {
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003582 // The object's class does not have a tp_dictoffset we can use.
Pablo Galindo109826c2020-10-20 06:22:44 +01003583 OPCACHE_DEOPT_LOAD_ATTR();
3584 }
3585 } else if (type->tp_getattro != PyObject_GenericGetAttr) {
3586 OPCACHE_DEOPT_LOAD_ATTR();
3587 }
3588 }
3589
Guido van Rossum5c5a9382021-01-29 18:02:29 -08003590 // Slow path.
Pablo Galindo109826c2020-10-20 06:22:44 +01003591 res = PyObject_GetAttr(owner, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003592 Py_DECREF(owner);
3593 SET_TOP(res);
3594 if (res == NULL)
3595 goto error;
3596 DISPATCH();
3597 }
3598
Benjamin Petersonddd19492018-09-16 22:38:02 -07003599 case TARGET(COMPARE_OP): {
Mark Shannon9af0e472020-01-14 10:12:45 +00003600 assert(oparg <= Py_GE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003601 PyObject *right = POP();
3602 PyObject *left = TOP();
Mark Shannon9af0e472020-01-14 10:12:45 +00003603 PyObject *res = PyObject_RichCompare(left, right, oparg);
3604 SET_TOP(res);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003605 Py_DECREF(left);
3606 Py_DECREF(right);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003607 if (res == NULL)
3608 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 PREDICT(POP_JUMP_IF_FALSE);
3610 PREDICT(POP_JUMP_IF_TRUE);
3611 DISPATCH();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003612 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003613
Mark Shannon9af0e472020-01-14 10:12:45 +00003614 case TARGET(IS_OP): {
3615 PyObject *right = POP();
3616 PyObject *left = TOP();
Victor Stinner09bbebe2021-04-11 00:17:39 +02003617 int res = Py_Is(left, right) ^ oparg;
Mark Shannon9af0e472020-01-14 10:12:45 +00003618 PyObject *b = res ? Py_True : Py_False;
3619 Py_INCREF(b);
3620 SET_TOP(b);
3621 Py_DECREF(left);
3622 Py_DECREF(right);
3623 PREDICT(POP_JUMP_IF_FALSE);
3624 PREDICT(POP_JUMP_IF_TRUE);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003625 DISPATCH();
Mark Shannon9af0e472020-01-14 10:12:45 +00003626 }
3627
3628 case TARGET(CONTAINS_OP): {
3629 PyObject *right = POP();
3630 PyObject *left = POP();
3631 int res = PySequence_Contains(right, left);
3632 Py_DECREF(left);
3633 Py_DECREF(right);
3634 if (res < 0) {
3635 goto error;
3636 }
3637 PyObject *b = (res^oparg) ? Py_True : Py_False;
3638 Py_INCREF(b);
3639 PUSH(b);
3640 PREDICT(POP_JUMP_IF_FALSE);
3641 PREDICT(POP_JUMP_IF_TRUE);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003642 DISPATCH();
Mark Shannon9af0e472020-01-14 10:12:45 +00003643 }
3644
3645#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
3646 "BaseException is not allowed"
3647
3648 case TARGET(JUMP_IF_NOT_EXC_MATCH): {
3649 PyObject *right = POP();
3650 PyObject *left = POP();
3651 if (PyTuple_Check(right)) {
3652 Py_ssize_t i, length;
3653 length = PyTuple_GET_SIZE(right);
3654 for (i = 0; i < length; i++) {
3655 PyObject *exc = PyTuple_GET_ITEM(right, i);
3656 if (!PyExceptionClass_Check(exc)) {
3657 _PyErr_SetString(tstate, PyExc_TypeError,
3658 CANNOT_CATCH_MSG);
3659 Py_DECREF(left);
3660 Py_DECREF(right);
3661 goto error;
3662 }
3663 }
3664 }
3665 else {
3666 if (!PyExceptionClass_Check(right)) {
3667 _PyErr_SetString(tstate, PyExc_TypeError,
3668 CANNOT_CATCH_MSG);
3669 Py_DECREF(left);
3670 Py_DECREF(right);
3671 goto error;
3672 }
3673 }
3674 int res = PyErr_GivenExceptionMatches(left, right);
3675 Py_DECREF(left);
3676 Py_DECREF(right);
3677 if (res > 0) {
3678 /* Exception matches -- Do nothing */;
3679 }
3680 else if (res == 0) {
3681 JUMPTO(oparg);
3682 }
3683 else {
3684 goto error;
3685 }
3686 DISPATCH();
3687 }
3688
Benjamin Petersonddd19492018-09-16 22:38:02 -07003689 case TARGET(IMPORT_NAME): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003690 PyObject *name = GETITEM(names, oparg);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03003691 PyObject *fromlist = POP();
3692 PyObject *level = TOP();
3693 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02003694 res = import_name(tstate, f, name, fromlist, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03003695 Py_DECREF(level);
3696 Py_DECREF(fromlist);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003697 SET_TOP(res);
3698 if (res == NULL)
3699 goto error;
3700 DISPATCH();
3701 }
3702
Benjamin Petersonddd19492018-09-16 22:38:02 -07003703 case TARGET(IMPORT_STAR): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003704 PyObject *from = POP(), *locals;
3705 int err;
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003706 if (PyFrame_FastToLocalsWithError(f) < 0) {
3707 Py_DECREF(from);
Victor Stinner41bb43a2013-10-29 01:19:37 +01003708 goto error;
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003709 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01003710
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003711 locals = f->f_locals;
3712 if (locals == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02003713 _PyErr_SetString(tstate, PyExc_SystemError,
3714 "no locals found during 'import *'");
Matthias Bussonnier160edb42017-02-25 21:58:05 -08003715 Py_DECREF(from);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003716 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 }
Victor Stinner438a12d2019-05-24 17:01:38 +02003718 err = import_all_from(tstate, locals, from);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 PyFrame_LocalsToFast(f, 0);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003720 Py_DECREF(from);
3721 if (err != 0)
3722 goto error;
3723 DISPATCH();
3724 }
Guido van Rossum25831651993-05-19 14:50:45 +00003725
Benjamin Petersonddd19492018-09-16 22:38:02 -07003726 case TARGET(IMPORT_FROM): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003727 PyObject *name = GETITEM(names, oparg);
3728 PyObject *from = TOP();
3729 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02003730 res = import_from(tstate, from, name);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003731 PUSH(res);
3732 if (res == NULL)
3733 goto error;
3734 DISPATCH();
3735 }
Thomas Wouters52152252000-08-17 22:55:00 +00003736
Benjamin Petersonddd19492018-09-16 22:38:02 -07003737 case TARGET(JUMP_FORWARD): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 JUMPBY(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003739 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003740 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003741
Benjamin Petersonddd19492018-09-16 22:38:02 -07003742 case TARGET(POP_JUMP_IF_FALSE): {
3743 PREDICTED(POP_JUMP_IF_FALSE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003744 PyObject *cond = POP();
3745 int err;
Victor Stinner09bbebe2021-04-11 00:17:39 +02003746 if (Py_IsTrue(cond)) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003747 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003748 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 }
Victor Stinner09bbebe2021-04-11 00:17:39 +02003750 if (Py_IsFalse(cond)) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003751 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003753 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003755 err = PyObject_IsTrue(cond);
3756 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 if (err > 0)
Adrian Wielgosik50c28502017-06-23 13:35:41 -07003758 ;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 else if (err == 0)
3760 JUMPTO(oparg);
3761 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003762 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003764 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003765
Benjamin Petersonddd19492018-09-16 22:38:02 -07003766 case TARGET(POP_JUMP_IF_TRUE): {
3767 PREDICTED(POP_JUMP_IF_TRUE);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003768 PyObject *cond = POP();
3769 int err;
Victor Stinner09bbebe2021-04-11 00:17:39 +02003770 if (Py_IsFalse(cond)) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003771 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003772 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 }
Victor Stinner09bbebe2021-04-11 00:17:39 +02003774 if (Py_IsTrue(cond)) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003775 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003777 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003779 err = PyObject_IsTrue(cond);
3780 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 if (err > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 JUMPTO(oparg);
3783 }
3784 else if (err == 0)
3785 ;
3786 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003787 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003789 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003790
Benjamin Petersonddd19492018-09-16 22:38:02 -07003791 case TARGET(JUMP_IF_FALSE_OR_POP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003792 PyObject *cond = TOP();
3793 int err;
Victor Stinner09bbebe2021-04-11 00:17:39 +02003794 if (Py_IsTrue(cond)) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003795 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003796 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003797 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 }
Victor Stinner09bbebe2021-04-11 00:17:39 +02003799 if (Py_IsFalse(cond)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003801 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003803 err = PyObject_IsTrue(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 if (err > 0) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003805 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003806 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 }
3808 else if (err == 0)
3809 JUMPTO(oparg);
3810 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003811 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003813 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003814
Benjamin Petersonddd19492018-09-16 22:38:02 -07003815 case TARGET(JUMP_IF_TRUE_OR_POP): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003816 PyObject *cond = TOP();
3817 int err;
Victor Stinner09bbebe2021-04-11 00:17:39 +02003818 if (Py_IsFalse(cond)) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003819 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003820 Py_DECREF(cond);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003821 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 }
Victor Stinner09bbebe2021-04-11 00:17:39 +02003823 if (Py_IsTrue(cond)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003825 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003827 err = PyObject_IsTrue(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 if (err > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 JUMPTO(oparg);
3830 }
3831 else if (err == 0) {
costypetrisor8ed317f2018-07-31 20:55:14 +00003832 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003833 Py_DECREF(cond);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 }
3835 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003836 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003838 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003839
Benjamin Petersonddd19492018-09-16 22:38:02 -07003840 case TARGET(JUMP_ABSOLUTE): {
3841 PREDICTED(JUMP_ABSOLUTE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 JUMPTO(oparg);
Mark Shannon4958f5d2021-03-24 17:56:12 +00003843 CHECK_EVAL_BREAKER();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04003845 }
Guido van Rossumac7be682001-01-17 15:42:30 +00003846
Brandt Bucher145bf262021-02-26 14:51:55 -08003847 case TARGET(GET_LEN): {
3848 // PUSH(len(TOS))
3849 Py_ssize_t len_i = PyObject_Length(TOP());
3850 if (len_i < 0) {
3851 goto error;
3852 }
3853 PyObject *len_o = PyLong_FromSsize_t(len_i);
3854 if (len_o == NULL) {
3855 goto error;
3856 }
3857 PUSH(len_o);
3858 DISPATCH();
3859 }
3860
3861 case TARGET(MATCH_CLASS): {
3862 // Pop TOS. On success, set TOS to True and TOS1 to a tuple of
3863 // attributes. On failure, set TOS to False.
3864 PyObject *names = POP();
3865 PyObject *type = TOP();
3866 PyObject *subject = SECOND();
3867 assert(PyTuple_CheckExact(names));
3868 PyObject *attrs = match_class(tstate, subject, type, oparg, names);
3869 Py_DECREF(names);
3870 if (attrs) {
3871 // Success!
3872 assert(PyTuple_CheckExact(attrs));
3873 Py_DECREF(subject);
3874 SET_SECOND(attrs);
3875 }
3876 else if (_PyErr_Occurred(tstate)) {
3877 goto error;
3878 }
3879 Py_DECREF(type);
3880 SET_TOP(PyBool_FromLong(!!attrs));
3881 DISPATCH();
3882 }
3883
3884 case TARGET(MATCH_MAPPING): {
3885 // PUSH(isinstance(TOS, _collections_abc.Mapping))
3886 PyObject *subject = TOP();
3887 // Fast path for dicts:
3888 if (PyDict_Check(subject)) {
3889 Py_INCREF(Py_True);
3890 PUSH(Py_True);
3891 DISPATCH();
3892 }
3893 // Lazily import _collections_abc.Mapping, and keep it handy on the
3894 // PyInterpreterState struct (it gets cleaned up at exit):
3895 PyInterpreterState *interp = PyInterpreterState_Get();
3896 if (interp->map_abc == NULL) {
3897 PyObject *abc = PyImport_ImportModule("_collections_abc");
3898 if (abc == NULL) {
3899 goto error;
3900 }
3901 interp->map_abc = PyObject_GetAttrString(abc, "Mapping");
3902 if (interp->map_abc == NULL) {
3903 goto error;
3904 }
3905 }
3906 int match = PyObject_IsInstance(subject, interp->map_abc);
3907 if (match < 0) {
3908 goto error;
3909 }
3910 PUSH(PyBool_FromLong(match));
3911 DISPATCH();
3912 }
3913
3914 case TARGET(MATCH_SEQUENCE): {
3915 // PUSH(not isinstance(TOS, (bytearray, bytes, str))
3916 // and isinstance(TOS, _collections_abc.Sequence))
3917 PyObject *subject = TOP();
3918 // Fast path for lists and tuples:
3919 if (PyType_FastSubclass(Py_TYPE(subject),
3920 Py_TPFLAGS_LIST_SUBCLASS |
3921 Py_TPFLAGS_TUPLE_SUBCLASS))
3922 {
3923 Py_INCREF(Py_True);
3924 PUSH(Py_True);
3925 DISPATCH();
3926 }
3927 // Bail on some possible Sequences that we intentionally exclude:
3928 if (PyType_FastSubclass(Py_TYPE(subject),
3929 Py_TPFLAGS_BYTES_SUBCLASS |
3930 Py_TPFLAGS_UNICODE_SUBCLASS) ||
3931 PyByteArray_Check(subject))
3932 {
3933 Py_INCREF(Py_False);
3934 PUSH(Py_False);
3935 DISPATCH();
3936 }
3937 // Lazily import _collections_abc.Sequence, and keep it handy on the
3938 // PyInterpreterState struct (it gets cleaned up at exit):
3939 PyInterpreterState *interp = PyInterpreterState_Get();
3940 if (interp->seq_abc == NULL) {
3941 PyObject *abc = PyImport_ImportModule("_collections_abc");
3942 if (abc == NULL) {
3943 goto error;
3944 }
3945 interp->seq_abc = PyObject_GetAttrString(abc, "Sequence");
3946 if (interp->seq_abc == NULL) {
3947 goto error;
3948 }
3949 }
3950 int match = PyObject_IsInstance(subject, interp->seq_abc);
3951 if (match < 0) {
3952 goto error;
3953 }
3954 PUSH(PyBool_FromLong(match));
3955 DISPATCH();
3956 }
3957
3958 case TARGET(MATCH_KEYS): {
3959 // On successful match for all keys, PUSH(values) and PUSH(True).
3960 // Otherwise, PUSH(None) and PUSH(False).
3961 PyObject *keys = TOP();
3962 PyObject *subject = SECOND();
3963 PyObject *values_or_none = match_keys(tstate, subject, keys);
3964 if (values_or_none == NULL) {
3965 goto error;
3966 }
3967 PUSH(values_or_none);
Victor Stinner09bbebe2021-04-11 00:17:39 +02003968 if (Py_IsNone(values_or_none)) {
Brandt Bucher145bf262021-02-26 14:51:55 -08003969 Py_INCREF(Py_False);
3970 PUSH(Py_False);
3971 DISPATCH();
3972 }
3973 assert(PyTuple_CheckExact(values_or_none));
3974 Py_INCREF(Py_True);
3975 PUSH(Py_True);
3976 DISPATCH();
3977 }
3978
3979 case TARGET(COPY_DICT_WITHOUT_KEYS): {
3980 // rest = dict(TOS1)
3981 // for key in TOS:
3982 // del rest[key]
3983 // SET_TOP(rest)
3984 PyObject *keys = TOP();
3985 PyObject *subject = SECOND();
3986 PyObject *rest = PyDict_New();
3987 if (rest == NULL || PyDict_Update(rest, subject)) {
3988 Py_XDECREF(rest);
3989 goto error;
3990 }
3991 // This may seem a bit inefficient, but keys is rarely big enough to
3992 // actually impact runtime.
3993 assert(PyTuple_CheckExact(keys));
3994 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(keys); i++) {
3995 if (PyDict_DelItem(rest, PyTuple_GET_ITEM(keys, i))) {
3996 Py_DECREF(rest);
3997 goto error;
3998 }
3999 }
4000 Py_DECREF(keys);
4001 SET_TOP(rest);
4002 DISPATCH();
4003 }
4004
Benjamin Petersonddd19492018-09-16 22:38:02 -07004005 case TARGET(GET_ITER): {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 /* before: [obj]; after [getiter(obj)] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004007 PyObject *iterable = TOP();
Yury Selivanov5376ba92015-06-22 12:19:30 -04004008 PyObject *iter = PyObject_GetIter(iterable);
4009 Py_DECREF(iterable);
4010 SET_TOP(iter);
4011 if (iter == NULL)
4012 goto error;
4013 PREDICT(FOR_ITER);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004014 PREDICT(CALL_FUNCTION);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004015 DISPATCH();
4016 }
4017
Benjamin Petersonddd19492018-09-16 22:38:02 -07004018 case TARGET(GET_YIELD_FROM_ITER): {
Yury Selivanov5376ba92015-06-22 12:19:30 -04004019 /* before: [obj]; after [getiter(obj)] */
4020 PyObject *iterable = TOP();
Yury Selivanov75445082015-05-11 22:57:16 -04004021 PyObject *iter;
Yury Selivanov5376ba92015-06-22 12:19:30 -04004022 if (PyCoro_CheckExact(iterable)) {
4023 /* `iterable` is a coroutine */
4024 if (!(co->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))) {
4025 /* and it is used in a 'yield from' expression of a
4026 regular generator. */
4027 Py_DECREF(iterable);
4028 SET_TOP(NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02004029 _PyErr_SetString(tstate, PyExc_TypeError,
4030 "cannot 'yield from' a coroutine object "
4031 "in a non-coroutine generator");
Yury Selivanov5376ba92015-06-22 12:19:30 -04004032 goto error;
4033 }
4034 }
4035 else if (!PyGen_CheckExact(iterable)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004036 /* `iterable` is not a generator. */
4037 iter = PyObject_GetIter(iterable);
4038 Py_DECREF(iterable);
4039 SET_TOP(iter);
4040 if (iter == NULL)
4041 goto error;
4042 }
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004043 PREDICT(LOAD_CONST);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004044 DISPATCH();
4045 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00004046
Benjamin Petersonddd19492018-09-16 22:38:02 -07004047 case TARGET(FOR_ITER): {
4048 PREDICTED(FOR_ITER);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 /* before: [iter]; after: [iter, iter()] *or* [] */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004050 PyObject *iter = TOP();
Victor Stinnera102ed72020-02-07 02:24:48 +01004051 PyObject *next = (*Py_TYPE(iter)->tp_iternext)(iter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004052 if (next != NULL) {
4053 PUSH(next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 PREDICT(STORE_FAST);
4055 PREDICT(UNPACK_SEQUENCE);
4056 DISPATCH();
4057 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004058 if (_PyErr_Occurred(tstate)) {
4059 if (!_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004060 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02004061 }
4062 else if (tstate->c_tracefunc != NULL) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00004063 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, tstate, f, &trace_info);
Victor Stinner438a12d2019-05-24 17:01:38 +02004064 }
4065 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 }
4067 /* iterator ended normally */
costypetrisor8ed317f2018-07-31 20:55:14 +00004068 STACK_SHRINK(1);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004069 Py_DECREF(iter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 JUMPBY(oparg);
4071 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004072 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00004073
Benjamin Petersonddd19492018-09-16 22:38:02 -07004074 case TARGET(SETUP_FINALLY): {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004075 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 STACK_LEVEL());
4077 DISPATCH();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004078 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004079
Benjamin Petersonddd19492018-09-16 22:38:02 -07004080 case TARGET(BEFORE_ASYNC_WITH): {
Yury Selivanov75445082015-05-11 22:57:16 -04004081 _Py_IDENTIFIER(__aenter__);
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004082 _Py_IDENTIFIER(__aexit__);
Yury Selivanov75445082015-05-11 22:57:16 -04004083 PyObject *mgr = TOP();
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004084 PyObject *enter = special_lookup(tstate, mgr, &PyId___aenter__);
Yury Selivanov75445082015-05-11 22:57:16 -04004085 PyObject *res;
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004086 if (enter == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04004087 goto error;
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004088 }
4089 PyObject *exit = special_lookup(tstate, mgr, &PyId___aexit__);
4090 if (exit == NULL) {
4091 Py_DECREF(enter);
4092 goto error;
4093 }
Yury Selivanov75445082015-05-11 22:57:16 -04004094 SET_TOP(exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004095 Py_DECREF(mgr);
Victor Stinnerf17c3de2016-12-06 18:46:19 +01004096 res = _PyObject_CallNoArg(enter);
Yury Selivanov75445082015-05-11 22:57:16 -04004097 Py_DECREF(enter);
4098 if (res == NULL)
4099 goto error;
4100 PUSH(res);
Serhiy Storchakada9c5132016-06-27 18:58:57 +03004101 PREDICT(GET_AWAITABLE);
Yury Selivanov75445082015-05-11 22:57:16 -04004102 DISPATCH();
4103 }
4104
Benjamin Petersonddd19492018-09-16 22:38:02 -07004105 case TARGET(SETUP_ASYNC_WITH): {
Yury Selivanov75445082015-05-11 22:57:16 -04004106 PyObject *res = POP();
4107 /* Setup the finally block before pushing the result
4108 of __aenter__ on the stack. */
4109 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
4110 STACK_LEVEL());
4111 PUSH(res);
4112 DISPATCH();
4113 }
4114
Benjamin Petersonddd19492018-09-16 22:38:02 -07004115 case TARGET(SETUP_WITH): {
Benjamin Petersonce798522012-01-22 11:24:29 -05004116 _Py_IDENTIFIER(__enter__);
Géry Ogam1d1b97a2020-01-14 12:58:29 +01004117 _Py_IDENTIFIER(__exit__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004118 PyObject *mgr = TOP();
Victor Stinner438a12d2019-05-24 17:01:38 +02004119 PyObject *enter = special_lookup(tstate, mgr, &PyId___enter__);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004120 PyObject *res;
Victor Stinner438a12d2019-05-24 17:01:38 +02004121 if (enter == NULL) {
Raymond Hettingera3fec152016-11-21 17:24:23 -08004122 goto error;
Victor Stinner438a12d2019-05-24 17:01:38 +02004123 }
4124 PyObject *exit = special_lookup(tstate, mgr, &PyId___exit__);
Raymond Hettinger64e2f9a2016-11-22 11:50:40 -08004125 if (exit == NULL) {
4126 Py_DECREF(enter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004127 goto error;
Raymond Hettinger64e2f9a2016-11-22 11:50:40 -08004128 }
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004129 SET_TOP(exit);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004130 Py_DECREF(mgr);
Victor Stinnerf17c3de2016-12-06 18:46:19 +01004131 res = _PyObject_CallNoArg(enter);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004132 Py_DECREF(enter);
4133 if (res == NULL)
4134 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 /* Setup the finally block before pushing the result
4136 of __enter__ on the stack. */
4137 PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg,
4138 STACK_LEVEL());
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004139
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004140 PUSH(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 DISPATCH();
4142 }
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004143
Mark Shannonfee55262019-11-21 09:11:43 +00004144 case TARGET(WITH_EXCEPT_START): {
4145 /* At the top of the stack are 7 values:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 - (TOP, SECOND, THIRD) = exc_info()
Mark Shannonfee55262019-11-21 09:11:43 +00004147 - (FOURTH, FIFTH, SIXTH) = previous exception for EXCEPT_HANDLER
4148 - SEVENTH: the context.__exit__ bound method
4149 We call SEVENTH(TOP, SECOND, THIRD).
4150 Then we push again the TOP exception and the __exit__
4151 return value.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 PyObject *exit_func;
Victor Stinner842cfff2016-12-01 14:45:31 +01004154 PyObject *exc, *val, *tb, *res;
4155
Victor Stinner842cfff2016-12-01 14:45:31 +01004156 exc = TOP();
Mark Shannonfee55262019-11-21 09:11:43 +00004157 val = SECOND();
4158 tb = THIRD();
Victor Stinner09bbebe2021-04-11 00:17:39 +02004159 assert(!Py_IsNone(exc));
Mark Shannonfee55262019-11-21 09:11:43 +00004160 assert(!PyLong_Check(exc));
4161 exit_func = PEEK(7);
Jeroen Demeyer469d1a72019-07-03 12:52:21 +02004162 PyObject *stack[4] = {NULL, exc, val, tb};
Petr Viktorinffd97532020-02-11 17:46:57 +01004163 res = PyObject_Vectorcall(exit_func, stack + 1,
Jeroen Demeyer469d1a72019-07-03 12:52:21 +02004164 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004165 if (res == NULL)
4166 goto error;
Amaury Forgeot d'Arc10b24e82008-12-10 23:49:33 +00004167
Yury Selivanov75445082015-05-11 22:57:16 -04004168 PUSH(res);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004169 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00004171
Benjamin Petersonddd19492018-09-16 22:38:02 -07004172 case TARGET(LOAD_METHOD): {
Andreyb021ba52019-04-29 14:33:26 +10004173 /* Designed to work in tandem with CALL_METHOD. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004174 PyObject *name = GETITEM(names, oparg);
4175 PyObject *obj = TOP();
4176 PyObject *meth = NULL;
4177
4178 int meth_found = _PyObject_GetMethod(obj, name, &meth);
4179
Yury Selivanovf2392132016-12-13 19:03:51 -05004180 if (meth == NULL) {
4181 /* Most likely attribute wasn't found. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004182 goto error;
4183 }
4184
4185 if (meth_found) {
INADA Naoki015bce62017-01-16 17:23:30 +09004186 /* We can bypass temporary bound method object.
4187 meth is unbound method and obj is self.
Victor Stinnera8cb5152017-01-18 14:12:51 +01004188
INADA Naoki015bce62017-01-16 17:23:30 +09004189 meth | self | arg1 | ... | argN
4190 */
4191 SET_TOP(meth);
4192 PUSH(obj); // self
Yury Selivanovf2392132016-12-13 19:03:51 -05004193 }
4194 else {
INADA Naoki015bce62017-01-16 17:23:30 +09004195 /* meth is not an unbound method (but a regular attr, or
4196 something was returned by a descriptor protocol). Set
4197 the second element of the stack to NULL, to signal
Yury Selivanovf2392132016-12-13 19:03:51 -05004198 CALL_METHOD that it's not a method call.
INADA Naoki015bce62017-01-16 17:23:30 +09004199
4200 NULL | meth | arg1 | ... | argN
Yury Selivanovf2392132016-12-13 19:03:51 -05004201 */
INADA Naoki015bce62017-01-16 17:23:30 +09004202 SET_TOP(NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004203 Py_DECREF(obj);
INADA Naoki015bce62017-01-16 17:23:30 +09004204 PUSH(meth);
Yury Selivanovf2392132016-12-13 19:03:51 -05004205 }
4206 DISPATCH();
4207 }
4208
Benjamin Petersonddd19492018-09-16 22:38:02 -07004209 case TARGET(CALL_METHOD): {
Yury Selivanovf2392132016-12-13 19:03:51 -05004210 /* Designed to work in tamdem with LOAD_METHOD. */
INADA Naoki015bce62017-01-16 17:23:30 +09004211 PyObject **sp, *res, *meth;
Yury Selivanovf2392132016-12-13 19:03:51 -05004212
4213 sp = stack_pointer;
4214
INADA Naoki015bce62017-01-16 17:23:30 +09004215 meth = PEEK(oparg + 2);
4216 if (meth == NULL) {
4217 /* `meth` is NULL when LOAD_METHOD thinks that it's not
4218 a method call.
Yury Selivanovf2392132016-12-13 19:03:51 -05004219
4220 Stack layout:
4221
INADA Naoki015bce62017-01-16 17:23:30 +09004222 ... | NULL | callable | arg1 | ... | argN
4223 ^- TOP()
4224 ^- (-oparg)
4225 ^- (-oparg-1)
4226 ^- (-oparg-2)
Yury Selivanovf2392132016-12-13 19:03:51 -05004227
Ville Skyttä49b27342017-08-03 09:00:59 +03004228 `callable` will be POPed by call_function.
INADA Naoki015bce62017-01-16 17:23:30 +09004229 NULL will will be POPed manually later.
Yury Selivanovf2392132016-12-13 19:03:51 -05004230 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00004231 res = call_function(tstate, &trace_info, &sp, oparg, NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004232 stack_pointer = sp;
INADA Naoki015bce62017-01-16 17:23:30 +09004233 (void)POP(); /* POP the NULL. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004234 }
4235 else {
4236 /* This is a method call. Stack layout:
4237
INADA Naoki015bce62017-01-16 17:23:30 +09004238 ... | method | self | arg1 | ... | argN
Yury Selivanovf2392132016-12-13 19:03:51 -05004239 ^- TOP()
4240 ^- (-oparg)
INADA Naoki015bce62017-01-16 17:23:30 +09004241 ^- (-oparg-1)
4242 ^- (-oparg-2)
Yury Selivanovf2392132016-12-13 19:03:51 -05004243
INADA Naoki015bce62017-01-16 17:23:30 +09004244 `self` and `method` will be POPed by call_function.
Yury Selivanovf2392132016-12-13 19:03:51 -05004245 We'll be passing `oparg + 1` to call_function, to
INADA Naoki015bce62017-01-16 17:23:30 +09004246 make it accept the `self` as a first argument.
Yury Selivanovf2392132016-12-13 19:03:51 -05004247 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00004248 res = call_function(tstate, &trace_info, &sp, oparg + 1, NULL);
Yury Selivanovf2392132016-12-13 19:03:51 -05004249 stack_pointer = sp;
4250 }
4251
4252 PUSH(res);
4253 if (res == NULL)
4254 goto error;
Mark Shannon4958f5d2021-03-24 17:56:12 +00004255 CHECK_EVAL_BREAKER();
Yury Selivanovf2392132016-12-13 19:03:51 -05004256 DISPATCH();
4257 }
4258
Benjamin Petersonddd19492018-09-16 22:38:02 -07004259 case TARGET(CALL_FUNCTION): {
4260 PREDICTED(CALL_FUNCTION);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004261 PyObject **sp, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 sp = stack_pointer;
Mark Shannon8e1b4062021-03-05 14:45:50 +00004263 res = call_function(tstate, &trace_info, &sp, oparg, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 stack_pointer = sp;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004265 PUSH(res);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004266 if (res == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004267 goto error;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004268 }
Mark Shannon4958f5d2021-03-24 17:56:12 +00004269 CHECK_EVAL_BREAKER();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004270 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004272
Benjamin Petersonddd19492018-09-16 22:38:02 -07004273 case TARGET(CALL_FUNCTION_KW): {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004274 PyObject **sp, *res, *names;
4275
4276 names = POP();
Jeroen Demeyer05677862019-08-16 12:41:27 +02004277 assert(PyTuple_Check(names));
4278 assert(PyTuple_GET_SIZE(names) <= oparg);
4279 /* We assume without checking that names contains only strings */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 sp = stack_pointer;
Mark Shannon8e1b4062021-03-05 14:45:50 +00004281 res = call_function(tstate, &trace_info, &sp, oparg, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 stack_pointer = sp;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004283 PUSH(res);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004284 Py_DECREF(names);
4285
4286 if (res == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004287 goto error;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004288 }
Mark Shannon4958f5d2021-03-24 17:56:12 +00004289 CHECK_EVAL_BREAKER();
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004290 DISPATCH();
4291 }
4292
Benjamin Petersonddd19492018-09-16 22:38:02 -07004293 case TARGET(CALL_FUNCTION_EX): {
Brandt Bucherf185a732019-09-28 17:12:49 -07004294 PREDICTED(CALL_FUNCTION_EX);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004295 PyObject *func, *callargs, *kwargs = NULL, *result;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004296 if (oparg & 0x01) {
4297 kwargs = POP();
Serhiy Storchakab7281052016-09-12 00:52:40 +03004298 if (!PyDict_CheckExact(kwargs)) {
4299 PyObject *d = PyDict_New();
4300 if (d == NULL)
4301 goto error;
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02004302 if (_PyDict_MergeEx(d, kwargs, 2) < 0) {
Serhiy Storchakab7281052016-09-12 00:52:40 +03004303 Py_DECREF(d);
Victor Stinner438a12d2019-05-24 17:01:38 +02004304 format_kwargs_error(tstate, SECOND(), kwargs);
Victor Stinnereece2222016-09-12 11:16:37 +02004305 Py_DECREF(kwargs);
Serhiy Storchakab7281052016-09-12 00:52:40 +03004306 goto error;
4307 }
4308 Py_DECREF(kwargs);
4309 kwargs = d;
4310 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004311 assert(PyDict_CheckExact(kwargs));
4312 }
4313 callargs = POP();
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004314 func = TOP();
Serhiy Storchaka63dc5482016-09-22 19:41:20 +03004315 if (!PyTuple_CheckExact(callargs)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02004316 if (check_args_iterable(tstate, func, callargs) < 0) {
Victor Stinnereece2222016-09-12 11:16:37 +02004317 Py_DECREF(callargs);
Serhiy Storchakab7281052016-09-12 00:52:40 +03004318 goto error;
4319 }
4320 Py_SETREF(callargs, PySequence_Tuple(callargs));
4321 if (callargs == NULL) {
4322 goto error;
4323 }
4324 }
Serhiy Storchaka63dc5482016-09-22 19:41:20 +03004325 assert(PyTuple_CheckExact(callargs));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004326
Mark Shannon8e1b4062021-03-05 14:45:50 +00004327 result = do_call_core(tstate, &trace_info, func, callargs, kwargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004328 Py_DECREF(func);
4329 Py_DECREF(callargs);
4330 Py_XDECREF(kwargs);
4331
4332 SET_TOP(result);
4333 if (result == NULL) {
4334 goto error;
4335 }
Mark Shannon4958f5d2021-03-24 17:56:12 +00004336 CHECK_EVAL_BREAKER();
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004337 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 }
Guido van Rossumac7be682001-01-17 15:42:30 +00004339
Benjamin Petersonddd19492018-09-16 22:38:02 -07004340 case TARGET(MAKE_FUNCTION): {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004341 PyObject *qualname = POP();
4342 PyObject *codeobj = POP();
4343 PyFunctionObject *func = (PyFunctionObject *)
4344 PyFunction_NewWithQualName(codeobj, f->f_globals, qualname);
Guido van Rossum4f72a782006-10-27 23:31:49 +00004345
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004346 Py_DECREF(codeobj);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004347 Py_DECREF(qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004348 if (func == NULL) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004349 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 }
Neal Norwitzc1505362006-12-28 06:47:50 +00004351
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004352 if (oparg & 0x08) {
4353 assert(PyTuple_CheckExact(TOP()));
Mark Shannond6c33fb2021-01-29 13:24:55 +00004354 func->func_closure = POP();
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004355 }
4356 if (oparg & 0x04) {
Yurii Karabas73019792020-11-25 12:43:18 +02004357 assert(PyTuple_CheckExact(TOP()));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004358 func->func_annotations = POP();
4359 }
4360 if (oparg & 0x02) {
4361 assert(PyDict_CheckExact(TOP()));
4362 func->func_kwdefaults = POP();
4363 }
4364 if (oparg & 0x01) {
4365 assert(PyTuple_CheckExact(TOP()));
4366 func->func_defaults = POP();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 }
Neal Norwitzc1505362006-12-28 06:47:50 +00004368
Serhiy Storchaka64204de2016-06-12 17:36:24 +03004369 PUSH((PyObject *)func);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004370 DISPATCH();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004372
Benjamin Petersonddd19492018-09-16 22:38:02 -07004373 case TARGET(BUILD_SLICE): {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004374 PyObject *start, *stop, *step, *slice;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 if (oparg == 3)
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004376 step = POP();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 else
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004378 step = NULL;
4379 stop = POP();
4380 start = TOP();
4381 slice = PySlice_New(start, stop, step);
4382 Py_DECREF(start);
4383 Py_DECREF(stop);
4384 Py_XDECREF(step);
4385 SET_TOP(slice);
4386 if (slice == NULL)
4387 goto error;
4388 DISPATCH();
4389 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004390
Benjamin Petersonddd19492018-09-16 22:38:02 -07004391 case TARGET(FORMAT_VALUE): {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004392 /* Handles f-string value formatting. */
4393 PyObject *result;
4394 PyObject *fmt_spec;
4395 PyObject *value;
4396 PyObject *(*conv_fn)(PyObject *);
4397 int which_conversion = oparg & FVC_MASK;
4398 int have_fmt_spec = (oparg & FVS_MASK) == FVS_HAVE_SPEC;
4399
4400 fmt_spec = have_fmt_spec ? POP() : NULL;
Eric V. Smith135d5f42016-02-05 18:23:08 -05004401 value = POP();
Eric V. Smitha78c7952015-11-03 12:45:05 -05004402
4403 /* See if any conversion is specified. */
4404 switch (which_conversion) {
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004405 case FVC_NONE: conv_fn = NULL; break;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004406 case FVC_STR: conv_fn = PyObject_Str; break;
4407 case FVC_REPR: conv_fn = PyObject_Repr; break;
4408 case FVC_ASCII: conv_fn = PyObject_ASCII; break;
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004409 default:
Victor Stinner438a12d2019-05-24 17:01:38 +02004410 _PyErr_Format(tstate, PyExc_SystemError,
4411 "unexpected conversion flag %d",
4412 which_conversion);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004413 goto error;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004414 }
4415
4416 /* If there's a conversion function, call it and replace
4417 value with that result. Otherwise, just use value,
4418 without conversion. */
Eric V. Smitheb588a12016-02-05 18:26:20 -05004419 if (conv_fn != NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004420 result = conv_fn(value);
4421 Py_DECREF(value);
Eric V. Smitheb588a12016-02-05 18:26:20 -05004422 if (result == NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004423 Py_XDECREF(fmt_spec);
4424 goto error;
4425 }
4426 value = result;
4427 }
4428
4429 /* If value is a unicode object, and there's no fmt_spec,
4430 then we know the result of format(value) is value
4431 itself. In that case, skip calling format(). I plan to
4432 move this optimization in to PyObject_Format()
4433 itself. */
4434 if (PyUnicode_CheckExact(value) && fmt_spec == NULL) {
4435 /* Do nothing, just transfer ownership to result. */
4436 result = value;
4437 } else {
4438 /* Actually call format(). */
4439 result = PyObject_Format(value, fmt_spec);
4440 Py_DECREF(value);
4441 Py_XDECREF(fmt_spec);
Eric V. Smitheb588a12016-02-05 18:26:20 -05004442 if (result == NULL) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004443 goto error;
Eric V. Smitheb588a12016-02-05 18:26:20 -05004444 }
Eric V. Smitha78c7952015-11-03 12:45:05 -05004445 }
4446
Eric V. Smith135d5f42016-02-05 18:23:08 -05004447 PUSH(result);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004448 DISPATCH();
4449 }
4450
Benjamin Petersonddd19492018-09-16 22:38:02 -07004451 case TARGET(EXTENDED_ARG): {
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03004452 int oldoparg = oparg;
4453 NEXTOPARG();
4454 oparg |= oldoparg << 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 goto dispatch_opcode;
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004456 }
Guido van Rossum8861b741996-07-30 16:49:37 +00004457
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004458
Antoine Pitrou042b1282010-08-13 21:15:58 +00004459#if USE_COMPUTED_GOTOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 _unknown_opcode:
Antoine Pitroub52ec782009-01-25 16:34:23 +00004461#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 default:
4463 fprintf(stderr,
4464 "XXX lineno: %d, opcode: %d\n",
4465 PyFrame_GetLineNumber(f),
4466 opcode);
Victor Stinner438a12d2019-05-24 17:01:38 +02004467 _PyErr_SetString(tstate, PyExc_SystemError, "unknown opcode");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004468 goto error;
Guido van Rossum04691fc1992-08-12 15:35:34 +00004469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 } /* switch */
Guido van Rossum374a9221991-04-04 10:40:29 +00004471
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004472 /* This should never be reached. Every opcode should end with DISPATCH()
4473 or goto error. */
Barry Warsawb2e57942017-09-14 18:13:16 -07004474 Py_UNREACHABLE();
Guido van Rossumac7be682001-01-17 15:42:30 +00004475
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004476error:
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004477 /* Double-check exception status. */
Victor Stinner365b6932013-07-12 00:11:58 +02004478#ifdef NDEBUG
Victor Stinner438a12d2019-05-24 17:01:38 +02004479 if (!_PyErr_Occurred(tstate)) {
4480 _PyErr_SetString(tstate, PyExc_SystemError,
4481 "error return without exception set");
4482 }
Victor Stinner365b6932013-07-12 00:11:58 +02004483#else
Victor Stinner438a12d2019-05-24 17:01:38 +02004484 assert(_PyErr_Occurred(tstate));
Victor Stinner365b6932013-07-12 00:11:58 +02004485#endif
Guido van Rossum374a9221991-04-04 10:40:29 +00004486
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004487 /* Log traceback info. */
4488 PyTraceBack_Here(f);
Guido van Rossumac7be682001-01-17 15:42:30 +00004489
Mark Shannoncb9879b2020-07-17 11:44:23 +01004490 if (tstate->c_tracefunc != NULL) {
4491 /* Make sure state is set to FRAME_EXECUTING for tracing */
4492 assert(f->f_state == FRAME_EXECUTING);
4493 f->f_state = FRAME_UNWINDING;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01004494 call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004495 tstate, f, &trace_info);
Mark Shannoncb9879b2020-07-17 11:44:23 +01004496 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004497exception_unwind:
Mark Shannoncb9879b2020-07-17 11:44:23 +01004498 f->f_state = FRAME_UNWINDING;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004499 /* Unwind stacks if an exception occurred */
4500 while (f->f_iblock > 0) {
4501 /* Pop the current block. */
4502 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 if (b->b_type == EXCEPT_HANDLER) {
4505 UNWIND_EXCEPT_HANDLER(b);
4506 continue;
4507 }
4508 UNWIND_BLOCK(b);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004509 if (b->b_type == SETUP_FINALLY) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 PyObject *exc, *val, *tb;
4511 int handler = b->b_handler;
Mark Shannonae3087c2017-10-22 22:41:51 +01004512 _PyErr_StackItem *exc_info = tstate->exc_info;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 /* Beware, this invalidates all b->b_* fields */
Mark Shannonbf353f32020-12-17 13:55:28 +00004514 PyFrame_BlockSetup(f, EXCEPT_HANDLER, f->f_lasti, STACK_LEVEL());
Mark Shannonae3087c2017-10-22 22:41:51 +01004515 PUSH(exc_info->exc_traceback);
4516 PUSH(exc_info->exc_value);
4517 if (exc_info->exc_type != NULL) {
4518 PUSH(exc_info->exc_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 }
4520 else {
4521 Py_INCREF(Py_None);
4522 PUSH(Py_None);
4523 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004524 _PyErr_Fetch(tstate, &exc, &val, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 /* Make the raw exception data
4526 available to the handler,
4527 so a program can emulate the
4528 Python main loop. */
Victor Stinner438a12d2019-05-24 17:01:38 +02004529 _PyErr_NormalizeException(tstate, &exc, &val, &tb);
Victor Stinner7eab0d02013-07-15 21:16:27 +02004530 if (tb != NULL)
4531 PyException_SetTraceback(val, tb);
4532 else
4533 PyException_SetTraceback(val, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 Py_INCREF(exc);
Mark Shannonae3087c2017-10-22 22:41:51 +01004535 exc_info->exc_type = exc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 Py_INCREF(val);
Mark Shannonae3087c2017-10-22 22:41:51 +01004537 exc_info->exc_value = val;
4538 exc_info->exc_traceback = tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 if (tb == NULL)
4540 tb = Py_None;
4541 Py_INCREF(tb);
4542 PUSH(tb);
4543 PUSH(val);
4544 PUSH(exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 JUMPTO(handler);
Victor Stinnerdab84232020-03-17 18:56:44 +01004546 if (_Py_TracingPossible(ceval2)) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00004547 trace_info.instr_prev = INT_MAX;
Mark Shannonfee55262019-11-21 09:11:43 +00004548 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004549 /* Resume normal execution */
Mark Shannoncb9879b2020-07-17 11:44:23 +01004550 f->f_state = FRAME_EXECUTING;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004551 goto main_loop;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 }
4553 } /* unwind stack */
Guido van Rossum374a9221991-04-04 10:40:29 +00004554
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004555 /* End the loop as we still have an error */
4556 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 } /* main loop */
Guido van Rossumac7be682001-01-17 15:42:30 +00004558
Pablo Galindof00828a2019-05-09 16:52:02 +01004559 assert(retval == NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02004560 assert(_PyErr_Occurred(tstate));
Pablo Galindof00828a2019-05-09 16:52:02 +01004561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 /* Pop remaining stack entries. */
4563 while (!EMPTY()) {
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04004564 PyObject *o = POP();
4565 Py_XDECREF(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 }
Mark Shannoncb9879b2020-07-17 11:44:23 +01004567 f->f_stackdepth = 0;
4568 f->f_state = FRAME_RAISED;
Mark Shannone7c9f4a2020-01-13 12:51:26 +00004569exiting:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 if (tstate->use_tracing) {
Benjamin Peterson51f46162013-01-23 08:38:47 -05004571 if (tstate->c_tracefunc) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004572 if (call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004573 tstate, f, &trace_info, PyTrace_RETURN, retval)) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004574 Py_CLEAR(retval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 }
4576 }
4577 if (tstate->c_profilefunc) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004578 if (call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj,
Mark Shannon8e1b4062021-03-05 14:45:50 +00004579 tstate, f, &trace_info, PyTrace_RETURN, retval)) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004580 Py_CLEAR(retval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 }
4582 }
4583 }
Guido van Rossuma4240131997-01-21 21:18:36 +00004584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 /* pop frame */
Thomas Woutersce272b62007-09-19 21:19:28 +00004586exit_eval_frame:
Łukasz Langaa785c872016-09-09 17:37:37 -07004587 if (PyDTrace_FUNCTION_RETURN_ENABLED())
4588 dtrace_function_return(f);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01004589 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 tstate->frame = f->f_back;
Guido van Rossumac7be682001-01-17 15:42:30 +00004591
Victor Stinner0b72b232020-03-12 23:18:39 +01004592 return _Py_CheckFunctionResult(tstate, NULL, retval, __func__);
Guido van Rossum374a9221991-04-04 10:40:29 +00004593}
4594
Benjamin Petersonb204a422011-06-05 22:04:07 -05004595static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004596format_missing(PyThreadState *tstate, const char *kind,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004597 PyCodeObject *co, PyObject *names, PyObject *qualname)
Benjamin Petersone109c702011-06-24 09:37:26 -05004598{
4599 int err;
4600 Py_ssize_t len = PyList_GET_SIZE(names);
4601 PyObject *name_str, *comma, *tail, *tmp;
4602
4603 assert(PyList_CheckExact(names));
4604 assert(len >= 1);
4605 /* Deal with the joys of natural language. */
4606 switch (len) {
4607 case 1:
4608 name_str = PyList_GET_ITEM(names, 0);
4609 Py_INCREF(name_str);
4610 break;
4611 case 2:
4612 name_str = PyUnicode_FromFormat("%U and %U",
4613 PyList_GET_ITEM(names, len - 2),
4614 PyList_GET_ITEM(names, len - 1));
4615 break;
4616 default:
4617 tail = PyUnicode_FromFormat(", %U, and %U",
4618 PyList_GET_ITEM(names, len - 2),
4619 PyList_GET_ITEM(names, len - 1));
Benjamin Petersond1ab6082012-06-01 11:18:22 -07004620 if (tail == NULL)
4621 return;
Benjamin Petersone109c702011-06-24 09:37:26 -05004622 /* Chop off the last two objects in the list. This shouldn't actually
4623 fail, but we can't be too careful. */
4624 err = PyList_SetSlice(names, len - 2, len, NULL);
4625 if (err == -1) {
4626 Py_DECREF(tail);
4627 return;
4628 }
4629 /* Stitch everything up into a nice comma-separated list. */
4630 comma = PyUnicode_FromString(", ");
4631 if (comma == NULL) {
4632 Py_DECREF(tail);
4633 return;
4634 }
4635 tmp = PyUnicode_Join(comma, names);
4636 Py_DECREF(comma);
4637 if (tmp == NULL) {
4638 Py_DECREF(tail);
4639 return;
4640 }
4641 name_str = PyUnicode_Concat(tmp, tail);
4642 Py_DECREF(tmp);
4643 Py_DECREF(tail);
4644 break;
4645 }
4646 if (name_str == NULL)
4647 return;
Victor Stinner438a12d2019-05-24 17:01:38 +02004648 _PyErr_Format(tstate, PyExc_TypeError,
4649 "%U() missing %i required %s argument%s: %U",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004650 qualname,
Victor Stinner438a12d2019-05-24 17:01:38 +02004651 len,
4652 kind,
4653 len == 1 ? "" : "s",
4654 name_str);
Benjamin Petersone109c702011-06-24 09:37:26 -05004655 Py_DECREF(name_str);
4656}
4657
4658static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004659missing_arguments(PyThreadState *tstate, PyCodeObject *co,
4660 Py_ssize_t missing, Py_ssize_t defcount,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004661 PyObject **fastlocals, PyObject *qualname)
Benjamin Petersone109c702011-06-24 09:37:26 -05004662{
Victor Stinner74319ae2016-08-25 00:04:09 +02004663 Py_ssize_t i, j = 0;
4664 Py_ssize_t start, end;
4665 int positional = (defcount != -1);
Benjamin Petersone109c702011-06-24 09:37:26 -05004666 const char *kind = positional ? "positional" : "keyword-only";
4667 PyObject *missing_names;
4668
4669 /* Compute the names of the arguments that are missing. */
4670 missing_names = PyList_New(missing);
4671 if (missing_names == NULL)
4672 return;
4673 if (positional) {
4674 start = 0;
Pablo Galindocd74e662019-06-01 18:08:04 +01004675 end = co->co_argcount - defcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05004676 }
4677 else {
Pablo Galindocd74e662019-06-01 18:08:04 +01004678 start = co->co_argcount;
Benjamin Petersone109c702011-06-24 09:37:26 -05004679 end = start + co->co_kwonlyargcount;
4680 }
4681 for (i = start; i < end; i++) {
4682 if (GETLOCAL(i) == NULL) {
4683 PyObject *raw = PyTuple_GET_ITEM(co->co_varnames, i);
4684 PyObject *name = PyObject_Repr(raw);
4685 if (name == NULL) {
4686 Py_DECREF(missing_names);
4687 return;
4688 }
4689 PyList_SET_ITEM(missing_names, j++, name);
4690 }
4691 }
4692 assert(j == missing);
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004693 format_missing(tstate, kind, co, missing_names, qualname);
Benjamin Petersone109c702011-06-24 09:37:26 -05004694 Py_DECREF(missing_names);
4695}
4696
4697static void
Victor Stinner438a12d2019-05-24 17:01:38 +02004698too_many_positional(PyThreadState *tstate, PyCodeObject *co,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004699 Py_ssize_t given, PyObject *defaults,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004700 PyObject **fastlocals, PyObject *qualname)
Benjamin Petersonb204a422011-06-05 22:04:07 -05004701{
4702 int plural;
Victor Stinner74319ae2016-08-25 00:04:09 +02004703 Py_ssize_t kwonly_given = 0;
4704 Py_ssize_t i;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004705 PyObject *sig, *kwonly_sig;
Victor Stinner74319ae2016-08-25 00:04:09 +02004706 Py_ssize_t co_argcount = co->co_argcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004707
Benjamin Petersone109c702011-06-24 09:37:26 -05004708 assert((co->co_flags & CO_VARARGS) == 0);
4709 /* Count missing keyword-only args. */
Pablo Galindocd74e662019-06-01 18:08:04 +01004710 for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
Victor Stinner74319ae2016-08-25 00:04:09 +02004711 if (GETLOCAL(i) != NULL) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004712 kwonly_given++;
Victor Stinner74319ae2016-08-25 00:04:09 +02004713 }
4714 }
Mark Shannond6c33fb2021-01-29 13:24:55 +00004715 Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
Benjamin Petersone109c702011-06-24 09:37:26 -05004716 if (defcount) {
Pablo Galindocd74e662019-06-01 18:08:04 +01004717 Py_ssize_t atleast = co_argcount - defcount;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004718 plural = 1;
Pablo Galindocd74e662019-06-01 18:08:04 +01004719 sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004720 }
4721 else {
Pablo Galindocd74e662019-06-01 18:08:04 +01004722 plural = (co_argcount != 1);
4723 sig = PyUnicode_FromFormat("%zd", co_argcount);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004724 }
4725 if (sig == NULL)
4726 return;
4727 if (kwonly_given) {
Victor Stinner74319ae2016-08-25 00:04:09 +02004728 const char *format = " positional argument%s (and %zd keyword-only argument%s)";
4729 kwonly_sig = PyUnicode_FromFormat(format,
4730 given != 1 ? "s" : "",
4731 kwonly_given,
4732 kwonly_given != 1 ? "s" : "");
Benjamin Petersonb204a422011-06-05 22:04:07 -05004733 if (kwonly_sig == NULL) {
4734 Py_DECREF(sig);
4735 return;
4736 }
4737 }
4738 else {
4739 /* This will not fail. */
4740 kwonly_sig = PyUnicode_FromString("");
Benjamin Petersone109c702011-06-24 09:37:26 -05004741 assert(kwonly_sig != NULL);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004742 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004743 _PyErr_Format(tstate, PyExc_TypeError,
4744 "%U() takes %U positional argument%s but %zd%U %s given",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004745 qualname,
Victor Stinner438a12d2019-05-24 17:01:38 +02004746 sig,
4747 plural ? "s" : "",
4748 given,
4749 kwonly_sig,
4750 given == 1 && !kwonly_given ? "was" : "were");
Benjamin Petersonb204a422011-06-05 22:04:07 -05004751 Py_DECREF(sig);
4752 Py_DECREF(kwonly_sig);
4753}
4754
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004755static int
Victor Stinner438a12d2019-05-24 17:01:38 +02004756positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
Mark Shannon0332e562021-02-01 10:42:03 +00004757 Py_ssize_t kwcount, PyObject* kwnames,
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004758 PyObject *qualname)
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004759{
4760 int posonly_conflicts = 0;
4761 PyObject* posonly_names = PyList_New(0);
4762
4763 for(int k=0; k < co->co_posonlyargcount; k++){
4764 PyObject* posonly_name = PyTuple_GET_ITEM(co->co_varnames, k);
4765
4766 for (int k2=0; k2<kwcount; k2++){
4767 /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
Mark Shannon0332e562021-02-01 10:42:03 +00004768 PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004769 if (kwname == posonly_name){
4770 if(PyList_Append(posonly_names, kwname) != 0) {
4771 goto fail;
4772 }
4773 posonly_conflicts++;
4774 continue;
4775 }
4776
4777 int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
4778
4779 if ( cmp > 0) {
4780 if(PyList_Append(posonly_names, kwname) != 0) {
4781 goto fail;
4782 }
4783 posonly_conflicts++;
4784 } else if (cmp < 0) {
4785 goto fail;
4786 }
4787
4788 }
4789 }
4790 if (posonly_conflicts) {
4791 PyObject* comma = PyUnicode_FromString(", ");
4792 if (comma == NULL) {
4793 goto fail;
4794 }
4795 PyObject* error_names = PyUnicode_Join(comma, posonly_names);
4796 Py_DECREF(comma);
4797 if (error_names == NULL) {
4798 goto fail;
4799 }
Victor Stinner438a12d2019-05-24 17:01:38 +02004800 _PyErr_Format(tstate, PyExc_TypeError,
4801 "%U() got some positional-only arguments passed"
4802 " as keyword arguments: '%U'",
Dennis Sweeneyb5cc2082020-05-22 16:40:17 -04004803 qualname, error_names);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004804 Py_DECREF(error_names);
4805 goto fail;
4806 }
4807
4808 Py_DECREF(posonly_names);
4809 return 0;
4810
4811fail:
4812 Py_XDECREF(posonly_names);
4813 return 1;
4814
4815}
4816
Skip Montanaro786ea6b2004-03-01 15:44:05 +00004817
Mark Shannon0332e562021-02-01 10:42:03 +00004818PyFrameObject *
4819_PyEval_MakeFrameVector(PyThreadState *tstate,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004820 PyFrameConstructor *con, PyObject *locals,
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02004821 PyObject *const *args, Py_ssize_t argcount,
Mark Shannon0332e562021-02-01 10:42:03 +00004822 PyObject *kwnames)
Tim Peters5ca576e2001-06-18 22:08:13 +00004823{
Victor Stinnerda2914d2020-03-20 09:29:08 +01004824 assert(is_tstate_valid(tstate));
Victor Stinnerb5e170f2019-11-16 01:03:22 +01004825
Mark Shannond6c33fb2021-01-29 13:24:55 +00004826 PyCodeObject *co = (PyCodeObject*)con->fc_code;
4827 assert(con->fc_defaults == NULL || PyTuple_CheckExact(con->fc_defaults));
Pablo Galindocd74e662019-06-01 18:08:04 +01004828 const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
Tim Peters5ca576e2001-06-18 22:08:13 +00004829
Victor Stinnerc7020012016-08-16 23:40:29 +02004830 /* Create the frame */
Mark Shannon0332e562021-02-01 10:42:03 +00004831 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, con, locals);
Victor Stinnerc7020012016-08-16 23:40:29 +02004832 if (f == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 return NULL;
Victor Stinnerc7020012016-08-16 23:40:29 +02004834 }
Victor Stinner232dda62020-06-04 15:19:02 +02004835 PyObject **fastlocals = f->f_localsplus;
4836 PyObject **freevars = f->f_localsplus + co->co_nlocals;
Tim Peters5ca576e2001-06-18 22:08:13 +00004837
Victor Stinnerc7020012016-08-16 23:40:29 +02004838 /* Create a dictionary for keyword parameters (**kwags) */
Victor Stinner232dda62020-06-04 15:19:02 +02004839 PyObject *kwdict;
4840 Py_ssize_t i;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004841 if (co->co_flags & CO_VARKEYWORDS) {
4842 kwdict = PyDict_New();
4843 if (kwdict == NULL)
4844 goto fail;
4845 i = total_args;
Victor Stinnerc7020012016-08-16 23:40:29 +02004846 if (co->co_flags & CO_VARARGS) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004847 i++;
Victor Stinnerc7020012016-08-16 23:40:29 +02004848 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004849 SETLOCAL(i, kwdict);
4850 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004851 else {
4852 kwdict = NULL;
4853 }
4854
Pablo Galindocd74e662019-06-01 18:08:04 +01004855 /* Copy all positional arguments into local variables */
Victor Stinner232dda62020-06-04 15:19:02 +02004856 Py_ssize_t j, n;
Pablo Galindocd74e662019-06-01 18:08:04 +01004857 if (argcount > co->co_argcount) {
4858 n = co->co_argcount;
Victor Stinnerc7020012016-08-16 23:40:29 +02004859 }
4860 else {
4861 n = argcount;
4862 }
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004863 for (j = 0; j < n; j++) {
Victor Stinner232dda62020-06-04 15:19:02 +02004864 PyObject *x = args[j];
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004865 Py_INCREF(x);
4866 SETLOCAL(j, x);
4867 }
4868
Victor Stinnerc7020012016-08-16 23:40:29 +02004869 /* Pack other positional arguments into the *args argument */
Benjamin Petersonb204a422011-06-05 22:04:07 -05004870 if (co->co_flags & CO_VARARGS) {
Victor Stinner232dda62020-06-04 15:19:02 +02004871 PyObject *u = _PyTuple_FromArray(args + n, argcount - n);
Victor Stinnerc7020012016-08-16 23:40:29 +02004872 if (u == NULL) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004873 goto fail;
Victor Stinnerc7020012016-08-16 23:40:29 +02004874 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004875 SETLOCAL(total_args, u);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004876 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004877
Mark Shannon0332e562021-02-01 10:42:03 +00004878 /* Handle keyword arguments */
4879 if (kwnames != NULL) {
4880 Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
4881 for (i = 0; i < kwcount; i++) {
4882 PyObject **co_varnames;
4883 PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
4884 PyObject *value = args[i+argcount];
4885 Py_ssize_t j;
Victor Stinnerc7020012016-08-16 23:40:29 +02004886
Mark Shannon0332e562021-02-01 10:42:03 +00004887 if (keyword == NULL || !PyUnicode_Check(keyword)) {
4888 _PyErr_Format(tstate, PyExc_TypeError,
4889 "%U() keywords must be strings",
Mark Shannond6c33fb2021-01-29 13:24:55 +00004890 con->fc_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 goto fail;
Victor Stinner6fea7f72016-08-22 23:17:30 +02004892 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004893
Mark Shannon0332e562021-02-01 10:42:03 +00004894 /* Speed hack: do raw pointer compares. As names are
4895 normally interned this should almost always hit. */
4896 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
4897 for (j = co->co_posonlyargcount; j < total_args; j++) {
4898 PyObject *varname = co_varnames[j];
4899 if (varname == keyword) {
4900 goto kw_found;
4901 }
4902 }
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004903
Mark Shannon0332e562021-02-01 10:42:03 +00004904 /* Slow fallback, just in case */
4905 for (j = co->co_posonlyargcount; j < total_args; j++) {
4906 PyObject *varname = co_varnames[j];
4907 int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
4908 if (cmp > 0) {
4909 goto kw_found;
4910 }
4911 else if (cmp < 0) {
4912 goto fail;
4913 }
4914 }
4915
4916 assert(j >= total_args);
4917 if (kwdict == NULL) {
4918
4919 if (co->co_posonlyargcount
4920 && positional_only_passed_as_keyword(tstate, co,
4921 kwcount, kwnames,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004922 con->fc_qualname))
Mark Shannon0332e562021-02-01 10:42:03 +00004923 {
4924 goto fail;
4925 }
4926
4927 _PyErr_Format(tstate, PyExc_TypeError,
4928 "%U() got an unexpected keyword argument '%S'",
4929 con->fc_qualname, keyword);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01004930 goto fail;
4931 }
4932
Mark Shannon0332e562021-02-01 10:42:03 +00004933 if (PyDict_SetItem(kwdict, keyword, value) == -1) {
4934 goto fail;
4935 }
4936 continue;
Victor Stinnerc7020012016-08-16 23:40:29 +02004937
Mark Shannon0332e562021-02-01 10:42:03 +00004938 kw_found:
4939 if (GETLOCAL(j) != NULL) {
4940 _PyErr_Format(tstate, PyExc_TypeError,
4941 "%U() got multiple values for argument '%S'",
Mark Shannond6c33fb2021-01-29 13:24:55 +00004942 con->fc_qualname, keyword);
Mark Shannon0332e562021-02-01 10:42:03 +00004943 goto fail;
4944 }
4945 Py_INCREF(value);
4946 SETLOCAL(j, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004949
4950 /* Check the number of positional arguments */
Pablo Galindocd74e662019-06-01 18:08:04 +01004951 if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00004952 too_many_positional(tstate, co, argcount, con->fc_defaults, fastlocals,
4953 con->fc_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 goto fail;
4955 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004956
4957 /* Add missing positional arguments (copy default values from defs) */
Pablo Galindocd74e662019-06-01 18:08:04 +01004958 if (argcount < co->co_argcount) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00004959 Py_ssize_t defcount = con->fc_defaults == NULL ? 0 : PyTuple_GET_SIZE(con->fc_defaults);
Pablo Galindocd74e662019-06-01 18:08:04 +01004960 Py_ssize_t m = co->co_argcount - defcount;
Victor Stinner17061a92016-08-16 23:39:42 +02004961 Py_ssize_t missing = 0;
4962 for (i = argcount; i < m; i++) {
4963 if (GETLOCAL(i) == NULL) {
Benjamin Petersone109c702011-06-24 09:37:26 -05004964 missing++;
Victor Stinner17061a92016-08-16 23:39:42 +02004965 }
4966 }
Benjamin Petersone109c702011-06-24 09:37:26 -05004967 if (missing) {
Victor Stinner232dda62020-06-04 15:19:02 +02004968 missing_arguments(tstate, co, missing, defcount, fastlocals,
Mark Shannond6c33fb2021-01-29 13:24:55 +00004969 con->fc_qualname);
Benjamin Petersone109c702011-06-24 09:37:26 -05004970 goto fail;
Benjamin Petersonb204a422011-06-05 22:04:07 -05004971 }
4972 if (n > m)
4973 i = n - m;
4974 else
4975 i = 0;
Mark Shannond6c33fb2021-01-29 13:24:55 +00004976 if (defcount) {
4977 PyObject **defs = &PyTuple_GET_ITEM(con->fc_defaults, 0);
4978 for (; i < defcount; i++) {
4979 if (GETLOCAL(m+i) == NULL) {
4980 PyObject *def = defs[i];
4981 Py_INCREF(def);
4982 SETLOCAL(m+i, def);
4983 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05004984 }
4985 }
4986 }
Victor Stinnerc7020012016-08-16 23:40:29 +02004987
4988 /* Add missing keyword arguments (copy default values from kwdefs) */
Benjamin Petersonb204a422011-06-05 22:04:07 -05004989 if (co->co_kwonlyargcount > 0) {
Victor Stinner17061a92016-08-16 23:39:42 +02004990 Py_ssize_t missing = 0;
Pablo Galindocd74e662019-06-01 18:08:04 +01004991 for (i = co->co_argcount; i < total_args; i++) {
Benjamin Petersonb204a422011-06-05 22:04:07 -05004992 if (GETLOCAL(i) != NULL)
4993 continue;
Victor Stinner232dda62020-06-04 15:19:02 +02004994 PyObject *varname = PyTuple_GET_ITEM(co->co_varnames, i);
Mark Shannond6c33fb2021-01-29 13:24:55 +00004995 if (con->fc_kwdefaults != NULL) {
4996 PyObject *def = PyDict_GetItemWithError(con->fc_kwdefaults, varname);
Benjamin Petersonb204a422011-06-05 22:04:07 -05004997 if (def) {
4998 Py_INCREF(def);
4999 SETLOCAL(i, def);
5000 continue;
5001 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005002 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02005003 goto fail;
5004 }
Benjamin Petersonb204a422011-06-05 22:04:07 -05005005 }
Benjamin Petersone109c702011-06-24 09:37:26 -05005006 missing++;
5007 }
5008 if (missing) {
Victor Stinner232dda62020-06-04 15:19:02 +02005009 missing_arguments(tstate, co, missing, -1, fastlocals,
Mark Shannond6c33fb2021-01-29 13:24:55 +00005010 con->fc_qualname);
Benjamin Petersonb204a422011-06-05 22:04:07 -05005011 goto fail;
5012 }
5013 }
5014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 /* Allocate and initialize storage for cell vars, and copy free
Benjamin Peterson90037602011-06-25 22:54:45 -05005016 vars into frame. */
5017 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 PyObject *c;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +02005019 Py_ssize_t arg;
Benjamin Peterson90037602011-06-25 22:54:45 -05005020 /* Possibly account for the cell variable being an argument. */
5021 if (co->co_cell2arg != NULL &&
Guido van Rossum6832c812013-05-10 08:47:42 -07005022 (arg = co->co_cell2arg[i]) != CO_CELL_NOT_AN_ARG) {
Benjamin Peterson90037602011-06-25 22:54:45 -05005023 c = PyCell_New(GETLOCAL(arg));
Benjamin Peterson159ae412013-05-12 18:16:06 -05005024 /* Clear the local copy. */
5025 SETLOCAL(arg, NULL);
Guido van Rossum6832c812013-05-10 08:47:42 -07005026 }
5027 else {
Benjamin Peterson90037602011-06-25 22:54:45 -05005028 c = PyCell_New(NULL);
Guido van Rossum6832c812013-05-10 08:47:42 -07005029 }
Benjamin Peterson159ae412013-05-12 18:16:06 -05005030 if (c == NULL)
5031 goto fail;
Benjamin Peterson90037602011-06-25 22:54:45 -05005032 SETLOCAL(co->co_nlocals + i, c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 }
Victor Stinnerc7020012016-08-16 23:40:29 +02005034
5035 /* Copy closure variables to free variables */
Benjamin Peterson90037602011-06-25 22:54:45 -05005036 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
Mark Shannond6c33fb2021-01-29 13:24:55 +00005037 PyObject *o = PyTuple_GET_ITEM(con->fc_closure, i);
Benjamin Peterson90037602011-06-25 22:54:45 -05005038 Py_INCREF(o);
5039 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 }
Tim Peters5ca576e2001-06-18 22:08:13 +00005041
Mark Shannon0332e562021-02-01 10:42:03 +00005042 return f;
Tim Peters5ca576e2001-06-18 22:08:13 +00005043
Thomas Woutersce272b62007-09-19 21:19:28 +00005044fail: /* Jump here from prelude on failure */
Tim Peters5ca576e2001-06-18 22:08:13 +00005045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 /* decref'ing the frame can cause __del__ methods to get invoked,
5047 which can call back into Python. While we're done with the
5048 current Python frame (f), the associated C stack is still in use,
5049 so recursion_depth must be boosted for the duration.
5050 */
INADA Naoki5a625d02016-12-24 20:19:08 +09005051 if (Py_REFCNT(f) > 1) {
5052 Py_DECREF(f);
5053 _PyObject_GC_TRACK(f);
5054 }
5055 else {
5056 ++tstate->recursion_depth;
5057 Py_DECREF(f);
5058 --tstate->recursion_depth;
5059 }
Mark Shannon0332e562021-02-01 10:42:03 +00005060 return NULL;
5061}
5062
5063static PyObject *
5064make_coro(PyFrameConstructor *con, PyFrameObject *f)
5065{
5066 assert (((PyCodeObject *)con->fc_code)->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR));
5067 PyObject *gen;
5068 int is_coro = ((PyCodeObject *)con->fc_code)->co_flags & CO_COROUTINE;
5069
5070 /* Don't need to keep the reference to f_back, it will be set
5071 * when the generator is resumed. */
5072 Py_CLEAR(f->f_back);
5073
5074 /* Create a new generator that owns the ready to run frame
5075 * and return that as the value. */
5076 if (is_coro) {
5077 gen = PyCoro_New(f, con->fc_name, con->fc_qualname);
5078 } else if (((PyCodeObject *)con->fc_code)->co_flags & CO_ASYNC_GENERATOR) {
5079 gen = PyAsyncGen_New(f, con->fc_name, con->fc_qualname);
5080 } else {
5081 gen = PyGen_NewWithQualName(f, con->fc_name, con->fc_qualname);
5082 }
5083 if (gen == NULL) {
5084 return NULL;
5085 }
5086
5087 _PyObject_GC_TRACK(f);
5088
5089 return gen;
5090}
5091
5092PyObject *
5093_PyEval_Vector(PyThreadState *tstate, PyFrameConstructor *con,
5094 PyObject *locals,
5095 PyObject* const* args, size_t argcount,
5096 PyObject *kwnames)
5097{
5098 PyFrameObject *f = _PyEval_MakeFrameVector(
5099 tstate, con, locals, args, argcount, kwnames);
5100 if (f == NULL) {
5101 return NULL;
5102 }
5103 if (((PyCodeObject *)con->fc_code)->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
5104 return make_coro(con, f);
5105 }
5106 PyObject *retval = _PyEval_EvalFrame(tstate, f, 0);
5107
5108 /* decref'ing the frame can cause __del__ methods to get invoked,
5109 which can call back into Python. While we're done with the
5110 current Python frame (f), the associated C stack is still in use,
5111 so recursion_depth must be boosted for the duration.
5112 */
5113 if (Py_REFCNT(f) > 1) {
5114 Py_DECREF(f);
5115 _PyObject_GC_TRACK(f);
5116 }
5117 else {
5118 ++tstate->recursion_depth;
5119 Py_DECREF(f);
5120 --tstate->recursion_depth;
5121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 return retval;
Tim Peters5ca576e2001-06-18 22:08:13 +00005123}
5124
Mark Shannond6c33fb2021-01-29 13:24:55 +00005125/* Legacy API */
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005126PyObject *
Mark Shannon0332e562021-02-01 10:42:03 +00005127PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
5128 PyObject *const *args, int argcount,
5129 PyObject *const *kws, int kwcount,
5130 PyObject *const *defs, int defcount,
5131 PyObject *kwdefs, PyObject *closure)
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005132{
Victor Stinner46496f92021-02-20 15:17:18 +01005133 PyThreadState *tstate = _PyThreadState_GET();
Mark Shannon0332e562021-02-01 10:42:03 +00005134 PyObject *res;
Mark Shannond6c33fb2021-01-29 13:24:55 +00005135 PyObject *defaults = _PyTuple_FromArray(defs, defcount);
5136 if (defaults == NULL) {
5137 return NULL;
5138 }
Victor Stinnerfc980e02021-03-18 14:51:24 +01005139 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Mark Shannond6c33fb2021-01-29 13:24:55 +00005140 if (builtins == NULL) {
5141 Py_DECREF(defaults);
5142 return NULL;
5143 }
Mark Shannon0332e562021-02-01 10:42:03 +00005144 if (locals == NULL) {
5145 locals = globals;
5146 }
5147 PyObject *kwnames;
5148 PyObject *const *allargs;
5149 PyObject **newargs;
5150 if (kwcount == 0) {
5151 allargs = args;
5152 kwnames = NULL;
5153 }
5154 else {
5155 kwnames = PyTuple_New(kwcount);
5156 if (kwnames == NULL) {
5157 res = NULL;
5158 goto fail;
5159 }
5160 newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
5161 if (newargs == NULL) {
5162 res = NULL;
5163 Py_DECREF(kwnames);
5164 goto fail;
5165 }
5166 for (int i = 0; i < argcount; i++) {
5167 newargs[i] = args[i];
5168 }
5169 for (int i = 0; i < kwcount; i++) {
5170 Py_INCREF(kws[2*i]);
5171 PyTuple_SET_ITEM(kwnames, i, kws[2*i]);
5172 newargs[argcount+i] = kws[2*i+1];
5173 }
5174 allargs = newargs;
5175 }
5176 PyObject **kwargs = PyMem_Malloc(sizeof(PyObject *)*kwcount);
5177 if (kwargs == NULL) {
5178 res = NULL;
5179 Py_DECREF(kwnames);
5180 goto fail;
5181 }
5182 for (int i = 0; i < kwcount; i++) {
5183 Py_INCREF(kws[2*i]);
5184 PyTuple_SET_ITEM(kwnames, i, kws[2*i]);
5185 kwargs[i] = kws[2*i+1];
5186 }
Mark Shannond6c33fb2021-01-29 13:24:55 +00005187 PyFrameConstructor constr = {
5188 .fc_globals = globals,
5189 .fc_builtins = builtins,
Mark Shannon0332e562021-02-01 10:42:03 +00005190 .fc_name = ((PyCodeObject *)_co)->co_name,
5191 .fc_qualname = ((PyCodeObject *)_co)->co_name,
Mark Shannond6c33fb2021-01-29 13:24:55 +00005192 .fc_code = _co,
5193 .fc_defaults = defaults,
5194 .fc_kwdefaults = kwdefs,
5195 .fc_closure = closure
5196 };
Mark Shannon0332e562021-02-01 10:42:03 +00005197 res = _PyEval_Vector(tstate, &constr, locals,
Victor Stinner44085a32021-02-18 19:20:16 +01005198 allargs, argcount,
5199 kwnames);
Mark Shannon0332e562021-02-01 10:42:03 +00005200 if (kwcount) {
5201 Py_DECREF(kwnames);
5202 PyMem_Free(newargs);
5203 }
5204fail:
Mark Shannond6c33fb2021-01-29 13:24:55 +00005205 Py_DECREF(defaults);
Mark Shannond6c33fb2021-01-29 13:24:55 +00005206 return res;
Victor Stinnerb5e170f2019-11-16 01:03:22 +01005207}
5208
Tim Peters5ca576e2001-06-18 22:08:13 +00005209
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005210static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02005211special_lookup(PyThreadState *tstate, PyObject *o, _Py_Identifier *id)
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 PyObject *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05005214 res = _PyObject_LookupSpecial(o, id);
Victor Stinner438a12d2019-05-24 17:01:38 +02005215 if (res == NULL && !_PyErr_Occurred(tstate)) {
Victor Stinner4804b5b2020-05-12 01:43:38 +02005216 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(id));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 return NULL;
5218 }
5219 return res;
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005220}
5221
5222
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005223/* Logic for the raise statement (too complicated for inlining).
5224 This *consumes* a reference count to each of its arguments. */
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005225static int
Victor Stinner09532fe2019-05-10 23:39:09 +02005226do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 PyObject *type = NULL, *value = NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00005229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 if (exc == NULL) {
5231 /* Reraise */
Mark Shannonae3087c2017-10-22 22:41:51 +01005232 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 PyObject *tb;
Mark Shannonae3087c2017-10-22 22:41:51 +01005234 type = exc_info->exc_type;
5235 value = exc_info->exc_value;
5236 tb = exc_info->exc_traceback;
Victor Stinner09bbebe2021-04-11 00:17:39 +02005237 if (Py_IsNone(type) || type == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005238 _PyErr_SetString(tstate, PyExc_RuntimeError,
5239 "No active exception to reraise");
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005240 return 0;
5241 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 Py_XINCREF(type);
5243 Py_XINCREF(value);
5244 Py_XINCREF(tb);
Victor Stinner438a12d2019-05-24 17:01:38 +02005245 _PyErr_Restore(tstate, type, value, tb);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005246 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 }
Guido van Rossumac7be682001-01-17 15:42:30 +00005248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 /* We support the following forms of raise:
5250 raise
Collin Winter828f04a2007-08-31 00:04:24 +00005251 raise <instance>
5252 raise <type> */
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005254 if (PyExceptionClass_Check(exc)) {
5255 type = exc;
Victor Stinnera5ed5f02016-12-06 18:45:50 +01005256 value = _PyObject_CallNoArg(exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 if (value == NULL)
5258 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05005259 if (!PyExceptionInstance_Check(value)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005260 _PyErr_Format(tstate, PyExc_TypeError,
5261 "calling %R should have returned an instance of "
5262 "BaseException, not %R",
5263 type, Py_TYPE(value));
5264 goto raise_error;
Benjamin Peterson5afa03a2011-07-15 14:09:26 -05005265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 }
5267 else if (PyExceptionInstance_Check(exc)) {
5268 value = exc;
5269 type = PyExceptionInstance_Class(exc);
5270 Py_INCREF(type);
5271 }
5272 else {
5273 /* Not something you can raise. You get an exception
5274 anyway, just not what you specified :-) */
5275 Py_DECREF(exc);
Victor Stinner438a12d2019-05-24 17:01:38 +02005276 _PyErr_SetString(tstate, PyExc_TypeError,
5277 "exceptions must derive from BaseException");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 goto raise_error;
5279 }
Collin Winter828f04a2007-08-31 00:04:24 +00005280
Serhiy Storchakac0191582016-09-27 11:37:10 +03005281 assert(type != NULL);
5282 assert(value != NULL);
5283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 if (cause) {
5285 PyObject *fixed_cause;
5286 if (PyExceptionClass_Check(cause)) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +01005287 fixed_cause = _PyObject_CallNoArg(cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 if (fixed_cause == NULL)
5289 goto raise_error;
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005290 Py_DECREF(cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005292 else if (PyExceptionInstance_Check(cause)) {
5293 fixed_cause = cause;
5294 }
Victor Stinner09bbebe2021-04-11 00:17:39 +02005295 else if (Py_IsNone(cause)) {
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005296 Py_DECREF(cause);
5297 fixed_cause = NULL;
5298 }
5299 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005300 _PyErr_SetString(tstate, PyExc_TypeError,
5301 "exception causes must derive from "
5302 "BaseException");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 goto raise_error;
5304 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07005305 PyException_SetCause(value, fixed_cause);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 }
Collin Winter828f04a2007-08-31 00:04:24 +00005307
Victor Stinner438a12d2019-05-24 17:01:38 +02005308 _PyErr_SetObject(tstate, type, value);
Victor Stinner61f4db82020-01-28 03:37:45 +01005309 /* _PyErr_SetObject incref's its arguments */
Serhiy Storchakac0191582016-09-27 11:37:10 +03005310 Py_DECREF(value);
5311 Py_DECREF(type);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005312 return 0;
Collin Winter828f04a2007-08-31 00:04:24 +00005313
5314raise_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 Py_XDECREF(value);
5316 Py_XDECREF(type);
5317 Py_XDECREF(cause);
Benjamin Peterson31a58ff2012-10-12 11:34:51 -04005318 return 0;
Guido van Rossum0aa9ee61996-12-10 18:07:35 +00005319}
5320
Tim Petersd6d010b2001-06-21 02:49:55 +00005321/* Iterate v argcnt times and store the results on the stack (via decreasing
Guido van Rossum0368b722007-05-11 16:50:42 +00005322 sp). Return 1 for success, 0 if error.
Antoine Pitrou9a2310d2008-07-25 22:39:39 +00005323
Guido van Rossum0368b722007-05-11 16:50:42 +00005324 If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
5325 with a variable target.
5326*/
Tim Petersd6d010b2001-06-21 02:49:55 +00005327
Barry Warsawe42b18f1997-08-25 22:13:04 +00005328static int
Victor Stinner438a12d2019-05-24 17:01:38 +02005329unpack_iterable(PyThreadState *tstate, PyObject *v,
5330 int argcnt, int argcntafter, PyObject **sp)
Barry Warsawe42b18f1997-08-25 22:13:04 +00005331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 int i = 0, j = 0;
5333 Py_ssize_t ll = 0;
5334 PyObject *it; /* iter(v) */
5335 PyObject *w;
5336 PyObject *l = NULL; /* variable list */
Guido van Rossumac7be682001-01-17 15:42:30 +00005337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 assert(v != NULL);
Tim Petersd6d010b2001-06-21 02:49:55 +00005339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 it = PyObject_GetIter(v);
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005341 if (it == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005342 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
Victor Stinnera102ed72020-02-07 02:24:48 +01005343 Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005344 {
Victor Stinner438a12d2019-05-24 17:01:38 +02005345 _PyErr_Format(tstate, PyExc_TypeError,
5346 "cannot unpack non-iterable %.200s object",
Victor Stinnera102ed72020-02-07 02:24:48 +01005347 Py_TYPE(v)->tp_name);
Serhiy Storchaka13a6c092017-12-26 12:30:41 +02005348 }
5349 return 0;
5350 }
Tim Petersd6d010b2001-06-21 02:49:55 +00005351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 for (; i < argcnt; i++) {
5353 w = PyIter_Next(it);
5354 if (w == NULL) {
5355 /* Iterator done, via error or exhaustion. */
Victor Stinner438a12d2019-05-24 17:01:38 +02005356 if (!_PyErr_Occurred(tstate)) {
R David Murray4171bbe2015-04-15 17:08:45 -04005357 if (argcntafter == -1) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005358 _PyErr_Format(tstate, PyExc_ValueError,
5359 "not enough values to unpack "
5360 "(expected %d, got %d)",
5361 argcnt, i);
R David Murray4171bbe2015-04-15 17:08:45 -04005362 }
5363 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005364 _PyErr_Format(tstate, PyExc_ValueError,
5365 "not enough values to unpack "
5366 "(expected at least %d, got %d)",
5367 argcnt + argcntafter, i);
R David Murray4171bbe2015-04-15 17:08:45 -04005368 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 }
5370 goto Error;
5371 }
5372 *--sp = w;
5373 }
Tim Petersd6d010b2001-06-21 02:49:55 +00005374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 if (argcntafter == -1) {
5376 /* We better have exhausted the iterator now. */
5377 w = PyIter_Next(it);
5378 if (w == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005379 if (_PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 goto Error;
5381 Py_DECREF(it);
5382 return 1;
5383 }
5384 Py_DECREF(w);
Victor Stinner438a12d2019-05-24 17:01:38 +02005385 _PyErr_Format(tstate, PyExc_ValueError,
5386 "too many values to unpack (expected %d)",
5387 argcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 goto Error;
5389 }
Guido van Rossum0368b722007-05-11 16:50:42 +00005390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 l = PySequence_List(it);
5392 if (l == NULL)
5393 goto Error;
5394 *--sp = l;
5395 i++;
Guido van Rossum0368b722007-05-11 16:50:42 +00005396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 ll = PyList_GET_SIZE(l);
5398 if (ll < argcntafter) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005399 _PyErr_Format(tstate, PyExc_ValueError,
R David Murray4171bbe2015-04-15 17:08:45 -04005400 "not enough values to unpack (expected at least %d, got %zd)",
5401 argcnt + argcntafter, argcnt + ll);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 goto Error;
5403 }
Guido van Rossum0368b722007-05-11 16:50:42 +00005404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 /* Pop the "after-variable" args off the list. */
5406 for (j = argcntafter; j > 0; j--, i++) {
5407 *--sp = PyList_GET_ITEM(l, ll - j);
5408 }
5409 /* Resize the list. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005410 Py_SET_SIZE(l, ll - argcntafter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 Py_DECREF(it);
5412 return 1;
Guido van Rossum0368b722007-05-11 16:50:42 +00005413
Tim Petersd6d010b2001-06-21 02:49:55 +00005414Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 for (; i > 0; i--, sp++)
5416 Py_DECREF(*sp);
5417 Py_XDECREF(it);
5418 return 0;
Barry Warsawe42b18f1997-08-25 22:13:04 +00005419}
5420
Guido van Rossum96a42c81992-01-12 02:29:51 +00005421#ifdef LLTRACE
Guido van Rossum3f5da241990-12-20 15:06:42 +00005422static int
Victor Stinner438a12d2019-05-24 17:01:38 +02005423prtrace(PyThreadState *tstate, PyObject *v, const char *str)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 printf("%s ", str);
Victor Stinner438a12d2019-05-24 17:01:38 +02005426 if (PyObject_Print(v, stdout, 0) != 0) {
5427 /* Don't know what else to do */
5428 _PyErr_Clear(tstate);
5429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 printf("\n");
5431 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005432}
Guido van Rossum3f5da241990-12-20 15:06:42 +00005433#endif
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005434
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005435static void
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005436call_exc_trace(Py_tracefunc func, PyObject *self,
Mark Shannon86433452021-01-07 16:49:02 +00005437 PyThreadState *tstate,
5438 PyFrameObject *f,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005439 PyTraceInfo *trace_info)
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005440{
Victor Stinneraaa8ed82013-07-10 13:57:55 +02005441 PyObject *type, *value, *traceback, *orig_traceback, *arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 int err;
Victor Stinner438a12d2019-05-24 17:01:38 +02005443 _PyErr_Fetch(tstate, &type, &value, &orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 if (value == NULL) {
5445 value = Py_None;
5446 Py_INCREF(value);
5447 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005448 _PyErr_NormalizeException(tstate, &type, &value, &orig_traceback);
Antoine Pitrou89335212013-11-23 14:05:23 +01005449 traceback = (orig_traceback != NULL) ? orig_traceback : Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 arg = PyTuple_Pack(3, type, value, traceback);
5451 if (arg == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005452 _PyErr_Restore(tstate, type, value, orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005453 return;
5454 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00005455 err = call_trace(func, self, tstate, f, trace_info, PyTrace_EXCEPTION, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 Py_DECREF(arg);
Victor Stinner438a12d2019-05-24 17:01:38 +02005457 if (err == 0) {
5458 _PyErr_Restore(tstate, type, value, orig_traceback);
5459 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 else {
5461 Py_XDECREF(type);
5462 Py_XDECREF(value);
Victor Stinneraaa8ed82013-07-10 13:57:55 +02005463 Py_XDECREF(orig_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 }
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005465}
5466
Amaury Forgeot d'Arcf05149a2007-11-13 01:05:30 +00005467static int
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005468call_trace_protected(Py_tracefunc func, PyObject *obj,
5469 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005470 PyTraceInfo *trace_info,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 int what, PyObject *arg)
Fred Drake4ec5d562001-10-04 19:26:43 +00005472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 PyObject *type, *value, *traceback;
5474 int err;
Victor Stinner438a12d2019-05-24 17:01:38 +02005475 _PyErr_Fetch(tstate, &type, &value, &traceback);
Mark Shannon8e1b4062021-03-05 14:45:50 +00005476 err = call_trace(func, obj, tstate, frame, trace_info, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 if (err == 0)
5478 {
Victor Stinner438a12d2019-05-24 17:01:38 +02005479 _PyErr_Restore(tstate, type, value, traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 return 0;
5481 }
5482 else {
5483 Py_XDECREF(type);
5484 Py_XDECREF(value);
5485 Py_XDECREF(traceback);
5486 return -1;
5487 }
Fred Drake4ec5d562001-10-04 19:26:43 +00005488}
5489
Mark Shannon8e1b4062021-03-05 14:45:50 +00005490static void
5491initialize_trace_info(PyTraceInfo *trace_info, PyFrameObject *frame)
5492{
5493 if (trace_info->code != frame->f_code) {
5494 trace_info->code = frame->f_code;
5495 trace_info->instr_prev = -1;
5496 _PyCode_InitAddressRange(frame->f_code, &trace_info->bounds);
5497 }
5498}
5499
Guido van Rossum9c8d70d1992-03-23 18:19:28 +00005500static int
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005501call_trace(Py_tracefunc func, PyObject *obj,
5502 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005503 PyTraceInfo *trace_info,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 int what, PyObject *arg)
Guido van Rossum96a42c81992-01-12 02:29:51 +00005505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 int result;
5507 if (tstate->tracing)
5508 return 0;
5509 tstate->tracing++;
5510 tstate->use_tracing = 0;
Mark Shannon86433452021-01-07 16:49:02 +00005511 if (frame->f_lasti < 0) {
5512 frame->f_lineno = frame->f_code->co_firstlineno;
5513 }
5514 else {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005515 initialize_trace_info(trace_info, frame);
Mark Shannonfcb55c02021-04-01 16:00:31 +01005516 frame->f_lineno = _PyCode_CheckLineNumber(frame->f_lasti*2, &trace_info->bounds);
Mark Shannon86433452021-01-07 16:49:02 +00005517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 result = func(obj, frame, what, arg);
Mark Shannon86433452021-01-07 16:49:02 +00005519 frame->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
5521 || (tstate->c_profilefunc != NULL));
5522 tstate->tracing--;
5523 return result;
Guido van Rossum96a42c81992-01-12 02:29:51 +00005524}
5525
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005526PyObject *
5527_PyEval_CallTracing(PyObject *func, PyObject *args)
5528{
Victor Stinner50b48572018-11-01 01:51:40 +01005529 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 int save_tracing = tstate->tracing;
5531 int save_use_tracing = tstate->use_tracing;
5532 PyObject *result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 tstate->tracing = 0;
5535 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
5536 || (tstate->c_profilefunc != NULL));
5537 result = PyObject_Call(func, args, NULL);
5538 tstate->tracing = save_tracing;
5539 tstate->use_tracing = save_use_tracing;
5540 return result;
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00005541}
5542
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005543/* See Objects/lnotab_notes.txt for a description of how tracing works. */
Michael W. Hudson006c7522002-11-08 13:08:46 +00005544static int
Tim Peters8a5c3c72004-04-05 19:36:21 +00005545maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005546 PyThreadState *tstate, PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005547 PyTraceInfo *trace_info)
Michael W. Hudsondd32a912002-08-15 14:59:02 +00005548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 int result = 0;
Michael W. Hudson006c7522002-11-08 13:08:46 +00005550
Nick Coghlan5a851672017-09-08 10:14:16 +10005551 /* If the last instruction falls at the start of a line or if it
5552 represents a jump backwards, update the frame's line number and
5553 then call the trace function if we're tracing source lines.
5554 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00005555 initialize_trace_info(trace_info, frame);
5556 int lastline = trace_info->bounds.ar_line;
Mark Shannonfcb55c02021-04-01 16:00:31 +01005557 int line = _PyCode_CheckLineNumber(frame->f_lasti*2, &trace_info->bounds);
Mark Shannonee9f98d2021-01-05 12:04:10 +00005558 if (line != -1 && frame->f_trace_lines) {
5559 /* Trace backward edges or first instruction of a new line */
Mark Shannon8e1b4062021-03-05 14:45:50 +00005560 if (frame->f_lasti < trace_info->instr_prev ||
Mark Shannonfcb55c02021-04-01 16:00:31 +01005561 (line != lastline && frame->f_lasti*2 == trace_info->bounds.ar_start))
Mark Shannonee9f98d2021-01-05 12:04:10 +00005562 {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005563 result = call_trace(func, obj, tstate, frame, trace_info, PyTrace_LINE, Py_None);
Nick Coghlan5a851672017-09-08 10:14:16 +10005564 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 }
George King20faa682017-10-18 17:44:22 -07005566 /* Always emit an opcode event if we're tracing all opcodes. */
5567 if (frame->f_trace_opcodes) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005568 result = call_trace(func, obj, tstate, frame, trace_info, PyTrace_OPCODE, Py_None);
George King20faa682017-10-18 17:44:22 -07005569 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00005570 trace_info->instr_prev = frame->f_lasti;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 return result;
Michael W. Hudsondd32a912002-08-15 14:59:02 +00005572}
5573
Victor Stinner309d7cc2020-03-13 16:39:12 +01005574int
5575_PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
5576{
Victor Stinnerda2914d2020-03-20 09:29:08 +01005577 assert(is_tstate_valid(tstate));
Victor Stinner309d7cc2020-03-13 16:39:12 +01005578 /* The caller must hold the GIL */
5579 assert(PyGILState_Check());
5580
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005581 /* Call _PySys_Audit() in the context of the current thread state,
Victor Stinner309d7cc2020-03-13 16:39:12 +01005582 even if tstate is not the current thread state. */
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005583 PyThreadState *current_tstate = _PyThreadState_GET();
5584 if (_PySys_Audit(current_tstate, "sys.setprofile", NULL) < 0) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01005585 return -1;
5586 }
5587
5588 PyObject *profileobj = tstate->c_profileobj;
5589
5590 tstate->c_profilefunc = NULL;
5591 tstate->c_profileobj = NULL;
5592 /* Must make sure that tracing is not ignored if 'profileobj' is freed */
5593 tstate->use_tracing = tstate->c_tracefunc != NULL;
5594 Py_XDECREF(profileobj);
5595
5596 Py_XINCREF(arg);
5597 tstate->c_profileobj = arg;
5598 tstate->c_profilefunc = func;
5599
5600 /* Flag that tracing or profiling is turned on */
5601 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
5602 return 0;
5603}
5604
Fred Drake5755ce62001-06-27 19:19:46 +00005605void
5606PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
Fred Draked0838392001-06-16 21:02:31 +00005607{
Victor Stinner309d7cc2020-03-13 16:39:12 +01005608 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerf6a58502020-03-16 17:41:44 +01005609 if (_PyEval_SetProfile(tstate, func, arg) < 0) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005610 /* Log _PySys_Audit() error */
Victor Stinnerf6a58502020-03-16 17:41:44 +01005611 _PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL);
5612 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01005613}
5614
5615int
5616_PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
5617{
Victor Stinnerda2914d2020-03-20 09:29:08 +01005618 assert(is_tstate_valid(tstate));
Victor Stinner309d7cc2020-03-13 16:39:12 +01005619 /* The caller must hold the GIL */
5620 assert(PyGILState_Check());
5621
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005622 /* Call _PySys_Audit() in the context of the current thread state,
Victor Stinner309d7cc2020-03-13 16:39:12 +01005623 even if tstate is not the current thread state. */
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005624 PyThreadState *current_tstate = _PyThreadState_GET();
5625 if (_PySys_Audit(current_tstate, "sys.settrace", NULL) < 0) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01005626 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005627 }
5628
Victor Stinnerda2914d2020-03-20 09:29:08 +01005629 struct _ceval_state *ceval2 = &tstate->interp->ceval;
Victor Stinner309d7cc2020-03-13 16:39:12 +01005630 PyObject *traceobj = tstate->c_traceobj;
Victor Stinnerda2914d2020-03-20 09:29:08 +01005631 ceval2->tracing_possible += (func != NULL) - (tstate->c_tracefunc != NULL);
Victor Stinner309d7cc2020-03-13 16:39:12 +01005632
5633 tstate->c_tracefunc = NULL;
5634 tstate->c_traceobj = NULL;
5635 /* Must make sure that profiling is not ignored if 'traceobj' is freed */
5636 tstate->use_tracing = (tstate->c_profilefunc != NULL);
5637 Py_XDECREF(traceobj);
5638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005639 Py_XINCREF(arg);
Victor Stinner309d7cc2020-03-13 16:39:12 +01005640 tstate->c_traceobj = arg;
5641 tstate->c_tracefunc = func;
5642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 /* Flag that tracing or profiling is turned on */
Victor Stinner309d7cc2020-03-13 16:39:12 +01005644 tstate->use_tracing = ((func != NULL)
5645 || (tstate->c_profilefunc != NULL));
5646
5647 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00005648}
5649
5650void
5651PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
5652{
Victor Stinner309d7cc2020-03-13 16:39:12 +01005653 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerf6a58502020-03-16 17:41:44 +01005654 if (_PyEval_SetTrace(tstate, func, arg) < 0) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005655 /* Log _PySys_Audit() error */
Victor Stinnerf6a58502020-03-16 17:41:44 +01005656 _PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL);
5657 }
Fred Draked0838392001-06-16 21:02:31 +00005658}
5659
Victor Stinner309d7cc2020-03-13 16:39:12 +01005660
Yury Selivanov75445082015-05-11 22:57:16 -04005661void
Victor Stinner838f2642019-06-13 22:41:23 +02005662_PyEval_SetCoroutineOriginTrackingDepth(PyThreadState *tstate, int new_depth)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005663{
5664 assert(new_depth >= 0);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005665 tstate->coroutine_origin_tracking_depth = new_depth;
5666}
5667
5668int
5669_PyEval_GetCoroutineOriginTrackingDepth(void)
5670{
Victor Stinner50b48572018-11-01 01:51:40 +01005671 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08005672 return tstate->coroutine_origin_tracking_depth;
5673}
5674
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005675int
Yury Selivanoveb636452016-09-08 22:01:51 -07005676_PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
5677{
Victor Stinner50b48572018-11-01 01:51:40 +01005678 PyThreadState *tstate = _PyThreadState_GET();
Steve Dowerb82e17e2019-05-23 08:45:22 -07005679
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005680 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005681 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005682 }
5683
Yury Selivanoveb636452016-09-08 22:01:51 -07005684 Py_XINCREF(firstiter);
5685 Py_XSETREF(tstate->async_gen_firstiter, firstiter);
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005686 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07005687}
5688
5689PyObject *
5690_PyEval_GetAsyncGenFirstiter(void)
5691{
Victor Stinner50b48572018-11-01 01:51:40 +01005692 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07005693 return tstate->async_gen_firstiter;
5694}
5695
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005696int
Yury Selivanoveb636452016-09-08 22:01:51 -07005697_PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
5698{
Victor Stinner50b48572018-11-01 01:51:40 +01005699 PyThreadState *tstate = _PyThreadState_GET();
Steve Dowerb82e17e2019-05-23 08:45:22 -07005700
Victor Stinner1c1e68c2020-03-27 15:11:45 +01005701 if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005702 return -1;
Steve Dowerb82e17e2019-05-23 08:45:22 -07005703 }
5704
Yury Selivanoveb636452016-09-08 22:01:51 -07005705 Py_XINCREF(finalizer);
5706 Py_XSETREF(tstate->async_gen_finalizer, finalizer);
Zackery Spytz79ceccd2020-03-26 06:11:13 -06005707 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07005708}
5709
5710PyObject *
5711_PyEval_GetAsyncGenFinalizer(void)
5712{
Victor Stinner50b48572018-11-01 01:51:40 +01005713 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07005714 return tstate->async_gen_finalizer;
5715}
5716
Victor Stinner438a12d2019-05-24 17:01:38 +02005717PyFrameObject *
5718PyEval_GetFrame(void)
5719{
5720 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005721 return tstate->frame;
Victor Stinner438a12d2019-05-24 17:01:38 +02005722}
5723
Guido van Rossumb209a111997-04-29 18:18:01 +00005724PyObject *
Victor Stinner46496f92021-02-20 15:17:18 +01005725_PyEval_GetBuiltins(PyThreadState *tstate)
5726{
5727 PyFrameObject *frame = tstate->frame;
5728 if (frame != NULL) {
5729 return frame->f_builtins;
5730 }
5731 return tstate->interp->builtins;
5732}
5733
5734PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005735PyEval_GetBuiltins(void)
Guido van Rossum6135a871995-01-09 17:53:26 +00005736{
Victor Stinner438a12d2019-05-24 17:01:38 +02005737 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner46496f92021-02-20 15:17:18 +01005738 return _PyEval_GetBuiltins(tstate);
Guido van Rossum6135a871995-01-09 17:53:26 +00005739}
5740
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005741/* Convenience function to get a builtin from its name */
5742PyObject *
5743_PyEval_GetBuiltinId(_Py_Identifier *name)
5744{
Victor Stinner438a12d2019-05-24 17:01:38 +02005745 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005746 PyObject *attr = _PyDict_GetItemIdWithError(PyEval_GetBuiltins(), name);
5747 if (attr) {
5748 Py_INCREF(attr);
5749 }
Victor Stinner438a12d2019-05-24 17:01:38 +02005750 else if (!_PyErr_Occurred(tstate)) {
5751 _PyErr_SetObject(tstate, PyExc_AttributeError, _PyUnicode_FromId(name));
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02005752 }
5753 return attr;
5754}
5755
Guido van Rossumb209a111997-04-29 18:18:01 +00005756PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005757PyEval_GetLocals(void)
Guido van Rossum5b722181993-03-30 17:46:03 +00005758{
Victor Stinner438a12d2019-05-24 17:01:38 +02005759 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005760 PyFrameObject *current_frame = tstate->frame;
Victor Stinner41bb43a2013-10-29 01:19:37 +01005761 if (current_frame == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02005762 _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 return NULL;
Victor Stinner41bb43a2013-10-29 01:19:37 +01005764 }
5765
Victor Stinner438a12d2019-05-24 17:01:38 +02005766 if (PyFrame_FastToLocalsWithError(current_frame) < 0) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01005767 return NULL;
Victor Stinner438a12d2019-05-24 17:01:38 +02005768 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01005769
5770 assert(current_frame->f_locals != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005771 return current_frame->f_locals;
Guido van Rossum5b722181993-03-30 17:46:03 +00005772}
5773
Guido van Rossumb209a111997-04-29 18:18:01 +00005774PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00005775PyEval_GetGlobals(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +00005776{
Victor Stinner438a12d2019-05-24 17:01:38 +02005777 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005778 PyFrameObject *current_frame = tstate->frame;
Victor Stinner438a12d2019-05-24 17:01:38 +02005779 if (current_frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 return NULL;
Victor Stinner438a12d2019-05-24 17:01:38 +02005781 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01005782
5783 assert(current_frame->f_globals != NULL);
5784 return current_frame->f_globals;
Guido van Rossum3f5da241990-12-20 15:06:42 +00005785}
5786
Guido van Rossum6135a871995-01-09 17:53:26 +00005787int
Tim Peters5ba58662001-07-16 02:29:45 +00005788PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Jeremy Hylton061d1062001-03-22 02:32:48 +00005789{
Victor Stinner438a12d2019-05-24 17:01:38 +02005790 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner6723e932020-03-20 17:46:56 +01005791 PyFrameObject *current_frame = tstate->frame;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005792 int result = cf->cf_flags != 0;
Tim Peters5ba58662001-07-16 02:29:45 +00005793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 if (current_frame != NULL) {
5795 const int codeflags = current_frame->f_code->co_flags;
5796 const int compilerflags = codeflags & PyCF_MASK;
5797 if (compilerflags) {
5798 result = 1;
5799 cf->cf_flags |= compilerflags;
5800 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00005801#if 0 /* future keyword */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 if (codeflags & CO_GENERATOR_ALLOWED) {
5803 result = 1;
5804 cf->cf_flags |= CO_GENERATOR_ALLOWED;
5805 }
Neil Schemenauerc24ea082002-03-22 23:53:36 +00005806#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 }
5808 return result;
Jeremy Hylton061d1062001-03-22 02:32:48 +00005809}
5810
Guido van Rossum3f5da241990-12-20 15:06:42 +00005811
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00005812const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005813PyEval_GetFuncName(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00005814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005815 if (PyMethod_Check(func))
5816 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
5817 else if (PyFunction_Check(func))
Serhiy Storchaka06515832016-11-20 09:13:07 +02005818 return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 else if (PyCFunction_Check(func))
5820 return ((PyCFunctionObject*)func)->m_ml->ml_name;
5821 else
Victor Stinnera102ed72020-02-07 02:24:48 +01005822 return Py_TYPE(func)->tp_name;
Jeremy Hylton512a2372001-04-11 13:52:29 +00005823}
5824
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00005825const char *
Tim Peters6d6c1a32001-08-02 04:15:00 +00005826PyEval_GetFuncDesc(PyObject *func)
Jeremy Hylton512a2372001-04-11 13:52:29 +00005827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 if (PyMethod_Check(func))
5829 return "()";
5830 else if (PyFunction_Check(func))
5831 return "()";
5832 else if (PyCFunction_Check(func))
5833 return "()";
5834 else
5835 return " object";
Jeremy Hylton512a2372001-04-11 13:52:29 +00005836}
5837
Armin Rigo1c2d7e52005-09-20 18:34:01 +00005838#define C_TRACE(x, call) \
Nicholas Bastind858a772004-06-25 23:31:06 +00005839if (tstate->use_tracing && tstate->c_profilefunc) { \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005840 if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005841 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005842 PyTrace_C_CALL, func)) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 x = NULL; \
5844 } \
5845 else { \
5846 x = call; \
5847 if (tstate->c_profilefunc != NULL) { \
5848 if (x == NULL) { \
5849 call_trace_protected(tstate->c_profilefunc, \
5850 tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005851 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005852 PyTrace_C_EXCEPTION, func); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005853 /* XXX should pass (type, value, tb) */ \
5854 } else { \
5855 if (call_trace(tstate->c_profilefunc, \
5856 tstate->c_profileobj, \
Mark Shannon8e1b4062021-03-05 14:45:50 +00005857 tstate, tstate->frame, trace_info, \
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +01005858 PyTrace_C_RETURN, func)) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005859 Py_DECREF(x); \
5860 x = NULL; \
5861 } \
5862 } \
5863 } \
5864 } \
Nicholas Bastind858a772004-06-25 23:31:06 +00005865} else { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 x = call; \
5867 }
Nicholas Bastinc69ebe82004-03-24 21:57:10 +00005868
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005869
5870static PyObject *
5871trace_call_function(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005872 PyTraceInfo *trace_info,
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005873 PyObject *func,
5874 PyObject **args, Py_ssize_t nargs,
5875 PyObject *kwnames)
5876{
5877 PyObject *x;
scoder4c9ea092020-05-12 16:12:41 +02005878 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005879 C_TRACE(x, PyObject_Vectorcall(func, args, nargs, kwnames));
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005880 return x;
5881 }
Andy Lesterdffe4c02020-03-04 07:15:20 -06005882 else if (Py_IS_TYPE(func, &PyMethodDescr_Type) && nargs > 0) {
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005883 /* We need to create a temporary bound method as argument
5884 for profiling.
5885
5886 If nargs == 0, then this cannot work because we have no
5887 "self". In any case, the call itself would raise
5888 TypeError (foo needs an argument), so we just skip
5889 profiling. */
5890 PyObject *self = args[0];
5891 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5892 if (func == NULL) {
5893 return NULL;
5894 }
Petr Viktorinffd97532020-02-11 17:46:57 +01005895 C_TRACE(x, PyObject_Vectorcall(func,
Jeroen Demeyer0d722f32019-07-05 14:48:24 +02005896 args+1, nargs-1,
5897 kwnames));
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005898 Py_DECREF(func);
5899 return x;
5900 }
Petr Viktorinffd97532020-02-11 17:46:57 +01005901 return PyObject_Vectorcall(func, args, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005902}
5903
Victor Stinner415c5102017-01-11 00:54:57 +01005904/* Issue #29227: Inline call_function() into _PyEval_EvalFrameDefault()
5905 to reduce the stack consumption. */
5906Py_LOCAL_INLINE(PyObject *) _Py_HOT_FUNCTION
Mark Shannon86433452021-01-07 16:49:02 +00005907call_function(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005908 PyTraceInfo *trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00005909 PyObject ***pp_stack,
5910 Py_ssize_t oparg,
5911 PyObject *kwnames)
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005912{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005913 PyObject **pfunc = (*pp_stack) - oparg - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005914 PyObject *func = *pfunc;
5915 PyObject *x, *w;
Victor Stinnerd8735722016-09-09 12:36:44 -07005916 Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
5917 Py_ssize_t nargs = oparg - nkwargs;
INADA Naoki5566bbb2017-02-03 07:43:03 +09005918 PyObject **stack = (*pp_stack) - nargs - nkwargs;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005919
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02005920 if (tstate->use_tracing) {
Mark Shannon8e1b4062021-03-05 14:45:50 +00005921 x = trace_call_function(tstate, trace_info, func, stack, nargs, kwnames);
INADA Naoki5566bbb2017-02-03 07:43:03 +09005922 }
Victor Stinner4a7cc882015-03-06 23:35:27 +01005923 else {
Petr Viktorinffd97532020-02-11 17:46:57 +01005924 x = PyObject_Vectorcall(func, stack, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 }
Tim Peters8a5c3c72004-04-05 19:36:21 +00005926
Victor Stinner438a12d2019-05-24 17:01:38 +02005927 assert((x != NULL) ^ (_PyErr_Occurred(tstate) != NULL));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005928
Victor Stinnerc22bfaa2017-02-12 19:27:05 +01005929 /* Clear the stack of the function object. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 while ((*pp_stack) > pfunc) {
5931 w = EXT_POP(*pp_stack);
5932 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005933 }
Victor Stinnerace47d72013-07-18 01:41:08 +02005934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935 return x;
Jeremy Hyltone8c04322002-08-16 17:47:26 +00005936}
5937
Jeremy Hylton52820442001-01-03 23:52:36 +00005938static PyObject *
Mark Shannon86433452021-01-07 16:49:02 +00005939do_call_core(PyThreadState *tstate,
Mark Shannon8e1b4062021-03-05 14:45:50 +00005940 PyTraceInfo *trace_info,
Mark Shannon86433452021-01-07 16:49:02 +00005941 PyObject *func,
5942 PyObject *callargs,
5943 PyObject *kwdict)
Jeremy Hylton52820442001-01-03 23:52:36 +00005944{
jdemeyere89de732018-09-19 12:06:20 +02005945 PyObject *result;
5946
scoder4c9ea092020-05-12 16:12:41 +02005947 if (PyCFunction_CheckExact(func) || PyCMethod_CheckExact(func)) {
Jeroen Demeyer7a6873c2019-09-11 13:01:01 +02005948 C_TRACE(result, PyObject_Call(func, callargs, kwdict));
Victor Stinnerf9b760f2016-09-09 10:17:08 -07005949 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005950 }
Andy Lesterdffe4c02020-03-04 07:15:20 -06005951 else if (Py_IS_TYPE(func, &PyMethodDescr_Type)) {
jdemeyere89de732018-09-19 12:06:20 +02005952 Py_ssize_t nargs = PyTuple_GET_SIZE(callargs);
5953 if (nargs > 0 && tstate->use_tracing) {
5954 /* We need to create a temporary bound method as argument
5955 for profiling.
5956
5957 If nargs == 0, then this cannot work because we have no
5958 "self". In any case, the call itself would raise
5959 TypeError (foo needs an argument), so we just skip
5960 profiling. */
5961 PyObject *self = PyTuple_GET_ITEM(callargs, 0);
5962 func = Py_TYPE(func)->tp_descr_get(func, self, (PyObject*)Py_TYPE(self));
5963 if (func == NULL) {
5964 return NULL;
5965 }
5966
Victor Stinner4d231bc2019-11-14 13:36:21 +01005967 C_TRACE(result, _PyObject_FastCallDictTstate(
5968 tstate, func,
5969 &_PyTuple_ITEMS(callargs)[1],
5970 nargs - 1,
5971 kwdict));
jdemeyere89de732018-09-19 12:06:20 +02005972 Py_DECREF(func);
5973 return result;
5974 }
Victor Stinner74319ae2016-08-25 00:04:09 +02005975 }
jdemeyere89de732018-09-19 12:06:20 +02005976 return PyObject_Call(func, callargs, kwdict);
Jeremy Hylton52820442001-01-03 23:52:36 +00005977}
5978
Serhiy Storchaka483405b2015-02-17 10:14:30 +02005979/* Extract a slice index from a PyLong or an object with the
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005980 nb_index slot defined, and store in *pi.
5981 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
Xiang Zhang2ddf5a12017-05-10 18:19:41 +08005982 and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
Martin v. Löwisdde99d22006-02-17 15:57:41 +00005983 Return 0 on error, 1 on success.
Tim Peterscb479e72001-12-16 19:11:44 +00005984*/
Guido van Rossum20c6add2000-05-08 14:06:50 +00005985int
Martin v. Löwis18e16552006-02-15 17:27:45 +00005986_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005987{
Victor Stinner438a12d2019-05-24 17:01:38 +02005988 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner09bbebe2021-04-11 00:17:39 +02005989 if (!Py_IsNone(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 Py_ssize_t x;
Victor Stinnera15e2602020-04-08 02:01:56 +02005991 if (_PyIndex_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 x = PyNumber_AsSsize_t(v, NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02005993 if (x == -1 && _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 return 0;
5995 }
5996 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02005997 _PyErr_SetString(tstate, PyExc_TypeError,
5998 "slice indices must be integers or "
5999 "None or have an __index__ method");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006000 return 0;
6001 }
6002 *pi = x;
6003 }
6004 return 1;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00006005}
6006
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006007int
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006008_PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006009{
Victor Stinner438a12d2019-05-24 17:01:38 +02006010 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006011 Py_ssize_t x;
Victor Stinnera15e2602020-04-08 02:01:56 +02006012 if (_PyIndex_Check(v)) {
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006013 x = PyNumber_AsSsize_t(v, NULL);
Victor Stinner438a12d2019-05-24 17:01:38 +02006014 if (x == -1 && _PyErr_Occurred(tstate))
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006015 return 0;
6016 }
6017 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006018 _PyErr_SetString(tstate, PyExc_TypeError,
6019 "slice indices must be integers or "
6020 "have an __index__ method");
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03006021 return 0;
6022 }
6023 *pi = x;
6024 return 1;
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02006025}
6026
Thomas Wouters52152252000-08-17 22:55:00 +00006027static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006028import_name(PyThreadState *tstate, PyFrameObject *f,
6029 PyObject *name, PyObject *fromlist, PyObject *level)
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006030{
6031 _Py_IDENTIFIER(__import__);
Victor Stinnerdf142fd2016-08-20 00:44:42 +02006032 PyObject *import_func, *res;
6033 PyObject* stack[5];
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006034
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006035 import_func = _PyDict_GetItemIdWithError(f->f_builtins, &PyId___import__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006036 if (import_func == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006037 if (!_PyErr_Occurred(tstate)) {
6038 _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006039 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006040 return NULL;
6041 }
6042
6043 /* Fast path for not overloaded __import__. */
Victor Stinner438a12d2019-05-24 17:01:38 +02006044 if (import_func == tstate->interp->import_func) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006045 int ilevel = _PyLong_AsInt(level);
Victor Stinner438a12d2019-05-24 17:01:38 +02006046 if (ilevel == -1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006047 return NULL;
6048 }
6049 res = PyImport_ImportModuleLevelObject(
6050 name,
6051 f->f_globals,
6052 f->f_locals == NULL ? Py_None : f->f_locals,
6053 fromlist,
6054 ilevel);
6055 return res;
6056 }
6057
6058 Py_INCREF(import_func);
Victor Stinnerdf142fd2016-08-20 00:44:42 +02006059
6060 stack[0] = name;
6061 stack[1] = f->f_globals;
6062 stack[2] = f->f_locals == NULL ? Py_None : f->f_locals;
6063 stack[3] = fromlist;
6064 stack[4] = level;
Victor Stinner559bb6a2016-08-22 22:48:54 +02006065 res = _PyObject_FastCall(import_func, stack, 5);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03006066 Py_DECREF(import_func);
6067 return res;
6068}
6069
6070static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006071import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
Guido van Rossume9736fc1990-11-18 17:33:06 +00006072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006073 PyObject *x;
Xiang Zhang4830f582017-03-21 11:13:42 +08006074 PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg;
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00006075
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006076 if (_PyObject_LookupAttr(v, name, &x) != 0) {
Antoine Pitrou0373a102014-10-13 20:19:45 +02006077 return x;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006078 }
Antoine Pitrou0373a102014-10-13 20:19:45 +02006079 /* Issue #17636: in case this failed because of a circular relative
6080 import, try to fallback on reading the module directly from
6081 sys.modules. */
Antoine Pitrou0373a102014-10-13 20:19:45 +02006082 pkgname = _PyObject_GetAttrId(v, &PyId___name__);
Brett Cannon3008bc02015-08-11 18:01:31 -07006083 if (pkgname == NULL) {
6084 goto error;
6085 }
Oren Milman6db70332017-09-19 14:23:01 +03006086 if (!PyUnicode_Check(pkgname)) {
6087 Py_CLEAR(pkgname);
6088 goto error;
6089 }
Antoine Pitrou0373a102014-10-13 20:19:45 +02006090 fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
Brett Cannon3008bc02015-08-11 18:01:31 -07006091 if (fullmodname == NULL) {
Xiang Zhang4830f582017-03-21 11:13:42 +08006092 Py_DECREF(pkgname);
Antoine Pitrou0373a102014-10-13 20:19:45 +02006093 return NULL;
Brett Cannon3008bc02015-08-11 18:01:31 -07006094 }
Eric Snow3f9eee62017-09-15 16:35:20 -06006095 x = PyImport_GetModule(fullmodname);
Antoine Pitrou0373a102014-10-13 20:19:45 +02006096 Py_DECREF(fullmodname);
Victor Stinner438a12d2019-05-24 17:01:38 +02006097 if (x == NULL && !_PyErr_Occurred(tstate)) {
Brett Cannon3008bc02015-08-11 18:01:31 -07006098 goto error;
6099 }
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006100 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006101 return x;
Brett Cannon3008bc02015-08-11 18:01:31 -07006102 error:
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006103 pkgpath = PyModule_GetFilenameObject(v);
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006104 if (pkgname == NULL) {
6105 pkgname_or_unknown = PyUnicode_FromString("<unknown module name>");
6106 if (pkgname_or_unknown == NULL) {
6107 Py_XDECREF(pkgpath);
6108 return NULL;
6109 }
6110 } else {
6111 pkgname_or_unknown = pkgname;
6112 }
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006113
6114 if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006115 _PyErr_Clear(tstate);
Xiang Zhang4830f582017-03-21 11:13:42 +08006116 errmsg = PyUnicode_FromFormat(
6117 "cannot import name %R from %R (unknown location)",
6118 name, pkgname_or_unknown
6119 );
Stefan Krah027b09c2019-03-25 21:50:58 +01006120 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
Xiang Zhang4830f582017-03-21 11:13:42 +08006121 PyErr_SetImportError(errmsg, pkgname, NULL);
6122 }
6123 else {
Anthony Sottile65366bc2019-09-09 08:17:50 -07006124 _Py_IDENTIFIER(__spec__);
6125 PyObject *spec = _PyObject_GetAttrId(v, &PyId___spec__);
Anthony Sottile65366bc2019-09-09 08:17:50 -07006126 const char *fmt =
6127 _PyModuleSpec_IsInitializing(spec) ?
6128 "cannot import name %R from partially initialized module %R "
6129 "(most likely due to a circular import) (%S)" :
6130 "cannot import name %R from %R (%S)";
6131 Py_XDECREF(spec);
6132
6133 errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
Stefan Krah027b09c2019-03-25 21:50:58 +01006134 /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
Xiang Zhang4830f582017-03-21 11:13:42 +08006135 PyErr_SetImportError(errmsg, pkgname, pkgpath);
Matthias Bussonnierbc4bed42017-02-14 16:05:25 -08006136 }
6137
Xiang Zhang4830f582017-03-21 11:13:42 +08006138 Py_XDECREF(errmsg);
Matthias Bussonnier1bc15642017-02-22 07:06:50 -08006139 Py_XDECREF(pkgname_or_unknown);
6140 Py_XDECREF(pkgpath);
Brett Cannon3008bc02015-08-11 18:01:31 -07006141 return NULL;
Thomas Wouters52152252000-08-17 22:55:00 +00006142}
Guido van Rossumac7be682001-01-17 15:42:30 +00006143
Thomas Wouters52152252000-08-17 22:55:00 +00006144static int
Victor Stinner438a12d2019-05-24 17:01:38 +02006145import_all_from(PyThreadState *tstate, PyObject *locals, PyObject *v)
Thomas Wouters52152252000-08-17 22:55:00 +00006146{
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02006147 _Py_IDENTIFIER(__all__);
6148 _Py_IDENTIFIER(__dict__);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006149 PyObject *all, *dict, *name, *value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006150 int skip_leading_underscores = 0;
6151 int pos, err;
Thomas Wouters52152252000-08-17 22:55:00 +00006152
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006153 if (_PyObject_LookupAttrId(v, &PyId___all__, &all) < 0) {
6154 return -1; /* Unexpected error */
6155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 if (all == NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006157 if (_PyObject_LookupAttrId(v, &PyId___dict__, &dict) < 0) {
6158 return -1;
6159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006160 if (dict == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006161 _PyErr_SetString(tstate, PyExc_ImportError,
Serhiy Storchakaf320be72018-01-25 10:49:40 +02006162 "from-import-* object has no __dict__ and no __all__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006163 return -1;
6164 }
6165 all = PyMapping_Keys(dict);
6166 Py_DECREF(dict);
6167 if (all == NULL)
6168 return -1;
6169 skip_leading_underscores = 1;
6170 }
Guido van Rossum18d4d8f2001-01-12 16:24:03 +00006171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006172 for (pos = 0, err = 0; ; pos++) {
6173 name = PySequence_GetItem(all, pos);
6174 if (name == NULL) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006175 if (!_PyErr_ExceptionMatches(tstate, PyExc_IndexError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006176 err = -1;
Victor Stinner438a12d2019-05-24 17:01:38 +02006177 }
6178 else {
6179 _PyErr_Clear(tstate);
6180 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006181 break;
6182 }
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006183 if (!PyUnicode_Check(name)) {
6184 PyObject *modname = _PyObject_GetAttrId(v, &PyId___name__);
6185 if (modname == NULL) {
6186 Py_DECREF(name);
6187 err = -1;
6188 break;
6189 }
6190 if (!PyUnicode_Check(modname)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006191 _PyErr_Format(tstate, PyExc_TypeError,
6192 "module __name__ must be a string, not %.100s",
6193 Py_TYPE(modname)->tp_name);
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006194 }
6195 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006196 _PyErr_Format(tstate, PyExc_TypeError,
6197 "%s in %U.%s must be str, not %.100s",
6198 skip_leading_underscores ? "Key" : "Item",
6199 modname,
6200 skip_leading_underscores ? "__dict__" : "__all__",
6201 Py_TYPE(name)->tp_name);
Xiang Zhangd8b291a2018-03-24 18:39:36 +08006202 }
6203 Py_DECREF(modname);
6204 Py_DECREF(name);
6205 err = -1;
6206 break;
6207 }
6208 if (skip_leading_underscores) {
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03006209 if (PyUnicode_READY(name) == -1) {
6210 Py_DECREF(name);
6211 err = -1;
6212 break;
6213 }
6214 if (PyUnicode_READ_CHAR(name, 0) == '_') {
6215 Py_DECREF(name);
6216 continue;
6217 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006218 }
6219 value = PyObject_GetAttr(v, name);
6220 if (value == NULL)
6221 err = -1;
6222 else if (PyDict_CheckExact(locals))
6223 err = PyDict_SetItem(locals, name, value);
6224 else
6225 err = PyObject_SetItem(locals, name, value);
6226 Py_DECREF(name);
6227 Py_XDECREF(value);
6228 if (err != 0)
6229 break;
6230 }
6231 Py_DECREF(all);
6232 return err;
Guido van Rossume9736fc1990-11-18 17:33:06 +00006233}
6234
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006235static int
Victor Stinner438a12d2019-05-24 17:01:38 +02006236check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006237{
Victor Stinnera102ed72020-02-07 02:24:48 +01006238 if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006239 /* check_args_iterable() may be called with a live exception:
6240 * clear it to prevent calling _PyObject_FunctionStr() with an
6241 * exception set. */
Victor Stinner61f4db82020-01-28 03:37:45 +01006242 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006243 PyObject *funcstr = _PyObject_FunctionStr(func);
6244 if (funcstr != NULL) {
6245 _PyErr_Format(tstate, PyExc_TypeError,
6246 "%U argument after * must be an iterable, not %.200s",
6247 funcstr, Py_TYPE(args)->tp_name);
6248 Py_DECREF(funcstr);
6249 }
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006250 return -1;
6251 }
6252 return 0;
6253}
6254
6255static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006256format_kwargs_error(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006257{
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006258 /* _PyDict_MergeEx raises attribute
6259 * error (percolated from an attempt
6260 * to get 'keys' attribute) instead of
6261 * a type error if its second argument
6262 * is not a mapping.
6263 */
Victor Stinner438a12d2019-05-24 17:01:38 +02006264 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Victor Stinner61f4db82020-01-28 03:37:45 +01006265 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006266 PyObject *funcstr = _PyObject_FunctionStr(func);
6267 if (funcstr != NULL) {
6268 _PyErr_Format(
6269 tstate, PyExc_TypeError,
6270 "%U argument after ** must be a mapping, not %.200s",
6271 funcstr, Py_TYPE(kwargs)->tp_name);
6272 Py_DECREF(funcstr);
6273 }
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006274 }
Victor Stinner438a12d2019-05-24 17:01:38 +02006275 else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006276 PyObject *exc, *val, *tb;
Victor Stinner438a12d2019-05-24 17:01:38 +02006277 _PyErr_Fetch(tstate, &exc, &val, &tb);
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006278 if (val && PyTuple_Check(val) && PyTuple_GET_SIZE(val) == 1) {
Victor Stinner61f4db82020-01-28 03:37:45 +01006279 _PyErr_Clear(tstate);
Jeroen Demeyerbf17d412019-11-05 16:48:04 +01006280 PyObject *funcstr = _PyObject_FunctionStr(func);
6281 if (funcstr != NULL) {
6282 PyObject *key = PyTuple_GET_ITEM(val, 0);
6283 _PyErr_Format(
6284 tstate, PyExc_TypeError,
6285 "%U got multiple values for keyword argument '%S'",
6286 funcstr, key);
6287 Py_DECREF(funcstr);
6288 }
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006289 Py_XDECREF(exc);
6290 Py_XDECREF(val);
6291 Py_XDECREF(tb);
6292 }
6293 else {
Victor Stinner438a12d2019-05-24 17:01:38 +02006294 _PyErr_Restore(tstate, exc, val, tb);
Serhiy Storchakaf1ec3ce2019-01-12 10:12:24 +02006295 }
6296 }
Serhiy Storchaka25e4f772017-08-03 11:37:15 +03006297}
6298
Guido van Rossumac7be682001-01-17 15:42:30 +00006299static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006300format_exc_check_arg(PyThreadState *tstate, PyObject *exc,
6301 const char *format_str, PyObject *obj)
Paul Prescode68140d2000-08-30 20:25:01 +00006302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006303 const char *obj_str;
Paul Prescode68140d2000-08-30 20:25:01 +00006304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006305 if (!obj)
6306 return;
Paul Prescode68140d2000-08-30 20:25:01 +00006307
Serhiy Storchaka06515832016-11-20 09:13:07 +02006308 obj_str = PyUnicode_AsUTF8(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006309 if (!obj_str)
6310 return;
Paul Prescode68140d2000-08-30 20:25:01 +00006311
Victor Stinner438a12d2019-05-24 17:01:38 +02006312 _PyErr_Format(tstate, exc, format_str, obj_str);
Paul Prescode68140d2000-08-30 20:25:01 +00006313}
Guido van Rossum950361c1997-01-24 13:49:28 +00006314
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006315static void
Victor Stinner438a12d2019-05-24 17:01:38 +02006316format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006317{
6318 PyObject *name;
6319 /* Don't stomp existing exception */
Victor Stinner438a12d2019-05-24 17:01:38 +02006320 if (_PyErr_Occurred(tstate))
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006321 return;
6322 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
6323 name = PyTuple_GET_ITEM(co->co_cellvars,
6324 oparg);
Victor Stinner438a12d2019-05-24 17:01:38 +02006325 format_exc_check_arg(tstate,
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006326 PyExc_UnboundLocalError,
6327 UNBOUNDLOCAL_ERROR_MSG,
6328 name);
6329 } else {
6330 name = PyTuple_GET_ITEM(co->co_freevars, oparg -
6331 PyTuple_GET_SIZE(co->co_cellvars));
Victor Stinner438a12d2019-05-24 17:01:38 +02006332 format_exc_check_arg(tstate, PyExc_NameError,
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00006333 UNBOUNDFREE_ERROR_MSG, name);
6334 }
6335}
6336
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006337static void
Mark Shannonfee55262019-11-21 09:11:43 +00006338format_awaitable_error(PyThreadState *tstate, PyTypeObject *type, int prevprevopcode, int prevopcode)
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006339{
6340 if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
6341 if (prevopcode == BEFORE_ASYNC_WITH) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006342 _PyErr_Format(tstate, PyExc_TypeError,
6343 "'async with' received an object from __aenter__ "
6344 "that does not implement __await__: %.100s",
6345 type->tp_name);
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006346 }
Mark Shannonfee55262019-11-21 09:11:43 +00006347 else if (prevopcode == WITH_EXCEPT_START || (prevopcode == CALL_FUNCTION && prevprevopcode == DUP_TOP)) {
Victor Stinner438a12d2019-05-24 17:01:38 +02006348 _PyErr_Format(tstate, PyExc_TypeError,
6349 "'async with' received an object from __aexit__ "
6350 "that does not implement __await__: %.100s",
6351 type->tp_name);
Serhiy Storchakaa68f2f02018-04-03 01:41:38 +03006352 }
6353 }
6354}
6355
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006356static PyObject *
Victor Stinner438a12d2019-05-24 17:01:38 +02006357unicode_concatenate(PyThreadState *tstate, PyObject *v, PyObject *w,
Serhiy Storchakaab874002016-09-11 13:48:15 +03006358 PyFrameObject *f, const _Py_CODEUNIT *next_instr)
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006359{
6360 PyObject *res;
6361 if (Py_REFCNT(v) == 2) {
6362 /* In the common case, there are 2 references to the value
6363 * stored in 'variable' when the += is performed: one on the
6364 * value stack (in 'v') and one still stored in the
6365 * 'variable'. We try to delete the variable now to reduce
6366 * the refcnt to 1.
6367 */
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006368 int opcode, oparg;
6369 NEXTOPARG();
6370 switch (opcode) {
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006371 case STORE_FAST:
6372 {
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006373 PyObject **fastlocals = f->f_localsplus;
6374 if (GETLOCAL(oparg) == v)
6375 SETLOCAL(oparg, NULL);
6376 break;
6377 }
6378 case STORE_DEREF:
6379 {
6380 PyObject **freevars = (f->f_localsplus +
6381 f->f_code->co_nlocals);
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006382 PyObject *c = freevars[oparg];
Raymond Hettingerc32f9db2016-11-12 04:10:35 -05006383 if (PyCell_GET(c) == v) {
6384 PyCell_SET(c, NULL);
6385 Py_DECREF(v);
6386 }
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006387 break;
6388 }
6389 case STORE_NAME:
6390 {
6391 PyObject *names = f->f_code->co_names;
Serhiy Storchakaf60bf5f2016-05-25 20:02:01 +03006392 PyObject *name = GETITEM(names, oparg);
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006393 PyObject *locals = f->f_locals;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006394 if (locals && PyDict_CheckExact(locals)) {
6395 PyObject *w = PyDict_GetItemWithError(locals, name);
6396 if ((w == v && PyDict_DelItem(locals, name) != 0) ||
Victor Stinner438a12d2019-05-24 17:01:38 +02006397 (w == NULL && _PyErr_Occurred(tstate)))
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02006398 {
6399 Py_DECREF(v);
6400 return NULL;
Victor Stinnerd2a915d2011-10-02 20:34:20 +02006401 }
6402 }
6403 break;
6404 }
6405 }
6406 }
6407 res = v;
6408 PyUnicode_Append(&res, w);
6409 return res;
6410}
6411
Guido van Rossum950361c1997-01-24 13:49:28 +00006412#ifdef DYNAMIC_EXECUTION_PROFILE
6413
Skip Montanarof118cb12001-10-15 20:51:38 +00006414static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00006415getarray(long a[256])
Guido van Rossum950361c1997-01-24 13:49:28 +00006416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006417 int i;
6418 PyObject *l = PyList_New(256);
6419 if (l == NULL) return NULL;
6420 for (i = 0; i < 256; i++) {
6421 PyObject *x = PyLong_FromLong(a[i]);
6422 if (x == NULL) {
6423 Py_DECREF(l);
6424 return NULL;
6425 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07006426 PyList_SET_ITEM(l, i, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006427 }
6428 for (i = 0; i < 256; i++)
6429 a[i] = 0;
6430 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00006431}
6432
6433PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00006434_Py_GetDXProfile(PyObject *self, PyObject *args)
Guido van Rossum950361c1997-01-24 13:49:28 +00006435{
6436#ifndef DXPAIRS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006437 return getarray(dxp);
Guido van Rossum950361c1997-01-24 13:49:28 +00006438#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006439 int i;
6440 PyObject *l = PyList_New(257);
6441 if (l == NULL) return NULL;
6442 for (i = 0; i < 257; i++) {
6443 PyObject *x = getarray(dxpairs[i]);
6444 if (x == NULL) {
6445 Py_DECREF(l);
6446 return NULL;
6447 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07006448 PyList_SET_ITEM(l, i, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006449 }
6450 return l;
Guido van Rossum950361c1997-01-24 13:49:28 +00006451#endif
6452}
6453
6454#endif
Brett Cannon5c4de282016-09-07 11:16:41 -07006455
6456Py_ssize_t
6457_PyEval_RequestCodeExtraIndex(freefunc free)
6458{
Victor Stinner81a7be32020-04-14 15:14:01 +02006459 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannon5c4de282016-09-07 11:16:41 -07006460 Py_ssize_t new_index;
6461
Dino Viehlandf3cffd22017-06-21 14:44:36 -07006462 if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
Brett Cannon5c4de282016-09-07 11:16:41 -07006463 return -1;
6464 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -07006465 new_index = interp->co_extra_user_count++;
6466 interp->co_extra_freefuncs[new_index] = free;
Brett Cannon5c4de282016-09-07 11:16:41 -07006467 return new_index;
6468}
Łukasz Langaa785c872016-09-09 17:37:37 -07006469
6470static void
6471dtrace_function_entry(PyFrameObject *f)
6472{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006473 const char *filename;
6474 const char *funcname;
Łukasz Langaa785c872016-09-09 17:37:37 -07006475 int lineno;
6476
Victor Stinner6d86a232020-04-29 00:56:58 +02006477 PyCodeObject *code = f->f_code;
6478 filename = PyUnicode_AsUTF8(code->co_filename);
6479 funcname = PyUnicode_AsUTF8(code->co_name);
Mark Shannonfcb55c02021-04-01 16:00:31 +01006480 lineno = PyFrame_GetLineNumber(f);
Łukasz Langaa785c872016-09-09 17:37:37 -07006481
Andy Lestere6be9b52020-02-11 20:28:35 -06006482 PyDTrace_FUNCTION_ENTRY(filename, funcname, lineno);
Łukasz Langaa785c872016-09-09 17:37:37 -07006483}
6484
6485static void
6486dtrace_function_return(PyFrameObject *f)
6487{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006488 const char *filename;
6489 const char *funcname;
Łukasz Langaa785c872016-09-09 17:37:37 -07006490 int lineno;
6491
Victor Stinner6d86a232020-04-29 00:56:58 +02006492 PyCodeObject *code = f->f_code;
6493 filename = PyUnicode_AsUTF8(code->co_filename);
6494 funcname = PyUnicode_AsUTF8(code->co_name);
Mark Shannonfcb55c02021-04-01 16:00:31 +01006495 lineno = PyFrame_GetLineNumber(f);
Łukasz Langaa785c872016-09-09 17:37:37 -07006496
Andy Lestere6be9b52020-02-11 20:28:35 -06006497 PyDTrace_FUNCTION_RETURN(filename, funcname, lineno);
Łukasz Langaa785c872016-09-09 17:37:37 -07006498}
6499
6500/* DTrace equivalent of maybe_call_line_trace. */
6501static void
6502maybe_dtrace_line(PyFrameObject *frame,
Mark Shannon8e1b4062021-03-05 14:45:50 +00006503 PyTraceInfo *trace_info)
Łukasz Langaa785c872016-09-09 17:37:37 -07006504{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02006505 const char *co_filename, *co_name;
Łukasz Langaa785c872016-09-09 17:37:37 -07006506
6507 /* If the last instruction executed isn't in the current
6508 instruction window, reset the window.
6509 */
Mark Shannon8e1b4062021-03-05 14:45:50 +00006510 initialize_trace_info(trace_info, frame);
Mark Shannonfcb55c02021-04-01 16:00:31 +01006511 int line = _PyCode_CheckLineNumber(frame->f_lasti*2, &trace_info->bounds);
Łukasz Langaa785c872016-09-09 17:37:37 -07006512 /* If the last instruction falls at the start of a line or if
6513 it represents a jump backwards, update the frame's line
6514 number and call the trace function. */
Mark Shannon8e1b4062021-03-05 14:45:50 +00006515 if (line != frame->f_lineno || frame->f_lasti < trace_info->instr_prev) {
Mark Shannon877df852020-11-12 09:43:29 +00006516 if (line != -1) {
6517 frame->f_lineno = line;
6518 co_filename = PyUnicode_AsUTF8(frame->f_code->co_filename);
6519 if (!co_filename)
6520 co_filename = "?";
6521 co_name = PyUnicode_AsUTF8(frame->f_code->co_name);
6522 if (!co_name)
6523 co_name = "?";
6524 PyDTrace_LINE(co_filename, co_name, line);
6525 }
Łukasz Langaa785c872016-09-09 17:37:37 -07006526 }
Mark Shannon8e1b4062021-03-05 14:45:50 +00006527 trace_info->instr_prev = frame->f_lasti;
Łukasz Langaa785c872016-09-09 17:37:37 -07006528}
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006529
6530
6531/* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
6532 for the limited API. */
6533
6534#undef Py_EnterRecursiveCall
6535
6536int Py_EnterRecursiveCall(const char *where)
6537{
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006538 return _Py_EnterRecursiveCall_inline(where);
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006539}
6540
6541#undef Py_LeaveRecursiveCall
6542
6543void Py_LeaveRecursiveCall(void)
6544{
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006545 _Py_LeaveRecursiveCall_inline();
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +01006546}