blob: b0487c2b68811bab8d3c503460bf47beafc45a9a [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},
16 {"f_code", T_OBJECT, OFF(f_code), READONLY},
17 {"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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000057}
58
Mark Shannonfcb55c02021-04-01 16:00:31 +010059static PyObject *
60frame_getlasti(PyFrameObject *f, void *closure)
61{
62 if (f->f_lasti < 0) {
63 return PyLong_FromLong(-1);
64 }
65 return PyLong_FromLong(f->f_lasti*2);
66}
67
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020068
69/* Given the index of the effective opcode,
70 scan back to construct the oparg with EXTENDED_ARG */
71static unsigned int
72get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
73{
74 _Py_CODEUNIT word;
75 unsigned int oparg = _Py_OPARG(codestr[i]);
76 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
77 oparg |= _Py_OPARG(word) << 8;
78 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
79 oparg |= _Py_OPARG(word) << 16;
80 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
81 oparg |= _Py_OPARG(word) << 24;
82 }
83 }
84 }
85 return oparg;
86}
87
Mark Shannon57697242020-04-29 16:49:45 +010088typedef enum kind {
89 With = 1,
90 Loop = 2,
91 Try = 3,
92 Except = 4,
93} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +000094
Mark Shannon57697242020-04-29 16:49:45 +010095#define BITS_PER_BLOCK 3
96
97static inline int64_t
98push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +000099{
Mark Shannon57697242020-04-29 16:49:45 +0100100 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
101 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +0000102}
103
Mark Shannon57697242020-04-29 16:49:45 +0100104static inline int64_t
105pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000106{
Mark Shannon57697242020-04-29 16:49:45 +0100107 assert(stack > 0);
108 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +0000109}
110
Mark Shannon57697242020-04-29 16:49:45 +0100111static inline Kind
112top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000113{
Mark Shannon57697242020-04-29 16:49:45 +0100114 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +0000115}
116
Mark Shannon57697242020-04-29 16:49:45 +0100117static int64_t *
118markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000119{
Mark Shannon57697242020-04-29 16:49:45 +0100120 const _Py_CODEUNIT *code =
121 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
122 int64_t *blocks = PyMem_New(int64_t, len+1);
123 int i, j, opcode;
124
125 if (blocks == NULL) {
126 PyErr_NoMemory();
127 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000128 }
Mark Shannon57697242020-04-29 16:49:45 +0100129 memset(blocks, -1, (len+1)*sizeof(int64_t));
130 blocks[0] = 0;
131 int todo = 1;
132 while (todo) {
133 todo = 0;
134 for (i = 0; i < len; i++) {
135 int64_t block_stack = blocks[i];
136 int64_t except_stack;
137 if (block_stack == -1) {
138 continue;
139 }
140 opcode = _Py_OPCODE(code[i]);
141 switch (opcode) {
142 case JUMP_IF_FALSE_OR_POP:
143 case JUMP_IF_TRUE_OR_POP:
144 case POP_JUMP_IF_FALSE:
145 case POP_JUMP_IF_TRUE:
146 case JUMP_IF_NOT_EXC_MATCH:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100147 j = get_arg(code, i);
Mark Shannon57697242020-04-29 16:49:45 +0100148 assert(j < len);
149 if (blocks[j] == -1 && j < i) {
150 todo = 1;
151 }
152 assert(blocks[j] == -1 || blocks[j] == block_stack);
153 blocks[j] = block_stack;
154 blocks[i+1] = block_stack;
155 break;
156 case JUMP_ABSOLUTE:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100157 j = get_arg(code, i);
Mark Shannon57697242020-04-29 16:49:45 +0100158 assert(j < len);
159 if (blocks[j] == -1 && j < i) {
160 todo = 1;
161 }
162 assert(blocks[j] == -1 || blocks[j] == block_stack);
163 blocks[j] = block_stack;
164 break;
165 case SETUP_FINALLY:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100166 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100167 assert(j < len);
168 except_stack = push_block(block_stack, Except);
169 assert(blocks[j] == -1 || blocks[j] == except_stack);
170 blocks[j] = except_stack;
171 block_stack = push_block(block_stack, Try);
172 blocks[i+1] = block_stack;
173 break;
174 case SETUP_WITH:
175 case SETUP_ASYNC_WITH:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100176 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100177 assert(j < len);
178 except_stack = push_block(block_stack, Except);
179 assert(blocks[j] == -1 || blocks[j] == except_stack);
180 blocks[j] = except_stack;
181 block_stack = push_block(block_stack, With);
182 blocks[i+1] = block_stack;
183 break;
184 case JUMP_FORWARD:
Mark Shannonfcb55c02021-04-01 16:00:31 +0100185 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100186 assert(j < len);
187 assert(blocks[j] == -1 || blocks[j] == block_stack);
188 blocks[j] = block_stack;
189 break;
190 case GET_ITER:
191 case GET_AITER:
192 block_stack = push_block(block_stack, Loop);
193 blocks[i+1] = block_stack;
194 break;
195 case FOR_ITER:
196 blocks[i+1] = block_stack;
197 block_stack = pop_block(block_stack);
Mark Shannonfcb55c02021-04-01 16:00:31 +0100198 j = get_arg(code, i) + i + 1;
Mark Shannon57697242020-04-29 16:49:45 +0100199 assert(j < len);
200 assert(blocks[j] == -1 || blocks[j] == block_stack);
201 blocks[j] = block_stack;
202 break;
203 case POP_BLOCK:
204 case POP_EXCEPT:
205 block_stack = pop_block(block_stack);
206 blocks[i+1] = block_stack;
207 break;
208 case END_ASYNC_FOR:
209 block_stack = pop_block(pop_block(block_stack));
210 blocks[i+1] = block_stack;
211 break;
212 case RETURN_VALUE:
213 case RAISE_VARARGS:
214 case RERAISE:
215 /* End of block */
216 break;
217 default:
218 blocks[i+1] = block_stack;
219
220 }
221 }
222 }
223 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000224}
225
226static int
Mark Shannon57697242020-04-29 16:49:45 +0100227compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000228{
Mark Shannon57697242020-04-29 16:49:45 +0100229 if (to_stack < 0) {
230 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000231 }
Mark Shannon57697242020-04-29 16:49:45 +0100232 while(from_stack > to_stack) {
233 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000234 }
Mark Shannon57697242020-04-29 16:49:45 +0100235 return from_stack == to_stack;
236}
237
238static const char *
239explain_incompatible_block_stack(int64_t to_stack)
240{
241 Kind target_kind = top_block(to_stack);
242 switch(target_kind) {
243 case Except:
244 return "can't jump into an 'except' block as there's no exception";
245 case Try:
246 return "can't jump into the body of a try statement";
247 case With:
248 return "can't jump into the body of a with statement";
249 case Loop:
250 return "can't jump into the body of a for loop";
251 default:
252 Py_UNREACHABLE();
253 }
254}
255
256static int *
257marklines(PyCodeObject *code, int len)
258{
Mark Shannon877df852020-11-12 09:43:29 +0000259 PyCodeAddressRange bounds;
260 _PyCode_InitAddressRange(code, &bounds);
261 assert (bounds.ar_end == 0);
262
Mark Shannon57697242020-04-29 16:49:45 +0100263 int *linestarts = PyMem_New(int, len);
264 if (linestarts == NULL) {
265 return NULL;
266 }
Mark Shannon877df852020-11-12 09:43:29 +0000267 for (int i = 0; i < len; i++) {
268 linestarts[i] = -1;
Mark Shannon57697242020-04-29 16:49:45 +0100269 }
Mark Shannon877df852020-11-12 09:43:29 +0000270
271 while (PyLineTable_NextAddressRange(&bounds)) {
272 assert(bounds.ar_start/2 < len);
273 linestarts[bounds.ar_start/2] = bounds.ar_line;
Mark Shannon57697242020-04-29 16:49:45 +0100274 }
Mark Shannon57697242020-04-29 16:49:45 +0100275 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000276}
277
278static int
Mark Shannon57697242020-04-29 16:49:45 +0100279first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000280{
281 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100282 for (int i = 0; i < len; i++) {
283 if (lines[i] < result && lines[i] >= line) {
284 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000285 }
Mark Shannonfee55262019-11-21 09:11:43 +0000286 }
287 if (result == INT_MAX) {
288 return -1;
289 }
290 return result;
291}
292
Mark Shannonfee55262019-11-21 09:11:43 +0000293static void
294frame_stack_pop(PyFrameObject *f)
295{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100296 assert(f->f_stackdepth >= 0);
297 f->f_stackdepth--;
298 PyObject *v = f->f_valuestack[f->f_stackdepth];
Mark Shannonfee55262019-11-21 09:11:43 +0000299 Py_DECREF(v);
300}
301
302static void
303frame_block_unwind(PyFrameObject *f)
304{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100305 assert(f->f_stackdepth >= 0);
Mark Shannonfee55262019-11-21 09:11:43 +0000306 assert(f->f_iblock > 0);
307 f->f_iblock--;
308 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Mark Shannoncb9879b2020-07-17 11:44:23 +0100309 intptr_t delta = f->f_stackdepth - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000310 while (delta > 0) {
311 frame_stack_pop(f);
312 delta--;
313 }
314}
315
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200316
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000317/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000319 * lines are OK to jump to because they don't make any assumptions about the
320 * state of the stack (obvious because you could remove the line and the code
321 * would still work without any stack errors), but there are some constructs
322 * that limit jumping:
323 *
324 * o Lines with an 'except' statement on them can't be jumped to, because
325 * they expect an exception to be on the top of the stack.
326 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000327 * we cannot be sure which state the interpreter was in or would be in
328 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200329 * o 'try', 'with' and 'async with' blocks can't be jumped into because
330 * the blockstack needs to be set up before their code runs.
331 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000332 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100333 * o Jumps cannot be made from within a trace function invoked with a
334 * 'return' or 'exception' event since the eval loop has been exited at
335 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000336 */
337static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200338frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000339{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700340 if (p_new_lineno == NULL) {
341 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
342 return -1;
343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 /* f_lineno must be an integer. */
345 if (!PyLong_CheckExact(p_new_lineno)) {
346 PyErr_SetString(PyExc_ValueError,
347 "lineno must be an integer");
348 return -1;
349 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000350
Mark Shannoncb9879b2020-07-17 11:44:23 +0100351 /*
352 * This code preserves the historical restrictions on
353 * setting the line number of a frame.
354 * Jumps are forbidden on a 'return' trace event (except after a yield).
355 * Jumps from 'call' trace events are also forbidden.
356 * In addition, jumps are forbidden when not tracing,
357 * as this is a debugging feature.
358 */
359 switch(f->f_state) {
360 case FRAME_CREATED:
361 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100362 "can't jump from the 'call' trace event of a new frame");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100363 return -1;
364 case FRAME_RETURNED:
365 case FRAME_UNWINDING:
366 case FRAME_RAISED:
367 case FRAME_CLEARED:
368 PyErr_SetString(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100369 "can only jump from a 'line' trace event");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100370 return -1;
371 case FRAME_EXECUTING:
372 case FRAME_SUSPENDED:
373 /* You can only do this from within a trace function, not via
374 * _getframe or similar hackery. */
375 if (!f->f_trace) {
376 PyErr_Format(PyExc_ValueError,
377 "f_lineno can only be set by a trace function");
378 return -1;
379 }
380 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000382
Mark Shannonfee55262019-11-21 09:11:43 +0000383 int new_lineno;
384
Mark Shannon57697242020-04-29 16:49:45 +0100385 /* Fail if the line falls outside the code block and
386 select first line with actual code. */
387 int overflow;
388 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
389 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000390#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100391 || l_new_lineno > INT_MAX
392 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000393#endif
Mark Shannon57697242020-04-29 16:49:45 +0100394 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000395 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100396 "lineno out of range");
397 return -1;
398 }
399 new_lineno = (int)l_new_lineno;
400
401 if (new_lineno < f->f_code->co_firstlineno) {
402 PyErr_Format(PyExc_ValueError,
403 "line %d comes before the current code block",
404 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return -1;
406 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000407
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000408 /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
409 * should never overflow. */
410 int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT));
Mark Shannon57697242020-04-29 16:49:45 +0100411 int *lines = marklines(f->f_code, len);
412 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 return -1;
414 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000415
Mark Shannon57697242020-04-29 16:49:45 +0100416 new_lineno = first_line_not_before(lines, len, new_lineno);
417 if (new_lineno < 0) {
418 PyErr_Format(PyExc_ValueError,
419 "line %d comes after the current code block",
420 (int)l_new_lineno);
421 PyMem_Free(lines);
422 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000423 }
424
Mark Shannon57697242020-04-29 16:49:45 +0100425 int64_t *blocks = markblocks(f->f_code, len);
426 if (blocks == NULL) {
427 PyMem_Free(lines);
428 return -1;
429 }
430
431 int64_t target_block_stack = -1;
432 int64_t best_block_stack = -1;
433 int best_addr = -1;
Mark Shannonfcb55c02021-04-01 16:00:31 +0100434 int64_t start_block_stack = blocks[f->f_lasti];
Mark Shannon57697242020-04-29 16:49:45 +0100435 const char *msg = "cannot find bytecode for specified line";
436 for (int i = 0; i < len; i++) {
437 if (lines[i] == new_lineno) {
438 target_block_stack = blocks[i];
439 if (compatible_block_stack(start_block_stack, target_block_stack)) {
440 msg = NULL;
441 if (target_block_stack > best_block_stack) {
442 best_block_stack = target_block_stack;
Mark Shannonfcb55c02021-04-01 16:00:31 +0100443 best_addr = i;
Mark Shannon57697242020-04-29 16:49:45 +0100444 }
445 }
446 else if (msg) {
447 if (target_block_stack >= 0) {
448 msg = explain_incompatible_block_stack(target_block_stack);
449 }
450 else {
451 msg = "code may be unreachable.";
452 }
453 }
Mark Shannonfee55262019-11-21 09:11:43 +0000454 }
455 }
Mark Shannon57697242020-04-29 16:49:45 +0100456 PyMem_Free(blocks);
457 PyMem_Free(lines);
458 if (msg != NULL) {
459 PyErr_SetString(PyExc_ValueError, msg);
460 return -1;
461 }
Mark Shannonfee55262019-11-21 09:11:43 +0000462
463 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100464 while (start_block_stack > best_block_stack) {
465 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000466 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100467 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000468 frame_stack_pop(f);
469 break;
Mark Shannon57697242020-04-29 16:49:45 +0100470 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000471 frame_block_unwind(f);
472 break;
Mark Shannon57697242020-04-29 16:49:45 +0100473 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000474 frame_block_unwind(f);
475 // Pop the exit function
476 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 break;
Mark Shannon57697242020-04-29 16:49:45 +0100478 case Except:
479 PyErr_SetString(PyExc_ValueError,
480 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000481 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 }
Mark Shannon57697242020-04-29 16:49:45 +0100483 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 }
Mark Shannonfee55262019-11-21 09:11:43 +0000485
Mark Shannonee9f98d2021-01-05 12:04:10 +0000486 /* Finally set the new f_lasti and return OK. */
487 f->f_lineno = 0;
Mark Shannon57697242020-04-29 16:49:45 +0100488 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000490}
491
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000492static PyObject *
493frame_gettrace(PyFrameObject *f, void *closure)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (trace == NULL)
498 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000503}
504
505static int
506frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
507{
Mark Shannonee9f98d2021-01-05 12:04:10 +0000508 if (v == Py_None) {
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300509 v = NULL;
Mark Shannonee9f98d2021-01-05 12:04:10 +0000510 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300512 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000515}
516
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000517
Guido van Rossum32d34c82001-09-20 21:45:26 +0000518static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 {"f_locals", (getter)frame_getlocals, NULL, NULL},
520 {"f_lineno", (getter)frame_getlineno,
521 (setter)frame_setlineno, NULL},
522 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
Mark Shannonfcb55c02021-04-01 16:00:31 +0100523 {"f_lasti", (getter)frame_getlasti, NULL, NULL},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000525};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000526
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000527/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000528 In an attempt to improve the speed of function calls, we:
529
530 1. Hold a single "zombie" frame on each code object. This retains
531 the allocated and initialised frame object from an invocation of
532 the code object. The zombie is reanimated the next time we need a
533 frame object for that code object. Doing this saves the malloc/
534 realloc required when using a free_list frame that isn't the
535 correct size. It also saves some field initialisation.
536
537 In zombie mode, no field of PyFrameObject holds a reference, but
538 the following fields are still valid:
539
540 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541
Mark Shannonae3087c2017-10-22 22:41:51 +0100542 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543
544 * f_localsplus does not require re-allocation and
545 the local variables in f_localsplus are NULL.
546
547 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000548 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549 a stack frame is on the free list, only the following members have
550 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 ob_type == &Frametype
552 f_back next item on free list, or NULL
553 f_stacksize size of value stack
554 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000555 Note that the value and block stacks are preserved -- this can save
556 another malloc() call or two (and two free() calls as well!).
557 Also note that, unlike for integers, each frame object is a
558 malloc'ed object in its own right -- it is only the actual calls to
559 malloc() that we are trying to save here, not the administration.
560 After all, while a typical program may make millions of calls, a
561 call depth of more than 20 or 30 is probably already exceptional
562 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000563
Christian Heimes2202f872008-02-06 14:31:34 +0000564 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000565 free_list. Else programs creating lots of cyclic trash involving
566 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000567*/
Christian Heimes2202f872008-02-06 14:31:34 +0000568/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000570
Victor Stinnerc6944e72016-11-11 02:13:35 +0100571static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000572frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000573{
Victor Stinner3744ed22020-06-05 01:39:24 +0200574 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900575 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200576 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200579 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200580 PyObject **valuestack = f->f_valuestack;
581 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200582 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200583 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200584
585 /* Free stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100586 for (int i = 0; i < f->f_stackdepth; i++) {
587 Py_XDECREF(f->f_valuestack[i]);
Antoine Pitrou93963562013-05-14 20:37:52 +0200588 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100589 f->f_stackdepth = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 Py_XDECREF(f->f_back);
592 Py_DECREF(f->f_builtins);
593 Py_DECREF(f->f_globals);
594 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200595 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000596
Victor Stinner3744ed22020-06-05 01:39:24 +0200597 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200598 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200600 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200601 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200602 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200603#ifdef Py_DEBUG
604 // frame_dealloc() must not be called after _PyFrame_Fini()
605 assert(state->numfree != -1);
606#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200607 if (state->numfree < PyFrame_MAXFREELIST) {
608 ++state->numfree;
609 f->f_back = state->free_list;
610 state->free_list = f;
611 }
612 else {
613 PyObject_GC_Del(f);
614 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200615 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 Py_DECREF(co);
618 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000619}
620
Victor Stinner6d86a232020-04-29 00:56:58 +0200621static inline Py_ssize_t
622frame_nslots(PyFrameObject *frame)
623{
624 PyCodeObject *code = frame->f_code;
625 return (code->co_nlocals
626 + PyTuple_GET_SIZE(code->co_cellvars)
627 + PyTuple_GET_SIZE(code->co_freevars));
628}
629
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000630static int
631frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 Py_VISIT(f->f_back);
634 Py_VISIT(f->f_code);
635 Py_VISIT(f->f_builtins);
636 Py_VISIT(f->f_globals);
637 Py_VISIT(f->f_locals);
638 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200641 PyObject **fastlocals = f->f_localsplus;
642 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200644 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100647 for (int i = 0; i < f->f_stackdepth; i++) {
648 Py_VISIT(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 }
650 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000651}
652
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200653static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200654frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000655{
Antoine Pitrou93963562013-05-14 20:37:52 +0200656 /* Before anything else, make sure that this frame is clearly marked
657 * as being defunct! Else, e.g., a generator reachable from this
658 * frame may also point to this frame, believe itself to still be
659 * active, and try cleaning up this frame again.
660 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100661 f->f_state = FRAME_CLEARED;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200666 PyObject **fastlocals = f->f_localsplus;
667 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200669 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100672 for (int i = 0; i < f->f_stackdepth; i++) {
673 Py_CLEAR(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100675 f->f_stackdepth = 0;
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200676 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000677}
678
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000679static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530680frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200681{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100682 if (_PyFrame_IsExecuting(f)) {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200683 PyErr_SetString(PyExc_RuntimeError,
684 "cannot clear an executing frame");
685 return NULL;
686 }
687 if (f->f_gen) {
688 _PyGen_Finalize(f->f_gen);
689 assert(f->f_gen == NULL);
690 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200691 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200692 Py_RETURN_NONE;
693}
694
695PyDoc_STRVAR(clear__doc__,
696"F.clear(): clear most references held by the frame");
697
698static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530699frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000702
Victor Stinner6d86a232020-04-29 00:56:58 +0200703 PyCodeObject *code = f->f_code;
704 ncells = PyTuple_GET_SIZE(code->co_cellvars);
705 nfrees = PyTuple_GET_SIZE(code->co_freevars);
706 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 /* subtract one as it is already included in PyFrameObject */
708 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000711}
712
713PyDoc_STRVAR(sizeof__doc__,
714"F.__sizeof__() -> size of F in memory, in bytes");
715
Antoine Pitrou14709142017-12-31 22:35:22 +0100716static PyObject *
717frame_repr(PyFrameObject *f)
718{
719 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200720 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100721 return PyUnicode_FromFormat(
722 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200723 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100724}
725
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000726static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200727 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
728 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
730 sizeof__doc__},
731 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000732};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000733
Guido van Rossum18752471997-04-29 14:49:28 +0000734PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyVarObject_HEAD_INIT(&PyType_Type, 0)
736 "frame",
737 sizeof(PyFrameObject),
738 sizeof(PyObject *),
739 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200740 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 0, /* tp_getattr */
742 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200743 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100744 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 0, /* tp_as_number */
746 0, /* tp_as_sequence */
747 0, /* tp_as_mapping */
748 0, /* tp_hash */
749 0, /* tp_call */
750 0, /* tp_str */
751 PyObject_GenericGetAttr, /* tp_getattro */
752 PyObject_GenericSetAttr, /* tp_setattro */
753 0, /* tp_as_buffer */
754 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
755 0, /* tp_doc */
756 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200757 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 0, /* tp_richcompare */
759 0, /* tp_weaklistoffset */
760 0, /* tp_iter */
761 0, /* tp_iternext */
762 frame_methods, /* tp_methods */
763 frame_memberlist, /* tp_members */
764 frame_getsetlist, /* tp_getset */
765 0, /* tp_base */
766 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000767};
768
Victor Stinner07e9e382013-11-07 22:22:39 +0100769_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000770
Victor Stinnerb4b53862020-05-05 19:55:29 +0200771static inline PyFrameObject*
772frame_alloc(PyCodeObject *code)
773{
Victor Stinner44085a32021-02-18 19:20:16 +0100774 PyFrameObject *f = code->co_zombieframe;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200775 if (f != NULL) {
776 code->co_zombieframe = NULL;
777 _Py_NewReference((PyObject *)f);
778 assert(f->f_code == code);
779 return f;
780 }
781
782 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
783 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
784 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200785 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200786 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200787 {
788 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
789 if (f == NULL) {
790 return NULL;
791 }
792 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200793 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200794#ifdef Py_DEBUG
795 // frame_alloc() must not be called after _PyFrame_Fini()
796 assert(state->numfree != -1);
797#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200798 assert(state->numfree > 0);
799 --state->numfree;
800 f = state->free_list;
801 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200802 if (Py_SIZE(f) < extras) {
803 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
804 if (new_f == NULL) {
805 PyObject_GC_Del(f);
806 return NULL;
807 }
808 f = new_f;
809 }
810 _Py_NewReference((PyObject *)f);
811 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200812
Victor Stinnerb4b53862020-05-05 19:55:29 +0200813 extras = code->co_nlocals + ncells + nfrees;
814 f->f_valuestack = f->f_localsplus + extras;
Victor Stinner44085a32021-02-18 19:20:16 +0100815 for (Py_ssize_t i=0; i < extras; i++) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200816 f->f_localsplus[i] = NULL;
817 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200818 return f;
819}
820
821
Victor Stinnerc6944e72016-11-11 02:13:35 +0100822PyFrameObject* _Py_HOT_FUNCTION
Mark Shannon0332e562021-02-01 10:42:03 +0000823_PyFrame_New_NoTrack(PyThreadState *tstate, PyFrameConstructor *con, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000824{
Victor Stinner44085a32021-02-18 19:20:16 +0100825 assert(con != NULL);
826 assert(con->fc_globals != NULL);
827 assert(con->fc_builtins != NULL);
828 assert(con->fc_code != NULL);
829 assert(locals == NULL || PyMapping_Check(locals));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000830
Mark Shannon0332e562021-02-01 10:42:03 +0000831 PyFrameObject *f = frame_alloc((PyCodeObject *)con->fc_code);
Victor Stinnerb4b53862020-05-05 19:55:29 +0200832 if (f == NULL) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200833 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200835
Victor Stinner44085a32021-02-18 19:20:16 +0100836 f->f_back = (PyFrameObject*)Py_XNewRef(tstate->frame);
837 f->f_code = (PyCodeObject *)Py_NewRef(con->fc_code);
838 f->f_builtins = Py_NewRef(con->fc_builtins);
839 f->f_globals = Py_NewRef(con->fc_globals);
840 f->f_locals = Py_XNewRef(locals);
841 // f_valuestack initialized by frame_alloc()
842 f->f_trace = NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100843 f->f_stackdepth = 0;
Victor Stinner44085a32021-02-18 19:20:16 +0100844 f->f_trace_lines = 1;
845 f->f_trace_opcodes = 0;
846 f->f_gen = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 f->f_lasti = -1;
Mark Shannon877df852020-11-12 09:43:29 +0000848 f->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 f->f_iblock = 0;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100850 f->f_state = FRAME_CREATED;
Victor Stinner44085a32021-02-18 19:20:16 +0100851 // f_blockstack and f_localsplus initialized by frame_alloc()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000853}
854
Mark Shannon0332e562021-02-01 10:42:03 +0000855/* Legacy API */
INADA Naoki5a625d02016-12-24 20:19:08 +0900856PyFrameObject*
857PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
858 PyObject *globals, PyObject *locals)
859{
Victor Stinnerfc980e02021-03-18 14:51:24 +0100860 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
Victor Stinner44085a32021-02-18 19:20:16 +0100861 if (builtins == NULL) {
862 return NULL;
863 }
Mark Shannon0332e562021-02-01 10:42:03 +0000864 PyFrameConstructor desc = {
865 .fc_globals = globals,
866 .fc_builtins = builtins,
867 .fc_name = code->co_name,
868 .fc_qualname = code->co_name,
869 .fc_code = (PyObject *)code,
870 .fc_defaults = NULL,
871 .fc_kwdefaults = NULL,
872 .fc_closure = NULL
873 };
874 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, &desc, locals);
Victor Stinner44085a32021-02-18 19:20:16 +0100875 if (f) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900876 _PyObject_GC_TRACK(f);
Victor Stinner44085a32021-02-18 19:20:16 +0100877 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900878 return f;
879}
880
881
Guido van Rossum3f5da241990-12-20 15:06:42 +0000882/* Block management */
883
884void
Fred Drake1b190b42000-07-09 05:40:56 +0000885PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100888 if (f->f_iblock >= CO_MAXBLOCKS) {
889 Py_FatalError("block stack overflow");
890 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 b = &f->f_blockstack[f->f_iblock++];
892 b->b_type = type;
893 b->b_level = level;
894 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000895}
896
Guido van Rossum18752471997-04-29 14:49:28 +0000897PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000898PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100901 if (f->f_iblock <= 0) {
902 Py_FatalError("block stack underflow");
903 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 b = &f->f_blockstack[--f->f_iblock];
905 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000906}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000907
Guido van Rossumd8faa362007-04-27 19:54:29 +0000908/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909
910 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000911 values is an array of PyObject*. At index i, map[i] is the name of
912 the variable with value values[i]. The function copies the first
913 nmap variable from map/values into dict. If values[i] is NULL,
914 the variable is deleted from dict.
915
916 If deref is true, then the values being copied are cell variables
917 and the value is extracted from the cell variable before being put
918 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000919 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000920
Victor Stinner41bb43a2013-10-29 01:19:37 +0100921static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000922map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 Py_ssize_t j;
926 assert(PyTuple_Check(map));
927 assert(PyDict_Check(dict));
928 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800929 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 PyObject *key = PyTuple_GET_ITEM(map, j);
931 PyObject *value = values[j];
932 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400933 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 assert(PyCell_Check(value));
935 value = PyCell_GET(value);
936 }
937 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100938 if (PyObject_DelItem(dict, key) != 0) {
939 if (PyErr_ExceptionMatches(PyExc_KeyError))
940 PyErr_Clear();
941 else
942 return -1;
943 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
945 else {
946 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100947 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 }
949 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100950 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000951}
952
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953/* Copy values from the "locals" dict into the fast locals.
954
955 dict is an input argument containing string keys representing
956 variables names and arbitrary PyObject* as values.
957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959 values is an array of PyObject*. At index i, map[i] is the name of
960 the variable with value values[i]. The function copies the first
961 nmap variable from map/values into dict. If values[i] is NULL,
962 the variable is deleted from dict.
963
964 If deref is true, then the values being copied are cell variables
965 and the value is extracted from the cell variable before being put
966 in dict. If clear is true, then variables in map but not in dict
967 are set to NULL in map; if clear is false, variables missing in
968 dict are ignored.
969
970 Exceptions raised while modifying the dict are silently ignored,
971 because there is no good way to report them.
972*/
973
Guido van Rossum6b356e72001-04-14 17:55:41 +0000974static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000975dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 Py_ssize_t j;
979 assert(PyTuple_Check(map));
980 assert(PyDict_Check(dict));
981 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800982 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *key = PyTuple_GET_ITEM(map, j);
984 PyObject *value = PyObject_GetItem(dict, key);
985 assert(PyUnicode_Check(key));
986 /* We only care about NULLs if clear is true. */
987 if (value == NULL) {
988 PyErr_Clear();
989 if (!clear)
990 continue;
991 }
992 if (deref) {
993 assert(PyCell_Check(values[j]));
994 if (PyCell_GET(values[j]) != value) {
995 if (PyCell_Set(values[j], value) < 0)
996 PyErr_Clear();
997 }
998 } else if (values[j] != value) {
999 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001000 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 }
1002 Py_XDECREF(value);
1003 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001004}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001005
Victor Stinner41bb43a2013-10-29 01:19:37 +01001006int
1007PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 /* Merge fast locals into f->f_locals */
1010 PyObject *locals, *map;
1011 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyCodeObject *co;
1013 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001014 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001015
1016 if (f == NULL) {
1017 PyErr_BadInternalCall();
1018 return -1;
1019 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 locals = f->f_locals;
1021 if (locals == NULL) {
1022 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001023 if (locals == NULL)
1024 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 }
1026 co = f->f_code;
1027 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001028 if (!PyTuple_Check(map)) {
1029 PyErr_Format(PyExc_SystemError,
1030 "co_varnames must be a tuple, not %s",
1031 Py_TYPE(map)->tp_name);
1032 return -1;
1033 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 fast = f->f_localsplus;
1035 j = PyTuple_GET_SIZE(map);
1036 if (j > co->co_nlocals)
1037 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001038 if (co->co_nlocals) {
1039 if (map_to_dict(map, j, locals, fast, 0) < 0)
1040 return -1;
1041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1043 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1044 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001045 if (map_to_dict(co->co_cellvars, ncells,
1046 locals, fast + co->co_nlocals, 1))
1047 return -1;
1048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 /* If the namespace is unoptimized, then one of the
1050 following cases applies:
1051 1. It does not contain free variables, because it
1052 uses import * or is a top-level namespace.
1053 2. It is a class namespace.
1054 We don't want to accidentally copy free variables
1055 into the locals dict used by the class.
1056 */
1057 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001058 if (map_to_dict(co->co_freevars, nfreevars,
1059 locals, fast + co->co_nlocals + ncells, 1) < 0)
1060 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 }
1062 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001063 return 0;
1064}
1065
1066void
1067PyFrame_FastToLocals(PyFrameObject *f)
1068{
1069 int res;
1070
1071 assert(!PyErr_Occurred());
1072
1073 res = PyFrame_FastToLocalsWithError(f);
1074 if (res < 0)
1075 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001076}
1077
1078void
Fred Drake1b190b42000-07-09 05:40:56 +00001079PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* Merge f->f_locals into fast locals */
1082 PyObject *locals, *map;
1083 PyObject **fast;
1084 PyObject *error_type, *error_value, *error_traceback;
1085 PyCodeObject *co;
1086 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001087 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (f == NULL)
1089 return;
1090 locals = f->f_locals;
1091 co = f->f_code;
1092 map = co->co_varnames;
1093 if (locals == NULL)
1094 return;
1095 if (!PyTuple_Check(map))
1096 return;
1097 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1098 fast = f->f_localsplus;
1099 j = PyTuple_GET_SIZE(map);
1100 if (j > co->co_nlocals)
1101 j = co->co_nlocals;
1102 if (co->co_nlocals)
1103 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1104 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1105 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1106 if (ncells || nfreevars) {
1107 dict_to_map(co->co_cellvars, ncells,
1108 locals, fast + co->co_nlocals, 1, clear);
1109 /* Same test as in PyFrame_FastToLocals() above. */
1110 if (co->co_flags & CO_OPTIMIZED) {
1111 dict_to_map(co->co_freevars, nfreevars,
1112 locals, fast + co->co_nlocals + ncells, 1,
1113 clear);
1114 }
1115 }
1116 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001117}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001118
1119/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001120void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001121_PyFrame_ClearFreeList(PyInterpreterState *interp)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001122{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001123 struct _Py_frame_state *state = &interp->frame;
Victor Stinner3744ed22020-06-05 01:39:24 +02001124 while (state->free_list != NULL) {
1125 PyFrameObject *f = state->free_list;
1126 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001128 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001130 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001131}
1132
1133void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001134_PyFrame_Fini(PyInterpreterState *interp)
Christian Heimesa156e092008-02-16 07:38:31 +00001135{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001136 _PyFrame_ClearFreeList(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001137#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001138 struct _Py_frame_state *state = &interp->frame;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001139 state->numfree = -1;
1140#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001141}
David Malcolm49526f42012-06-22 14:55:41 -04001142
1143/* Print summary info about the state of the optimized allocator */
1144void
1145_PyFrame_DebugMallocStats(FILE *out)
1146{
Victor Stinner522691c2020-06-23 16:40:40 +02001147 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001148 _PyDebugAllocatorStats(out,
1149 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001150 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001151}
1152
Victor Stinnera42ca742020-04-28 19:01:31 +02001153
1154PyCodeObject *
1155PyFrame_GetCode(PyFrameObject *frame)
1156{
1157 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001158 PyCodeObject *code = frame->f_code;
1159 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001160 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001161 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001162}
Victor Stinner70364772020-04-29 03:28:46 +02001163
1164
1165PyFrameObject*
1166PyFrame_GetBack(PyFrameObject *frame)
1167{
1168 assert(frame != NULL);
1169 PyFrameObject *back = frame->f_back;
1170 Py_XINCREF(back);
1171 return back;
1172}
Mark Shannond6c33fb2021-01-29 13:24:55 +00001173
Victor Stinner44085a32021-02-18 19:20:16 +01001174PyObject*
Victor Stinner46496f92021-02-20 15:17:18 +01001175_PyEval_BuiltinsFromGlobals(PyThreadState *tstate, PyObject *globals)
Victor Stinner44085a32021-02-18 19:20:16 +01001176{
Mark Shannond6c33fb2021-01-29 13:24:55 +00001177 PyObject *builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
1178 if (builtins) {
1179 if (PyModule_Check(builtins)) {
Victor Stinnercdad2722021-04-22 00:52:52 +02001180 builtins = _PyModule_GetDict(builtins);
Mark Shannond6c33fb2021-01-29 13:24:55 +00001181 assert(builtins != NULL);
1182 }
Victor Stinner46496f92021-02-20 15:17:18 +01001183 return builtins;
Mark Shannond6c33fb2021-01-29 13:24:55 +00001184 }
Victor Stinner44085a32021-02-18 19:20:16 +01001185 if (PyErr_Occurred()) {
1186 return NULL;
1187 }
1188
Victor Stinner46496f92021-02-20 15:17:18 +01001189 return _PyEval_GetBuiltins(tstate);
Mark Shannond6c33fb2021-01-29 13:24:55 +00001190}