blob: 45a275bd901240f77e22ff138bf7ffa1f0642803 [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
INADA Naoki5a625d02016-12-24 20:19:08 +0900819_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
Mark Shannond6c33fb2021-01-29 13:24:55 +0000820 PyObject *globals, PyObject *builtins, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000821{
Michael W. Hudson69734a52002-08-19 16:54:08 +0000822#ifdef Py_DEBUG
Mark Shannond6c33fb2021-01-29 13:24:55 +0000823 if (code == NULL || globals == NULL || builtins == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 (locals != NULL && !PyMapping_Check(locals))) {
825 PyErr_BadInternalCall();
826 return NULL;
827 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000828#endif
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000829
Victor Stinnerb4b53862020-05-05 19:55:29 +0200830 PyFrameObject *back = tstate->frame;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000831
Victor Stinnerb4b53862020-05-05 19:55:29 +0200832 PyFrameObject *f = frame_alloc(code);
833 if (f == NULL) {
Victor Stinnerb4b53862020-05-05 19:55:29 +0200834 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200836
Mark Shannoncb9879b2020-07-17 11:44:23 +0100837 f->f_stackdepth = 0;
Mark Shannond6c33fb2021-01-29 13:24:55 +0000838 Py_INCREF(builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 f->f_builtins = builtins;
840 Py_XINCREF(back);
841 f->f_back = back;
842 Py_INCREF(code);
843 Py_INCREF(globals);
844 f->f_globals = globals;
845 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
846 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
847 (CO_NEWLOCALS | CO_OPTIMIZED))
848 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
849 else if (code->co_flags & CO_NEWLOCALS) {
850 locals = PyDict_New();
851 if (locals == NULL) {
852 Py_DECREF(f);
853 return NULL;
854 }
855 f->f_locals = locals;
856 }
857 else {
Mark Shannond6c33fb2021-01-29 13:24:55 +0000858 if (locals == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 locals = globals;
Mark Shannond6c33fb2021-01-29 13:24:55 +0000860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 Py_INCREF(locals);
862 f->f_locals = locals;
863 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 f->f_lasti = -1;
Mark Shannon877df852020-11-12 09:43:29 +0000866 f->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 f->f_iblock = 0;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100868 f->f_state = FRAME_CREATED;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200869 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000870 f->f_trace_opcodes = 0;
871 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000872
Victor Stinner6d86a232020-04-29 00:56:58 +0200873 assert(f->f_code != NULL);
874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000876}
877
INADA Naoki5a625d02016-12-24 20:19:08 +0900878PyFrameObject*
879PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
880 PyObject *globals, PyObject *locals)
881{
Mark Shannond6c33fb2021-01-29 13:24:55 +0000882 PyObject *builtins = _PyEval_BuiltinsFromGlobals(globals);
883 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, builtins, locals);
884 Py_DECREF(builtins);
INADA Naoki5a625d02016-12-24 20:19:08 +0900885 if (f)
886 _PyObject_GC_TRACK(f);
887 return f;
888}
889
890
Guido van Rossum3f5da241990-12-20 15:06:42 +0000891/* Block management */
892
893void
Fred Drake1b190b42000-07-09 05:40:56 +0000894PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100897 if (f->f_iblock >= CO_MAXBLOCKS) {
898 Py_FatalError("block stack overflow");
899 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 b = &f->f_blockstack[f->f_iblock++];
901 b->b_type = type;
902 b->b_level = level;
903 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000904}
905
Guido van Rossum18752471997-04-29 14:49:28 +0000906PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000907PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100910 if (f->f_iblock <= 0) {
911 Py_FatalError("block stack underflow");
912 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 b = &f->f_blockstack[--f->f_iblock];
914 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000915}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000916
Guido van Rossumd8faa362007-04-27 19:54:29 +0000917/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918
919 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920 values is an array of PyObject*. At index i, map[i] is the name of
921 the variable with value values[i]. The function copies the first
922 nmap variable from map/values into dict. If values[i] is NULL,
923 the variable is deleted from dict.
924
925 If deref is true, then the values being copied are cell variables
926 and the value is extracted from the cell variable before being put
927 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000929
Victor Stinner41bb43a2013-10-29 01:19:37 +0100930static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000931map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 Py_ssize_t j;
935 assert(PyTuple_Check(map));
936 assert(PyDict_Check(dict));
937 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800938 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject *key = PyTuple_GET_ITEM(map, j);
940 PyObject *value = values[j];
941 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400942 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 assert(PyCell_Check(value));
944 value = PyCell_GET(value);
945 }
946 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100947 if (PyObject_DelItem(dict, key) != 0) {
948 if (PyErr_ExceptionMatches(PyExc_KeyError))
949 PyErr_Clear();
950 else
951 return -1;
952 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 }
954 else {
955 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100956 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 }
958 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100959 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000960}
961
Guido van Rossumd8faa362007-04-27 19:54:29 +0000962/* Copy values from the "locals" dict into the fast locals.
963
964 dict is an input argument containing string keys representing
965 variables names and arbitrary PyObject* as values.
966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968 values is an array of PyObject*. At index i, map[i] is the name of
969 the variable with value values[i]. The function copies the first
970 nmap variable from map/values into dict. If values[i] is NULL,
971 the variable is deleted from dict.
972
973 If deref is true, then the values being copied are cell variables
974 and the value is extracted from the cell variable before being put
975 in dict. If clear is true, then variables in map but not in dict
976 are set to NULL in map; if clear is false, variables missing in
977 dict are ignored.
978
979 Exceptions raised while modifying the dict are silently ignored,
980 because there is no good way to report them.
981*/
982
Guido van Rossum6b356e72001-04-14 17:55:41 +0000983static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000984dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 Py_ssize_t j;
988 assert(PyTuple_Check(map));
989 assert(PyDict_Check(dict));
990 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800991 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 PyObject *key = PyTuple_GET_ITEM(map, j);
993 PyObject *value = PyObject_GetItem(dict, key);
994 assert(PyUnicode_Check(key));
995 /* We only care about NULLs if clear is true. */
996 if (value == NULL) {
997 PyErr_Clear();
998 if (!clear)
999 continue;
1000 }
1001 if (deref) {
1002 assert(PyCell_Check(values[j]));
1003 if (PyCell_GET(values[j]) != value) {
1004 if (PyCell_Set(values[j], value) < 0)
1005 PyErr_Clear();
1006 }
1007 } else if (values[j] != value) {
1008 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001009 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 }
1011 Py_XDECREF(value);
1012 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001013}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001014
Victor Stinner41bb43a2013-10-29 01:19:37 +01001015int
1016PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* Merge fast locals into f->f_locals */
1019 PyObject *locals, *map;
1020 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyCodeObject *co;
1022 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001023 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001024
1025 if (f == NULL) {
1026 PyErr_BadInternalCall();
1027 return -1;
1028 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 locals = f->f_locals;
1030 if (locals == NULL) {
1031 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001032 if (locals == NULL)
1033 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 }
1035 co = f->f_code;
1036 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001037 if (!PyTuple_Check(map)) {
1038 PyErr_Format(PyExc_SystemError,
1039 "co_varnames must be a tuple, not %s",
1040 Py_TYPE(map)->tp_name);
1041 return -1;
1042 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 fast = f->f_localsplus;
1044 j = PyTuple_GET_SIZE(map);
1045 if (j > co->co_nlocals)
1046 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001047 if (co->co_nlocals) {
1048 if (map_to_dict(map, j, locals, fast, 0) < 0)
1049 return -1;
1050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1052 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1053 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001054 if (map_to_dict(co->co_cellvars, ncells,
1055 locals, fast + co->co_nlocals, 1))
1056 return -1;
1057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* If the namespace is unoptimized, then one of the
1059 following cases applies:
1060 1. It does not contain free variables, because it
1061 uses import * or is a top-level namespace.
1062 2. It is a class namespace.
1063 We don't want to accidentally copy free variables
1064 into the locals dict used by the class.
1065 */
1066 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001067 if (map_to_dict(co->co_freevars, nfreevars,
1068 locals, fast + co->co_nlocals + ncells, 1) < 0)
1069 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 }
1071 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001072 return 0;
1073}
1074
1075void
1076PyFrame_FastToLocals(PyFrameObject *f)
1077{
1078 int res;
1079
1080 assert(!PyErr_Occurred());
1081
1082 res = PyFrame_FastToLocalsWithError(f);
1083 if (res < 0)
1084 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001085}
1086
1087void
Fred Drake1b190b42000-07-09 05:40:56 +00001088PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* Merge f->f_locals into fast locals */
1091 PyObject *locals, *map;
1092 PyObject **fast;
1093 PyObject *error_type, *error_value, *error_traceback;
1094 PyCodeObject *co;
1095 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001096 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (f == NULL)
1098 return;
1099 locals = f->f_locals;
1100 co = f->f_code;
1101 map = co->co_varnames;
1102 if (locals == NULL)
1103 return;
1104 if (!PyTuple_Check(map))
1105 return;
1106 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1107 fast = f->f_localsplus;
1108 j = PyTuple_GET_SIZE(map);
1109 if (j > co->co_nlocals)
1110 j = co->co_nlocals;
1111 if (co->co_nlocals)
1112 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1113 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1114 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1115 if (ncells || nfreevars) {
1116 dict_to_map(co->co_cellvars, ncells,
1117 locals, fast + co->co_nlocals, 1, clear);
1118 /* Same test as in PyFrame_FastToLocals() above. */
1119 if (co->co_flags & CO_OPTIMIZED) {
1120 dict_to_map(co->co_freevars, nfreevars,
1121 locals, fast + co->co_nlocals + ncells, 1,
1122 clear);
1123 }
1124 }
1125 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001126}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001127
1128/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001129void
Victor Stinner3744ed22020-06-05 01:39:24 +02001130_PyFrame_ClearFreeList(PyThreadState *tstate)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001131{
Victor Stinner3744ed22020-06-05 01:39:24 +02001132 struct _Py_frame_state *state = &tstate->interp->frame;
1133 while (state->free_list != NULL) {
1134 PyFrameObject *f = state->free_list;
1135 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001137 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001139 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001140}
1141
1142void
Victor Stinner3744ed22020-06-05 01:39:24 +02001143_PyFrame_Fini(PyThreadState *tstate)
Christian Heimesa156e092008-02-16 07:38:31 +00001144{
Victor Stinner3744ed22020-06-05 01:39:24 +02001145 _PyFrame_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001146#ifdef Py_DEBUG
1147 struct _Py_frame_state *state = &tstate->interp->frame;
1148 state->numfree = -1;
1149#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001150}
David Malcolm49526f42012-06-22 14:55:41 -04001151
1152/* Print summary info about the state of the optimized allocator */
1153void
1154_PyFrame_DebugMallocStats(FILE *out)
1155{
Victor Stinner522691c2020-06-23 16:40:40 +02001156 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001157 _PyDebugAllocatorStats(out,
1158 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001159 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001160}
1161
Victor Stinnera42ca742020-04-28 19:01:31 +02001162
1163PyCodeObject *
1164PyFrame_GetCode(PyFrameObject *frame)
1165{
1166 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001167 PyCodeObject *code = frame->f_code;
1168 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001169 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001170 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001171}
Victor Stinner70364772020-04-29 03:28:46 +02001172
1173
1174PyFrameObject*
1175PyFrame_GetBack(PyFrameObject *frame)
1176{
1177 assert(frame != NULL);
1178 PyFrameObject *back = frame->f_back;
1179 Py_XINCREF(back);
1180 return back;
1181}
Mark Shannond6c33fb2021-01-29 13:24:55 +00001182
1183PyObject *_PyEval_BuiltinsFromGlobals(PyObject *globals) {
1184 PyObject *builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
1185 if (builtins) {
1186 if (PyModule_Check(builtins)) {
1187 builtins = PyModule_GetDict(builtins);
1188 assert(builtins != NULL);
1189 }
1190 }
1191 if (builtins == NULL) {
1192 if (PyErr_Occurred()) {
1193 return NULL;
1194 }
1195 /* No builtins! Make up a minimal one
1196 Give them 'None', at least. */
1197 builtins = PyDict_New();
1198 if (builtins == NULL ||
1199 PyDict_SetItemString(
1200 builtins, "None", Py_None) < 0)
1201 return NULL;
1202 }
1203 else
1204 Py_INCREF(builtins);
1205 return builtins;
1206}