blob: 787cd8b272bb18fdad001d1b1dca52cd9b81d972 [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);
47 if (f->f_trace) {
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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 /* Finally set the new f_lineno and f_lasti and return OK. */
480 f->f_lineno = new_lineno;
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* We rely on f_lineno being accurate when f_trace is set. */
502 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000503
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300504 if (v == Py_None)
505 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300507 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000510}
511
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000512
Guido van Rossum32d34c82001-09-20 21:45:26 +0000513static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 {"f_locals", (getter)frame_getlocals, NULL, NULL},
515 {"f_lineno", (getter)frame_getlineno,
516 (setter)frame_setlineno, NULL},
517 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
518 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000519};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000520
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000521/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522 In an attempt to improve the speed of function calls, we:
523
524 1. Hold a single "zombie" frame on each code object. This retains
525 the allocated and initialised frame object from an invocation of
526 the code object. The zombie is reanimated the next time we need a
527 frame object for that code object. Doing this saves the malloc/
528 realloc required when using a free_list frame that isn't the
529 correct size. It also saves some field initialisation.
530
531 In zombie mode, no field of PyFrameObject holds a reference, but
532 the following fields are still valid:
533
534 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535
Mark Shannonae3087c2017-10-22 22:41:51 +0100536 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000537
538 * f_localsplus does not require re-allocation and
539 the local variables in f_localsplus are NULL.
540
541 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000542 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 a stack frame is on the free list, only the following members have
544 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 ob_type == &Frametype
546 f_back next item on free list, or NULL
547 f_stacksize size of value stack
548 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000549 Note that the value and block stacks are preserved -- this can save
550 another malloc() call or two (and two free() calls as well!).
551 Also note that, unlike for integers, each frame object is a
552 malloc'ed object in its own right -- it is only the actual calls to
553 malloc() that we are trying to save here, not the administration.
554 After all, while a typical program may make millions of calls, a
555 call depth of more than 20 or 30 is probably already exceptional
556 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000557
Christian Heimes2202f872008-02-06 14:31:34 +0000558 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000559 free_list. Else programs creating lots of cyclic trash involving
560 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000561*/
Christian Heimes2202f872008-02-06 14:31:34 +0000562/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000564
Victor Stinnerc6944e72016-11-11 02:13:35 +0100565static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000566frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000567{
Victor Stinner3744ed22020-06-05 01:39:24 +0200568 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900569 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200570 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200573 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200574 PyObject **valuestack = f->f_valuestack;
575 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200576 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200577 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200578
579 /* Free stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100580 for (int i = 0; i < f->f_stackdepth; i++) {
581 Py_XDECREF(f->f_valuestack[i]);
Antoine Pitrou93963562013-05-14 20:37:52 +0200582 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100583 f->f_stackdepth = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 Py_XDECREF(f->f_back);
586 Py_DECREF(f->f_builtins);
587 Py_DECREF(f->f_globals);
588 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200589 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590
Victor Stinner3744ed22020-06-05 01:39:24 +0200591 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200592 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200594 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200595 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200596 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200597#ifdef Py_DEBUG
598 // frame_dealloc() must not be called after _PyFrame_Fini()
599 assert(state->numfree != -1);
600#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200601 if (state->numfree < PyFrame_MAXFREELIST) {
602 ++state->numfree;
603 f->f_back = state->free_list;
604 state->free_list = f;
605 }
606 else {
607 PyObject_GC_Del(f);
608 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200609 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 Py_DECREF(co);
612 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000613}
614
Victor Stinner6d86a232020-04-29 00:56:58 +0200615static inline Py_ssize_t
616frame_nslots(PyFrameObject *frame)
617{
618 PyCodeObject *code = frame->f_code;
619 return (code->co_nlocals
620 + PyTuple_GET_SIZE(code->co_cellvars)
621 + PyTuple_GET_SIZE(code->co_freevars));
622}
623
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000624static int
625frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 Py_VISIT(f->f_back);
628 Py_VISIT(f->f_code);
629 Py_VISIT(f->f_builtins);
630 Py_VISIT(f->f_globals);
631 Py_VISIT(f->f_locals);
632 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200635 PyObject **fastlocals = f->f_localsplus;
636 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200638 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100641 for (int i = 0; i < f->f_stackdepth; i++) {
642 Py_VISIT(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 }
644 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000645}
646
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200647static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200648frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000649{
Antoine Pitrou93963562013-05-14 20:37:52 +0200650 /* Before anything else, make sure that this frame is clearly marked
651 * as being defunct! Else, e.g., a generator reachable from this
652 * frame may also point to this frame, believe itself to still be
653 * active, and try cleaning up this frame again.
654 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100655 f->f_state = FRAME_CLEARED;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200660 PyObject **fastlocals = f->f_localsplus;
661 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200663 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 /* stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100666 for (int i = 0; i < f->f_stackdepth; i++) {
667 Py_CLEAR(f->f_valuestack[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100669 f->f_stackdepth = 0;
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200670 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000671}
672
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000673static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530674frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200675{
Mark Shannoncb9879b2020-07-17 11:44:23 +0100676 if (_PyFrame_IsExecuting(f)) {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200677 PyErr_SetString(PyExc_RuntimeError,
678 "cannot clear an executing frame");
679 return NULL;
680 }
681 if (f->f_gen) {
682 _PyGen_Finalize(f->f_gen);
683 assert(f->f_gen == NULL);
684 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200685 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200686 Py_RETURN_NONE;
687}
688
689PyDoc_STRVAR(clear__doc__,
690"F.clear(): clear most references held by the frame");
691
692static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530693frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000696
Victor Stinner6d86a232020-04-29 00:56:58 +0200697 PyCodeObject *code = f->f_code;
698 ncells = PyTuple_GET_SIZE(code->co_cellvars);
699 nfrees = PyTuple_GET_SIZE(code->co_freevars);
700 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 /* subtract one as it is already included in PyFrameObject */
702 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000705}
706
707PyDoc_STRVAR(sizeof__doc__,
708"F.__sizeof__() -> size of F in memory, in bytes");
709
Antoine Pitrou14709142017-12-31 22:35:22 +0100710static PyObject *
711frame_repr(PyFrameObject *f)
712{
713 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200714 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100715 return PyUnicode_FromFormat(
716 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200717 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100718}
719
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000720static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200721 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
722 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
724 sizeof__doc__},
725 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000726};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000727
Guido van Rossum18752471997-04-29 14:49:28 +0000728PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyVarObject_HEAD_INIT(&PyType_Type, 0)
730 "frame",
731 sizeof(PyFrameObject),
732 sizeof(PyObject *),
733 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200734 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 0, /* tp_getattr */
736 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200737 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100738 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 0, /* tp_as_number */
740 0, /* tp_as_sequence */
741 0, /* tp_as_mapping */
742 0, /* tp_hash */
743 0, /* tp_call */
744 0, /* tp_str */
745 PyObject_GenericGetAttr, /* tp_getattro */
746 PyObject_GenericSetAttr, /* tp_setattro */
747 0, /* tp_as_buffer */
748 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
749 0, /* tp_doc */
750 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200751 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 0, /* tp_richcompare */
753 0, /* tp_weaklistoffset */
754 0, /* tp_iter */
755 0, /* tp_iternext */
756 frame_methods, /* tp_methods */
757 frame_memberlist, /* tp_members */
758 frame_getsetlist, /* tp_getset */
759 0, /* tp_base */
760 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000761};
762
Victor Stinner07e9e382013-11-07 22:22:39 +0100763_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000764
Victor Stinnerb4b53862020-05-05 19:55:29 +0200765static inline PyFrameObject*
766frame_alloc(PyCodeObject *code)
767{
768 PyFrameObject *f;
769
770 f = code->co_zombieframe;
771 if (f != NULL) {
772 code->co_zombieframe = NULL;
773 _Py_NewReference((PyObject *)f);
774 assert(f->f_code == code);
775 return f;
776 }
777
778 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
779 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
780 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200781 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200782 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200783 {
784 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
785 if (f == NULL) {
786 return NULL;
787 }
788 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200789 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200790#ifdef Py_DEBUG
791 // frame_alloc() must not be called after _PyFrame_Fini()
792 assert(state->numfree != -1);
793#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200794 assert(state->numfree > 0);
795 --state->numfree;
796 f = state->free_list;
797 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200798 if (Py_SIZE(f) < extras) {
799 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
800 if (new_f == NULL) {
801 PyObject_GC_Del(f);
802 return NULL;
803 }
804 f = new_f;
805 }
806 _Py_NewReference((PyObject *)f);
807 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200808
809 f->f_code = code;
810 extras = code->co_nlocals + ncells + nfrees;
811 f->f_valuestack = f->f_localsplus + extras;
812 for (Py_ssize_t i=0; i<extras; i++) {
813 f->f_localsplus[i] = NULL;
814 }
815 f->f_locals = NULL;
816 f->f_trace = NULL;
817 return f;
818}
819
820
821static inline PyObject *
822frame_get_builtins(PyFrameObject *back, PyObject *globals)
823{
824 PyObject *builtins;
825
826 if (back != NULL && back->f_globals == globals) {
827 /* If we share the globals, we share the builtins.
828 Save a lookup and a call. */
829 builtins = back->f_builtins;
830 assert(builtins != NULL);
831 Py_INCREF(builtins);
832 return builtins;
833 }
834
835 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
836 if (builtins != NULL && PyModule_Check(builtins)) {
837 builtins = PyModule_GetDict(builtins);
838 assert(builtins != NULL);
839 }
840 if (builtins != NULL) {
841 Py_INCREF(builtins);
842 return builtins;
843 }
844
845 if (PyErr_Occurred()) {
846 return NULL;
847 }
848
849 /* No builtins! Make up a minimal one.
850 Give them 'None', at least. */
851 builtins = PyDict_New();
852 if (builtins == NULL) {
853 return NULL;
854 }
855 if (PyDict_SetItemString(builtins, "None", Py_None) < 0) {
856 Py_DECREF(builtins);
857 return NULL;
858 }
859 return builtins;
860}
861
862
Victor Stinnerc6944e72016-11-11 02:13:35 +0100863PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900864_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
865 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000866{
Michael W. Hudson69734a52002-08-19 16:54:08 +0000867#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
869 (locals != NULL && !PyMapping_Check(locals))) {
870 PyErr_BadInternalCall();
871 return NULL;
872 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000873#endif
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000874
Victor Stinnerb4b53862020-05-05 19:55:29 +0200875 PyFrameObject *back = tstate->frame;
876 PyObject *builtins = frame_get_builtins(back, globals);
877 if (builtins == NULL) {
878 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000880
Victor Stinnerb4b53862020-05-05 19:55:29 +0200881 PyFrameObject *f = frame_alloc(code);
882 if (f == NULL) {
883 Py_DECREF(builtins);
884 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200886
Mark Shannoncb9879b2020-07-17 11:44:23 +0100887 f->f_stackdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 f->f_builtins = builtins;
889 Py_XINCREF(back);
890 f->f_back = back;
891 Py_INCREF(code);
892 Py_INCREF(globals);
893 f->f_globals = globals;
894 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
895 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
896 (CO_NEWLOCALS | CO_OPTIMIZED))
897 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
898 else if (code->co_flags & CO_NEWLOCALS) {
899 locals = PyDict_New();
900 if (locals == NULL) {
901 Py_DECREF(f);
902 return NULL;
903 }
904 f->f_locals = locals;
905 }
906 else {
907 if (locals == NULL)
908 locals = globals;
909 Py_INCREF(locals);
910 f->f_locals = locals;
911 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 f->f_lasti = -1;
Mark Shannon877df852020-11-12 09:43:29 +0000914 f->f_lineno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 f->f_iblock = 0;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100916 f->f_state = FRAME_CREATED;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200917 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000918 f->f_trace_opcodes = 0;
919 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000920
Victor Stinner6d86a232020-04-29 00:56:58 +0200921 assert(f->f_code != NULL);
922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000924}
925
INADA Naoki5a625d02016-12-24 20:19:08 +0900926PyFrameObject*
927PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
928 PyObject *globals, PyObject *locals)
929{
930 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
931 if (f)
932 _PyObject_GC_TRACK(f);
933 return f;
934}
935
936
Guido van Rossum3f5da241990-12-20 15:06:42 +0000937/* Block management */
938
939void
Fred Drake1b190b42000-07-09 05:40:56 +0000940PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100943 if (f->f_iblock >= CO_MAXBLOCKS) {
944 Py_FatalError("block stack overflow");
945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 b = &f->f_blockstack[f->f_iblock++];
947 b->b_type = type;
948 b->b_level = level;
949 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000950}
951
Guido van Rossum18752471997-04-29 14:49:28 +0000952PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000953PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100956 if (f->f_iblock <= 0) {
957 Py_FatalError("block stack underflow");
958 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 b = &f->f_blockstack[--f->f_iblock];
960 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000961}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000962
Guido van Rossumd8faa362007-04-27 19:54:29 +0000963/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964
965 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000966 values is an array of PyObject*. At index i, map[i] is the name of
967 the variable with value values[i]. The function copies the first
968 nmap variable from map/values into dict. If values[i] is NULL,
969 the variable is deleted from dict.
970
971 If deref is true, then the values being copied are cell variables
972 and the value is extracted from the cell variable before being put
973 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000975
Victor Stinner41bb43a2013-10-29 01:19:37 +0100976static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000977map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 Py_ssize_t j;
981 assert(PyTuple_Check(map));
982 assert(PyDict_Check(dict));
983 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800984 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject *key = PyTuple_GET_ITEM(map, j);
986 PyObject *value = values[j];
987 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400988 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 assert(PyCell_Check(value));
990 value = PyCell_GET(value);
991 }
992 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100993 if (PyObject_DelItem(dict, key) != 0) {
994 if (PyErr_ExceptionMatches(PyExc_KeyError))
995 PyErr_Clear();
996 else
997 return -1;
998 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 }
1000 else {
1001 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +01001002 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 }
1004 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001005 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001006}
1007
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008/* Copy values from the "locals" dict into the fast locals.
1009
1010 dict is an input argument containing string keys representing
1011 variables names and arbitrary PyObject* as values.
1012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014 values is an array of PyObject*. At index i, map[i] is the name of
1015 the variable with value values[i]. The function copies the first
1016 nmap variable from map/values into dict. If values[i] is NULL,
1017 the variable is deleted from dict.
1018
1019 If deref is true, then the values being copied are cell variables
1020 and the value is extracted from the cell variable before being put
1021 in dict. If clear is true, then variables in map but not in dict
1022 are set to NULL in map; if clear is false, variables missing in
1023 dict are ignored.
1024
1025 Exceptions raised while modifying the dict are silently ignored,
1026 because there is no good way to report them.
1027*/
1028
Guido van Rossum6b356e72001-04-14 17:55:41 +00001029static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001030dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 Py_ssize_t j;
1034 assert(PyTuple_Check(map));
1035 assert(PyDict_Check(dict));
1036 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001037 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyObject *key = PyTuple_GET_ITEM(map, j);
1039 PyObject *value = PyObject_GetItem(dict, key);
1040 assert(PyUnicode_Check(key));
1041 /* We only care about NULLs if clear is true. */
1042 if (value == NULL) {
1043 PyErr_Clear();
1044 if (!clear)
1045 continue;
1046 }
1047 if (deref) {
1048 assert(PyCell_Check(values[j]));
1049 if (PyCell_GET(values[j]) != value) {
1050 if (PyCell_Set(values[j], value) < 0)
1051 PyErr_Clear();
1052 }
1053 } else if (values[j] != value) {
1054 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001055 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 }
1057 Py_XDECREF(value);
1058 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001059}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001060
Victor Stinner41bb43a2013-10-29 01:19:37 +01001061int
1062PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* Merge fast locals into f->f_locals */
1065 PyObject *locals, *map;
1066 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyCodeObject *co;
1068 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001069 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001070
1071 if (f == NULL) {
1072 PyErr_BadInternalCall();
1073 return -1;
1074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 locals = f->f_locals;
1076 if (locals == NULL) {
1077 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001078 if (locals == NULL)
1079 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
1081 co = f->f_code;
1082 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001083 if (!PyTuple_Check(map)) {
1084 PyErr_Format(PyExc_SystemError,
1085 "co_varnames must be a tuple, not %s",
1086 Py_TYPE(map)->tp_name);
1087 return -1;
1088 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 fast = f->f_localsplus;
1090 j = PyTuple_GET_SIZE(map);
1091 if (j > co->co_nlocals)
1092 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001093 if (co->co_nlocals) {
1094 if (map_to_dict(map, j, locals, fast, 0) < 0)
1095 return -1;
1096 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1098 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1099 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001100 if (map_to_dict(co->co_cellvars, ncells,
1101 locals, fast + co->co_nlocals, 1))
1102 return -1;
1103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 /* If the namespace is unoptimized, then one of the
1105 following cases applies:
1106 1. It does not contain free variables, because it
1107 uses import * or is a top-level namespace.
1108 2. It is a class namespace.
1109 We don't want to accidentally copy free variables
1110 into the locals dict used by the class.
1111 */
1112 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001113 if (map_to_dict(co->co_freevars, nfreevars,
1114 locals, fast + co->co_nlocals + ncells, 1) < 0)
1115 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 }
1117 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001118 return 0;
1119}
1120
1121void
1122PyFrame_FastToLocals(PyFrameObject *f)
1123{
1124 int res;
1125
1126 assert(!PyErr_Occurred());
1127
1128 res = PyFrame_FastToLocalsWithError(f);
1129 if (res < 0)
1130 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001131}
1132
1133void
Fred Drake1b190b42000-07-09 05:40:56 +00001134PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* Merge f->f_locals into fast locals */
1137 PyObject *locals, *map;
1138 PyObject **fast;
1139 PyObject *error_type, *error_value, *error_traceback;
1140 PyCodeObject *co;
1141 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001142 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (f == NULL)
1144 return;
1145 locals = f->f_locals;
1146 co = f->f_code;
1147 map = co->co_varnames;
1148 if (locals == NULL)
1149 return;
1150 if (!PyTuple_Check(map))
1151 return;
1152 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1153 fast = f->f_localsplus;
1154 j = PyTuple_GET_SIZE(map);
1155 if (j > co->co_nlocals)
1156 j = co->co_nlocals;
1157 if (co->co_nlocals)
1158 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1159 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1160 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1161 if (ncells || nfreevars) {
1162 dict_to_map(co->co_cellvars, ncells,
1163 locals, fast + co->co_nlocals, 1, clear);
1164 /* Same test as in PyFrame_FastToLocals() above. */
1165 if (co->co_flags & CO_OPTIMIZED) {
1166 dict_to_map(co->co_freevars, nfreevars,
1167 locals, fast + co->co_nlocals + ncells, 1,
1168 clear);
1169 }
1170 }
1171 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001172}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001173
1174/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001175void
Victor Stinner3744ed22020-06-05 01:39:24 +02001176_PyFrame_ClearFreeList(PyThreadState *tstate)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001177{
Victor Stinner3744ed22020-06-05 01:39:24 +02001178 struct _Py_frame_state *state = &tstate->interp->frame;
1179 while (state->free_list != NULL) {
1180 PyFrameObject *f = state->free_list;
1181 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001183 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001185 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001186}
1187
1188void
Victor Stinner3744ed22020-06-05 01:39:24 +02001189_PyFrame_Fini(PyThreadState *tstate)
Christian Heimesa156e092008-02-16 07:38:31 +00001190{
Victor Stinner3744ed22020-06-05 01:39:24 +02001191 _PyFrame_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001192#ifdef Py_DEBUG
1193 struct _Py_frame_state *state = &tstate->interp->frame;
1194 state->numfree = -1;
1195#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001196}
David Malcolm49526f42012-06-22 14:55:41 -04001197
1198/* Print summary info about the state of the optimized allocator */
1199void
1200_PyFrame_DebugMallocStats(FILE *out)
1201{
Victor Stinner522691c2020-06-23 16:40:40 +02001202 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001203 _PyDebugAllocatorStats(out,
1204 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001205 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001206}
1207
Victor Stinnera42ca742020-04-28 19:01:31 +02001208
1209PyCodeObject *
1210PyFrame_GetCode(PyFrameObject *frame)
1211{
1212 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001213 PyCodeObject *code = frame->f_code;
1214 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001215 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001216 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001217}
Victor Stinner70364772020-04-29 03:28:46 +02001218
1219
1220PyFrameObject*
1221PyFrame_GetBack(PyFrameObject *frame)
1222{
1223 assert(frame != NULL);
1224 PyFrameObject *back = frame->f_back;
1225 Py_XINCREF(back);
1226 return back;
1227}