blob: 57105e1a9eb1e062a65956ea6ff06f06c5441cc5 [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 Stinnerbcda8f12018-11-21 22:27:47 +01004#include "pycore_object.h"
Victor Stinnere5014be2020-04-14 17:52:15 +02005#include "pycore_gc.h" // _PyObject_GC_IS_TRACKED()
Guido van Rossum3f5da241990-12-20 15:06:42 +00006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#include "frameobject.h"
9#include "opcode.h"
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},
19 {"f_lasti", T_INT, OFF(f_lasti), READONLY},
Nick Coghlan5a851672017-09-08 10:14:16 +100020 {"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
21 {"f_trace_opcodes", T_BOOL, OFF(f_trace_opcodes), 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000023};
24
Victor Stinner522691c2020-06-23 16:40:40 +020025static struct _Py_frame_state *
26get_frame_state(void)
27{
28 PyInterpreterState *interp = _PyInterpreterState_GET();
29 return &interp->frame;
30}
31
32
Guido van Rossum18752471997-04-29 14:49:28 +000033static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000034frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000035{
Victor Stinner41bb43a2013-10-29 01:19:37 +010036 if (PyFrame_FastToLocalsWithError(f) < 0)
37 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 Py_INCREF(f->f_locals);
39 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000040}
41
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000042int
43PyFrame_GetLineNumber(PyFrameObject *f)
44{
Victor Stinner7c59d7c2020-04-28 16:32:48 +020045 assert(f != NULL);
Mark Shannonee9f98d2021-01-05 12:04:10 +000046 if (f->f_lineno != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return f->f_lineno;
Victor Stinner7c59d7c2020-04-28 16:32:48 +020048 }
49 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Victor Stinner7c59d7c2020-04-28 16:32:48 +020051 }
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000052}
53
Michael W. Hudsondd32a912002-08-15 14:59:02 +000054static PyObject *
55frame_getlineno(PyFrameObject *f, void *closure)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000058}
59
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020060
61/* Given the index of the effective opcode,
62 scan back to construct the oparg with EXTENDED_ARG */
63static unsigned int
64get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
65{
66 _Py_CODEUNIT word;
67 unsigned int oparg = _Py_OPARG(codestr[i]);
68 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
69 oparg |= _Py_OPARG(word) << 8;
70 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
71 oparg |= _Py_OPARG(word) << 16;
72 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
73 oparg |= _Py_OPARG(word) << 24;
74 }
75 }
76 }
77 return oparg;
78}
79
Mark Shannon57697242020-04-29 16:49:45 +010080typedef enum kind {
81 With = 1,
82 Loop = 2,
83 Try = 3,
84 Except = 4,
85} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +000086
Mark Shannon57697242020-04-29 16:49:45 +010087#define BITS_PER_BLOCK 3
88
89static inline int64_t
90push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +000091{
Mark Shannon57697242020-04-29 16:49:45 +010092 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
93 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +000094}
95
Mark Shannon57697242020-04-29 16:49:45 +010096static inline int64_t
97pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +000098{
Mark Shannon57697242020-04-29 16:49:45 +010099 assert(stack > 0);
100 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +0000101}
102
Mark Shannon57697242020-04-29 16:49:45 +0100103static inline Kind
104top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000105{
Mark Shannon57697242020-04-29 16:49:45 +0100106 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +0000107}
108
Mark Shannon57697242020-04-29 16:49:45 +0100109static int64_t *
110markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000111{
Mark Shannon57697242020-04-29 16:49:45 +0100112 const _Py_CODEUNIT *code =
113 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
114 int64_t *blocks = PyMem_New(int64_t, len+1);
115 int i, j, opcode;
116
117 if (blocks == NULL) {
118 PyErr_NoMemory();
119 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000120 }
Mark Shannon57697242020-04-29 16:49:45 +0100121 memset(blocks, -1, (len+1)*sizeof(int64_t));
122 blocks[0] = 0;
123 int todo = 1;
124 while (todo) {
125 todo = 0;
126 for (i = 0; i < len; i++) {
127 int64_t block_stack = blocks[i];
128 int64_t except_stack;
129 if (block_stack == -1) {
130 continue;
131 }
132 opcode = _Py_OPCODE(code[i]);
133 switch (opcode) {
134 case JUMP_IF_FALSE_OR_POP:
135 case JUMP_IF_TRUE_OR_POP:
136 case POP_JUMP_IF_FALSE:
137 case POP_JUMP_IF_TRUE:
138 case JUMP_IF_NOT_EXC_MATCH:
139 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
140 assert(j < len);
141 if (blocks[j] == -1 && j < i) {
142 todo = 1;
143 }
144 assert(blocks[j] == -1 || blocks[j] == block_stack);
145 blocks[j] = block_stack;
146 blocks[i+1] = block_stack;
147 break;
148 case JUMP_ABSOLUTE:
149 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
150 assert(j < len);
151 if (blocks[j] == -1 && j < i) {
152 todo = 1;
153 }
154 assert(blocks[j] == -1 || blocks[j] == block_stack);
155 blocks[j] = block_stack;
156 break;
157 case SETUP_FINALLY:
158 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
159 assert(j < len);
160 except_stack = push_block(block_stack, Except);
161 assert(blocks[j] == -1 || blocks[j] == except_stack);
162 blocks[j] = except_stack;
163 block_stack = push_block(block_stack, Try);
164 blocks[i+1] = block_stack;
165 break;
166 case SETUP_WITH:
167 case SETUP_ASYNC_WITH:
168 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
169 assert(j < len);
170 except_stack = push_block(block_stack, Except);
171 assert(blocks[j] == -1 || blocks[j] == except_stack);
172 blocks[j] = except_stack;
173 block_stack = push_block(block_stack, With);
174 blocks[i+1] = block_stack;
175 break;
176 case JUMP_FORWARD:
177 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
178 assert(j < len);
179 assert(blocks[j] == -1 || blocks[j] == block_stack);
180 blocks[j] = block_stack;
181 break;
182 case GET_ITER:
183 case GET_AITER:
184 block_stack = push_block(block_stack, Loop);
185 blocks[i+1] = block_stack;
186 break;
187 case FOR_ITER:
188 blocks[i+1] = block_stack;
189 block_stack = pop_block(block_stack);
190 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
191 assert(j < len);
192 assert(blocks[j] == -1 || blocks[j] == block_stack);
193 blocks[j] = block_stack;
194 break;
195 case POP_BLOCK:
196 case POP_EXCEPT:
197 block_stack = pop_block(block_stack);
198 blocks[i+1] = block_stack;
199 break;
200 case END_ASYNC_FOR:
201 block_stack = pop_block(pop_block(block_stack));
202 blocks[i+1] = block_stack;
203 break;
204 case RETURN_VALUE:
205 case RAISE_VARARGS:
206 case RERAISE:
207 /* End of block */
208 break;
209 default:
210 blocks[i+1] = block_stack;
211
212 }
213 }
214 }
215 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000216}
217
218static int
Mark Shannon57697242020-04-29 16:49:45 +0100219compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000220{
Mark Shannon57697242020-04-29 16:49:45 +0100221 if (to_stack < 0) {
222 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000223 }
Mark Shannon57697242020-04-29 16:49:45 +0100224 while(from_stack > to_stack) {
225 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000226 }
Mark Shannon57697242020-04-29 16:49:45 +0100227 return from_stack == to_stack;
228}
229
230static const char *
231explain_incompatible_block_stack(int64_t to_stack)
232{
233 Kind target_kind = top_block(to_stack);
234 switch(target_kind) {
235 case Except:
236 return "can't jump into an 'except' block as there's no exception";
237 case Try:
238 return "can't jump into the body of a try statement";
239 case With:
240 return "can't jump into the body of a with statement";
241 case Loop:
242 return "can't jump into the body of a for loop";
243 default:
244 Py_UNREACHABLE();
245 }
246}
247
248static int *
249marklines(PyCodeObject *code, int len)
250{
Mark Shannon877df852020-11-12 09:43:29 +0000251 PyCodeAddressRange bounds;
252 _PyCode_InitAddressRange(code, &bounds);
253 assert (bounds.ar_end == 0);
254
Mark Shannon57697242020-04-29 16:49:45 +0100255 int *linestarts = PyMem_New(int, len);
256 if (linestarts == NULL) {
257 return NULL;
258 }
Mark Shannon877df852020-11-12 09:43:29 +0000259 for (int i = 0; i < len; i++) {
260 linestarts[i] = -1;
Mark Shannon57697242020-04-29 16:49:45 +0100261 }
Mark Shannon877df852020-11-12 09:43:29 +0000262
263 while (PyLineTable_NextAddressRange(&bounds)) {
264 assert(bounds.ar_start/2 < len);
265 linestarts[bounds.ar_start/2] = bounds.ar_line;
Mark Shannon57697242020-04-29 16:49:45 +0100266 }
Mark Shannon57697242020-04-29 16:49:45 +0100267 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000268}
269
270static int
Mark Shannon57697242020-04-29 16:49:45 +0100271first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000272{
273 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100274 for (int i = 0; i < len; i++) {
275 if (lines[i] < result && lines[i] >= line) {
276 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000277 }
Mark Shannonfee55262019-11-21 09:11:43 +0000278 }
279 if (result == INT_MAX) {
280 return -1;
281 }
282 return result;
283}
284
Mark Shannonfee55262019-11-21 09:11:43 +0000285static void
286frame_stack_pop(PyFrameObject *f)
287{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100288 assert(f->f_stackdepth >= 0);
289 f->f_stackdepth--;
290 PyObject *v = f->f_valuestack[f->f_stackdepth];
Mark Shannonfee55262019-11-21 09:11:43 +0000291 Py_DECREF(v);
292}
293
294static void
295frame_block_unwind(PyFrameObject *f)
296{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100297 assert(f->f_stackdepth >= 0);
Mark Shannonfee55262019-11-21 09:11:43 +0000298 assert(f->f_iblock > 0);
299 f->f_iblock--;
300 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Mark Shannoncb9879b2020-07-17 11:44:23 +0100301 intptr_t delta = f->f_stackdepth - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000302 while (delta > 0) {
303 frame_stack_pop(f);
304 delta--;
305 }
306}
307
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200308
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000309/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000311 * lines are OK to jump to because they don't make any assumptions about the
312 * state of the stack (obvious because you could remove the line and the code
313 * would still work without any stack errors), but there are some constructs
314 * that limit jumping:
315 *
316 * o Lines with an 'except' statement on them can't be jumped to, because
317 * they expect an exception to be on the top of the stack.
318 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000319 * we cannot be sure which state the interpreter was in or would be in
320 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200321 * o 'try', 'with' and 'async with' blocks can't be jumped into because
322 * the blockstack needs to be set up before their code runs.
323 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000324 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100325 * o Jumps cannot be made from within a trace function invoked with a
326 * 'return' or 'exception' event since the eval loop has been exited at
327 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000328 */
329static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200330frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000331{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700332 if (p_new_lineno == NULL) {
333 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
334 return -1;
335 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* f_lineno must be an integer. */
337 if (!PyLong_CheckExact(p_new_lineno)) {
338 PyErr_SetString(PyExc_ValueError,
339 "lineno must be an integer");
340 return -1;
341 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000342
Mark Shannoncb9879b2020-07-17 11:44:23 +0100343 /*
344 * This code preserves the historical restrictions on
345 * setting the line number of a frame.
346 * Jumps are forbidden on a 'return' trace event (except after a yield).
347 * Jumps from 'call' trace events are also forbidden.
348 * In addition, jumps are forbidden when not tracing,
349 * as this is a debugging feature.
350 */
351 switch(f->f_state) {
352 case FRAME_CREATED:
353 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100354 "can't jump from the 'call' trace event of a new frame");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100355 return -1;
356 case FRAME_RETURNED:
357 case FRAME_UNWINDING:
358 case FRAME_RAISED:
359 case FRAME_CLEARED:
360 PyErr_SetString(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100361 "can only jump from a 'line' trace event");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100362 return -1;
363 case FRAME_EXECUTING:
364 case FRAME_SUSPENDED:
365 /* You can only do this from within a trace function, not via
366 * _getframe or similar hackery. */
367 if (!f->f_trace) {
368 PyErr_Format(PyExc_ValueError,
369 "f_lineno can only be set by a trace function");
370 return -1;
371 }
372 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000374
Mark Shannonfee55262019-11-21 09:11:43 +0000375 int new_lineno;
376
Mark Shannon57697242020-04-29 16:49:45 +0100377 /* Fail if the line falls outside the code block and
378 select first line with actual code. */
379 int overflow;
380 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
381 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000382#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100383 || l_new_lineno > INT_MAX
384 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000385#endif
Mark Shannon57697242020-04-29 16:49:45 +0100386 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000387 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100388 "lineno out of range");
389 return -1;
390 }
391 new_lineno = (int)l_new_lineno;
392
393 if (new_lineno < f->f_code->co_firstlineno) {
394 PyErr_Format(PyExc_ValueError,
395 "line %d comes before the current code block",
396 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 return -1;
398 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000399
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000400 /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
401 * should never overflow. */
402 int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT));
Mark Shannon57697242020-04-29 16:49:45 +0100403 int *lines = marklines(f->f_code, len);
404 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return -1;
406 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000407
Mark Shannon57697242020-04-29 16:49:45 +0100408 new_lineno = first_line_not_before(lines, len, new_lineno);
409 if (new_lineno < 0) {
410 PyErr_Format(PyExc_ValueError,
411 "line %d comes after the current code block",
412 (int)l_new_lineno);
413 PyMem_Free(lines);
414 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000415 }
416
Mark Shannon57697242020-04-29 16:49:45 +0100417 int64_t *blocks = markblocks(f->f_code, len);
418 if (blocks == NULL) {
419 PyMem_Free(lines);
420 return -1;
421 }
422
423 int64_t target_block_stack = -1;
424 int64_t best_block_stack = -1;
425 int best_addr = -1;
426 int64_t start_block_stack = blocks[f->f_lasti/sizeof(_Py_CODEUNIT)];
427 const char *msg = "cannot find bytecode for specified line";
428 for (int i = 0; i < len; i++) {
429 if (lines[i] == new_lineno) {
430 target_block_stack = blocks[i];
431 if (compatible_block_stack(start_block_stack, target_block_stack)) {
432 msg = NULL;
433 if (target_block_stack > best_block_stack) {
434 best_block_stack = target_block_stack;
435 best_addr = i*sizeof(_Py_CODEUNIT);
436 }
437 }
438 else if (msg) {
439 if (target_block_stack >= 0) {
440 msg = explain_incompatible_block_stack(target_block_stack);
441 }
442 else {
443 msg = "code may be unreachable.";
444 }
445 }
Mark Shannonfee55262019-11-21 09:11:43 +0000446 }
447 }
Mark Shannon57697242020-04-29 16:49:45 +0100448 PyMem_Free(blocks);
449 PyMem_Free(lines);
450 if (msg != NULL) {
451 PyErr_SetString(PyExc_ValueError, msg);
452 return -1;
453 }
Mark Shannonfee55262019-11-21 09:11:43 +0000454
455 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100456 while (start_block_stack > best_block_stack) {
457 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000458 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100459 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000460 frame_stack_pop(f);
461 break;
Mark Shannon57697242020-04-29 16:49:45 +0100462 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000463 frame_block_unwind(f);
464 break;
Mark Shannon57697242020-04-29 16:49:45 +0100465 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000466 frame_block_unwind(f);
467 // Pop the exit function
468 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 break;
Mark Shannon57697242020-04-29 16:49:45 +0100470 case Except:
471 PyErr_SetString(PyExc_ValueError,
472 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000473 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 }
Mark Shannon57697242020-04-29 16:49:45 +0100475 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 }
Mark Shannonfee55262019-11-21 09:11:43 +0000477
Mark Shannonee9f98d2021-01-05 12:04:10 +0000478 /* Finally set the new f_lasti and return OK. */
479 f->f_lineno = 0;
Mark Shannon57697242020-04-29 16:49:45 +0100480 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000482}
483
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000484static PyObject *
485frame_gettrace(PyFrameObject *f, void *closure)
486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (trace == NULL)
490 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000495}
496
497static int
498frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
499{
Mark Shannonee9f98d2021-01-05 12:04:10 +0000500 if (v == Py_None) {
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300501 v = NULL;
Mark Shannonee9f98d2021-01-05 12:04:10 +0000502 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300504 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000507}
508
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000509
Guido van Rossum32d34c82001-09-20 21:45:26 +0000510static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 {"f_locals", (getter)frame_getlocals, NULL, NULL},
512 {"f_lineno", (getter)frame_getlineno,
513 (setter)frame_setlineno, NULL},
514 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
515 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000516};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000517
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000518/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000519 In an attempt to improve the speed of function calls, we:
520
521 1. Hold a single "zombie" frame on each code object. This retains
522 the allocated and initialised frame object from an invocation of
523 the code object. The zombie is reanimated the next time we need a
524 frame object for that code object. Doing this saves the malloc/
525 realloc required when using a free_list frame that isn't the
526 correct size. It also saves some field initialisation.
527
528 In zombie mode, no field of PyFrameObject holds a reference, but
529 the following fields are still valid:
530
531 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532
Mark Shannonae3087c2017-10-22 22:41:51 +0100533 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534
535 * f_localsplus does not require re-allocation and
536 the local variables in f_localsplus are NULL.
537
538 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000539 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 a stack frame is on the free list, only the following members have
541 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 ob_type == &Frametype
543 f_back next item on free list, or NULL
544 f_stacksize size of value stack
545 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000546 Note that the value and block stacks are preserved -- this can save
547 another malloc() call or two (and two free() calls as well!).
548 Also note that, unlike for integers, each frame object is a
549 malloc'ed object in its own right -- it is only the actual calls to
550 malloc() that we are trying to save here, not the administration.
551 After all, while a typical program may make millions of calls, a
552 call depth of more than 20 or 30 is probably already exceptional
553 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000554
Christian Heimes2202f872008-02-06 14:31:34 +0000555 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000556 free_list. Else programs creating lots of cyclic trash involving
557 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000558*/
Christian Heimes2202f872008-02-06 14:31:34 +0000559/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000561
Victor Stinnerc6944e72016-11-11 02:13:35 +0100562static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000563frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000564{
Victor Stinner3744ed22020-06-05 01:39:24 +0200565 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900566 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200567 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200570 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200571 PyObject **valuestack = f->f_valuestack;
572 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200573 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200574 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200575
576 /* Free stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100577 for (int i = 0; i < f->f_stackdepth; i++) {
578 Py_XDECREF(f->f_valuestack[i]);
Antoine Pitrou93963562013-05-14 20:37:52 +0200579 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100580 f->f_stackdepth = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 Py_XDECREF(f->f_back);
583 Py_DECREF(f->f_builtins);
584 Py_DECREF(f->f_globals);
585 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200586 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587
Victor Stinner3744ed22020-06-05 01:39:24 +0200588 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200589 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200591 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200592 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200593 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200594#ifdef Py_DEBUG
595 // frame_dealloc() must not be called after _PyFrame_Fini()
596 assert(state->numfree != -1);
597#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200598 if (state->numfree < PyFrame_MAXFREELIST) {
599 ++state->numfree;
600 f->f_back = state->free_list;
601 state->free_list = f;
602 }
603 else {
604 PyObject_GC_Del(f);
605 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200606 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 Py_DECREF(co);
609 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000610}
611
Victor Stinner6d86a232020-04-29 00:56:58 +0200612static inline Py_ssize_t
613frame_nslots(PyFrameObject *frame)
614{
615 PyCodeObject *code = frame->f_code;
616 return (code->co_nlocals
617 + PyTuple_GET_SIZE(code->co_cellvars)
618 + PyTuple_GET_SIZE(code->co_freevars));
619}
620
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000621static int
622frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 Py_VISIT(f->f_back);
625 Py_VISIT(f->f_code);
626 Py_VISIT(f->f_builtins);
627 Py_VISIT(f->f_globals);
628 Py_VISIT(f->f_locals);
629 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200632 PyObject **fastlocals = f->f_localsplus;
633 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200635 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100638 for (int i = 0; i < f->f_stackdepth; i++) {
639 Py_VISIT(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 }
641 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000642}
643
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200644static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200645frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000646{
Antoine Pitrou93963562013-05-14 20:37:52 +0200647 /* Before anything else, make sure that this frame is clearly marked
648 * as being defunct! Else, e.g., a generator reachable from this
649 * frame may also point to this frame, believe itself to still be
650 * active, and try cleaning up this frame again.
651 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100652 f->f_state = FRAME_CLEARED;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200657 PyObject **fastlocals = f->f_localsplus;
658 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200660 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100663 for (int i = 0; i < f->f_stackdepth; i++) {
664 Py_CLEAR(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100666 f->f_stackdepth = 0;
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200667 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000668}
669
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000670static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530671frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200672{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100673 if (_PyFrame_IsExecuting(f)) {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200674 PyErr_SetString(PyExc_RuntimeError,
675 "cannot clear an executing frame");
676 return NULL;
677 }
678 if (f->f_gen) {
679 _PyGen_Finalize(f->f_gen);
680 assert(f->f_gen == NULL);
681 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200682 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200683 Py_RETURN_NONE;
684}
685
686PyDoc_STRVAR(clear__doc__,
687"F.clear(): clear most references held by the frame");
688
689static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530690frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000693
Victor Stinner6d86a232020-04-29 00:56:58 +0200694 PyCodeObject *code = f->f_code;
695 ncells = PyTuple_GET_SIZE(code->co_cellvars);
696 nfrees = PyTuple_GET_SIZE(code->co_freevars);
697 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 /* subtract one as it is already included in PyFrameObject */
699 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000702}
703
704PyDoc_STRVAR(sizeof__doc__,
705"F.__sizeof__() -> size of F in memory, in bytes");
706
Antoine Pitrou14709142017-12-31 22:35:22 +0100707static PyObject *
708frame_repr(PyFrameObject *f)
709{
710 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200711 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100712 return PyUnicode_FromFormat(
713 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200714 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100715}
716
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000717static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200718 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
719 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
721 sizeof__doc__},
722 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000723};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000724
Guido van Rossum18752471997-04-29 14:49:28 +0000725PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyVarObject_HEAD_INIT(&PyType_Type, 0)
727 "frame",
728 sizeof(PyFrameObject),
729 sizeof(PyObject *),
730 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200731 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 0, /* tp_getattr */
733 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200734 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100735 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 0, /* tp_as_number */
737 0, /* tp_as_sequence */
738 0, /* tp_as_mapping */
739 0, /* tp_hash */
740 0, /* tp_call */
741 0, /* tp_str */
742 PyObject_GenericGetAttr, /* tp_getattro */
743 PyObject_GenericSetAttr, /* tp_setattro */
744 0, /* tp_as_buffer */
745 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
746 0, /* tp_doc */
747 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200748 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 0, /* tp_richcompare */
750 0, /* tp_weaklistoffset */
751 0, /* tp_iter */
752 0, /* tp_iternext */
753 frame_methods, /* tp_methods */
754 frame_memberlist, /* tp_members */
755 frame_getsetlist, /* tp_getset */
756 0, /* tp_base */
757 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000758};
759
Victor Stinner07e9e382013-11-07 22:22:39 +0100760_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000761
Victor Stinnerb4b53862020-05-05 19:55:29 +0200762static inline PyFrameObject*
763frame_alloc(PyCodeObject *code)
764{
765 PyFrameObject *f;
766
767 f = code->co_zombieframe;
768 if (f != NULL) {
769 code->co_zombieframe = NULL;
770 _Py_NewReference((PyObject *)f);
771 assert(f->f_code == code);
772 return f;
773 }
774
775 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
776 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
777 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200778 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200779 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200780 {
781 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
782 if (f == NULL) {
783 return NULL;
784 }
785 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200786 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200787#ifdef Py_DEBUG
788 // frame_alloc() must not be called after _PyFrame_Fini()
789 assert(state->numfree != -1);
790#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200791 assert(state->numfree > 0);
792 --state->numfree;
793 f = state->free_list;
794 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200795 if (Py_SIZE(f) < extras) {
796 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
797 if (new_f == NULL) {
798 PyObject_GC_Del(f);
799 return NULL;
800 }
801 f = new_f;
802 }
803 _Py_NewReference((PyObject *)f);
804 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200805
806 f->f_code = code;
807 extras = code->co_nlocals + ncells + nfrees;
808 f->f_valuestack = f->f_localsplus + extras;
809 for (Py_ssize_t i=0; i<extras; i++) {
810 f->f_localsplus[i] = NULL;
811 }
812 f->f_locals = NULL;
813 f->f_trace = NULL;
814 return f;
815}
816
817
Victor Stinnerc6944e72016-11-11 02:13:35 +0100818PyFrameObject* _Py_HOT_FUNCTION
Mark Shannon0332e562021-02-01 10:42:03 +0000819_PyFrame_New_NoTrack(PyThreadState *tstate, PyFrameConstructor *con, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000820{
Michael W. Hudson69734a52002-08-19 16:54:08 +0000821#ifdef Py_DEBUG
Mark Shannon0332e562021-02-01 10:42:03 +0000822 if (con == NULL || con->fc_code == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 (locals != NULL && !PyMapping_Check(locals))) {
824 PyErr_BadInternalCall();
825 return NULL;
826 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000827#endif
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000828
Victor Stinnerb4b53862020-05-05 19:55:29 +0200829 PyFrameObject *back = tstate->frame;
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
Mark Shannoncb9879b2020-07-17 11:44:23 +0100836 f->f_stackdepth = 0;
Mark Shannon0332e562021-02-01 10:42:03 +0000837 Py_INCREF(con->fc_builtins);
838 f->f_builtins = con->fc_builtins;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 Py_XINCREF(back);
840 f->f_back = back;
Mark Shannon0332e562021-02-01 10:42:03 +0000841 Py_INCREF(con->fc_code);
842 Py_INCREF(con->fc_globals);
843 f->f_globals = con->fc_globals;
844 Py_XINCREF(locals);
845 f->f_locals = locals;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000846
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;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200851 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000852 f->f_trace_opcodes = 0;
853 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000854
Victor Stinner6d86a232020-04-29 00:56:58 +0200855 assert(f->f_code != NULL);
856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000858}
859
Mark Shannon0332e562021-02-01 10:42:03 +0000860/* Legacy API */
INADA Naoki5a625d02016-12-24 20:19:08 +0900861PyFrameObject*
862PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
863 PyObject *globals, PyObject *locals)
864{
Mark Shannond6c33fb2021-01-29 13:24:55 +0000865 PyObject *builtins = _PyEval_BuiltinsFromGlobals(globals);
Mark Shannon0332e562021-02-01 10:42:03 +0000866 PyFrameConstructor desc = {
867 .fc_globals = globals,
868 .fc_builtins = builtins,
869 .fc_name = code->co_name,
870 .fc_qualname = code->co_name,
871 .fc_code = (PyObject *)code,
872 .fc_defaults = NULL,
873 .fc_kwdefaults = NULL,
874 .fc_closure = NULL
875 };
876 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, &desc, locals);
Mark Shannond6c33fb2021-01-29 13:24:55 +0000877 Py_DECREF(builtins);
INADA Naoki5a625d02016-12-24 20:19:08 +0900878 if (f)
879 _PyObject_GC_TRACK(f);
880 return f;
881}
882
883
Guido van Rossum3f5da241990-12-20 15:06:42 +0000884/* Block management */
885
886void
Fred Drake1b190b42000-07-09 05:40:56 +0000887PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100890 if (f->f_iblock >= CO_MAXBLOCKS) {
891 Py_FatalError("block stack overflow");
892 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 b = &f->f_blockstack[f->f_iblock++];
894 b->b_type = type;
895 b->b_level = level;
896 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000897}
898
Guido van Rossum18752471997-04-29 14:49:28 +0000899PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000900PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100903 if (f->f_iblock <= 0) {
904 Py_FatalError("block stack underflow");
905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 b = &f->f_blockstack[--f->f_iblock];
907 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000908}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000909
Guido van Rossumd8faa362007-04-27 19:54:29 +0000910/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911
912 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000913 values is an array of PyObject*. At index i, map[i] is the name of
914 the variable with value values[i]. The function copies the first
915 nmap variable from map/values into dict. If values[i] is NULL,
916 the variable is deleted from dict.
917
918 If deref is true, then the values being copied are cell variables
919 and the value is extracted from the cell variable before being put
920 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000921 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000922
Victor Stinner41bb43a2013-10-29 01:19:37 +0100923static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000924map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 Py_ssize_t j;
928 assert(PyTuple_Check(map));
929 assert(PyDict_Check(dict));
930 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800931 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyObject *key = PyTuple_GET_ITEM(map, j);
933 PyObject *value = values[j];
934 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400935 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 assert(PyCell_Check(value));
937 value = PyCell_GET(value);
938 }
939 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100940 if (PyObject_DelItem(dict, key) != 0) {
941 if (PyErr_ExceptionMatches(PyExc_KeyError))
942 PyErr_Clear();
943 else
944 return -1;
945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 }
947 else {
948 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100949 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 }
951 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100952 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000953}
954
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955/* Copy values from the "locals" dict into the fast locals.
956
957 dict is an input argument containing string keys representing
958 variables names and arbitrary PyObject* as values.
959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000961 values is an array of PyObject*. At index i, map[i] is the name of
962 the variable with value values[i]. The function copies the first
963 nmap variable from map/values into dict. If values[i] is NULL,
964 the variable is deleted from dict.
965
966 If deref is true, then the values being copied are cell variables
967 and the value is extracted from the cell variable before being put
968 in dict. If clear is true, then variables in map but not in dict
969 are set to NULL in map; if clear is false, variables missing in
970 dict are ignored.
971
972 Exceptions raised while modifying the dict are silently ignored,
973 because there is no good way to report them.
974*/
975
Guido van Rossum6b356e72001-04-14 17:55:41 +0000976static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000977dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 Py_ssize_t j;
981 assert(PyTuple_Check(map));
982 assert(PyDict_Check(dict));
983 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800984 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject *key = PyTuple_GET_ITEM(map, j);
986 PyObject *value = PyObject_GetItem(dict, key);
987 assert(PyUnicode_Check(key));
988 /* We only care about NULLs if clear is true. */
989 if (value == NULL) {
990 PyErr_Clear();
991 if (!clear)
992 continue;
993 }
994 if (deref) {
995 assert(PyCell_Check(values[j]));
996 if (PyCell_GET(values[j]) != value) {
997 if (PyCell_Set(values[j], value) < 0)
998 PyErr_Clear();
999 }
1000 } else if (values[j] != value) {
1001 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001002 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 }
1004 Py_XDECREF(value);
1005 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001006}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001007
Victor Stinner41bb43a2013-10-29 01:19:37 +01001008int
1009PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 /* Merge fast locals into f->f_locals */
1012 PyObject *locals, *map;
1013 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PyCodeObject *co;
1015 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001016 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001017
1018 if (f == NULL) {
1019 PyErr_BadInternalCall();
1020 return -1;
1021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 locals = f->f_locals;
1023 if (locals == NULL) {
1024 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001025 if (locals == NULL)
1026 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 }
1028 co = f->f_code;
1029 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001030 if (!PyTuple_Check(map)) {
1031 PyErr_Format(PyExc_SystemError,
1032 "co_varnames must be a tuple, not %s",
1033 Py_TYPE(map)->tp_name);
1034 return -1;
1035 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 fast = f->f_localsplus;
1037 j = PyTuple_GET_SIZE(map);
1038 if (j > co->co_nlocals)
1039 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001040 if (co->co_nlocals) {
1041 if (map_to_dict(map, j, locals, fast, 0) < 0)
1042 return -1;
1043 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1045 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1046 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001047 if (map_to_dict(co->co_cellvars, ncells,
1048 locals, fast + co->co_nlocals, 1))
1049 return -1;
1050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 /* If the namespace is unoptimized, then one of the
1052 following cases applies:
1053 1. It does not contain free variables, because it
1054 uses import * or is a top-level namespace.
1055 2. It is a class namespace.
1056 We don't want to accidentally copy free variables
1057 into the locals dict used by the class.
1058 */
1059 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001060 if (map_to_dict(co->co_freevars, nfreevars,
1061 locals, fast + co->co_nlocals + ncells, 1) < 0)
1062 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 }
1064 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001065 return 0;
1066}
1067
1068void
1069PyFrame_FastToLocals(PyFrameObject *f)
1070{
1071 int res;
1072
1073 assert(!PyErr_Occurred());
1074
1075 res = PyFrame_FastToLocalsWithError(f);
1076 if (res < 0)
1077 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001078}
1079
1080void
Fred Drake1b190b42000-07-09 05:40:56 +00001081PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 /* Merge f->f_locals into fast locals */
1084 PyObject *locals, *map;
1085 PyObject **fast;
1086 PyObject *error_type, *error_value, *error_traceback;
1087 PyCodeObject *co;
1088 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001089 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 if (f == NULL)
1091 return;
1092 locals = f->f_locals;
1093 co = f->f_code;
1094 map = co->co_varnames;
1095 if (locals == NULL)
1096 return;
1097 if (!PyTuple_Check(map))
1098 return;
1099 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1100 fast = f->f_localsplus;
1101 j = PyTuple_GET_SIZE(map);
1102 if (j > co->co_nlocals)
1103 j = co->co_nlocals;
1104 if (co->co_nlocals)
1105 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1106 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1107 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1108 if (ncells || nfreevars) {
1109 dict_to_map(co->co_cellvars, ncells,
1110 locals, fast + co->co_nlocals, 1, clear);
1111 /* Same test as in PyFrame_FastToLocals() above. */
1112 if (co->co_flags & CO_OPTIMIZED) {
1113 dict_to_map(co->co_freevars, nfreevars,
1114 locals, fast + co->co_nlocals + ncells, 1,
1115 clear);
1116 }
1117 }
1118 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001119}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001120
1121/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001122void
Victor Stinner3744ed22020-06-05 01:39:24 +02001123_PyFrame_ClearFreeList(PyThreadState *tstate)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001124{
Victor Stinner3744ed22020-06-05 01:39:24 +02001125 struct _Py_frame_state *state = &tstate->interp->frame;
1126 while (state->free_list != NULL) {
1127 PyFrameObject *f = state->free_list;
1128 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001130 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001132 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001133}
1134
1135void
Victor Stinner3744ed22020-06-05 01:39:24 +02001136_PyFrame_Fini(PyThreadState *tstate)
Christian Heimesa156e092008-02-16 07:38:31 +00001137{
Victor Stinner3744ed22020-06-05 01:39:24 +02001138 _PyFrame_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001139#ifdef Py_DEBUG
1140 struct _Py_frame_state *state = &tstate->interp->frame;
1141 state->numfree = -1;
1142#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001143}
David Malcolm49526f42012-06-22 14:55:41 -04001144
1145/* Print summary info about the state of the optimized allocator */
1146void
1147_PyFrame_DebugMallocStats(FILE *out)
1148{
Victor Stinner522691c2020-06-23 16:40:40 +02001149 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001150 _PyDebugAllocatorStats(out,
1151 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001152 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001153}
1154
Victor Stinnera42ca742020-04-28 19:01:31 +02001155
1156PyCodeObject *
1157PyFrame_GetCode(PyFrameObject *frame)
1158{
1159 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001160 PyCodeObject *code = frame->f_code;
1161 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001162 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001163 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001164}
Victor Stinner70364772020-04-29 03:28:46 +02001165
1166
1167PyFrameObject*
1168PyFrame_GetBack(PyFrameObject *frame)
1169{
1170 assert(frame != NULL);
1171 PyFrameObject *back = frame->f_back;
1172 Py_XINCREF(back);
1173 return back;
1174}
Mark Shannond6c33fb2021-01-29 13:24:55 +00001175
1176PyObject *_PyEval_BuiltinsFromGlobals(PyObject *globals) {
1177 PyObject *builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
1178 if (builtins) {
1179 if (PyModule_Check(builtins)) {
1180 builtins = PyModule_GetDict(builtins);
1181 assert(builtins != NULL);
1182 }
1183 }
1184 if (builtins == NULL) {
1185 if (PyErr_Occurred()) {
1186 return NULL;
1187 }
1188 /* No builtins! Make up a minimal one
1189 Give them 'None', at least. */
1190 builtins = PyDict_New();
1191 if (builtins == NULL ||
1192 PyDict_SetItemString(
1193 builtins, "None", Py_None) < 0)
1194 return NULL;
1195 }
1196 else
1197 Py_INCREF(builtins);
1198 return builtins;
1199}