blob: 056d42a0d9ebb45dfdc90df4d5c25fa634692f8d [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},
18 {"f_lasti", T_INT, OFF(f_lasti), 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 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 return PyCode_Addr2Line(f->f_code, f->f_lasti);
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
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020059
60/* Given the index of the effective opcode,
61 scan back to construct the oparg with EXTENDED_ARG */
62static unsigned int
63get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
64{
65 _Py_CODEUNIT word;
66 unsigned int oparg = _Py_OPARG(codestr[i]);
67 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
68 oparg |= _Py_OPARG(word) << 8;
69 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
70 oparg |= _Py_OPARG(word) << 16;
71 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
72 oparg |= _Py_OPARG(word) << 24;
73 }
74 }
75 }
76 return oparg;
77}
78
Mark Shannon57697242020-04-29 16:49:45 +010079typedef enum kind {
80 With = 1,
81 Loop = 2,
82 Try = 3,
83 Except = 4,
84} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +000085
Mark Shannon57697242020-04-29 16:49:45 +010086#define BITS_PER_BLOCK 3
87
88static inline int64_t
89push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +000090{
Mark Shannon57697242020-04-29 16:49:45 +010091 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
92 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +000093}
94
Mark Shannon57697242020-04-29 16:49:45 +010095static inline int64_t
96pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +000097{
Mark Shannon57697242020-04-29 16:49:45 +010098 assert(stack > 0);
99 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +0000100}
101
Mark Shannon57697242020-04-29 16:49:45 +0100102static inline Kind
103top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000104{
Mark Shannon57697242020-04-29 16:49:45 +0100105 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +0000106}
107
Mark Shannon57697242020-04-29 16:49:45 +0100108static int64_t *
109markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000110{
Mark Shannon57697242020-04-29 16:49:45 +0100111 const _Py_CODEUNIT *code =
112 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
113 int64_t *blocks = PyMem_New(int64_t, len+1);
114 int i, j, opcode;
115
116 if (blocks == NULL) {
117 PyErr_NoMemory();
118 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000119 }
Mark Shannon57697242020-04-29 16:49:45 +0100120 memset(blocks, -1, (len+1)*sizeof(int64_t));
121 blocks[0] = 0;
122 int todo = 1;
123 while (todo) {
124 todo = 0;
125 for (i = 0; i < len; i++) {
126 int64_t block_stack = blocks[i];
127 int64_t except_stack;
128 if (block_stack == -1) {
129 continue;
130 }
131 opcode = _Py_OPCODE(code[i]);
132 switch (opcode) {
133 case JUMP_IF_FALSE_OR_POP:
134 case JUMP_IF_TRUE_OR_POP:
135 case POP_JUMP_IF_FALSE:
136 case POP_JUMP_IF_TRUE:
137 case JUMP_IF_NOT_EXC_MATCH:
138 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
139 assert(j < len);
140 if (blocks[j] == -1 && j < i) {
141 todo = 1;
142 }
143 assert(blocks[j] == -1 || blocks[j] == block_stack);
144 blocks[j] = block_stack;
145 blocks[i+1] = block_stack;
146 break;
147 case JUMP_ABSOLUTE:
148 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
149 assert(j < len);
150 if (blocks[j] == -1 && j < i) {
151 todo = 1;
152 }
153 assert(blocks[j] == -1 || blocks[j] == block_stack);
154 blocks[j] = block_stack;
155 break;
156 case SETUP_FINALLY:
157 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
158 assert(j < len);
159 except_stack = push_block(block_stack, Except);
160 assert(blocks[j] == -1 || blocks[j] == except_stack);
161 blocks[j] = except_stack;
162 block_stack = push_block(block_stack, Try);
163 blocks[i+1] = block_stack;
164 break;
165 case SETUP_WITH:
166 case SETUP_ASYNC_WITH:
167 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
168 assert(j < len);
169 except_stack = push_block(block_stack, Except);
170 assert(blocks[j] == -1 || blocks[j] == except_stack);
171 blocks[j] = except_stack;
172 block_stack = push_block(block_stack, With);
173 blocks[i+1] = block_stack;
174 break;
175 case JUMP_FORWARD:
176 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
177 assert(j < len);
178 assert(blocks[j] == -1 || blocks[j] == block_stack);
179 blocks[j] = block_stack;
180 break;
181 case GET_ITER:
182 case GET_AITER:
183 block_stack = push_block(block_stack, Loop);
184 blocks[i+1] = block_stack;
185 break;
186 case FOR_ITER:
187 blocks[i+1] = block_stack;
188 block_stack = pop_block(block_stack);
189 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
190 assert(j < len);
191 assert(blocks[j] == -1 || blocks[j] == block_stack);
192 blocks[j] = block_stack;
193 break;
194 case POP_BLOCK:
195 case POP_EXCEPT:
196 block_stack = pop_block(block_stack);
197 blocks[i+1] = block_stack;
198 break;
199 case END_ASYNC_FOR:
200 block_stack = pop_block(pop_block(block_stack));
201 blocks[i+1] = block_stack;
202 break;
203 case RETURN_VALUE:
204 case RAISE_VARARGS:
205 case RERAISE:
206 /* End of block */
207 break;
208 default:
209 blocks[i+1] = block_stack;
210
211 }
212 }
213 }
214 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000215}
216
217static int
Mark Shannon57697242020-04-29 16:49:45 +0100218compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000219{
Mark Shannon57697242020-04-29 16:49:45 +0100220 if (to_stack < 0) {
221 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000222 }
Mark Shannon57697242020-04-29 16:49:45 +0100223 while(from_stack > to_stack) {
224 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000225 }
Mark Shannon57697242020-04-29 16:49:45 +0100226 return from_stack == to_stack;
227}
228
229static const char *
230explain_incompatible_block_stack(int64_t to_stack)
231{
232 Kind target_kind = top_block(to_stack);
233 switch(target_kind) {
234 case Except:
235 return "can't jump into an 'except' block as there's no exception";
236 case Try:
237 return "can't jump into the body of a try statement";
238 case With:
239 return "can't jump into the body of a with statement";
240 case Loop:
241 return "can't jump into the body of a for loop";
242 default:
243 Py_UNREACHABLE();
244 }
245}
246
247static int *
248marklines(PyCodeObject *code, int len)
249{
Mark Shannon877df852020-11-12 09:43:29 +0000250 PyCodeAddressRange bounds;
251 _PyCode_InitAddressRange(code, &bounds);
252 assert (bounds.ar_end == 0);
253
Mark Shannon57697242020-04-29 16:49:45 +0100254 int *linestarts = PyMem_New(int, len);
255 if (linestarts == NULL) {
256 return NULL;
257 }
Mark Shannon877df852020-11-12 09:43:29 +0000258 for (int i = 0; i < len; i++) {
259 linestarts[i] = -1;
Mark Shannon57697242020-04-29 16:49:45 +0100260 }
Mark Shannon877df852020-11-12 09:43:29 +0000261
262 while (PyLineTable_NextAddressRange(&bounds)) {
263 assert(bounds.ar_start/2 < len);
264 linestarts[bounds.ar_start/2] = bounds.ar_line;
Mark Shannon57697242020-04-29 16:49:45 +0100265 }
Mark Shannon57697242020-04-29 16:49:45 +0100266 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000267}
268
269static int
Mark Shannon57697242020-04-29 16:49:45 +0100270first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000271{
272 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100273 for (int i = 0; i < len; i++) {
274 if (lines[i] < result && lines[i] >= line) {
275 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000276 }
Mark Shannonfee55262019-11-21 09:11:43 +0000277 }
278 if (result == INT_MAX) {
279 return -1;
280 }
281 return result;
282}
283
Mark Shannonfee55262019-11-21 09:11:43 +0000284static void
285frame_stack_pop(PyFrameObject *f)
286{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100287 assert(f->f_stackdepth >= 0);
288 f->f_stackdepth--;
289 PyObject *v = f->f_valuestack[f->f_stackdepth];
Mark Shannonfee55262019-11-21 09:11:43 +0000290 Py_DECREF(v);
291}
292
293static void
294frame_block_unwind(PyFrameObject *f)
295{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100296 assert(f->f_stackdepth >= 0);
Mark Shannonfee55262019-11-21 09:11:43 +0000297 assert(f->f_iblock > 0);
298 f->f_iblock--;
299 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Mark Shannoncb9879b2020-07-17 11:44:23 +0100300 intptr_t delta = f->f_stackdepth - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000301 while (delta > 0) {
302 frame_stack_pop(f);
303 delta--;
304 }
305}
306
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200307
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000308/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000310 * lines are OK to jump to because they don't make any assumptions about the
311 * state of the stack (obvious because you could remove the line and the code
312 * would still work without any stack errors), but there are some constructs
313 * that limit jumping:
314 *
315 * o Lines with an 'except' statement on them can't be jumped to, because
316 * they expect an exception to be on the top of the stack.
317 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000318 * we cannot be sure which state the interpreter was in or would be in
319 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200320 * o 'try', 'with' and 'async with' blocks can't be jumped into because
321 * the blockstack needs to be set up before their code runs.
322 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000323 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100324 * o Jumps cannot be made from within a trace function invoked with a
325 * 'return' or 'exception' event since the eval loop has been exited at
326 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000327 */
328static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200329frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000330{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700331 if (p_new_lineno == NULL) {
332 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
333 return -1;
334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* f_lineno must be an integer. */
336 if (!PyLong_CheckExact(p_new_lineno)) {
337 PyErr_SetString(PyExc_ValueError,
338 "lineno must be an integer");
339 return -1;
340 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000341
Mark Shannoncb9879b2020-07-17 11:44:23 +0100342 /*
343 * This code preserves the historical restrictions on
344 * setting the line number of a frame.
345 * Jumps are forbidden on a 'return' trace event (except after a yield).
346 * Jumps from 'call' trace events are also forbidden.
347 * In addition, jumps are forbidden when not tracing,
348 * as this is a debugging feature.
349 */
350 switch(f->f_state) {
351 case FRAME_CREATED:
352 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100353 "can't jump from the 'call' trace event of a new frame");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100354 return -1;
355 case FRAME_RETURNED:
356 case FRAME_UNWINDING:
357 case FRAME_RAISED:
358 case FRAME_CLEARED:
359 PyErr_SetString(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100360 "can only jump from a 'line' trace event");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100361 return -1;
362 case FRAME_EXECUTING:
363 case FRAME_SUSPENDED:
364 /* You can only do this from within a trace function, not via
365 * _getframe or similar hackery. */
366 if (!f->f_trace) {
367 PyErr_Format(PyExc_ValueError,
368 "f_lineno can only be set by a trace function");
369 return -1;
370 }
371 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000373
Mark Shannonfee55262019-11-21 09:11:43 +0000374 int new_lineno;
375
Mark Shannon57697242020-04-29 16:49:45 +0100376 /* Fail if the line falls outside the code block and
377 select first line with actual code. */
378 int overflow;
379 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
380 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000381#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100382 || l_new_lineno > INT_MAX
383 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000384#endif
Mark Shannon57697242020-04-29 16:49:45 +0100385 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000386 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100387 "lineno out of range");
388 return -1;
389 }
390 new_lineno = (int)l_new_lineno;
391
392 if (new_lineno < f->f_code->co_firstlineno) {
393 PyErr_Format(PyExc_ValueError,
394 "line %d comes before the current code block",
395 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 return -1;
397 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000398
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000399 /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
400 * should never overflow. */
401 int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT));
Mark Shannon57697242020-04-29 16:49:45 +0100402 int *lines = marklines(f->f_code, len);
403 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 return -1;
405 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000406
Mark Shannon57697242020-04-29 16:49:45 +0100407 new_lineno = first_line_not_before(lines, len, new_lineno);
408 if (new_lineno < 0) {
409 PyErr_Format(PyExc_ValueError,
410 "line %d comes after the current code block",
411 (int)l_new_lineno);
412 PyMem_Free(lines);
413 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000414 }
415
Mark Shannon57697242020-04-29 16:49:45 +0100416 int64_t *blocks = markblocks(f->f_code, len);
417 if (blocks == NULL) {
418 PyMem_Free(lines);
419 return -1;
420 }
421
422 int64_t target_block_stack = -1;
423 int64_t best_block_stack = -1;
424 int best_addr = -1;
425 int64_t start_block_stack = blocks[f->f_lasti/sizeof(_Py_CODEUNIT)];
426 const char *msg = "cannot find bytecode for specified line";
427 for (int i = 0; i < len; i++) {
428 if (lines[i] == new_lineno) {
429 target_block_stack = blocks[i];
430 if (compatible_block_stack(start_block_stack, target_block_stack)) {
431 msg = NULL;
432 if (target_block_stack > best_block_stack) {
433 best_block_stack = target_block_stack;
434 best_addr = i*sizeof(_Py_CODEUNIT);
435 }
436 }
437 else if (msg) {
438 if (target_block_stack >= 0) {
439 msg = explain_incompatible_block_stack(target_block_stack);
440 }
441 else {
442 msg = "code may be unreachable.";
443 }
444 }
Mark Shannonfee55262019-11-21 09:11:43 +0000445 }
446 }
Mark Shannon57697242020-04-29 16:49:45 +0100447 PyMem_Free(blocks);
448 PyMem_Free(lines);
449 if (msg != NULL) {
450 PyErr_SetString(PyExc_ValueError, msg);
451 return -1;
452 }
Mark Shannonfee55262019-11-21 09:11:43 +0000453
454 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100455 while (start_block_stack > best_block_stack) {
456 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000457 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100458 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000459 frame_stack_pop(f);
460 break;
Mark Shannon57697242020-04-29 16:49:45 +0100461 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000462 frame_block_unwind(f);
463 break;
Mark Shannon57697242020-04-29 16:49:45 +0100464 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000465 frame_block_unwind(f);
466 // Pop the exit function
467 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 break;
Mark Shannon57697242020-04-29 16:49:45 +0100469 case Except:
470 PyErr_SetString(PyExc_ValueError,
471 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000472 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 }
Mark Shannon57697242020-04-29 16:49:45 +0100474 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 }
Mark Shannonfee55262019-11-21 09:11:43 +0000476
Mark Shannonee9f98d2021-01-05 12:04:10 +0000477 /* Finally set the new f_lasti and return OK. */
478 f->f_lineno = 0;
Mark Shannon57697242020-04-29 16:49:45 +0100479 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000481}
482
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000483static PyObject *
484frame_gettrace(PyFrameObject *f, void *closure)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (trace == NULL)
489 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000494}
495
496static int
497frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
498{
Mark Shannonee9f98d2021-01-05 12:04:10 +0000499 if (v == Py_None) {
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300500 v = NULL;
Mark Shannonee9f98d2021-01-05 12:04:10 +0000501 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300503 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000506}
507
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000508
Guido van Rossum32d34c82001-09-20 21:45:26 +0000509static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 {"f_locals", (getter)frame_getlocals, NULL, NULL},
511 {"f_lineno", (getter)frame_getlineno,
512 (setter)frame_setlineno, NULL},
513 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
514 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000515};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000516
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000517/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000518 In an attempt to improve the speed of function calls, we:
519
520 1. Hold a single "zombie" frame on each code object. This retains
521 the allocated and initialised frame object from an invocation of
522 the code object. The zombie is reanimated the next time we need a
523 frame object for that code object. Doing this saves the malloc/
524 realloc required when using a free_list frame that isn't the
525 correct size. It also saves some field initialisation.
526
527 In zombie mode, no field of PyFrameObject holds a reference, but
528 the following fields are still valid:
529
530 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531
Mark Shannonae3087c2017-10-22 22:41:51 +0100532 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000533
534 * f_localsplus does not require re-allocation and
535 the local variables in f_localsplus are NULL.
536
537 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000538 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539 a stack frame is on the free list, only the following members have
540 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 ob_type == &Frametype
542 f_back next item on free list, or NULL
543 f_stacksize size of value stack
544 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000545 Note that the value and block stacks are preserved -- this can save
546 another malloc() call or two (and two free() calls as well!).
547 Also note that, unlike for integers, each frame object is a
548 malloc'ed object in its own right -- it is only the actual calls to
549 malloc() that we are trying to save here, not the administration.
550 After all, while a typical program may make millions of calls, a
551 call depth of more than 20 or 30 is probably already exceptional
552 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000553
Christian Heimes2202f872008-02-06 14:31:34 +0000554 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000555 free_list. Else programs creating lots of cyclic trash involving
556 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000557*/
Christian Heimes2202f872008-02-06 14:31:34 +0000558/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000560
Victor Stinnerc6944e72016-11-11 02:13:35 +0100561static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000562frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000563{
Victor Stinner3744ed22020-06-05 01:39:24 +0200564 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900565 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200566 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200569 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200570 PyObject **valuestack = f->f_valuestack;
571 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200572 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200573 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200574
575 /* Free stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100576 for (int i = 0; i < f->f_stackdepth; i++) {
577 Py_XDECREF(f->f_valuestack[i]);
Antoine Pitrou93963562013-05-14 20:37:52 +0200578 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100579 f->f_stackdepth = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 Py_XDECREF(f->f_back);
582 Py_DECREF(f->f_builtins);
583 Py_DECREF(f->f_globals);
584 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200585 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586
Victor Stinner3744ed22020-06-05 01:39:24 +0200587 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200588 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200590 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200591 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200592 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200593#ifdef Py_DEBUG
594 // frame_dealloc() must not be called after _PyFrame_Fini()
595 assert(state->numfree != -1);
596#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200597 if (state->numfree < PyFrame_MAXFREELIST) {
598 ++state->numfree;
599 f->f_back = state->free_list;
600 state->free_list = f;
601 }
602 else {
603 PyObject_GC_Del(f);
604 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200605 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 Py_DECREF(co);
608 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000609}
610
Victor Stinner6d86a232020-04-29 00:56:58 +0200611static inline Py_ssize_t
612frame_nslots(PyFrameObject *frame)
613{
614 PyCodeObject *code = frame->f_code;
615 return (code->co_nlocals
616 + PyTuple_GET_SIZE(code->co_cellvars)
617 + PyTuple_GET_SIZE(code->co_freevars));
618}
619
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000620static int
621frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 Py_VISIT(f->f_back);
624 Py_VISIT(f->f_code);
625 Py_VISIT(f->f_builtins);
626 Py_VISIT(f->f_globals);
627 Py_VISIT(f->f_locals);
628 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200631 PyObject **fastlocals = f->f_localsplus;
632 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200634 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100637 for (int i = 0; i < f->f_stackdepth; i++) {
638 Py_VISIT(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 }
640 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000641}
642
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200643static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200644frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000645{
Antoine Pitrou93963562013-05-14 20:37:52 +0200646 /* Before anything else, make sure that this frame is clearly marked
647 * as being defunct! Else, e.g., a generator reachable from this
648 * frame may also point to this frame, believe itself to still be
649 * active, and try cleaning up this frame again.
650 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100651 f->f_state = FRAME_CLEARED;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200656 PyObject **fastlocals = f->f_localsplus;
657 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200659 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100662 for (int i = 0; i < f->f_stackdepth; i++) {
663 Py_CLEAR(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100665 f->f_stackdepth = 0;
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200666 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000667}
668
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000669static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530670frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200671{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100672 if (_PyFrame_IsExecuting(f)) {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200673 PyErr_SetString(PyExc_RuntimeError,
674 "cannot clear an executing frame");
675 return NULL;
676 }
677 if (f->f_gen) {
678 _PyGen_Finalize(f->f_gen);
679 assert(f->f_gen == NULL);
680 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200681 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200682 Py_RETURN_NONE;
683}
684
685PyDoc_STRVAR(clear__doc__,
686"F.clear(): clear most references held by the frame");
687
688static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530689frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000692
Victor Stinner6d86a232020-04-29 00:56:58 +0200693 PyCodeObject *code = f->f_code;
694 ncells = PyTuple_GET_SIZE(code->co_cellvars);
695 nfrees = PyTuple_GET_SIZE(code->co_freevars);
696 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 /* subtract one as it is already included in PyFrameObject */
698 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000701}
702
703PyDoc_STRVAR(sizeof__doc__,
704"F.__sizeof__() -> size of F in memory, in bytes");
705
Antoine Pitrou14709142017-12-31 22:35:22 +0100706static PyObject *
707frame_repr(PyFrameObject *f)
708{
709 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200710 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100711 return PyUnicode_FromFormat(
712 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200713 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100714}
715
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000716static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200717 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
718 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
720 sizeof__doc__},
721 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000722};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000723
Guido van Rossum18752471997-04-29 14:49:28 +0000724PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyVarObject_HEAD_INIT(&PyType_Type, 0)
726 "frame",
727 sizeof(PyFrameObject),
728 sizeof(PyObject *),
729 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200730 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 0, /* tp_getattr */
732 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200733 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100734 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 0, /* tp_as_number */
736 0, /* tp_as_sequence */
737 0, /* tp_as_mapping */
738 0, /* tp_hash */
739 0, /* tp_call */
740 0, /* tp_str */
741 PyObject_GenericGetAttr, /* tp_getattro */
742 PyObject_GenericSetAttr, /* tp_setattro */
743 0, /* tp_as_buffer */
744 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
745 0, /* tp_doc */
746 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200747 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 0, /* tp_richcompare */
749 0, /* tp_weaklistoffset */
750 0, /* tp_iter */
751 0, /* tp_iternext */
752 frame_methods, /* tp_methods */
753 frame_memberlist, /* tp_members */
754 frame_getsetlist, /* tp_getset */
755 0, /* tp_base */
756 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000757};
758
Victor Stinner07e9e382013-11-07 22:22:39 +0100759_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000760
Victor Stinnerb4b53862020-05-05 19:55:29 +0200761static inline PyFrameObject*
762frame_alloc(PyCodeObject *code)
763{
Victor Stinner44085a32021-02-18 19:20:16 +0100764 PyFrameObject *f = code->co_zombieframe;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200765 if (f != NULL) {
766 code->co_zombieframe = NULL;
767 _Py_NewReference((PyObject *)f);
768 assert(f->f_code == code);
769 return f;
770 }
771
772 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
773 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
774 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200775 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200776 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200777 {
778 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
779 if (f == NULL) {
780 return NULL;
781 }
782 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200783 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200784#ifdef Py_DEBUG
785 // frame_alloc() must not be called after _PyFrame_Fini()
786 assert(state->numfree != -1);
787#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200788 assert(state->numfree > 0);
789 --state->numfree;
790 f = state->free_list;
791 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200792 if (Py_SIZE(f) < extras) {
793 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
794 if (new_f == NULL) {
795 PyObject_GC_Del(f);
796 return NULL;
797 }
798 f = new_f;
799 }
800 _Py_NewReference((PyObject *)f);
801 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200802
Victor Stinnerb4b53862020-05-05 19:55:29 +0200803 extras = code->co_nlocals + ncells + nfrees;
804 f->f_valuestack = f->f_localsplus + extras;
Victor Stinner44085a32021-02-18 19:20:16 +0100805 for (Py_ssize_t i=0; i < extras; i++) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200806 f->f_localsplus[i] = NULL;
807 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200808 return f;
809}
810
811
Victor Stinnerc6944e72016-11-11 02:13:35 +0100812PyFrameObject* _Py_HOT_FUNCTION
Mark Shannon0332e562021-02-01 10:42:03 +0000813_PyFrame_New_NoTrack(PyThreadState *tstate, PyFrameConstructor *con, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000814{
Victor Stinner44085a32021-02-18 19:20:16 +0100815 assert(con != NULL);
816 assert(con->fc_globals != NULL);
817 assert(con->fc_builtins != NULL);
818 assert(con->fc_code != NULL);
819 assert(locals == NULL || PyMapping_Check(locals));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000820
Mark Shannon0332e562021-02-01 10:42:03 +0000821 PyFrameObject *f = frame_alloc((PyCodeObject *)con->fc_code);
Victor Stinnerb4b53862020-05-05 19:55:29 +0200822 if (f == NULL) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200823 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200825
Victor Stinner44085a32021-02-18 19:20:16 +0100826 f->f_back = (PyFrameObject*)Py_XNewRef(tstate->frame);
827 f->f_code = (PyCodeObject *)Py_NewRef(con->fc_code);
828 f->f_builtins = Py_NewRef(con->fc_builtins);
829 f->f_globals = Py_NewRef(con->fc_globals);
830 f->f_locals = Py_XNewRef(locals);
831 // f_valuestack initialized by frame_alloc()
832 f->f_trace = NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100833 f->f_stackdepth = 0;
Victor Stinner44085a32021-02-18 19:20:16 +0100834 f->f_trace_lines = 1;
835 f->f_trace_opcodes = 0;
836 f->f_gen = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 f->f_lasti = -1;
Mark Shannon877df852020-11-12 09:43:29 +0000838 f->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 f->f_iblock = 0;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100840 f->f_state = FRAME_CREATED;
Victor Stinner44085a32021-02-18 19:20:16 +0100841 // f_blockstack and f_localsplus initialized by frame_alloc()
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000843}
844
Mark Shannon0332e562021-02-01 10:42:03 +0000845/* Legacy API */
INADA Naoki5a625d02016-12-24 20:19:08 +0900846PyFrameObject*
847PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
848 PyObject *globals, PyObject *locals)
849{
Victor Stinner46496f92021-02-20 15:17:18 +0100850 PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals);
Victor Stinner44085a32021-02-18 19:20:16 +0100851 if (builtins == NULL) {
852 return NULL;
853 }
Mark Shannon0332e562021-02-01 10:42:03 +0000854 PyFrameConstructor desc = {
855 .fc_globals = globals,
856 .fc_builtins = builtins,
857 .fc_name = code->co_name,
858 .fc_qualname = code->co_name,
859 .fc_code = (PyObject *)code,
860 .fc_defaults = NULL,
861 .fc_kwdefaults = NULL,
862 .fc_closure = NULL
863 };
864 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, &desc, locals);
Victor Stinner44085a32021-02-18 19:20:16 +0100865 if (f) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900866 _PyObject_GC_TRACK(f);
Victor Stinner44085a32021-02-18 19:20:16 +0100867 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900868 return f;
869}
870
871
Guido van Rossum3f5da241990-12-20 15:06:42 +0000872/* Block management */
873
874void
Fred Drake1b190b42000-07-09 05:40:56 +0000875PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100878 if (f->f_iblock >= CO_MAXBLOCKS) {
879 Py_FatalError("block stack overflow");
880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 b = &f->f_blockstack[f->f_iblock++];
882 b->b_type = type;
883 b->b_level = level;
884 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000885}
886
Guido van Rossum18752471997-04-29 14:49:28 +0000887PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000888PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100891 if (f->f_iblock <= 0) {
892 Py_FatalError("block stack underflow");
893 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 b = &f->f_blockstack[--f->f_iblock];
895 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000896}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000897
Guido van Rossumd8faa362007-04-27 19:54:29 +0000898/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899
900 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901 values is an array of PyObject*. At index i, map[i] is the name of
902 the variable with value values[i]. The function copies the first
903 nmap variable from map/values into dict. If values[i] is NULL,
904 the variable is deleted from dict.
905
906 If deref is true, then the values being copied are cell variables
907 and the value is extracted from the cell variable before being put
908 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000909 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000910
Victor Stinner41bb43a2013-10-29 01:19:37 +0100911static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 Py_ssize_t j;
916 assert(PyTuple_Check(map));
917 assert(PyDict_Check(dict));
918 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800919 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyObject *key = PyTuple_GET_ITEM(map, j);
921 PyObject *value = values[j];
922 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400923 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 assert(PyCell_Check(value));
925 value = PyCell_GET(value);
926 }
927 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100928 if (PyObject_DelItem(dict, key) != 0) {
929 if (PyErr_ExceptionMatches(PyExc_KeyError))
930 PyErr_Clear();
931 else
932 return -1;
933 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 }
935 else {
936 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100937 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 }
939 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100940 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000941}
942
Guido van Rossumd8faa362007-04-27 19:54:29 +0000943/* Copy values from the "locals" dict into the fast locals.
944
945 dict is an input argument containing string keys representing
946 variables names and arbitrary PyObject* as values.
947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949 values is an array of PyObject*. At index i, map[i] is the name of
950 the variable with value values[i]. The function copies the first
951 nmap variable from map/values into dict. If values[i] is NULL,
952 the variable is deleted from dict.
953
954 If deref is true, then the values being copied are cell variables
955 and the value is extracted from the cell variable before being put
956 in dict. If clear is true, then variables in map but not in dict
957 are set to NULL in map; if clear is false, variables missing in
958 dict are ignored.
959
960 Exceptions raised while modifying the dict are silently ignored,
961 because there is no good way to report them.
962*/
963
Guido van Rossum6b356e72001-04-14 17:55:41 +0000964static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000965dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 Py_ssize_t j;
969 assert(PyTuple_Check(map));
970 assert(PyDict_Check(dict));
971 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800972 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 PyObject *key = PyTuple_GET_ITEM(map, j);
974 PyObject *value = PyObject_GetItem(dict, key);
975 assert(PyUnicode_Check(key));
976 /* We only care about NULLs if clear is true. */
977 if (value == NULL) {
978 PyErr_Clear();
979 if (!clear)
980 continue;
981 }
982 if (deref) {
983 assert(PyCell_Check(values[j]));
984 if (PyCell_GET(values[j]) != value) {
985 if (PyCell_Set(values[j], value) < 0)
986 PyErr_Clear();
987 }
988 } else if (values[j] != value) {
989 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300990 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 }
992 Py_XDECREF(value);
993 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000994}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000995
Victor Stinner41bb43a2013-10-29 01:19:37 +0100996int
997PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Merge fast locals into f->f_locals */
1000 PyObject *locals, *map;
1001 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyCodeObject *co;
1003 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001004 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001005
1006 if (f == NULL) {
1007 PyErr_BadInternalCall();
1008 return -1;
1009 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 locals = f->f_locals;
1011 if (locals == NULL) {
1012 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001013 if (locals == NULL)
1014 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 }
1016 co = f->f_code;
1017 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001018 if (!PyTuple_Check(map)) {
1019 PyErr_Format(PyExc_SystemError,
1020 "co_varnames must be a tuple, not %s",
1021 Py_TYPE(map)->tp_name);
1022 return -1;
1023 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 fast = f->f_localsplus;
1025 j = PyTuple_GET_SIZE(map);
1026 if (j > co->co_nlocals)
1027 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001028 if (co->co_nlocals) {
1029 if (map_to_dict(map, j, locals, fast, 0) < 0)
1030 return -1;
1031 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1033 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1034 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001035 if (map_to_dict(co->co_cellvars, ncells,
1036 locals, fast + co->co_nlocals, 1))
1037 return -1;
1038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 /* If the namespace is unoptimized, then one of the
1040 following cases applies:
1041 1. It does not contain free variables, because it
1042 uses import * or is a top-level namespace.
1043 2. It is a class namespace.
1044 We don't want to accidentally copy free variables
1045 into the locals dict used by the class.
1046 */
1047 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001048 if (map_to_dict(co->co_freevars, nfreevars,
1049 locals, fast + co->co_nlocals + ncells, 1) < 0)
1050 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 }
1052 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001053 return 0;
1054}
1055
1056void
1057PyFrame_FastToLocals(PyFrameObject *f)
1058{
1059 int res;
1060
1061 assert(!PyErr_Occurred());
1062
1063 res = PyFrame_FastToLocalsWithError(f);
1064 if (res < 0)
1065 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001066}
1067
1068void
Fred Drake1b190b42000-07-09 05:40:56 +00001069PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 /* Merge f->f_locals into fast locals */
1072 PyObject *locals, *map;
1073 PyObject **fast;
1074 PyObject *error_type, *error_value, *error_traceback;
1075 PyCodeObject *co;
1076 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001077 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (f == NULL)
1079 return;
1080 locals = f->f_locals;
1081 co = f->f_code;
1082 map = co->co_varnames;
1083 if (locals == NULL)
1084 return;
1085 if (!PyTuple_Check(map))
1086 return;
1087 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1088 fast = f->f_localsplus;
1089 j = PyTuple_GET_SIZE(map);
1090 if (j > co->co_nlocals)
1091 j = co->co_nlocals;
1092 if (co->co_nlocals)
1093 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1094 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1095 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1096 if (ncells || nfreevars) {
1097 dict_to_map(co->co_cellvars, ncells,
1098 locals, fast + co->co_nlocals, 1, clear);
1099 /* Same test as in PyFrame_FastToLocals() above. */
1100 if (co->co_flags & CO_OPTIMIZED) {
1101 dict_to_map(co->co_freevars, nfreevars,
1102 locals, fast + co->co_nlocals + ncells, 1,
1103 clear);
1104 }
1105 }
1106 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001107}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001108
1109/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001110void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001111_PyFrame_ClearFreeList(PyInterpreterState *interp)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001112{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001113 struct _Py_frame_state *state = &interp->frame;
Victor Stinner3744ed22020-06-05 01:39:24 +02001114 while (state->free_list != NULL) {
1115 PyFrameObject *f = state->free_list;
1116 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001118 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001120 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001121}
1122
1123void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001124_PyFrame_Fini(PyInterpreterState *interp)
Christian Heimesa156e092008-02-16 07:38:31 +00001125{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001126 _PyFrame_ClearFreeList(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001127#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001128 struct _Py_frame_state *state = &interp->frame;
Victor Stinnerbcb19832020-06-08 02:14:47 +02001129 state->numfree = -1;
1130#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001131}
David Malcolm49526f42012-06-22 14:55:41 -04001132
1133/* Print summary info about the state of the optimized allocator */
1134void
1135_PyFrame_DebugMallocStats(FILE *out)
1136{
Victor Stinner522691c2020-06-23 16:40:40 +02001137 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001138 _PyDebugAllocatorStats(out,
1139 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001140 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001141}
1142
Victor Stinnera42ca742020-04-28 19:01:31 +02001143
1144PyCodeObject *
1145PyFrame_GetCode(PyFrameObject *frame)
1146{
1147 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001148 PyCodeObject *code = frame->f_code;
1149 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001150 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001151 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001152}
Victor Stinner70364772020-04-29 03:28:46 +02001153
1154
1155PyFrameObject*
1156PyFrame_GetBack(PyFrameObject *frame)
1157{
1158 assert(frame != NULL);
1159 PyFrameObject *back = frame->f_back;
1160 Py_XINCREF(back);
1161 return back;
1162}
Mark Shannond6c33fb2021-01-29 13:24:55 +00001163
Victor Stinner44085a32021-02-18 19:20:16 +01001164PyObject*
Victor Stinner46496f92021-02-20 15:17:18 +01001165_PyEval_BuiltinsFromGlobals(PyThreadState *tstate, PyObject *globals)
Victor Stinner44085a32021-02-18 19:20:16 +01001166{
Mark Shannond6c33fb2021-01-29 13:24:55 +00001167 PyObject *builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
1168 if (builtins) {
1169 if (PyModule_Check(builtins)) {
1170 builtins = PyModule_GetDict(builtins);
1171 assert(builtins != NULL);
1172 }
Victor Stinner46496f92021-02-20 15:17:18 +01001173 return builtins;
Mark Shannond6c33fb2021-01-29 13:24:55 +00001174 }
Victor Stinner44085a32021-02-18 19:20:16 +01001175 if (PyErr_Occurred()) {
1176 return NULL;
1177 }
1178
Victor Stinner46496f92021-02-20 15:17:18 +01001179 return _PyEval_GetBuiltins(tstate);
Mark Shannond6c33fb2021-01-29 13:24:55 +00001180}