blob: 9687ba5c7a93f85981f89b29756fe3632090782f [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()
5#include "pycore_object.h" // _PyObject_GC_UNTRACK()
Guido van Rossum3f5da241990-12-20 15:06:42 +00006
Victor Stinner44085a32021-02-18 19:20:16 +01007#include "frameobject.h" // PyFrameObject
8#include "opcode.h" // EXTENDED_ARG
Victor Stinner4a21e572020-04-15 02:35:41 +02009#include "structmember.h" // PyMemberDef
Guido van Rossum3f5da241990-12-20 15:06:42 +000010
Guido van Rossum18752471997-04-29 14:49:28 +000011#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012
Guido van Rossum6f799372001-09-20 20:46:19 +000013static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100014 {"f_back", T_OBJECT, OFF(f_back), READONLY},
15 {"f_code", T_OBJECT, OFF(f_code), READONLY},
16 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
17 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
Nick Coghlan5a851672017-09-08 10:14:16 +100018 {"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
19 {"f_trace_opcodes", T_BOOL, OFF(f_trace_opcodes), 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000021};
22
Victor Stinner522691c2020-06-23 16:40:40 +020023static struct _Py_frame_state *
24get_frame_state(void)
25{
26 PyInterpreterState *interp = _PyInterpreterState_GET();
27 return &interp->frame;
28}
29
30
Guido van Rossum18752471997-04-29 14:49:28 +000031static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000032frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000033{
Victor Stinner41bb43a2013-10-29 01:19:37 +010034 if (PyFrame_FastToLocalsWithError(f) < 0)
35 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 Py_INCREF(f->f_locals);
37 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000038}
39
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000040int
41PyFrame_GetLineNumber(PyFrameObject *f)
42{
Victor Stinner7c59d7c2020-04-28 16:32:48 +020043 assert(f != NULL);
Mark Shannonee9f98d2021-01-05 12:04:10 +000044 if (f->f_lineno != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 return f->f_lineno;
Victor Stinner7c59d7c2020-04-28 16:32:48 +020046 }
47 else {
Mark Shannonfcb55c02021-04-01 16:00:31 +010048 return PyCode_Addr2Line(f->f_code, f->f_lasti*2);
Victor Stinner7c59d7c2020-04-28 16:32:48 +020049 }
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000050}
51
Michael W. Hudsondd32a912002-08-15 14:59:02 +000052static PyObject *
53frame_getlineno(PyFrameObject *f, void *closure)
54{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000056}
57
Mark Shannonfcb55c02021-04-01 16:00:31 +010058static PyObject *
59frame_getlasti(PyFrameObject *f, void *closure)
60{
61 if (f->f_lasti < 0) {
62 return PyLong_FromLong(-1);
63 }
64 return PyLong_FromLong(f->f_lasti*2);
65}
66
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020067
68/* Given the index of the effective opcode,
69 scan back to construct the oparg with EXTENDED_ARG */
70static unsigned int
71get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
72{
73 _Py_CODEUNIT word;
74 unsigned int oparg = _Py_OPARG(codestr[i]);
75 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
76 oparg |= _Py_OPARG(word) << 8;
77 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
78 oparg |= _Py_OPARG(word) << 16;
79 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
80 oparg |= _Py_OPARG(word) << 24;
81 }
82 }
83 }
84 return oparg;
85}
86
Mark Shannon57697242020-04-29 16:49:45 +010087typedef enum kind {
88 With = 1,
89 Loop = 2,
90 Try = 3,
91 Except = 4,
92} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +000093
Mark Shannon57697242020-04-29 16:49:45 +010094#define BITS_PER_BLOCK 3
95
96static inline int64_t
97push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +000098{
Mark Shannon57697242020-04-29 16:49:45 +010099 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
100 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +0000101}
102
Mark Shannon57697242020-04-29 16:49:45 +0100103static inline int64_t
104pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000105{
Mark Shannon57697242020-04-29 16:49:45 +0100106 assert(stack > 0);
107 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +0000108}
109
Mark Shannon57697242020-04-29 16:49:45 +0100110static inline Kind
111top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000112{
Mark Shannon57697242020-04-29 16:49:45 +0100113 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +0000114}
115
Mark Shannon57697242020-04-29 16:49:45 +0100116static int64_t *
117markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000118{
Mark Shannon57697242020-04-29 16:49:45 +0100119 const _Py_CODEUNIT *code =
120 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
121 int64_t *blocks = PyMem_New(int64_t, len+1);
122 int i, j, opcode;
123
124 if (blocks == NULL) {
125 PyErr_NoMemory();
126 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000127 }
Mark Shannon57697242020-04-29 16:49:45 +0100128 memset(blocks, -1, (len+1)*sizeof(int64_t));
129 blocks[0] = 0;
130 int todo = 1;
131 while (todo) {
132 todo = 0;
133 for (i = 0; i < len; i++) {
134 int64_t block_stack = blocks[i];
135 int64_t except_stack;
136 if (block_stack == -1) {
137 continue;
138 }
139 opcode = _Py_OPCODE(code[i]);
140 switch (opcode) {
141 case JUMP_IF_FALSE_OR_POP:
142 case JUMP_IF_TRUE_OR_POP:
143 case POP_JUMP_IF_FALSE:
144 case POP_JUMP_IF_TRUE:
145 case JUMP_IF_NOT_EXC_MATCH:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100146 j = get_arg(code, i);
Mark Shannon57697242020-04-29 16:49:45 +0100147 assert(j < len);
148 if (blocks[j] == -1 && j < i) {
149 todo = 1;
150 }
151 assert(blocks[j] == -1 || blocks[j] == block_stack);
152 blocks[j] = block_stack;
153 blocks[i+1] = block_stack;
154 break;
155 case JUMP_ABSOLUTE:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100156 j = get_arg(code, i);
Mark Shannon57697242020-04-29 16:49:45 +0100157 assert(j < len);
158 if (blocks[j] == -1 && j < i) {
159 todo = 1;
160 }
161 assert(blocks[j] == -1 || blocks[j] == block_stack);
162 blocks[j] = block_stack;
163 break;
164 case SETUP_FINALLY:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100165 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100166 assert(j < len);
167 except_stack = push_block(block_stack, Except);
168 assert(blocks[j] == -1 || blocks[j] == except_stack);
169 blocks[j] = except_stack;
170 block_stack = push_block(block_stack, Try);
171 blocks[i+1] = block_stack;
172 break;
173 case SETUP_WITH:
174 case SETUP_ASYNC_WITH:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100175 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100176 assert(j < len);
177 except_stack = push_block(block_stack, Except);
178 assert(blocks[j] == -1 || blocks[j] == except_stack);
179 blocks[j] = except_stack;
180 block_stack = push_block(block_stack, With);
181 blocks[i+1] = block_stack;
182 break;
183 case JUMP_FORWARD:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100184 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100185 assert(j < len);
186 assert(blocks[j] == -1 || blocks[j] == block_stack);
187 blocks[j] = block_stack;
188 break;
189 case GET_ITER:
190 case GET_AITER:
191 block_stack = push_block(block_stack, Loop);
192 blocks[i+1] = block_stack;
193 break;
194 case FOR_ITER:
195 blocks[i+1] = block_stack;
196 block_stack = pop_block(block_stack);
Mark Shannonfcb55c02021-04-01 16:00:31 +0100197 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100198 assert(j < len);
199 assert(blocks[j] == -1 || blocks[j] == block_stack);
200 blocks[j] = block_stack;
201 break;
202 case POP_BLOCK:
203 case POP_EXCEPT:
204 block_stack = pop_block(block_stack);
205 blocks[i+1] = block_stack;
206 break;
207 case END_ASYNC_FOR:
208 block_stack = pop_block(pop_block(block_stack));
209 blocks[i+1] = block_stack;
210 break;
211 case RETURN_VALUE:
212 case RAISE_VARARGS:
213 case RERAISE:
214 /* End of block */
215 break;
216 default:
217 blocks[i+1] = block_stack;
218
219 }
220 }
221 }
222 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000223}
224
225static int
Mark Shannon57697242020-04-29 16:49:45 +0100226compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000227{
Mark Shannon57697242020-04-29 16:49:45 +0100228 if (to_stack < 0) {
229 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000230 }
Mark Shannon57697242020-04-29 16:49:45 +0100231 while(from_stack > to_stack) {
232 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000233 }
Mark Shannon57697242020-04-29 16:49:45 +0100234 return from_stack == to_stack;
235}
236
237static const char *
238explain_incompatible_block_stack(int64_t to_stack)
239{
240 Kind target_kind = top_block(to_stack);
241 switch(target_kind) {
242 case Except:
243 return "can't jump into an 'except' block as there's no exception";
244 case Try:
245 return "can't jump into the body of a try statement";
246 case With:
247 return "can't jump into the body of a with statement";
248 case Loop:
249 return "can't jump into the body of a for loop";
250 default:
251 Py_UNREACHABLE();
252 }
253}
254
255static int *
256marklines(PyCodeObject *code, int len)
257{
Mark Shannon877df852020-11-12 09:43:29 +0000258 PyCodeAddressRange bounds;
259 _PyCode_InitAddressRange(code, &bounds);
260 assert (bounds.ar_end == 0);
261
Mark Shannon57697242020-04-29 16:49:45 +0100262 int *linestarts = PyMem_New(int, len);
263 if (linestarts == NULL) {
264 return NULL;
265 }
Mark Shannon877df852020-11-12 09:43:29 +0000266 for (int i = 0; i < len; i++) {
267 linestarts[i] = -1;
Mark Shannon57697242020-04-29 16:49:45 +0100268 }
Mark Shannon877df852020-11-12 09:43:29 +0000269
270 while (PyLineTable_NextAddressRange(&bounds)) {
271 assert(bounds.ar_start/2 < len);
272 linestarts[bounds.ar_start/2] = bounds.ar_line;
Mark Shannon57697242020-04-29 16:49:45 +0100273 }
Mark Shannon57697242020-04-29 16:49:45 +0100274 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000275}
276
277static int
Mark Shannon57697242020-04-29 16:49:45 +0100278first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000279{
280 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100281 for (int i = 0; i < len; i++) {
282 if (lines[i] < result && lines[i] >= line) {
283 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000284 }
Mark Shannonfee55262019-11-21 09:11:43 +0000285 }
286 if (result == INT_MAX) {
287 return -1;
288 }
289 return result;
290}
291
Mark Shannonfee55262019-11-21 09:11:43 +0000292static void
293frame_stack_pop(PyFrameObject *f)
294{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100295 assert(f->f_stackdepth >= 0);
296 f->f_stackdepth--;
297 PyObject *v = f->f_valuestack[f->f_stackdepth];
Mark Shannonfee55262019-11-21 09:11:43 +0000298 Py_DECREF(v);
299}
300
301static void
302frame_block_unwind(PyFrameObject *f)
303{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100304 assert(f->f_stackdepth >= 0);
Mark Shannonfee55262019-11-21 09:11:43 +0000305 assert(f->f_iblock > 0);
306 f->f_iblock--;
307 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Mark Shannoncb9879b2020-07-17 11:44:23 +0100308 intptr_t delta = f->f_stackdepth - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000309 while (delta > 0) {
310 frame_stack_pop(f);
311 delta--;
312 }
313}
314
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200315
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000316/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000318 * lines are OK to jump to because they don't make any assumptions about the
319 * state of the stack (obvious because you could remove the line and the code
320 * would still work without any stack errors), but there are some constructs
321 * that limit jumping:
322 *
323 * o Lines with an 'except' statement on them can't be jumped to, because
324 * they expect an exception to be on the top of the stack.
325 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000326 * we cannot be sure which state the interpreter was in or would be in
327 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200328 * o 'try', 'with' and 'async with' blocks can't be jumped into because
329 * the blockstack needs to be set up before their code runs.
330 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000331 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100332 * o Jumps cannot be made from within a trace function invoked with a
333 * 'return' or 'exception' event since the eval loop has been exited at
334 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000335 */
336static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200337frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000338{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700339 if (p_new_lineno == NULL) {
340 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
341 return -1;
342 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 /* f_lineno must be an integer. */
344 if (!PyLong_CheckExact(p_new_lineno)) {
345 PyErr_SetString(PyExc_ValueError,
346 "lineno must be an integer");
347 return -1;
348 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000349
Mark Shannoncb9879b2020-07-17 11:44:23 +0100350 /*
351 * This code preserves the historical restrictions on
352 * setting the line number of a frame.
353 * Jumps are forbidden on a 'return' trace event (except after a yield).
354 * Jumps from 'call' trace events are also forbidden.
355 * In addition, jumps are forbidden when not tracing,
356 * as this is a debugging feature.
357 */
358 switch(f->f_state) {
359 case FRAME_CREATED:
360 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100361 "can't jump from the 'call' trace event of a new frame");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100362 return -1;
363 case FRAME_RETURNED:
364 case FRAME_UNWINDING:
365 case FRAME_RAISED:
366 case FRAME_CLEARED:
367 PyErr_SetString(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100368 "can only jump from a 'line' trace event");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100369 return -1;
370 case FRAME_EXECUTING:
371 case FRAME_SUSPENDED:
372 /* You can only do this from within a trace function, not via
373 * _getframe or similar hackery. */
374 if (!f->f_trace) {
375 PyErr_Format(PyExc_ValueError,
376 "f_lineno can only be set by a trace function");
377 return -1;
378 }
379 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000381
Mark Shannonfee55262019-11-21 09:11:43 +0000382 int new_lineno;
383
Mark Shannon57697242020-04-29 16:49:45 +0100384 /* Fail if the line falls outside the code block and
385 select first line with actual code. */
386 int overflow;
387 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
388 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000389#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100390 || l_new_lineno > INT_MAX
391 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000392#endif
Mark Shannon57697242020-04-29 16:49:45 +0100393 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000394 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100395 "lineno out of range");
396 return -1;
397 }
398 new_lineno = (int)l_new_lineno;
399
400 if (new_lineno < f->f_code->co_firstlineno) {
401 PyErr_Format(PyExc_ValueError,
402 "line %d comes before the current code block",
403 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 return -1;
405 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000406
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000407 /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
408 * should never overflow. */
409 int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT));
Mark Shannon57697242020-04-29 16:49:45 +0100410 int *lines = marklines(f->f_code, len);
411 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 return -1;
413 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000414
Mark Shannon57697242020-04-29 16:49:45 +0100415 new_lineno = first_line_not_before(lines, len, new_lineno);
416 if (new_lineno < 0) {
417 PyErr_Format(PyExc_ValueError,
418 "line %d comes after the current code block",
419 (int)l_new_lineno);
420 PyMem_Free(lines);
421 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000422 }
423
Mark Shannon57697242020-04-29 16:49:45 +0100424 int64_t *blocks = markblocks(f->f_code, len);
425 if (blocks == NULL) {
426 PyMem_Free(lines);
427 return -1;
428 }
429
430 int64_t target_block_stack = -1;
431 int64_t best_block_stack = -1;
432 int best_addr = -1;
Mark Shannonfcb55c02021-04-01 16:00:31 +0100433 int64_t start_block_stack = blocks[f->f_lasti];
Mark Shannon57697242020-04-29 16:49:45 +0100434 const char *msg = "cannot find bytecode for specified line";
435 for (int i = 0; i < len; i++) {
436 if (lines[i] == new_lineno) {
437 target_block_stack = blocks[i];
438 if (compatible_block_stack(start_block_stack, target_block_stack)) {
439 msg = NULL;
440 if (target_block_stack > best_block_stack) {
441 best_block_stack = target_block_stack;
Mark Shannonfcb55c02021-04-01 16:00:31 +0100442 best_addr = i;
Mark Shannon57697242020-04-29 16:49:45 +0100443 }
444 }
445 else if (msg) {
446 if (target_block_stack >= 0) {
447 msg = explain_incompatible_block_stack(target_block_stack);
448 }
449 else {
450 msg = "code may be unreachable.";
451 }
452 }
Mark Shannonfee55262019-11-21 09:11:43 +0000453 }
454 }
Mark Shannon57697242020-04-29 16:49:45 +0100455 PyMem_Free(blocks);
456 PyMem_Free(lines);
457 if (msg != NULL) {
458 PyErr_SetString(PyExc_ValueError, msg);
459 return -1;
460 }
Mark Shannonfee55262019-11-21 09:11:43 +0000461
462 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100463 while (start_block_stack > best_block_stack) {
464 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000465 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100466 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000467 frame_stack_pop(f);
468 break;
Mark Shannon57697242020-04-29 16:49:45 +0100469 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000470 frame_block_unwind(f);
471 break;
Mark Shannon57697242020-04-29 16:49:45 +0100472 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000473 frame_block_unwind(f);
474 // Pop the exit function
475 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 break;
Mark Shannon57697242020-04-29 16:49:45 +0100477 case Except:
478 PyErr_SetString(PyExc_ValueError,
479 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000480 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 }
Mark Shannon57697242020-04-29 16:49:45 +0100482 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 }
Mark Shannonfee55262019-11-21 09:11:43 +0000484
Mark Shannonee9f98d2021-01-05 12:04:10 +0000485 /* Finally set the new f_lasti and return OK. */
486 f->f_lineno = 0;
Mark Shannon57697242020-04-29 16:49:45 +0100487 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000489}
490
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000491static PyObject *
492frame_gettrace(PyFrameObject *f, void *closure)
493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (trace == NULL)
497 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000502}
503
504static int
505frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
506{
Mark Shannonee9f98d2021-01-05 12:04:10 +0000507 if (v == Py_None) {
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300508 v = NULL;
Mark Shannonee9f98d2021-01-05 12:04:10 +0000509 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300511 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000514}
515
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000516
Guido van Rossum32d34c82001-09-20 21:45:26 +0000517static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 {"f_locals", (getter)frame_getlocals, NULL, NULL},
519 {"f_lineno", (getter)frame_getlineno,
520 (setter)frame_setlineno, NULL},
521 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
Mark Shannonfcb55c02021-04-01 16:00:31 +0100522 {"f_lasti", (getter)frame_getlasti, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000524};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000525
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000526/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000527 In an attempt to improve the speed of function calls, we:
528
529 1. Hold a single "zombie" frame on each code object. This retains
530 the allocated and initialised frame object from an invocation of
531 the code object. The zombie is reanimated the next time we need a
532 frame object for that code object. Doing this saves the malloc/
533 realloc required when using a free_list frame that isn't the
534 correct size. It also saves some field initialisation.
535
536 In zombie mode, no field of PyFrameObject holds a reference, but
537 the following fields are still valid:
538
539 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540
Mark Shannonae3087c2017-10-22 22:41:51 +0100541 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542
543 * f_localsplus does not require re-allocation and
544 the local variables in f_localsplus are NULL.
545
546 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000547 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548 a stack frame is on the free list, only the following members have
549 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 ob_type == &Frametype
551 f_back next item on free list, or NULL
552 f_stacksize size of value stack
553 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000554 Note that the value and block stacks are preserved -- this can save
555 another malloc() call or two (and two free() calls as well!).
556 Also note that, unlike for integers, each frame object is a
557 malloc'ed object in its own right -- it is only the actual calls to
558 malloc() that we are trying to save here, not the administration.
559 After all, while a typical program may make millions of calls, a
560 call depth of more than 20 or 30 is probably already exceptional
561 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000562
Christian Heimes2202f872008-02-06 14:31:34 +0000563 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000564 free_list. Else programs creating lots of cyclic trash involving
565 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000566*/
Christian Heimes2202f872008-02-06 14:31:34 +0000567/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000569
Victor Stinnerc6944e72016-11-11 02:13:35 +0100570static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000571frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000572{
Victor Stinner3744ed22020-06-05 01:39:24 +0200573 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900574 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200575 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200578 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200579 PyObject **valuestack = f->f_valuestack;
580 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200581 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200582 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200583
584 /* Free stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100585 for (int i = 0; i < f->f_stackdepth; i++) {
586 Py_XDECREF(f->f_valuestack[i]);
Antoine Pitrou93963562013-05-14 20:37:52 +0200587 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100588 f->f_stackdepth = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 Py_XDECREF(f->f_back);
591 Py_DECREF(f->f_builtins);
592 Py_DECREF(f->f_globals);
593 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200594 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000595
Victor Stinner3744ed22020-06-05 01:39:24 +0200596 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200597 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200599 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200600 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200601 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200602#ifdef Py_DEBUG
603 // frame_dealloc() must not be called after _PyFrame_Fini()
604 assert(state->numfree != -1);
605#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200606 if (state->numfree < PyFrame_MAXFREELIST) {
607 ++state->numfree;
608 f->f_back = state->free_list;
609 state->free_list = f;
610 }
611 else {
612 PyObject_GC_Del(f);
613 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200614 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 Py_DECREF(co);
617 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000618}
619
Victor Stinner6d86a232020-04-29 00:56:58 +0200620static inline Py_ssize_t
621frame_nslots(PyFrameObject *frame)
622{
623 PyCodeObject *code = frame->f_code;
624 return (code->co_nlocals
625 + PyTuple_GET_SIZE(code->co_cellvars)
626 + PyTuple_GET_SIZE(code->co_freevars));
627}
628
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000629static int
630frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 Py_VISIT(f->f_back);
633 Py_VISIT(f->f_code);
634 Py_VISIT(f->f_builtins);
635 Py_VISIT(f->f_globals);
636 Py_VISIT(f->f_locals);
637 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200640 PyObject **fastlocals = f->f_localsplus;
641 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200643 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100646 for (int i = 0; i < f->f_stackdepth; i++) {
647 Py_VISIT(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
649 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000650}
651
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200652static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200653frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000654{
Antoine Pitrou93963562013-05-14 20:37:52 +0200655 /* Before anything else, make sure that this frame is clearly marked
656 * as being defunct! Else, e.g., a generator reachable from this
657 * frame may also point to this frame, believe itself to still be
658 * active, and try cleaning up this frame again.
659 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100660 f->f_state = FRAME_CLEARED;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200665 PyObject **fastlocals = f->f_localsplus;
666 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200668 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100671 for (int i = 0; i < f->f_stackdepth; i++) {
672 Py_CLEAR(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100674 f->f_stackdepth = 0;
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200675 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000676}
677
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000678static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530679frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200680{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100681 if (_PyFrame_IsExecuting(f)) {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200682 PyErr_SetString(PyExc_RuntimeError,
683 "cannot clear an executing frame");
684 return NULL;
685 }
686 if (f->f_gen) {
687 _PyGen_Finalize(f->f_gen);
688 assert(f->f_gen == NULL);
689 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200690 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200691 Py_RETURN_NONE;
692}
693
694PyDoc_STRVAR(clear__doc__,
695"F.clear(): clear most references held by the frame");
696
697static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530698frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000701
Victor Stinner6d86a232020-04-29 00:56:58 +0200702 PyCodeObject *code = f->f_code;
703 ncells = PyTuple_GET_SIZE(code->co_cellvars);
704 nfrees = PyTuple_GET_SIZE(code->co_freevars);
705 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 /* subtract one as it is already included in PyFrameObject */
707 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000710}
711
712PyDoc_STRVAR(sizeof__doc__,
713"F.__sizeof__() -> size of F in memory, in bytes");
714
Antoine Pitrou14709142017-12-31 22:35:22 +0100715static PyObject *
716frame_repr(PyFrameObject *f)
717{
718 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200719 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100720 return PyUnicode_FromFormat(
721 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200722 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100723}
724
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000725static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200726 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
727 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
729 sizeof__doc__},
730 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000731};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000732
Guido van Rossum18752471997-04-29 14:49:28 +0000733PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyVarObject_HEAD_INIT(&PyType_Type, 0)
735 "frame",
736 sizeof(PyFrameObject),
737 sizeof(PyObject *),
738 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200739 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 0, /* tp_getattr */
741 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200742 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100743 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 0, /* tp_as_number */
745 0, /* tp_as_sequence */
746 0, /* tp_as_mapping */
747 0, /* tp_hash */
748 0, /* tp_call */
749 0, /* tp_str */
750 PyObject_GenericGetAttr, /* tp_getattro */
751 PyObject_GenericSetAttr, /* tp_setattro */
752 0, /* tp_as_buffer */
753 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
754 0, /* tp_doc */
755 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200756 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 0, /* tp_richcompare */
758 0, /* tp_weaklistoffset */
759 0, /* tp_iter */
760 0, /* tp_iternext */
761 frame_methods, /* tp_methods */
762 frame_memberlist, /* tp_members */
763 frame_getsetlist, /* tp_getset */
764 0, /* tp_base */
765 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000766};
767
Victor Stinner07e9e382013-11-07 22:22:39 +0100768_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000769
Victor Stinnerb4b53862020-05-05 19:55:29 +0200770static inline PyFrameObject*
771frame_alloc(PyCodeObject *code)
772{
Victor Stinner44085a32021-02-18 19:20:16 +0100773 PyFrameObject *f = code->co_zombieframe;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200774 if (f != NULL) {
775 code->co_zombieframe = NULL;
776 _Py_NewReference((PyObject *)f);
777 assert(f->f_code == code);
778 return f;
779 }
780
781 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
782 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
783 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200784 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200785 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200786 {
787 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
788 if (f == NULL) {
789 return NULL;
790 }
791 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200792 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200793#ifdef Py_DEBUG
794 // frame_alloc() must not be called after _PyFrame_Fini()
795 assert(state->numfree != -1);
796#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200797 assert(state->numfree > 0);
798 --state->numfree;
799 f = state->free_list;
800 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200801 if (Py_SIZE(f) < extras) {
802 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
803 if (new_f == NULL) {
804 PyObject_GC_Del(f);
805 return NULL;
806 }
807 f = new_f;
808 }
809 _Py_NewReference((PyObject *)f);
810 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200811
Victor Stinnerb4b53862020-05-05 19:55:29 +0200812 extras = code->co_nlocals + ncells + nfrees;
813 f->f_valuestack = f->f_localsplus + extras;
Victor Stinner44085a32021-02-18 19:20:16 +0100814 for (Py_ssize_t i=0; i < extras; i++) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200815 f->f_localsplus[i] = NULL;
816 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200817 return f;
818}
819
820
Victor Stinnerc6944e72016-11-11 02:13:35 +0100821PyFrameObject* _Py_HOT_FUNCTION
Mark Shannon0332e562021-02-01 10:42:03 +0000822_PyFrame_New_NoTrack(PyThreadState *tstate, PyFrameConstructor *con, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000823{
Victor Stinner44085a32021-02-18 19:20:16 +0100824 assert(con != NULL);
825 assert(con->fc_globals != NULL);
826 assert(con->fc_builtins != NULL);
827 assert(con->fc_code != NULL);
828 assert(locals == NULL || PyMapping_Check(locals));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829
Mark Shannon0332e562021-02-01 10:42:03 +0000830 PyFrameObject *f = frame_alloc((PyCodeObject *)con->fc_code);
Victor Stinnerb4b53862020-05-05 19:55:29 +0200831 if (f == NULL) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200832 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200834
Victor Stinner44085a32021-02-18 19:20:16 +0100835 f->f_back = (PyFrameObject*)Py_XNewRef(tstate->frame);
836 f->f_code = (PyCodeObject *)Py_NewRef(con->fc_code);
837 f->f_builtins = Py_NewRef(con->fc_builtins);
838 f->f_globals = Py_NewRef(con->fc_globals);
839 f->f_locals = Py_XNewRef(locals);
840 // f_valuestack initialized by frame_alloc()
841 f->f_trace = NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100842 f->f_stackdepth = 0;
Victor Stinner44085a32021-02-18 19:20:16 +0100843 f->f_trace_lines = 1;
844 f->f_trace_opcodes = 0;
845 f->f_gen = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 f->f_lasti = -1;
Mark Shannon877df852020-11-12 09:43:29 +0000847 f->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 f->f_iblock = 0;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100849 f->f_state = FRAME_CREATED;
Victor Stinner44085a32021-02-18 19:20:16 +0100850 // f_blockstack and f_localsplus initialized by frame_alloc()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000852}
853
Mark Shannon0332e562021-02-01 10:42:03 +0000854/* Legacy API */
INADA Naoki5a625d02016-12-24 20:19:08 +0900855PyFrameObject*
856PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
857 PyObject *globals, PyObject *locals)
858{
Victor Stinnerfc980e02021-03-18 14:51:24 +0100859 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Victor Stinner44085a32021-02-18 19:20:16 +0100860 if (builtins == NULL) {
861 return NULL;
862 }
Mark Shannon0332e562021-02-01 10:42:03 +0000863 PyFrameConstructor desc = {
864 .fc_globals = globals,
865 .fc_builtins = builtins,
866 .fc_name = code->co_name,
867 .fc_qualname = code->co_name,
868 .fc_code = (PyObject *)code,
869 .fc_defaults = NULL,
870 .fc_kwdefaults = NULL,
871 .fc_closure = NULL
872 };
873 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, &desc, locals);
Victor Stinner44085a32021-02-18 19:20:16 +0100874 if (f) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900875 _PyObject_GC_TRACK(f);
Victor Stinner44085a32021-02-18 19:20:16 +0100876 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900877 return f;
878}
879
880
Guido van Rossum3f5da241990-12-20 15:06:42 +0000881/* Block management */
882
883void
Fred Drake1b190b42000-07-09 05:40:56 +0000884PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100887 if (f->f_iblock >= CO_MAXBLOCKS) {
888 Py_FatalError("block stack overflow");
889 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 b = &f->f_blockstack[f->f_iblock++];
891 b->b_type = type;
892 b->b_level = level;
893 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000894}
895
Guido van Rossum18752471997-04-29 14:49:28 +0000896PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000897PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100900 if (f->f_iblock <= 0) {
901 Py_FatalError("block stack underflow");
902 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 b = &f->f_blockstack[--f->f_iblock];
904 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000905}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000906
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908
909 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000910 values is an array of PyObject*. At index i, map[i] is the name of
911 the variable with value values[i]. The function copies the first
912 nmap variable from map/values into dict. If values[i] is NULL,
913 the variable is deleted from dict.
914
915 If deref is true, then the values being copied are cell variables
916 and the value is extracted from the cell variable before being put
917 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000918 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000919
Victor Stinner41bb43a2013-10-29 01:19:37 +0100920static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000921map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 Py_ssize_t j;
925 assert(PyTuple_Check(map));
926 assert(PyDict_Check(dict));
927 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800928 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyObject *key = PyTuple_GET_ITEM(map, j);
930 PyObject *value = values[j];
931 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400932 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 assert(PyCell_Check(value));
934 value = PyCell_GET(value);
935 }
936 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100937 if (PyObject_DelItem(dict, key) != 0) {
938 if (PyErr_ExceptionMatches(PyExc_KeyError))
939 PyErr_Clear();
940 else
941 return -1;
942 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 }
944 else {
945 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100946 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
948 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100949 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000950}
951
Guido van Rossumd8faa362007-04-27 19:54:29 +0000952/* Copy values from the "locals" dict into the fast locals.
953
954 dict is an input argument containing string keys representing
955 variables names and arbitrary PyObject* as values.
956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000958 values is an array of PyObject*. At index i, map[i] is the name of
959 the variable with value values[i]. The function copies the first
960 nmap variable from map/values into dict. If values[i] is NULL,
961 the variable is deleted from dict.
962
963 If deref is true, then the values being copied are cell variables
964 and the value is extracted from the cell variable before being put
965 in dict. If clear is true, then variables in map but not in dict
966 are set to NULL in map; if clear is false, variables missing in
967 dict are ignored.
968
969 Exceptions raised while modifying the dict are silently ignored,
970 because there is no good way to report them.
971*/
972
Guido van Rossum6b356e72001-04-14 17:55:41 +0000973static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000974dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 Py_ssize_t j;
978 assert(PyTuple_Check(map));
979 assert(PyDict_Check(dict));
980 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800981 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *key = PyTuple_GET_ITEM(map, j);
983 PyObject *value = PyObject_GetItem(dict, key);
984 assert(PyUnicode_Check(key));
985 /* We only care about NULLs if clear is true. */
986 if (value == NULL) {
987 PyErr_Clear();
988 if (!clear)
989 continue;
990 }
991 if (deref) {
992 assert(PyCell_Check(values[j]));
993 if (PyCell_GET(values[j]) != value) {
994 if (PyCell_Set(values[j], value) < 0)
995 PyErr_Clear();
996 }
997 } else if (values[j] != value) {
998 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300999 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 }
1001 Py_XDECREF(value);
1002 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001003}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001004
Victor Stinner41bb43a2013-10-29 01:19:37 +01001005int
1006PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* Merge fast locals into f->f_locals */
1009 PyObject *locals, *map;
1010 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyCodeObject *co;
1012 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001013 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001014
1015 if (f == NULL) {
1016 PyErr_BadInternalCall();
1017 return -1;
1018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 locals = f->f_locals;
1020 if (locals == NULL) {
1021 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001022 if (locals == NULL)
1023 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 }
1025 co = f->f_code;
1026 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001027 if (!PyTuple_Check(map)) {
1028 PyErr_Format(PyExc_SystemError,
1029 "co_varnames must be a tuple, not %s",
1030 Py_TYPE(map)->tp_name);
1031 return -1;
1032 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 fast = f->f_localsplus;
1034 j = PyTuple_GET_SIZE(map);
1035 if (j > co->co_nlocals)
1036 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001037 if (co->co_nlocals) {
1038 if (map_to_dict(map, j, locals, fast, 0) < 0)
1039 return -1;
1040 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1042 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1043 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001044 if (map_to_dict(co->co_cellvars, ncells,
1045 locals, fast + co->co_nlocals, 1))
1046 return -1;
1047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* If the namespace is unoptimized, then one of the
1049 following cases applies:
1050 1. It does not contain free variables, because it
1051 uses import * or is a top-level namespace.
1052 2. It is a class namespace.
1053 We don't want to accidentally copy free variables
1054 into the locals dict used by the class.
1055 */
1056 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001057 if (map_to_dict(co->co_freevars, nfreevars,
1058 locals, fast + co->co_nlocals + ncells, 1) < 0)
1059 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 }
1061 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001062 return 0;
1063}
1064
1065void
1066PyFrame_FastToLocals(PyFrameObject *f)
1067{
1068 int res;
1069
1070 assert(!PyErr_Occurred());
1071
1072 res = PyFrame_FastToLocalsWithError(f);
1073 if (res < 0)
1074 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001075}
1076
1077void
Fred Drake1b190b42000-07-09 05:40:56 +00001078PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* Merge f->f_locals into fast locals */
1081 PyObject *locals, *map;
1082 PyObject **fast;
1083 PyObject *error_type, *error_value, *error_traceback;
1084 PyCodeObject *co;
1085 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001086 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (f == NULL)
1088 return;
1089 locals = f->f_locals;
1090 co = f->f_code;
1091 map = co->co_varnames;
1092 if (locals == NULL)
1093 return;
1094 if (!PyTuple_Check(map))
1095 return;
1096 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1097 fast = f->f_localsplus;
1098 j = PyTuple_GET_SIZE(map);
1099 if (j > co->co_nlocals)
1100 j = co->co_nlocals;
1101 if (co->co_nlocals)
1102 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1103 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1104 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1105 if (ncells || nfreevars) {
1106 dict_to_map(co->co_cellvars, ncells,
1107 locals, fast + co->co_nlocals, 1, clear);
1108 /* Same test as in PyFrame_FastToLocals() above. */
1109 if (co->co_flags & CO_OPTIMIZED) {
1110 dict_to_map(co->co_freevars, nfreevars,
1111 locals, fast + co->co_nlocals + ncells, 1,
1112 clear);
1113 }
1114 }
1115 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001116}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001117
1118/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001119void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001120_PyFrame_ClearFreeList(PyInterpreterState *interp)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001121{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001122 struct _Py_frame_state *state = &interp->frame;
Victor Stinner3744ed22020-06-05 01:39:24 +02001123 while (state->free_list != NULL) {
1124 PyFrameObject *f = state->free_list;
1125 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001127 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001129 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001130}
1131
1132void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001133_PyFrame_Fini(PyInterpreterState *interp)
Christian Heimesa156e092008-02-16 07:38:31 +00001134{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001135 _PyFrame_ClearFreeList(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001136#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001137 struct _Py_frame_state *state = &interp->frame;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001138 state->numfree = -1;
1139#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001140}
David Malcolm49526f42012-06-22 14:55:41 -04001141
1142/* Print summary info about the state of the optimized allocator */
1143void
1144_PyFrame_DebugMallocStats(FILE *out)
1145{
Victor Stinner522691c2020-06-23 16:40:40 +02001146 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001147 _PyDebugAllocatorStats(out,
1148 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001149 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001150}
1151
Victor Stinnera42ca742020-04-28 19:01:31 +02001152
1153PyCodeObject *
1154PyFrame_GetCode(PyFrameObject *frame)
1155{
1156 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001157 PyCodeObject *code = frame->f_code;
1158 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001159 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001160 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001161}
Victor Stinner70364772020-04-29 03:28:46 +02001162
1163
1164PyFrameObject*
1165PyFrame_GetBack(PyFrameObject *frame)
1166{
1167 assert(frame != NULL);
1168 PyFrameObject *back = frame->f_back;
1169 Py_XINCREF(back);
1170 return back;
1171}
Mark Shannond6c33fb2021-01-29 13:24:55 +00001172
Victor Stinner44085a32021-02-18 19:20:16 +01001173PyObject*
Victor Stinner46496f92021-02-20 15:17:18 +01001174_PyEval_BuiltinsFromGlobals(PyThreadState *tstate, PyObject *globals)
Victor Stinner44085a32021-02-18 19:20:16 +01001175{
Mark Shannond6c33fb2021-01-29 13:24:55 +00001176 PyObject *builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
1177 if (builtins) {
1178 if (PyModule_Check(builtins)) {
1179 builtins = PyModule_GetDict(builtins);
1180 assert(builtins != NULL);
1181 }
Victor Stinner46496f92021-02-20 15:17:18 +01001182 return builtins;
Mark Shannond6c33fb2021-01-29 13:24:55 +00001183 }
Victor Stinner44085a32021-02-18 19:20:16 +01001184 if (PyErr_Occurred()) {
1185 return NULL;
1186 }
1187
Victor Stinner46496f92021-02-20 15:17:18 +01001188 return _PyEval_GetBuiltins(tstate);
Mark Shannond6c33fb2021-01-29 13:24:55 +00001189}