blob: 034b908ade31cce6887e8040830cf69339eb7ce8 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Frame object implementation */
2
Guido van Rossum18752471997-04-29 14:49:28 +00003#include "Python.h"
Victor Stinner44085a32021-02-18 19:20:16 +01004#include "pycore_ceval.h" // _PyEval_BuiltinsFromGlobals()
Victor Stinnercdad2722021-04-22 00:52:52 +02005#include "pycore_moduleobject.h" // _PyModule_GetDict()
Victor Stinner44085a32021-02-18 19:20:16 +01006#include "pycore_object.h" // _PyObject_GC_UNTRACK()
Guido van Rossum3f5da241990-12-20 15:06:42 +00007
Victor Stinner44085a32021-02-18 19:20:16 +01008#include "frameobject.h" // PyFrameObject
9#include "opcode.h" // EXTENDED_ARG
Victor Stinner4a21e572020-04-15 02:35:41 +020010#include "structmember.h" // PyMemberDef
Guido van Rossum3f5da241990-12-20 15:06:42 +000011
Guido van Rossum18752471997-04-29 14:49:28 +000012#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000013
Guido van Rossum6f799372001-09-20 20:46:19 +000014static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100015 {"f_back", T_OBJECT, OFF(f_back), READONLY},
Steve Dower87655e22021-04-30 01:08:55 +010016 {"f_code", T_OBJECT, OFF(f_code), READONLY|PY_AUDIT_READ},
Nick Coghlan1f7ce622012-01-13 21:43:40 +100017 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
18 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
Nick Coghlan5a851672017-09-08 10:14:16 +100019 {"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
20 {"f_trace_opcodes", T_BOOL, OFF(f_trace_opcodes), 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000022};
23
Victor Stinner522691c2020-06-23 16:40:40 +020024static struct _Py_frame_state *
25get_frame_state(void)
26{
27 PyInterpreterState *interp = _PyInterpreterState_GET();
28 return &interp->frame;
29}
30
31
Guido van Rossum18752471997-04-29 14:49:28 +000032static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000033frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000034{
Victor Stinner41bb43a2013-10-29 01:19:37 +010035 if (PyFrame_FastToLocalsWithError(f) < 0)
36 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 Py_INCREF(f->f_locals);
38 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000039}
40
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000041int
42PyFrame_GetLineNumber(PyFrameObject *f)
43{
Victor Stinner7c59d7c2020-04-28 16:32:48 +020044 assert(f != NULL);
Mark Shannonee9f98d2021-01-05 12:04:10 +000045 if (f->f_lineno != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 return f->f_lineno;
Victor Stinner7c59d7c2020-04-28 16:32:48 +020047 }
48 else {
Mark Shannonfcb55c02021-04-01 16:00:31 +010049 return PyCode_Addr2Line(f->f_code, f->f_lasti*2);
Victor Stinner7c59d7c2020-04-28 16:32:48 +020050 }
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000051}
52
Michael W. Hudsondd32a912002-08-15 14:59:02 +000053static PyObject *
54frame_getlineno(PyFrameObject *f, void *closure)
55{
Mark Shannon088a15c2021-04-29 19:28:50 +010056 int lineno = PyFrame_GetLineNumber(f);
57 if (lineno < 0) {
58 Py_RETURN_NONE;
59 }
60 else {
61 return PyLong_FromLong(lineno);
62 }
Michael W. Hudsondd32a912002-08-15 14:59:02 +000063}
64
Mark Shannonfcb55c02021-04-01 16:00:31 +010065static PyObject *
66frame_getlasti(PyFrameObject *f, void *closure)
67{
68 if (f->f_lasti < 0) {
69 return PyLong_FromLong(-1);
70 }
71 return PyLong_FromLong(f->f_lasti*2);
72}
73
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020074
75/* Given the index of the effective opcode,
76 scan back to construct the oparg with EXTENDED_ARG */
77static unsigned int
78get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
79{
80 _Py_CODEUNIT word;
81 unsigned int oparg = _Py_OPARG(codestr[i]);
82 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
83 oparg |= _Py_OPARG(word) << 8;
84 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
85 oparg |= _Py_OPARG(word) << 16;
86 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
87 oparg |= _Py_OPARG(word) << 24;
88 }
89 }
90 }
91 return oparg;
92}
93
Mark Shannon57697242020-04-29 16:49:45 +010094typedef enum kind {
95 With = 1,
96 Loop = 2,
97 Try = 3,
98 Except = 4,
99} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +0000100
Mark Shannon57697242020-04-29 16:49:45 +0100101#define BITS_PER_BLOCK 3
102
103static inline int64_t
104push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +0000105{
Mark Shannon57697242020-04-29 16:49:45 +0100106 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
107 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +0000108}
109
Mark Shannon57697242020-04-29 16:49:45 +0100110static inline int64_t
111pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000112{
Mark Shannon57697242020-04-29 16:49:45 +0100113 assert(stack > 0);
114 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +0000115}
116
Mark Shannon57697242020-04-29 16:49:45 +0100117static inline Kind
118top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000119{
Mark Shannon57697242020-04-29 16:49:45 +0100120 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +0000121}
122
Mark Shannon57697242020-04-29 16:49:45 +0100123static int64_t *
124markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000125{
Mark Shannon57697242020-04-29 16:49:45 +0100126 const _Py_CODEUNIT *code =
127 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
128 int64_t *blocks = PyMem_New(int64_t, len+1);
129 int i, j, opcode;
130
131 if (blocks == NULL) {
132 PyErr_NoMemory();
133 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000134 }
Mark Shannon57697242020-04-29 16:49:45 +0100135 memset(blocks, -1, (len+1)*sizeof(int64_t));
136 blocks[0] = 0;
137 int todo = 1;
138 while (todo) {
139 todo = 0;
140 for (i = 0; i < len; i++) {
141 int64_t block_stack = blocks[i];
142 int64_t except_stack;
143 if (block_stack == -1) {
144 continue;
145 }
146 opcode = _Py_OPCODE(code[i]);
147 switch (opcode) {
148 case JUMP_IF_FALSE_OR_POP:
149 case JUMP_IF_TRUE_OR_POP:
150 case POP_JUMP_IF_FALSE:
151 case POP_JUMP_IF_TRUE:
152 case JUMP_IF_NOT_EXC_MATCH:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100153 j = get_arg(code, i);
Mark Shannon57697242020-04-29 16:49:45 +0100154 assert(j < len);
155 if (blocks[j] == -1 && j < i) {
156 todo = 1;
157 }
158 assert(blocks[j] == -1 || blocks[j] == block_stack);
159 blocks[j] = block_stack;
160 blocks[i+1] = block_stack;
161 break;
162 case JUMP_ABSOLUTE:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100163 j = get_arg(code, i);
Mark Shannon57697242020-04-29 16:49:45 +0100164 assert(j < len);
165 if (blocks[j] == -1 && j < i) {
166 todo = 1;
167 }
168 assert(blocks[j] == -1 || blocks[j] == block_stack);
169 blocks[j] = block_stack;
170 break;
171 case SETUP_FINALLY:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100172 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100173 assert(j < len);
174 except_stack = push_block(block_stack, Except);
175 assert(blocks[j] == -1 || blocks[j] == except_stack);
176 blocks[j] = except_stack;
177 block_stack = push_block(block_stack, Try);
178 blocks[i+1] = block_stack;
179 break;
180 case SETUP_WITH:
181 case SETUP_ASYNC_WITH:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100182 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100183 assert(j < len);
184 except_stack = push_block(block_stack, Except);
185 assert(blocks[j] == -1 || blocks[j] == except_stack);
186 blocks[j] = except_stack;
187 block_stack = push_block(block_stack, With);
188 blocks[i+1] = block_stack;
189 break;
190 case JUMP_FORWARD:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100191 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100192 assert(j < len);
193 assert(blocks[j] == -1 || blocks[j] == block_stack);
194 blocks[j] = block_stack;
195 break;
196 case GET_ITER:
197 case GET_AITER:
198 block_stack = push_block(block_stack, Loop);
199 blocks[i+1] = block_stack;
200 break;
201 case FOR_ITER:
202 blocks[i+1] = block_stack;
203 block_stack = pop_block(block_stack);
Mark Shannonfcb55c02021-04-01 16:00:31 +0100204 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100205 assert(j < len);
206 assert(blocks[j] == -1 || blocks[j] == block_stack);
207 blocks[j] = block_stack;
208 break;
209 case POP_BLOCK:
210 case POP_EXCEPT:
211 block_stack = pop_block(block_stack);
212 blocks[i+1] = block_stack;
213 break;
214 case END_ASYNC_FOR:
215 block_stack = pop_block(pop_block(block_stack));
216 blocks[i+1] = block_stack;
217 break;
218 case RETURN_VALUE:
219 case RAISE_VARARGS:
220 case RERAISE:
221 /* End of block */
222 break;
223 default:
224 blocks[i+1] = block_stack;
225
226 }
227 }
228 }
229 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000230}
231
232static int
Mark Shannon57697242020-04-29 16:49:45 +0100233compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000234{
Mark Shannon57697242020-04-29 16:49:45 +0100235 if (to_stack < 0) {
236 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000237 }
Mark Shannon57697242020-04-29 16:49:45 +0100238 while(from_stack > to_stack) {
239 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000240 }
Mark Shannon57697242020-04-29 16:49:45 +0100241 return from_stack == to_stack;
242}
243
244static const char *
245explain_incompatible_block_stack(int64_t to_stack)
246{
247 Kind target_kind = top_block(to_stack);
248 switch(target_kind) {
249 case Except:
250 return "can't jump into an 'except' block as there's no exception";
251 case Try:
252 return "can't jump into the body of a try statement";
253 case With:
254 return "can't jump into the body of a with statement";
255 case Loop:
256 return "can't jump into the body of a for loop";
257 default:
258 Py_UNREACHABLE();
259 }
260}
261
262static int *
263marklines(PyCodeObject *code, int len)
264{
Mark Shannon877df852020-11-12 09:43:29 +0000265 PyCodeAddressRange bounds;
266 _PyCode_InitAddressRange(code, &bounds);
267 assert (bounds.ar_end == 0);
268
Mark Shannon57697242020-04-29 16:49:45 +0100269 int *linestarts = PyMem_New(int, len);
270 if (linestarts == NULL) {
271 return NULL;
272 }
Mark Shannon877df852020-11-12 09:43:29 +0000273 for (int i = 0; i < len; i++) {
274 linestarts[i] = -1;
Mark Shannon57697242020-04-29 16:49:45 +0100275 }
Mark Shannon877df852020-11-12 09:43:29 +0000276
277 while (PyLineTable_NextAddressRange(&bounds)) {
278 assert(bounds.ar_start/2 < len);
279 linestarts[bounds.ar_start/2] = bounds.ar_line;
Mark Shannon57697242020-04-29 16:49:45 +0100280 }
Mark Shannon57697242020-04-29 16:49:45 +0100281 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000282}
283
284static int
Mark Shannon57697242020-04-29 16:49:45 +0100285first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000286{
287 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100288 for (int i = 0; i < len; i++) {
289 if (lines[i] < result && lines[i] >= line) {
290 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000291 }
Mark Shannonfee55262019-11-21 09:11:43 +0000292 }
293 if (result == INT_MAX) {
294 return -1;
295 }
296 return result;
297}
298
Mark Shannonfee55262019-11-21 09:11:43 +0000299static void
300frame_stack_pop(PyFrameObject *f)
301{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100302 assert(f->f_stackdepth >= 0);
303 f->f_stackdepth--;
304 PyObject *v = f->f_valuestack[f->f_stackdepth];
Mark Shannonfee55262019-11-21 09:11:43 +0000305 Py_DECREF(v);
306}
307
308static void
309frame_block_unwind(PyFrameObject *f)
310{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100311 assert(f->f_stackdepth >= 0);
Mark Shannonfee55262019-11-21 09:11:43 +0000312 assert(f->f_iblock > 0);
313 f->f_iblock--;
314 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Mark Shannoncb9879b2020-07-17 11:44:23 +0100315 intptr_t delta = f->f_stackdepth - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000316 while (delta > 0) {
317 frame_stack_pop(f);
318 delta--;
319 }
320}
321
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200322
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000323/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000325 * lines are OK to jump to because they don't make any assumptions about the
326 * state of the stack (obvious because you could remove the line and the code
327 * would still work without any stack errors), but there are some constructs
328 * that limit jumping:
329 *
330 * o Lines with an 'except' statement on them can't be jumped to, because
331 * they expect an exception to be on the top of the stack.
332 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000333 * we cannot be sure which state the interpreter was in or would be in
334 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200335 * o 'try', 'with' and 'async with' blocks can't be jumped into because
336 * the blockstack needs to be set up before their code runs.
337 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000338 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100339 * o Jumps cannot be made from within a trace function invoked with a
340 * 'return' or 'exception' event since the eval loop has been exited at
341 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000342 */
343static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200344frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000345{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700346 if (p_new_lineno == NULL) {
347 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
348 return -1;
349 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 /* f_lineno must be an integer. */
351 if (!PyLong_CheckExact(p_new_lineno)) {
352 PyErr_SetString(PyExc_ValueError,
353 "lineno must be an integer");
354 return -1;
355 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000356
Mark Shannoncb9879b2020-07-17 11:44:23 +0100357 /*
358 * This code preserves the historical restrictions on
359 * setting the line number of a frame.
360 * Jumps are forbidden on a 'return' trace event (except after a yield).
361 * Jumps from 'call' trace events are also forbidden.
362 * In addition, jumps are forbidden when not tracing,
363 * as this is a debugging feature.
364 */
365 switch(f->f_state) {
366 case FRAME_CREATED:
367 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100368 "can't jump from the 'call' trace event of a new frame");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100369 return -1;
370 case FRAME_RETURNED:
371 case FRAME_UNWINDING:
372 case FRAME_RAISED:
373 case FRAME_CLEARED:
374 PyErr_SetString(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100375 "can only jump from a 'line' trace event");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100376 return -1;
377 case FRAME_EXECUTING:
378 case FRAME_SUSPENDED:
379 /* You can only do this from within a trace function, not via
380 * _getframe or similar hackery. */
381 if (!f->f_trace) {
382 PyErr_Format(PyExc_ValueError,
383 "f_lineno can only be set by a trace function");
384 return -1;
385 }
386 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000388
Mark Shannonfee55262019-11-21 09:11:43 +0000389 int new_lineno;
390
Mark Shannon57697242020-04-29 16:49:45 +0100391 /* Fail if the line falls outside the code block and
392 select first line with actual code. */
393 int overflow;
394 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
395 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000396#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100397 || l_new_lineno > INT_MAX
398 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000399#endif
Mark Shannon57697242020-04-29 16:49:45 +0100400 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000401 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100402 "lineno out of range");
403 return -1;
404 }
405 new_lineno = (int)l_new_lineno;
406
407 if (new_lineno < f->f_code->co_firstlineno) {
408 PyErr_Format(PyExc_ValueError,
409 "line %d comes before the current code block",
410 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 return -1;
412 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000413
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000414 /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
415 * should never overflow. */
416 int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT));
Mark Shannon57697242020-04-29 16:49:45 +0100417 int *lines = marklines(f->f_code, len);
418 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 return -1;
420 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000421
Mark Shannon57697242020-04-29 16:49:45 +0100422 new_lineno = first_line_not_before(lines, len, new_lineno);
423 if (new_lineno < 0) {
424 PyErr_Format(PyExc_ValueError,
425 "line %d comes after the current code block",
426 (int)l_new_lineno);
427 PyMem_Free(lines);
428 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000429 }
430
Mark Shannon57697242020-04-29 16:49:45 +0100431 int64_t *blocks = markblocks(f->f_code, len);
432 if (blocks == NULL) {
433 PyMem_Free(lines);
434 return -1;
435 }
436
437 int64_t target_block_stack = -1;
438 int64_t best_block_stack = -1;
439 int best_addr = -1;
Mark Shannonfcb55c02021-04-01 16:00:31 +0100440 int64_t start_block_stack = blocks[f->f_lasti];
Mark Shannon57697242020-04-29 16:49:45 +0100441 const char *msg = "cannot find bytecode for specified line";
442 for (int i = 0; i < len; i++) {
443 if (lines[i] == new_lineno) {
444 target_block_stack = blocks[i];
445 if (compatible_block_stack(start_block_stack, target_block_stack)) {
446 msg = NULL;
447 if (target_block_stack > best_block_stack) {
448 best_block_stack = target_block_stack;
Mark Shannonfcb55c02021-04-01 16:00:31 +0100449 best_addr = i;
Mark Shannon57697242020-04-29 16:49:45 +0100450 }
451 }
452 else if (msg) {
453 if (target_block_stack >= 0) {
454 msg = explain_incompatible_block_stack(target_block_stack);
455 }
456 else {
457 msg = "code may be unreachable.";
458 }
459 }
Mark Shannonfee55262019-11-21 09:11:43 +0000460 }
461 }
Mark Shannon57697242020-04-29 16:49:45 +0100462 PyMem_Free(blocks);
463 PyMem_Free(lines);
464 if (msg != NULL) {
465 PyErr_SetString(PyExc_ValueError, msg);
466 return -1;
467 }
Mark Shannonfee55262019-11-21 09:11:43 +0000468
469 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100470 while (start_block_stack > best_block_stack) {
471 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000472 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100473 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000474 frame_stack_pop(f);
475 break;
Mark Shannon57697242020-04-29 16:49:45 +0100476 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000477 frame_block_unwind(f);
478 break;
Mark Shannon57697242020-04-29 16:49:45 +0100479 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000480 frame_block_unwind(f);
481 // Pop the exit function
482 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 break;
Mark Shannon57697242020-04-29 16:49:45 +0100484 case Except:
485 PyErr_SetString(PyExc_ValueError,
486 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000487 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 }
Mark Shannon57697242020-04-29 16:49:45 +0100489 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 }
Mark Shannonfee55262019-11-21 09:11:43 +0000491
Mark Shannonee9f98d2021-01-05 12:04:10 +0000492 /* Finally set the new f_lasti and return OK. */
493 f->f_lineno = 0;
Mark Shannon57697242020-04-29 16:49:45 +0100494 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000496}
497
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000498static PyObject *
499frame_gettrace(PyFrameObject *f, void *closure)
500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (trace == NULL)
504 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000509}
510
511static int
512frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
513{
Mark Shannonee9f98d2021-01-05 12:04:10 +0000514 if (v == Py_None) {
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300515 v = NULL;
Mark Shannonee9f98d2021-01-05 12:04:10 +0000516 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300518 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000521}
522
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000523
Guido van Rossum32d34c82001-09-20 21:45:26 +0000524static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 {"f_locals", (getter)frame_getlocals, NULL, NULL},
526 {"f_lineno", (getter)frame_getlineno,
527 (setter)frame_setlineno, NULL},
528 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
Mark Shannonfcb55c02021-04-01 16:00:31 +0100529 {"f_lasti", (getter)frame_getlasti, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000531};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000532
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000533/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534 In an attempt to improve the speed of function calls, we:
535
536 1. Hold a single "zombie" frame on each code object. This retains
537 the allocated and initialised frame object from an invocation of
538 the code object. The zombie is reanimated the next time we need a
539 frame object for that code object. Doing this saves the malloc/
540 realloc required when using a free_list frame that isn't the
541 correct size. It also saves some field initialisation.
542
543 In zombie mode, no field of PyFrameObject holds a reference, but
544 the following fields are still valid:
545
546 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547
Mark Shannonae3087c2017-10-22 22:41:51 +0100548 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
550 * f_localsplus does not require re-allocation and
551 the local variables in f_localsplus are NULL.
552
553 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000554 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555 a stack frame is on the free list, only the following members have
556 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 ob_type == &Frametype
558 f_back next item on free list, or NULL
559 f_stacksize size of value stack
560 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000561 Note that the value and block stacks are preserved -- this can save
562 another malloc() call or two (and two free() calls as well!).
563 Also note that, unlike for integers, each frame object is a
564 malloc'ed object in its own right -- it is only the actual calls to
565 malloc() that we are trying to save here, not the administration.
566 After all, while a typical program may make millions of calls, a
567 call depth of more than 20 or 30 is probably already exceptional
568 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000569
Christian Heimes2202f872008-02-06 14:31:34 +0000570 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000571 free_list. Else programs creating lots of cyclic trash involving
572 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000573*/
Christian Heimes2202f872008-02-06 14:31:34 +0000574/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000576
Victor Stinnerc6944e72016-11-11 02:13:35 +0100577static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000578frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000579{
Victor Stinner3744ed22020-06-05 01:39:24 +0200580 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900581 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200582 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200585 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200586 PyObject **valuestack = f->f_valuestack;
587 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200588 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200589 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200590
591 /* Free stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100592 for (int i = 0; i < f->f_stackdepth; i++) {
593 Py_XDECREF(f->f_valuestack[i]);
Antoine Pitrou93963562013-05-14 20:37:52 +0200594 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100595 f->f_stackdepth = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 Py_XDECREF(f->f_back);
598 Py_DECREF(f->f_builtins);
599 Py_DECREF(f->f_globals);
600 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200601 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000602
Victor Stinner3744ed22020-06-05 01:39:24 +0200603 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200604 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200606 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200607 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200608 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200609#ifdef Py_DEBUG
610 // frame_dealloc() must not be called after _PyFrame_Fini()
611 assert(state->numfree != -1);
612#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200613 if (state->numfree < PyFrame_MAXFREELIST) {
614 ++state->numfree;
615 f->f_back = state->free_list;
616 state->free_list = f;
617 }
618 else {
619 PyObject_GC_Del(f);
620 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200621 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 Py_DECREF(co);
624 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000625}
626
Victor Stinner6d86a232020-04-29 00:56:58 +0200627static inline Py_ssize_t
628frame_nslots(PyFrameObject *frame)
629{
630 PyCodeObject *code = frame->f_code;
631 return (code->co_nlocals
632 + PyTuple_GET_SIZE(code->co_cellvars)
633 + PyTuple_GET_SIZE(code->co_freevars));
634}
635
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000636static int
637frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 Py_VISIT(f->f_back);
640 Py_VISIT(f->f_code);
641 Py_VISIT(f->f_builtins);
642 Py_VISIT(f->f_globals);
643 Py_VISIT(f->f_locals);
644 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200647 PyObject **fastlocals = f->f_localsplus;
648 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200650 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100653 for (int i = 0; i < f->f_stackdepth; i++) {
654 Py_VISIT(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 }
656 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000657}
658
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200659static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200660frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000661{
Antoine Pitrou93963562013-05-14 20:37:52 +0200662 /* Before anything else, make sure that this frame is clearly marked
663 * as being defunct! Else, e.g., a generator reachable from this
664 * frame may also point to this frame, believe itself to still be
665 * active, and try cleaning up this frame again.
666 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100667 f->f_state = FRAME_CLEARED;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200672 PyObject **fastlocals = f->f_localsplus;
673 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200675 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100678 for (int i = 0; i < f->f_stackdepth; i++) {
679 Py_CLEAR(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100681 f->f_stackdepth = 0;
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200682 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000683}
684
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000685static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530686frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200687{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100688 if (_PyFrame_IsExecuting(f)) {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200689 PyErr_SetString(PyExc_RuntimeError,
690 "cannot clear an executing frame");
691 return NULL;
692 }
693 if (f->f_gen) {
694 _PyGen_Finalize(f->f_gen);
695 assert(f->f_gen == NULL);
696 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200697 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200698 Py_RETURN_NONE;
699}
700
701PyDoc_STRVAR(clear__doc__,
702"F.clear(): clear most references held by the frame");
703
704static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530705frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000708
Victor Stinner6d86a232020-04-29 00:56:58 +0200709 PyCodeObject *code = f->f_code;
710 ncells = PyTuple_GET_SIZE(code->co_cellvars);
711 nfrees = PyTuple_GET_SIZE(code->co_freevars);
712 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 /* subtract one as it is already included in PyFrameObject */
714 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000717}
718
719PyDoc_STRVAR(sizeof__doc__,
720"F.__sizeof__() -> size of F in memory, in bytes");
721
Antoine Pitrou14709142017-12-31 22:35:22 +0100722static PyObject *
723frame_repr(PyFrameObject *f)
724{
725 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200726 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100727 return PyUnicode_FromFormat(
728 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200729 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100730}
731
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000732static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200733 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
734 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
736 sizeof__doc__},
737 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000738};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000739
Guido van Rossum18752471997-04-29 14:49:28 +0000740PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyVarObject_HEAD_INIT(&PyType_Type, 0)
742 "frame",
743 sizeof(PyFrameObject),
744 sizeof(PyObject *),
745 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200746 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 0, /* tp_getattr */
748 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200749 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100750 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 0, /* tp_as_number */
752 0, /* tp_as_sequence */
753 0, /* tp_as_mapping */
754 0, /* tp_hash */
755 0, /* tp_call */
756 0, /* tp_str */
757 PyObject_GenericGetAttr, /* tp_getattro */
758 PyObject_GenericSetAttr, /* tp_setattro */
759 0, /* tp_as_buffer */
760 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
761 0, /* tp_doc */
762 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200763 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 0, /* tp_richcompare */
765 0, /* tp_weaklistoffset */
766 0, /* tp_iter */
767 0, /* tp_iternext */
768 frame_methods, /* tp_methods */
769 frame_memberlist, /* tp_members */
770 frame_getsetlist, /* tp_getset */
771 0, /* tp_base */
772 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000773};
774
Victor Stinner07e9e382013-11-07 22:22:39 +0100775_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000776
Victor Stinnerb4b53862020-05-05 19:55:29 +0200777static inline PyFrameObject*
778frame_alloc(PyCodeObject *code)
779{
Victor Stinner44085a32021-02-18 19:20:16 +0100780 PyFrameObject *f = code->co_zombieframe;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200781 if (f != NULL) {
782 code->co_zombieframe = NULL;
783 _Py_NewReference((PyObject *)f);
784 assert(f->f_code == code);
785 return f;
786 }
787
788 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
789 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
790 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200791 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200792 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200793 {
794 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
795 if (f == NULL) {
796 return NULL;
797 }
798 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200799 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200800#ifdef Py_DEBUG
801 // frame_alloc() must not be called after _PyFrame_Fini()
802 assert(state->numfree != -1);
803#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200804 assert(state->numfree > 0);
805 --state->numfree;
806 f = state->free_list;
807 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200808 if (Py_SIZE(f) < extras) {
809 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
810 if (new_f == NULL) {
811 PyObject_GC_Del(f);
812 return NULL;
813 }
814 f = new_f;
815 }
816 _Py_NewReference((PyObject *)f);
817 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200818
Victor Stinnerb4b53862020-05-05 19:55:29 +0200819 extras = code->co_nlocals + ncells + nfrees;
820 f->f_valuestack = f->f_localsplus + extras;
Victor Stinner44085a32021-02-18 19:20:16 +0100821 for (Py_ssize_t i=0; i < extras; i++) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200822 f->f_localsplus[i] = NULL;
823 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200824 return f;
825}
826
827
Victor Stinnerc6944e72016-11-11 02:13:35 +0100828PyFrameObject* _Py_HOT_FUNCTION
Mark Shannon0332e562021-02-01 10:42:03 +0000829_PyFrame_New_NoTrack(PyThreadState *tstate, PyFrameConstructor *con, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000830{
Victor Stinner44085a32021-02-18 19:20:16 +0100831 assert(con != NULL);
832 assert(con->fc_globals != NULL);
833 assert(con->fc_builtins != NULL);
834 assert(con->fc_code != NULL);
835 assert(locals == NULL || PyMapping_Check(locals));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000836
Mark Shannon0332e562021-02-01 10:42:03 +0000837 PyFrameObject *f = frame_alloc((PyCodeObject *)con->fc_code);
Victor Stinnerb4b53862020-05-05 19:55:29 +0200838 if (f == NULL) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200839 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200841
Victor Stinner44085a32021-02-18 19:20:16 +0100842 f->f_back = (PyFrameObject*)Py_XNewRef(tstate->frame);
843 f->f_code = (PyCodeObject *)Py_NewRef(con->fc_code);
844 f->f_builtins = Py_NewRef(con->fc_builtins);
845 f->f_globals = Py_NewRef(con->fc_globals);
846 f->f_locals = Py_XNewRef(locals);
847 // f_valuestack initialized by frame_alloc()
848 f->f_trace = NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100849 f->f_stackdepth = 0;
Victor Stinner44085a32021-02-18 19:20:16 +0100850 f->f_trace_lines = 1;
851 f->f_trace_opcodes = 0;
852 f->f_gen = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 f->f_lasti = -1;
Mark Shannon877df852020-11-12 09:43:29 +0000854 f->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 f->f_iblock = 0;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100856 f->f_state = FRAME_CREATED;
Victor Stinner44085a32021-02-18 19:20:16 +0100857 // f_blockstack and f_localsplus initialized by frame_alloc()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000859}
860
Mark Shannon0332e562021-02-01 10:42:03 +0000861/* Legacy API */
INADA Naoki5a625d02016-12-24 20:19:08 +0900862PyFrameObject*
863PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
864 PyObject *globals, PyObject *locals)
865{
Victor Stinnerfc980e02021-03-18 14:51:24 +0100866 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Victor Stinner44085a32021-02-18 19:20:16 +0100867 if (builtins == NULL) {
868 return NULL;
869 }
Mark Shannon0332e562021-02-01 10:42:03 +0000870 PyFrameConstructor desc = {
871 .fc_globals = globals,
872 .fc_builtins = builtins,
873 .fc_name = code->co_name,
874 .fc_qualname = code->co_name,
875 .fc_code = (PyObject *)code,
876 .fc_defaults = NULL,
877 .fc_kwdefaults = NULL,
878 .fc_closure = NULL
879 };
880 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, &desc, locals);
Victor Stinner44085a32021-02-18 19:20:16 +0100881 if (f) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900882 _PyObject_GC_TRACK(f);
Victor Stinner44085a32021-02-18 19:20:16 +0100883 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900884 return f;
885}
886
887
Guido van Rossum3f5da241990-12-20 15:06:42 +0000888/* Block management */
889
890void
Fred Drake1b190b42000-07-09 05:40:56 +0000891PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100894 if (f->f_iblock >= CO_MAXBLOCKS) {
895 Py_FatalError("block stack overflow");
896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 b = &f->f_blockstack[f->f_iblock++];
898 b->b_type = type;
899 b->b_level = level;
900 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000901}
902
Guido van Rossum18752471997-04-29 14:49:28 +0000903PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000904PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100907 if (f->f_iblock <= 0) {
908 Py_FatalError("block stack underflow");
909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 b = &f->f_blockstack[--f->f_iblock];
911 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000912}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000913
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915
916 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000917 values is an array of PyObject*. At index i, map[i] is the name of
918 the variable with value values[i]. The function copies the first
919 nmap variable from map/values into dict. If values[i] is NULL,
920 the variable is deleted from dict.
921
922 If deref is true, then the values being copied are cell variables
923 and the value is extracted from the cell variable before being put
924 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000925 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000926
Victor Stinner41bb43a2013-10-29 01:19:37 +0100927static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000928map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 Py_ssize_t j;
932 assert(PyTuple_Check(map));
933 assert(PyDict_Check(dict));
934 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800935 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject *key = PyTuple_GET_ITEM(map, j);
937 PyObject *value = values[j];
938 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400939 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 assert(PyCell_Check(value));
941 value = PyCell_GET(value);
942 }
943 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100944 if (PyObject_DelItem(dict, key) != 0) {
945 if (PyErr_ExceptionMatches(PyExc_KeyError))
946 PyErr_Clear();
947 else
948 return -1;
949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 }
951 else {
952 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100953 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 }
955 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100956 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000957}
958
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959/* Copy values from the "locals" dict into the fast locals.
960
961 dict is an input argument containing string keys representing
962 variables names and arbitrary PyObject* as values.
963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965 values is an array of PyObject*. At index i, map[i] is the name of
966 the variable with value values[i]. The function copies the first
967 nmap variable from map/values into dict. If values[i] is NULL,
968 the variable is deleted from dict.
969
970 If deref is true, then the values being copied are cell variables
971 and the value is extracted from the cell variable before being put
972 in dict. If clear is true, then variables in map but not in dict
973 are set to NULL in map; if clear is false, variables missing in
974 dict are ignored.
975
976 Exceptions raised while modifying the dict are silently ignored,
977 because there is no good way to report them.
978*/
979
Guido van Rossum6b356e72001-04-14 17:55:41 +0000980static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000981dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 Py_ssize_t j;
985 assert(PyTuple_Check(map));
986 assert(PyDict_Check(dict));
987 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800988 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 PyObject *key = PyTuple_GET_ITEM(map, j);
990 PyObject *value = PyObject_GetItem(dict, key);
991 assert(PyUnicode_Check(key));
992 /* We only care about NULLs if clear is true. */
993 if (value == NULL) {
994 PyErr_Clear();
995 if (!clear)
996 continue;
997 }
998 if (deref) {
999 assert(PyCell_Check(values[j]));
1000 if (PyCell_GET(values[j]) != value) {
1001 if (PyCell_Set(values[j], value) < 0)
1002 PyErr_Clear();
1003 }
1004 } else if (values[j] != value) {
1005 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001006 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 }
1008 Py_XDECREF(value);
1009 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001010}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001011
Victor Stinner41bb43a2013-10-29 01:19:37 +01001012int
1013PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 /* Merge fast locals into f->f_locals */
1016 PyObject *locals, *map;
1017 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyCodeObject *co;
1019 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001020 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001021
1022 if (f == NULL) {
1023 PyErr_BadInternalCall();
1024 return -1;
1025 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 locals = f->f_locals;
1027 if (locals == NULL) {
1028 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001029 if (locals == NULL)
1030 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 }
1032 co = f->f_code;
1033 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001034 if (!PyTuple_Check(map)) {
1035 PyErr_Format(PyExc_SystemError,
1036 "co_varnames must be a tuple, not %s",
1037 Py_TYPE(map)->tp_name);
1038 return -1;
1039 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 fast = f->f_localsplus;
1041 j = PyTuple_GET_SIZE(map);
1042 if (j > co->co_nlocals)
1043 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001044 if (co->co_nlocals) {
1045 if (map_to_dict(map, j, locals, fast, 0) < 0)
1046 return -1;
1047 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1049 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1050 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001051 if (map_to_dict(co->co_cellvars, ncells,
1052 locals, fast + co->co_nlocals, 1))
1053 return -1;
1054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 /* If the namespace is unoptimized, then one of the
1056 following cases applies:
1057 1. It does not contain free variables, because it
1058 uses import * or is a top-level namespace.
1059 2. It is a class namespace.
1060 We don't want to accidentally copy free variables
1061 into the locals dict used by the class.
1062 */
1063 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001064 if (map_to_dict(co->co_freevars, nfreevars,
1065 locals, fast + co->co_nlocals + ncells, 1) < 0)
1066 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 }
1068 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001069 return 0;
1070}
1071
1072void
1073PyFrame_FastToLocals(PyFrameObject *f)
1074{
1075 int res;
1076
1077 assert(!PyErr_Occurred());
1078
1079 res = PyFrame_FastToLocalsWithError(f);
1080 if (res < 0)
1081 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001082}
1083
1084void
Fred Drake1b190b42000-07-09 05:40:56 +00001085PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 /* Merge f->f_locals into fast locals */
1088 PyObject *locals, *map;
1089 PyObject **fast;
1090 PyObject *error_type, *error_value, *error_traceback;
1091 PyCodeObject *co;
1092 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001093 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (f == NULL)
1095 return;
1096 locals = f->f_locals;
1097 co = f->f_code;
1098 map = co->co_varnames;
1099 if (locals == NULL)
1100 return;
1101 if (!PyTuple_Check(map))
1102 return;
1103 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1104 fast = f->f_localsplus;
1105 j = PyTuple_GET_SIZE(map);
1106 if (j > co->co_nlocals)
1107 j = co->co_nlocals;
1108 if (co->co_nlocals)
1109 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1110 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1111 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1112 if (ncells || nfreevars) {
1113 dict_to_map(co->co_cellvars, ncells,
1114 locals, fast + co->co_nlocals, 1, clear);
1115 /* Same test as in PyFrame_FastToLocals() above. */
1116 if (co->co_flags & CO_OPTIMIZED) {
1117 dict_to_map(co->co_freevars, nfreevars,
1118 locals, fast + co->co_nlocals + ncells, 1,
1119 clear);
1120 }
1121 }
1122 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001123}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001124
1125/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001126void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001127_PyFrame_ClearFreeList(PyInterpreterState *interp)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001128{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001129 struct _Py_frame_state *state = &interp->frame;
Victor Stinner3744ed22020-06-05 01:39:24 +02001130 while (state->free_list != NULL) {
1131 PyFrameObject *f = state->free_list;
1132 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001134 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001136 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001137}
1138
1139void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001140_PyFrame_Fini(PyInterpreterState *interp)
Christian Heimesa156e092008-02-16 07:38:31 +00001141{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001142 _PyFrame_ClearFreeList(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001143#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001144 struct _Py_frame_state *state = &interp->frame;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001145 state->numfree = -1;
1146#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001147}
David Malcolm49526f42012-06-22 14:55:41 -04001148
1149/* Print summary info about the state of the optimized allocator */
1150void
1151_PyFrame_DebugMallocStats(FILE *out)
1152{
Victor Stinner522691c2020-06-23 16:40:40 +02001153 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001154 _PyDebugAllocatorStats(out,
1155 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001156 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001157}
1158
Victor Stinnera42ca742020-04-28 19:01:31 +02001159
1160PyCodeObject *
1161PyFrame_GetCode(PyFrameObject *frame)
1162{
1163 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001164 PyCodeObject *code = frame->f_code;
1165 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001166 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001167 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001168}
Victor Stinner70364772020-04-29 03:28:46 +02001169
1170
1171PyFrameObject*
1172PyFrame_GetBack(PyFrameObject *frame)
1173{
1174 assert(frame != NULL);
1175 PyFrameObject *back = frame->f_back;
1176 Py_XINCREF(back);
1177 return back;
1178}
Mark Shannond6c33fb2021-01-29 13:24:55 +00001179
Victor Stinner44085a32021-02-18 19:20:16 +01001180PyObject*
Victor Stinner46496f92021-02-20 15:17:18 +01001181_PyEval_BuiltinsFromGlobals(PyThreadState *tstate, PyObject *globals)
Victor Stinner44085a32021-02-18 19:20:16 +01001182{
Mark Shannond6c33fb2021-01-29 13:24:55 +00001183 PyObject *builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
1184 if (builtins) {
1185 if (PyModule_Check(builtins)) {
Victor Stinnercdad2722021-04-22 00:52:52 +02001186 builtins = _PyModule_GetDict(builtins);
Mark Shannond6c33fb2021-01-29 13:24:55 +00001187 assert(builtins != NULL);
1188 }
Victor Stinner46496f92021-02-20 15:17:18 +01001189 return builtins;
Mark Shannond6c33fb2021-01-29 13:24:55 +00001190 }
Victor Stinner44085a32021-02-18 19:20:16 +01001191 if (PyErr_Occurred()) {
1192 return NULL;
1193 }
1194
Victor Stinner46496f92021-02-20 15:17:18 +01001195 return _PyEval_GetBuiltins(tstate);
Mark Shannond6c33fb2021-01-29 13:24:55 +00001196}