blob: 4c5eaa23d345bedc43f8cd9a048b9f3ca113cb0f [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 +020025
26static struct _Py_frame_state *
27get_frame_state(void)
28{
29 PyInterpreterState *interp = _PyInterpreterState_GET();
30 return &interp->frame;
31}
32
33
Guido van Rossum18752471997-04-29 14:49:28 +000034static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000035frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000036{
Victor Stinner41bb43a2013-10-29 01:19:37 +010037 if (PyFrame_FastToLocalsWithError(f) < 0)
38 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 Py_INCREF(f->f_locals);
40 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000041}
42
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000043int
44PyFrame_GetLineNumber(PyFrameObject *f)
45{
Victor Stinner7c59d7c2020-04-28 16:32:48 +020046 assert(f != NULL);
Mark Shannonee9f98d2021-01-05 12:04:10 +000047 if (f->f_lineno != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return f->f_lineno;
Victor Stinner7c59d7c2020-04-28 16:32:48 +020049 }
50 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Victor Stinner7c59d7c2020-04-28 16:32:48 +020052 }
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000053}
54
Michael W. Hudsondd32a912002-08-15 14:59:02 +000055static PyObject *
56frame_getlineno(PyFrameObject *f, void *closure)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000059}
60
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020061
62/* Given the index of the effective opcode,
63 scan back to construct the oparg with EXTENDED_ARG */
64static unsigned int
65get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
66{
67 _Py_CODEUNIT word;
68 unsigned int oparg = _Py_OPARG(codestr[i]);
69 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
70 oparg |= _Py_OPARG(word) << 8;
71 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
72 oparg |= _Py_OPARG(word) << 16;
73 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
74 oparg |= _Py_OPARG(word) << 24;
75 }
76 }
77 }
78 return oparg;
79}
80
Mark Shannon57697242020-04-29 16:49:45 +010081typedef enum kind {
82 With = 1,
83 Loop = 2,
84 Try = 3,
85 Except = 4,
86} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +000087
Mark Shannon57697242020-04-29 16:49:45 +010088#define BITS_PER_BLOCK 3
89
90static inline int64_t
91push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +000092{
Mark Shannon57697242020-04-29 16:49:45 +010093 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
94 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +000095}
96
Mark Shannon57697242020-04-29 16:49:45 +010097static inline int64_t
98pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +000099{
Mark Shannon57697242020-04-29 16:49:45 +0100100 assert(stack > 0);
101 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +0000102}
103
Mark Shannon57697242020-04-29 16:49:45 +0100104static inline Kind
105top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000106{
Mark Shannon57697242020-04-29 16:49:45 +0100107 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +0000108}
109
Mark Shannon57697242020-04-29 16:49:45 +0100110static int64_t *
111markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000112{
Mark Shannon57697242020-04-29 16:49:45 +0100113 const _Py_CODEUNIT *code =
114 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
115 int64_t *blocks = PyMem_New(int64_t, len+1);
116 int i, j, opcode;
117
118 if (blocks == NULL) {
119 PyErr_NoMemory();
120 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000121 }
Mark Shannon57697242020-04-29 16:49:45 +0100122 memset(blocks, -1, (len+1)*sizeof(int64_t));
123 blocks[0] = 0;
124 int todo = 1;
125 while (todo) {
126 todo = 0;
127 for (i = 0; i < len; i++) {
128 int64_t block_stack = blocks[i];
129 int64_t except_stack;
130 if (block_stack == -1) {
131 continue;
132 }
133 opcode = _Py_OPCODE(code[i]);
134 switch (opcode) {
135 case JUMP_IF_FALSE_OR_POP:
136 case JUMP_IF_TRUE_OR_POP:
137 case POP_JUMP_IF_FALSE:
138 case POP_JUMP_IF_TRUE:
139 case JUMP_IF_NOT_EXC_MATCH:
140 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
141 assert(j < len);
142 if (blocks[j] == -1 && j < i) {
143 todo = 1;
144 }
145 assert(blocks[j] == -1 || blocks[j] == block_stack);
146 blocks[j] = block_stack;
147 blocks[i+1] = block_stack;
148 break;
149 case JUMP_ABSOLUTE:
150 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
151 assert(j < len);
152 if (blocks[j] == -1 && j < i) {
153 todo = 1;
154 }
155 assert(blocks[j] == -1 || blocks[j] == block_stack);
156 blocks[j] = block_stack;
157 break;
158 case SETUP_FINALLY:
159 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
160 assert(j < len);
161 except_stack = push_block(block_stack, Except);
162 assert(blocks[j] == -1 || blocks[j] == except_stack);
163 blocks[j] = except_stack;
164 block_stack = push_block(block_stack, Try);
165 blocks[i+1] = block_stack;
166 break;
167 case SETUP_WITH:
168 case SETUP_ASYNC_WITH:
169 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
170 assert(j < len);
171 except_stack = push_block(block_stack, Except);
172 assert(blocks[j] == -1 || blocks[j] == except_stack);
173 blocks[j] = except_stack;
174 block_stack = push_block(block_stack, With);
175 blocks[i+1] = block_stack;
176 break;
177 case JUMP_FORWARD:
178 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
179 assert(j < len);
180 assert(blocks[j] == -1 || blocks[j] == block_stack);
181 blocks[j] = block_stack;
182 break;
183 case GET_ITER:
184 case GET_AITER:
185 block_stack = push_block(block_stack, Loop);
186 blocks[i+1] = block_stack;
187 break;
188 case FOR_ITER:
189 blocks[i+1] = block_stack;
190 block_stack = pop_block(block_stack);
191 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
192 assert(j < len);
193 assert(blocks[j] == -1 || blocks[j] == block_stack);
194 blocks[j] = block_stack;
195 break;
196 case POP_BLOCK:
197 case POP_EXCEPT:
198 block_stack = pop_block(block_stack);
199 blocks[i+1] = block_stack;
200 break;
201 case END_ASYNC_FOR:
202 block_stack = pop_block(pop_block(block_stack));
203 blocks[i+1] = block_stack;
204 break;
205 case RETURN_VALUE:
206 case RAISE_VARARGS:
207 case RERAISE:
208 /* End of block */
209 break;
210 default:
211 blocks[i+1] = block_stack;
212
213 }
214 }
215 }
216 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000217}
218
219static int
Mark Shannon57697242020-04-29 16:49:45 +0100220compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000221{
Mark Shannon57697242020-04-29 16:49:45 +0100222 if (to_stack < 0) {
223 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000224 }
Mark Shannon57697242020-04-29 16:49:45 +0100225 while(from_stack > to_stack) {
226 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000227 }
Mark Shannon57697242020-04-29 16:49:45 +0100228 return from_stack == to_stack;
229}
230
231static const char *
232explain_incompatible_block_stack(int64_t to_stack)
233{
234 Kind target_kind = top_block(to_stack);
235 switch(target_kind) {
236 case Except:
237 return "can't jump into an 'except' block as there's no exception";
238 case Try:
239 return "can't jump into the body of a try statement";
240 case With:
241 return "can't jump into the body of a with statement";
242 case Loop:
243 return "can't jump into the body of a for loop";
244 default:
245 Py_UNREACHABLE();
246 }
247}
248
249static int *
250marklines(PyCodeObject *code, int len)
251{
Mark Shannon877df852020-11-12 09:43:29 +0000252 PyCodeAddressRange bounds;
253 _PyCode_InitAddressRange(code, &bounds);
254 assert (bounds.ar_end == 0);
255
Mark Shannon57697242020-04-29 16:49:45 +0100256 int *linestarts = PyMem_New(int, len);
257 if (linestarts == NULL) {
258 return NULL;
259 }
Mark Shannon877df852020-11-12 09:43:29 +0000260 for (int i = 0; i < len; i++) {
261 linestarts[i] = -1;
Mark Shannon57697242020-04-29 16:49:45 +0100262 }
Mark Shannon877df852020-11-12 09:43:29 +0000263
264 while (PyLineTable_NextAddressRange(&bounds)) {
265 assert(bounds.ar_start/2 < len);
266 linestarts[bounds.ar_start/2] = bounds.ar_line;
Mark Shannon57697242020-04-29 16:49:45 +0100267 }
Mark Shannon57697242020-04-29 16:49:45 +0100268 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000269}
270
271static int
Mark Shannon57697242020-04-29 16:49:45 +0100272first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000273{
274 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100275 for (int i = 0; i < len; i++) {
276 if (lines[i] < result && lines[i] >= line) {
277 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000278 }
Mark Shannonfee55262019-11-21 09:11:43 +0000279 }
280 if (result == INT_MAX) {
281 return -1;
282 }
283 return result;
284}
285
Mark Shannonfee55262019-11-21 09:11:43 +0000286static void
287frame_stack_pop(PyFrameObject *f)
288{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100289 assert(f->f_stackdepth >= 0);
290 f->f_stackdepth--;
291 PyObject *v = f->f_valuestack[f->f_stackdepth];
Mark Shannonfee55262019-11-21 09:11:43 +0000292 Py_DECREF(v);
293}
294
295static void
296frame_block_unwind(PyFrameObject *f)
297{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100298 assert(f->f_stackdepth >= 0);
Mark Shannonfee55262019-11-21 09:11:43 +0000299 assert(f->f_iblock > 0);
300 f->f_iblock--;
301 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Mark Shannoncb9879b2020-07-17 11:44:23 +0100302 intptr_t delta = f->f_stackdepth - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000303 while (delta > 0) {
304 frame_stack_pop(f);
305 delta--;
306 }
307}
308
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200309
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000310/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000312 * lines are OK to jump to because they don't make any assumptions about the
313 * state of the stack (obvious because you could remove the line and the code
314 * would still work without any stack errors), but there are some constructs
315 * that limit jumping:
316 *
317 * o Lines with an 'except' statement on them can't be jumped to, because
318 * they expect an exception to be on the top of the stack.
319 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000320 * we cannot be sure which state the interpreter was in or would be in
321 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200322 * o 'try', 'with' and 'async with' blocks can't be jumped into because
323 * the blockstack needs to be set up before their code runs.
324 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000325 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100326 * o Jumps cannot be made from within a trace function invoked with a
327 * 'return' or 'exception' event since the eval loop has been exited at
328 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000329 */
330static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200331frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000332{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700333 if (p_new_lineno == NULL) {
334 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
335 return -1;
336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 /* f_lineno must be an integer. */
338 if (!PyLong_CheckExact(p_new_lineno)) {
339 PyErr_SetString(PyExc_ValueError,
340 "lineno must be an integer");
341 return -1;
342 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000343
Mark Shannoncb9879b2020-07-17 11:44:23 +0100344 /*
345 * This code preserves the historical restrictions on
346 * setting the line number of a frame.
347 * Jumps are forbidden on a 'return' trace event (except after a yield).
348 * Jumps from 'call' trace events are also forbidden.
349 * In addition, jumps are forbidden when not tracing,
350 * as this is a debugging feature.
351 */
352 switch(f->f_state) {
353 case FRAME_CREATED:
354 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100355 "can't jump from the 'call' trace event of a new frame");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100356 return -1;
357 case FRAME_RETURNED:
358 case FRAME_UNWINDING:
359 case FRAME_RAISED:
360 case FRAME_CLEARED:
361 PyErr_SetString(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100362 "can only jump from a 'line' trace event");
Mark Shannoncb9879b2020-07-17 11:44:23 +0100363 return -1;
364 case FRAME_EXECUTING:
365 case FRAME_SUSPENDED:
366 /* You can only do this from within a trace function, not via
367 * _getframe or similar hackery. */
368 if (!f->f_trace) {
369 PyErr_Format(PyExc_ValueError,
370 "f_lineno can only be set by a trace function");
371 return -1;
372 }
373 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000375
Mark Shannonfee55262019-11-21 09:11:43 +0000376 int new_lineno;
377
Mark Shannon57697242020-04-29 16:49:45 +0100378 /* Fail if the line falls outside the code block and
379 select first line with actual code. */
380 int overflow;
381 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
382 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000383#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100384 || l_new_lineno > INT_MAX
385 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000386#endif
Mark Shannon57697242020-04-29 16:49:45 +0100387 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000388 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100389 "lineno out of range");
390 return -1;
391 }
392 new_lineno = (int)l_new_lineno;
393
394 if (new_lineno < f->f_code->co_firstlineno) {
395 PyErr_Format(PyExc_ValueError,
396 "line %d comes before the current code block",
397 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 return -1;
399 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000400
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000401 /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
402 * should never overflow. */
403 int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT));
Mark Shannon57697242020-04-29 16:49:45 +0100404 int *lines = marklines(f->f_code, len);
405 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return -1;
407 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000408
Mark Shannon57697242020-04-29 16:49:45 +0100409 new_lineno = first_line_not_before(lines, len, new_lineno);
410 if (new_lineno < 0) {
411 PyErr_Format(PyExc_ValueError,
412 "line %d comes after the current code block",
413 (int)l_new_lineno);
414 PyMem_Free(lines);
415 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000416 }
417
Mark Shannon57697242020-04-29 16:49:45 +0100418 int64_t *blocks = markblocks(f->f_code, len);
419 if (blocks == NULL) {
420 PyMem_Free(lines);
421 return -1;
422 }
423
424 int64_t target_block_stack = -1;
425 int64_t best_block_stack = -1;
426 int best_addr = -1;
427 int64_t start_block_stack = blocks[f->f_lasti/sizeof(_Py_CODEUNIT)];
428 const char *msg = "cannot find bytecode for specified line";
429 for (int i = 0; i < len; i++) {
430 if (lines[i] == new_lineno) {
431 target_block_stack = blocks[i];
432 if (compatible_block_stack(start_block_stack, target_block_stack)) {
433 msg = NULL;
434 if (target_block_stack > best_block_stack) {
435 best_block_stack = target_block_stack;
436 best_addr = i*sizeof(_Py_CODEUNIT);
437 }
438 }
439 else if (msg) {
440 if (target_block_stack >= 0) {
441 msg = explain_incompatible_block_stack(target_block_stack);
442 }
443 else {
444 msg = "code may be unreachable.";
445 }
446 }
Mark Shannonfee55262019-11-21 09:11:43 +0000447 }
448 }
Mark Shannon57697242020-04-29 16:49:45 +0100449 PyMem_Free(blocks);
450 PyMem_Free(lines);
451 if (msg != NULL) {
452 PyErr_SetString(PyExc_ValueError, msg);
453 return -1;
454 }
Mark Shannonfee55262019-11-21 09:11:43 +0000455
456 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100457 while (start_block_stack > best_block_stack) {
458 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000459 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100460 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000461 frame_stack_pop(f);
462 break;
Mark Shannon57697242020-04-29 16:49:45 +0100463 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000464 frame_block_unwind(f);
465 break;
Mark Shannon57697242020-04-29 16:49:45 +0100466 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000467 frame_block_unwind(f);
468 // Pop the exit function
469 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 break;
Mark Shannon57697242020-04-29 16:49:45 +0100471 case Except:
472 PyErr_SetString(PyExc_ValueError,
473 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000474 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 }
Mark Shannon57697242020-04-29 16:49:45 +0100476 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 }
Mark Shannonfee55262019-11-21 09:11:43 +0000478
Mark Shannonee9f98d2021-01-05 12:04:10 +0000479 /* Finally set the new f_lasti and return OK. */
480 f->f_lineno = 0;
Mark Shannon57697242020-04-29 16:49:45 +0100481 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000483}
484
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000485static PyObject *
486frame_gettrace(PyFrameObject *f, void *closure)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (trace == NULL)
491 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000496}
497
498static int
499frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
500{
Mark Shannonee9f98d2021-01-05 12:04:10 +0000501 if (v == Py_None) {
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300502 v = NULL;
Mark Shannonee9f98d2021-01-05 12:04:10 +0000503 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300505 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000508}
509
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000510
Guido van Rossum32d34c82001-09-20 21:45:26 +0000511static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 {"f_locals", (getter)frame_getlocals, NULL, NULL},
513 {"f_lineno", (getter)frame_getlineno,
514 (setter)frame_setlineno, NULL},
515 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
516 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000517};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000518
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000519/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000520 In an attempt to improve the speed of function calls, we:
521
522 1. Hold a single "zombie" frame on each code object. This retains
523 the allocated and initialised frame object from an invocation of
524 the code object. The zombie is reanimated the next time we need a
525 frame object for that code object. Doing this saves the malloc/
526 realloc required when using a free_list frame that isn't the
527 correct size. It also saves some field initialisation.
528
529 In zombie mode, no field of PyFrameObject holds a reference, but
530 the following fields are still valid:
531
532 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533
Mark Shannonae3087c2017-10-22 22:41:51 +0100534 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535
536 * f_localsplus does not require re-allocation and
537 the local variables in f_localsplus are NULL.
538
539 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000540 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541 a stack frame is on the free list, only the following members have
542 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 ob_type == &Frametype
544 f_back next item on free list, or NULL
545 f_stacksize size of value stack
546 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000547 Note that the value and block stacks are preserved -- this can save
548 another malloc() call or two (and two free() calls as well!).
549 Also note that, unlike for integers, each frame object is a
550 malloc'ed object in its own right -- it is only the actual calls to
551 malloc() that we are trying to save here, not the administration.
552 After all, while a typical program may make millions of calls, a
553 call depth of more than 20 or 30 is probably already exceptional
554 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000555
Christian Heimes2202f872008-02-06 14:31:34 +0000556 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000557 free_list. Else programs creating lots of cyclic trash involving
558 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000559*/
Christian Heimes2202f872008-02-06 14:31:34 +0000560/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000562
Victor Stinnerc6944e72016-11-11 02:13:35 +0100563static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000564frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000565{
Victor Stinner3744ed22020-06-05 01:39:24 +0200566 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900567 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200568 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200571 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200572 PyObject **valuestack = f->f_valuestack;
573 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200574 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200575 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200576
577 /* Free stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100578 for (int i = 0; i < f->f_stackdepth; i++) {
579 Py_XDECREF(f->f_valuestack[i]);
Antoine Pitrou93963562013-05-14 20:37:52 +0200580 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100581 f->f_stackdepth = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 Py_XDECREF(f->f_back);
584 Py_DECREF(f->f_builtins);
585 Py_DECREF(f->f_globals);
586 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200587 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588
Victor Stinner3744ed22020-06-05 01:39:24 +0200589 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200590 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200592 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200593 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200594 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200595#ifdef Py_DEBUG
596 // frame_dealloc() must not be called after _PyFrame_Fini()
597 assert(state->numfree != -1);
598#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200599 if (state->numfree < PyFrame_MAXFREELIST) {
600 ++state->numfree;
601 f->f_back = state->free_list;
602 state->free_list = f;
603 }
604 else {
605 PyObject_GC_Del(f);
606 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200607 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 Py_DECREF(co);
610 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000611}
612
Victor Stinner6d86a232020-04-29 00:56:58 +0200613static inline Py_ssize_t
614frame_nslots(PyFrameObject *frame)
615{
616 PyCodeObject *code = frame->f_code;
617 return (code->co_nlocals
618 + PyTuple_GET_SIZE(code->co_cellvars)
619 + PyTuple_GET_SIZE(code->co_freevars));
620}
621
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000622static int
623frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 Py_VISIT(f->f_back);
626 Py_VISIT(f->f_code);
627 Py_VISIT(f->f_builtins);
628 Py_VISIT(f->f_globals);
629 Py_VISIT(f->f_locals);
630 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200633 PyObject **fastlocals = f->f_localsplus;
634 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200636 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100639 for (int i = 0; i < f->f_stackdepth; i++) {
640 Py_VISIT(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 }
642 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000643}
644
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200645static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200646frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000647{
Antoine Pitrou93963562013-05-14 20:37:52 +0200648 /* Before anything else, make sure that this frame is clearly marked
649 * as being defunct! Else, e.g., a generator reachable from this
650 * frame may also point to this frame, believe itself to still be
651 * active, and try cleaning up this frame again.
652 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100653 f->f_state = FRAME_CLEARED;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200658 PyObject **fastlocals = f->f_localsplus;
659 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200661 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100664 for (int i = 0; i < f->f_stackdepth; i++) {
665 Py_CLEAR(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100667 f->f_stackdepth = 0;
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200668 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000669}
670
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000671static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530672frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200673{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100674 if (_PyFrame_IsExecuting(f)) {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200675 PyErr_SetString(PyExc_RuntimeError,
676 "cannot clear an executing frame");
677 return NULL;
678 }
679 if (f->f_gen) {
680 _PyGen_Finalize(f->f_gen);
681 assert(f->f_gen == NULL);
682 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200683 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200684 Py_RETURN_NONE;
685}
686
687PyDoc_STRVAR(clear__doc__,
688"F.clear(): clear most references held by the frame");
689
690static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530691frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000694
Victor Stinner6d86a232020-04-29 00:56:58 +0200695 PyCodeObject *code = f->f_code;
696 ncells = PyTuple_GET_SIZE(code->co_cellvars);
697 nfrees = PyTuple_GET_SIZE(code->co_freevars);
698 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 /* subtract one as it is already included in PyFrameObject */
700 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000703}
704
705PyDoc_STRVAR(sizeof__doc__,
706"F.__sizeof__() -> size of F in memory, in bytes");
707
Antoine Pitrou14709142017-12-31 22:35:22 +0100708static PyObject *
709frame_repr(PyFrameObject *f)
710{
711 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200712 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100713 return PyUnicode_FromFormat(
714 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200715 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100716}
717
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000718static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200719 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
720 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
722 sizeof__doc__},
723 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000724};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000725
Guido van Rossum18752471997-04-29 14:49:28 +0000726PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 PyVarObject_HEAD_INIT(&PyType_Type, 0)
728 "frame",
729 sizeof(PyFrameObject),
730 sizeof(PyObject *),
731 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200732 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 0, /* tp_getattr */
734 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200735 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100736 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 0, /* tp_as_number */
738 0, /* tp_as_sequence */
739 0, /* tp_as_mapping */
740 0, /* tp_hash */
741 0, /* tp_call */
742 0, /* tp_str */
743 PyObject_GenericGetAttr, /* tp_getattro */
744 PyObject_GenericSetAttr, /* tp_setattro */
745 0, /* tp_as_buffer */
746 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
747 0, /* tp_doc */
748 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200749 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 0, /* tp_richcompare */
751 0, /* tp_weaklistoffset */
752 0, /* tp_iter */
753 0, /* tp_iternext */
754 frame_methods, /* tp_methods */
755 frame_memberlist, /* tp_members */
756 frame_getsetlist, /* tp_getset */
757 0, /* tp_base */
758 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000759};
760
Victor Stinner07e9e382013-11-07 22:22:39 +0100761_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000762
Victor Stinnerb4b53862020-05-05 19:55:29 +0200763static inline PyFrameObject*
764frame_alloc(PyCodeObject *code)
765{
766 PyFrameObject *f;
767
768 f = code->co_zombieframe;
769 if (f != NULL) {
770 code->co_zombieframe = NULL;
771 _Py_NewReference((PyObject *)f);
772 assert(f->f_code == code);
773 return f;
774 }
775
776 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
777 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
778 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200779 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200780 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200781 {
782 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
783 if (f == NULL) {
784 return NULL;
785 }
786 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200787 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200788#ifdef Py_DEBUG
789 // frame_alloc() must not be called after _PyFrame_Fini()
790 assert(state->numfree != -1);
791#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200792 assert(state->numfree > 0);
793 --state->numfree;
794 f = state->free_list;
795 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200796 if (Py_SIZE(f) < extras) {
797 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
798 if (new_f == NULL) {
799 PyObject_GC_Del(f);
800 return NULL;
801 }
802 f = new_f;
803 }
804 _Py_NewReference((PyObject *)f);
805 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200806
807 f->f_code = code;
808 extras = code->co_nlocals + ncells + nfrees;
809 f->f_valuestack = f->f_localsplus + extras;
810 for (Py_ssize_t i=0; i<extras; i++) {
811 f->f_localsplus[i] = NULL;
812 }
813 f->f_locals = NULL;
814 f->f_trace = NULL;
815 return f;
816}
817
818
819static inline PyObject *
820frame_get_builtins(PyFrameObject *back, PyObject *globals)
821{
822 PyObject *builtins;
823
824 if (back != NULL && back->f_globals == globals) {
825 /* If we share the globals, we share the builtins.
826 Save a lookup and a call. */
827 builtins = back->f_builtins;
828 assert(builtins != NULL);
829 Py_INCREF(builtins);
830 return builtins;
831 }
832
833 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
834 if (builtins != NULL && PyModule_Check(builtins)) {
835 builtins = PyModule_GetDict(builtins);
836 assert(builtins != NULL);
837 }
838 if (builtins != NULL) {
839 Py_INCREF(builtins);
840 return builtins;
841 }
842
843 if (PyErr_Occurred()) {
844 return NULL;
845 }
846
847 /* No builtins! Make up a minimal one.
848 Give them 'None', at least. */
849 builtins = PyDict_New();
850 if (builtins == NULL) {
851 return NULL;
852 }
853 if (PyDict_SetItemString(builtins, "None", Py_None) < 0) {
854 Py_DECREF(builtins);
855 return NULL;
856 }
857 return builtins;
858}
859
860
Victor Stinnerc6944e72016-11-11 02:13:35 +0100861PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900862_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
863 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000864{
Michael W. Hudson69734a52002-08-19 16:54:08 +0000865#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
867 (locals != NULL && !PyMapping_Check(locals))) {
868 PyErr_BadInternalCall();
869 return NULL;
870 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000871#endif
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000872
Victor Stinnerb4b53862020-05-05 19:55:29 +0200873 PyFrameObject *back = tstate->frame;
874 PyObject *builtins = frame_get_builtins(back, globals);
875 if (builtins == NULL) {
876 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000878
Victor Stinnerb4b53862020-05-05 19:55:29 +0200879 PyFrameObject *f = frame_alloc(code);
880 if (f == NULL) {
881 Py_DECREF(builtins);
882 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200884
Mark Shannoncb9879b2020-07-17 11:44:23 +0100885 f->f_stackdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 f->f_builtins = builtins;
887 Py_XINCREF(back);
888 f->f_back = back;
889 Py_INCREF(code);
890 Py_INCREF(globals);
891 f->f_globals = globals;
892 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
893 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
894 (CO_NEWLOCALS | CO_OPTIMIZED))
895 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
896 else if (code->co_flags & CO_NEWLOCALS) {
897 locals = PyDict_New();
898 if (locals == NULL) {
899 Py_DECREF(f);
900 return NULL;
901 }
902 f->f_locals = locals;
903 }
904 else {
905 if (locals == NULL)
906 locals = globals;
907 Py_INCREF(locals);
908 f->f_locals = locals;
909 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 f->f_lasti = -1;
Mark Shannon877df852020-11-12 09:43:29 +0000912 f->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 f->f_iblock = 0;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100914 f->f_state = FRAME_CREATED;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200915 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000916 f->f_trace_opcodes = 0;
917 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000918
Victor Stinner6d86a232020-04-29 00:56:58 +0200919 assert(f->f_code != NULL);
920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000922}
923
INADA Naoki5a625d02016-12-24 20:19:08 +0900924PyFrameObject*
925PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
926 PyObject *globals, PyObject *locals)
927{
928 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
929 if (f)
930 _PyObject_GC_TRACK(f);
931 return f;
932}
933
934
Guido van Rossum3f5da241990-12-20 15:06:42 +0000935/* Block management */
936
937void
Fred Drake1b190b42000-07-09 05:40:56 +0000938PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100941 if (f->f_iblock >= CO_MAXBLOCKS) {
942 Py_FatalError("block stack overflow");
943 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 b = &f->f_blockstack[f->f_iblock++];
945 b->b_type = type;
946 b->b_level = level;
947 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000948}
949
Guido van Rossum18752471997-04-29 14:49:28 +0000950PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000951PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100954 if (f->f_iblock <= 0) {
955 Py_FatalError("block stack underflow");
956 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 b = &f->f_blockstack[--f->f_iblock];
958 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000959}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000960
Guido van Rossumd8faa362007-04-27 19:54:29 +0000961/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962
963 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000964 values is an array of PyObject*. At index i, map[i] is the name of
965 the variable with value values[i]. The function copies the first
966 nmap variable from map/values into dict. If values[i] is NULL,
967 the variable is deleted from dict.
968
969 If deref is true, then the values being copied are cell variables
970 and the value is extracted from the cell variable before being put
971 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000973
Victor Stinner41bb43a2013-10-29 01:19:37 +0100974static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000975map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 Py_ssize_t j;
979 assert(PyTuple_Check(map));
980 assert(PyDict_Check(dict));
981 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800982 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *key = PyTuple_GET_ITEM(map, j);
984 PyObject *value = values[j];
985 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400986 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 assert(PyCell_Check(value));
988 value = PyCell_GET(value);
989 }
990 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100991 if (PyObject_DelItem(dict, key) != 0) {
992 if (PyErr_ExceptionMatches(PyExc_KeyError))
993 PyErr_Clear();
994 else
995 return -1;
996 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
998 else {
999 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +01001000 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 }
1002 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001003 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001004}
1005
Guido van Rossumd8faa362007-04-27 19:54:29 +00001006/* Copy values from the "locals" dict into the fast locals.
1007
1008 dict is an input argument containing string keys representing
1009 variables names and arbitrary PyObject* as values.
1010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001012 values is an array of PyObject*. At index i, map[i] is the name of
1013 the variable with value values[i]. The function copies the first
1014 nmap variable from map/values into dict. If values[i] is NULL,
1015 the variable is deleted from dict.
1016
1017 If deref is true, then the values being copied are cell variables
1018 and the value is extracted from the cell variable before being put
1019 in dict. If clear is true, then variables in map but not in dict
1020 are set to NULL in map; if clear is false, variables missing in
1021 dict are ignored.
1022
1023 Exceptions raised while modifying the dict are silently ignored,
1024 because there is no good way to report them.
1025*/
1026
Guido van Rossum6b356e72001-04-14 17:55:41 +00001027static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001028dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 Py_ssize_t j;
1032 assert(PyTuple_Check(map));
1033 assert(PyDict_Check(dict));
1034 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001035 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyObject *key = PyTuple_GET_ITEM(map, j);
1037 PyObject *value = PyObject_GetItem(dict, key);
1038 assert(PyUnicode_Check(key));
1039 /* We only care about NULLs if clear is true. */
1040 if (value == NULL) {
1041 PyErr_Clear();
1042 if (!clear)
1043 continue;
1044 }
1045 if (deref) {
1046 assert(PyCell_Check(values[j]));
1047 if (PyCell_GET(values[j]) != value) {
1048 if (PyCell_Set(values[j], value) < 0)
1049 PyErr_Clear();
1050 }
1051 } else if (values[j] != value) {
1052 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001053 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 }
1055 Py_XDECREF(value);
1056 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001057}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001058
Victor Stinner41bb43a2013-10-29 01:19:37 +01001059int
1060PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* Merge fast locals into f->f_locals */
1063 PyObject *locals, *map;
1064 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyCodeObject *co;
1066 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001067 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001068
1069 if (f == NULL) {
1070 PyErr_BadInternalCall();
1071 return -1;
1072 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 locals = f->f_locals;
1074 if (locals == NULL) {
1075 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001076 if (locals == NULL)
1077 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 }
1079 co = f->f_code;
1080 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001081 if (!PyTuple_Check(map)) {
1082 PyErr_Format(PyExc_SystemError,
1083 "co_varnames must be a tuple, not %s",
1084 Py_TYPE(map)->tp_name);
1085 return -1;
1086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 fast = f->f_localsplus;
1088 j = PyTuple_GET_SIZE(map);
1089 if (j > co->co_nlocals)
1090 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001091 if (co->co_nlocals) {
1092 if (map_to_dict(map, j, locals, fast, 0) < 0)
1093 return -1;
1094 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1096 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1097 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001098 if (map_to_dict(co->co_cellvars, ncells,
1099 locals, fast + co->co_nlocals, 1))
1100 return -1;
1101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* If the namespace is unoptimized, then one of the
1103 following cases applies:
1104 1. It does not contain free variables, because it
1105 uses import * or is a top-level namespace.
1106 2. It is a class namespace.
1107 We don't want to accidentally copy free variables
1108 into the locals dict used by the class.
1109 */
1110 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001111 if (map_to_dict(co->co_freevars, nfreevars,
1112 locals, fast + co->co_nlocals + ncells, 1) < 0)
1113 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 }
1115 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001116 return 0;
1117}
1118
1119void
1120PyFrame_FastToLocals(PyFrameObject *f)
1121{
1122 int res;
1123
1124 assert(!PyErr_Occurred());
1125
1126 res = PyFrame_FastToLocalsWithError(f);
1127 if (res < 0)
1128 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001129}
1130
1131void
Fred Drake1b190b42000-07-09 05:40:56 +00001132PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 /* Merge f->f_locals into fast locals */
1135 PyObject *locals, *map;
1136 PyObject **fast;
1137 PyObject *error_type, *error_value, *error_traceback;
1138 PyCodeObject *co;
1139 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001140 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (f == NULL)
1142 return;
1143 locals = f->f_locals;
1144 co = f->f_code;
1145 map = co->co_varnames;
1146 if (locals == NULL)
1147 return;
1148 if (!PyTuple_Check(map))
1149 return;
1150 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1151 fast = f->f_localsplus;
1152 j = PyTuple_GET_SIZE(map);
1153 if (j > co->co_nlocals)
1154 j = co->co_nlocals;
1155 if (co->co_nlocals)
1156 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1157 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1158 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1159 if (ncells || nfreevars) {
1160 dict_to_map(co->co_cellvars, ncells,
1161 locals, fast + co->co_nlocals, 1, clear);
1162 /* Same test as in PyFrame_FastToLocals() above. */
1163 if (co->co_flags & CO_OPTIMIZED) {
1164 dict_to_map(co->co_freevars, nfreevars,
1165 locals, fast + co->co_nlocals + ncells, 1,
1166 clear);
1167 }
1168 }
1169 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001170}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001171
1172/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001173void
Victor Stinner3744ed22020-06-05 01:39:24 +02001174_PyFrame_ClearFreeList(PyThreadState *tstate)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001175{
Victor Stinner3744ed22020-06-05 01:39:24 +02001176 struct _Py_frame_state *state = &tstate->interp->frame;
1177 while (state->free_list != NULL) {
1178 PyFrameObject *f = state->free_list;
1179 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001181 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001183 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001184}
1185
1186void
Victor Stinner3744ed22020-06-05 01:39:24 +02001187_PyFrame_Fini(PyThreadState *tstate)
Christian Heimesa156e092008-02-16 07:38:31 +00001188{
Victor Stinner3744ed22020-06-05 01:39:24 +02001189 _PyFrame_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001190#ifdef Py_DEBUG
1191 struct _Py_frame_state *state = &tstate->interp->frame;
1192 state->numfree = -1;
1193#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001194}
David Malcolm49526f42012-06-22 14:55:41 -04001195
1196/* Print summary info about the state of the optimized allocator */
1197void
1198_PyFrame_DebugMallocStats(FILE *out)
1199{
Victor Stinner522691c2020-06-23 16:40:40 +02001200 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001201 _PyDebugAllocatorStats(out,
1202 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001203 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001204}
1205
Victor Stinnera42ca742020-04-28 19:01:31 +02001206
1207PyCodeObject *
1208PyFrame_GetCode(PyFrameObject *frame)
1209{
1210 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001211 PyCodeObject *code = frame->f_code;
1212 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001213 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001214 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001215}
Victor Stinner70364772020-04-29 03:28:46 +02001216
1217
1218PyFrameObject*
1219PyFrame_GetBack(PyFrameObject *frame)
1220{
1221 assert(frame != NULL);
1222 PyFrameObject *back = frame->f_back;
1223 Py_XINCREF(back);
1224 return back;
1225}