blob: 4f5054d32bb01185232371bb4ec20e86af5c2b4d [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
Guido van Rossum18752471997-04-29 14:49:28 +000025static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000026frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000027{
Victor Stinner41bb43a2013-10-29 01:19:37 +010028 if (PyFrame_FastToLocalsWithError(f) < 0)
29 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 Py_INCREF(f->f_locals);
31 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000032}
33
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000034int
35PyFrame_GetLineNumber(PyFrameObject *f)
36{
Victor Stinner7c59d7c2020-04-28 16:32:48 +020037 assert(f != NULL);
38 if (f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 return f->f_lineno;
Victor Stinner7c59d7c2020-04-28 16:32:48 +020040 }
41 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Victor Stinner7c59d7c2020-04-28 16:32:48 +020043 }
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000044}
45
Michael W. Hudsondd32a912002-08-15 14:59:02 +000046static PyObject *
47frame_getlineno(PyFrameObject *f, void *closure)
48{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000050}
51
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020052
53/* Given the index of the effective opcode,
54 scan back to construct the oparg with EXTENDED_ARG */
55static unsigned int
56get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
57{
58 _Py_CODEUNIT word;
59 unsigned int oparg = _Py_OPARG(codestr[i]);
60 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
61 oparg |= _Py_OPARG(word) << 8;
62 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
63 oparg |= _Py_OPARG(word) << 16;
64 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
65 oparg |= _Py_OPARG(word) << 24;
66 }
67 }
68 }
69 return oparg;
70}
71
Mark Shannon57697242020-04-29 16:49:45 +010072typedef enum kind {
73 With = 1,
74 Loop = 2,
75 Try = 3,
76 Except = 4,
77} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +000078
Mark Shannon57697242020-04-29 16:49:45 +010079#define BITS_PER_BLOCK 3
80
81static inline int64_t
82push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +000083{
Mark Shannon57697242020-04-29 16:49:45 +010084 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
85 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +000086}
87
Mark Shannon57697242020-04-29 16:49:45 +010088static inline int64_t
89pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +000090{
Mark Shannon57697242020-04-29 16:49:45 +010091 assert(stack > 0);
92 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +000093}
94
Mark Shannon57697242020-04-29 16:49:45 +010095static inline Kind
96top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +000097{
Mark Shannon57697242020-04-29 16:49:45 +010098 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +000099}
100
Mark Shannon57697242020-04-29 16:49:45 +0100101static int64_t *
102markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000103{
Mark Shannon57697242020-04-29 16:49:45 +0100104 const _Py_CODEUNIT *code =
105 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
106 int64_t *blocks = PyMem_New(int64_t, len+1);
107 int i, j, opcode;
108
109 if (blocks == NULL) {
110 PyErr_NoMemory();
111 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000112 }
Mark Shannon57697242020-04-29 16:49:45 +0100113 memset(blocks, -1, (len+1)*sizeof(int64_t));
114 blocks[0] = 0;
115 int todo = 1;
116 while (todo) {
117 todo = 0;
118 for (i = 0; i < len; i++) {
119 int64_t block_stack = blocks[i];
120 int64_t except_stack;
121 if (block_stack == -1) {
122 continue;
123 }
124 opcode = _Py_OPCODE(code[i]);
125 switch (opcode) {
126 case JUMP_IF_FALSE_OR_POP:
127 case JUMP_IF_TRUE_OR_POP:
128 case POP_JUMP_IF_FALSE:
129 case POP_JUMP_IF_TRUE:
130 case JUMP_IF_NOT_EXC_MATCH:
131 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
132 assert(j < len);
133 if (blocks[j] == -1 && j < i) {
134 todo = 1;
135 }
136 assert(blocks[j] == -1 || blocks[j] == block_stack);
137 blocks[j] = block_stack;
138 blocks[i+1] = block_stack;
139 break;
140 case JUMP_ABSOLUTE:
141 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
142 assert(j < len);
143 if (blocks[j] == -1 && j < i) {
144 todo = 1;
145 }
146 assert(blocks[j] == -1 || blocks[j] == block_stack);
147 blocks[j] = block_stack;
148 break;
149 case SETUP_FINALLY:
150 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
151 assert(j < len);
152 except_stack = push_block(block_stack, Except);
153 assert(blocks[j] == -1 || blocks[j] == except_stack);
154 blocks[j] = except_stack;
155 block_stack = push_block(block_stack, Try);
156 blocks[i+1] = block_stack;
157 break;
158 case SETUP_WITH:
159 case SETUP_ASYNC_WITH:
160 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
161 assert(j < len);
162 except_stack = push_block(block_stack, Except);
163 assert(blocks[j] == -1 || blocks[j] == except_stack);
164 blocks[j] = except_stack;
165 block_stack = push_block(block_stack, With);
166 blocks[i+1] = block_stack;
167 break;
168 case JUMP_FORWARD:
169 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
170 assert(j < len);
171 assert(blocks[j] == -1 || blocks[j] == block_stack);
172 blocks[j] = block_stack;
173 break;
174 case GET_ITER:
175 case GET_AITER:
176 block_stack = push_block(block_stack, Loop);
177 blocks[i+1] = block_stack;
178 break;
179 case FOR_ITER:
180 blocks[i+1] = block_stack;
181 block_stack = pop_block(block_stack);
182 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
183 assert(j < len);
184 assert(blocks[j] == -1 || blocks[j] == block_stack);
185 blocks[j] = block_stack;
186 break;
187 case POP_BLOCK:
188 case POP_EXCEPT:
189 block_stack = pop_block(block_stack);
190 blocks[i+1] = block_stack;
191 break;
192 case END_ASYNC_FOR:
193 block_stack = pop_block(pop_block(block_stack));
194 blocks[i+1] = block_stack;
195 break;
196 case RETURN_VALUE:
197 case RAISE_VARARGS:
198 case RERAISE:
199 /* End of block */
200 break;
201 default:
202 blocks[i+1] = block_stack;
203
204 }
205 }
206 }
207 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000208}
209
210static int
Mark Shannon57697242020-04-29 16:49:45 +0100211compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000212{
Mark Shannon57697242020-04-29 16:49:45 +0100213 if (to_stack < 0) {
214 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000215 }
Mark Shannon57697242020-04-29 16:49:45 +0100216 while(from_stack > to_stack) {
217 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000218 }
Mark Shannon57697242020-04-29 16:49:45 +0100219 return from_stack == to_stack;
220}
221
222static const char *
223explain_incompatible_block_stack(int64_t to_stack)
224{
225 Kind target_kind = top_block(to_stack);
226 switch(target_kind) {
227 case Except:
228 return "can't jump into an 'except' block as there's no exception";
229 case Try:
230 return "can't jump into the body of a try statement";
231 case With:
232 return "can't jump into the body of a with statement";
233 case Loop:
234 return "can't jump into the body of a for loop";
235 default:
236 Py_UNREACHABLE();
237 }
238}
239
240static int *
241marklines(PyCodeObject *code, int len)
242{
243 int *linestarts = PyMem_New(int, len);
244 if (linestarts == NULL) {
245 return NULL;
246 }
247 Py_ssize_t size = PyBytes_GET_SIZE(code->co_lnotab) / 2;
248 unsigned char *p = (unsigned char*)PyBytes_AS_STRING(code->co_lnotab);
249 int line = code->co_firstlineno;
250 int addr = 0;
251 int index = 0;
252 while (--size >= 0) {
253 addr += *p++;
254 if (index*2 < addr) {
255 linestarts[index++] = line;
256 }
257 while (index*2 < addr) {
258 linestarts[index++] = -1;
259 if (index >= len) {
260 break;
261 }
262 }
263 line += (signed char)*p;
264 p++;
265 }
266 if (index < len) {
267 linestarts[index++] = line;
268 }
269 while (index < len) {
270 linestarts[index++] = -1;
271 }
272 assert(index == len);
273 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000274}
275
276static int
Mark Shannon57697242020-04-29 16:49:45 +0100277first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000278{
279 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100280 for (int i = 0; i < len; i++) {
281 if (lines[i] < result && lines[i] >= line) {
282 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000283 }
Mark Shannonfee55262019-11-21 09:11:43 +0000284 }
285 if (result == INT_MAX) {
286 return -1;
287 }
288 return result;
289}
290
Mark Shannonfee55262019-11-21 09:11:43 +0000291static void
292frame_stack_pop(PyFrameObject *f)
293{
294 PyObject *v = (*--f->f_stacktop);
295 Py_DECREF(v);
296}
297
298static void
299frame_block_unwind(PyFrameObject *f)
300{
301 assert(f->f_iblock > 0);
302 f->f_iblock--;
303 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Victor Stinner629023c2020-01-21 12:47:29 +0100304 intptr_t delta = (f->f_stacktop - f->f_valuestack) - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000305 while (delta > 0) {
306 frame_stack_pop(f);
307 delta--;
308 }
309}
310
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200311
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000312/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000314 * lines are OK to jump to because they don't make any assumptions about the
315 * state of the stack (obvious because you could remove the line and the code
316 * would still work without any stack errors), but there are some constructs
317 * that limit jumping:
318 *
319 * o Lines with an 'except' statement on them can't be jumped to, because
320 * they expect an exception to be on the top of the stack.
321 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000322 * we cannot be sure which state the interpreter was in or would be in
323 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200324 * o 'try', 'with' and 'async with' blocks can't be jumped into because
325 * the blockstack needs to be set up before their code runs.
326 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000327 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100328 * o Jumps cannot be made from within a trace function invoked with a
329 * 'return' or 'exception' event since the eval loop has been exited at
330 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000331 */
332static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200333frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000334{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700335 if (p_new_lineno == NULL) {
336 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
337 return -1;
338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* f_lineno must be an integer. */
340 if (!PyLong_CheckExact(p_new_lineno)) {
341 PyErr_SetString(PyExc_ValueError,
342 "lineno must be an integer");
343 return -1;
344 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000345
xdegayeb8e9d6c2018-03-13 18:31:31 +0100346 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
347 * f->f_trace is NULL, check first on the first condition.
348 * Forbidding jumps from the 'call' event of a new frame is a side effect
349 * of allowing to set f_lineno only from trace functions. */
350 if (f->f_lasti == -1) {
351 PyErr_Format(PyExc_ValueError,
352 "can't jump from the 'call' trace event of a new frame");
353 return -1;
354 }
355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 /* You can only do this from within a trace function, not via
357 * _getframe or similar hackery. */
xdegayeb8e9d6c2018-03-13 18:31:31 +0100358 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100360 "f_lineno can only be set by a trace function");
361 return -1;
362 }
363
364 /* Forbid jumps upon a 'return' trace event (except after executing a
365 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
366 * and upon an 'exception' trace event.
367 * Jumps from 'call' trace events have already been forbidden above for new
368 * frames, so this check does not change anything for 'call' events. */
369 if (f->f_stacktop == NULL) {
370 PyErr_SetString(PyExc_ValueError,
371 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 return -1;
373 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000374
Mark Shannonfee55262019-11-21 09:11:43 +0000375 int new_lineno;
376
Mark Shannon57697242020-04-29 16:49:45 +0100377 /* Fail if the line falls outside the code block and
378 select first line with actual code. */
379 int overflow;
380 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
381 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000382#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100383 || l_new_lineno > INT_MAX
384 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000385#endif
Mark Shannon57697242020-04-29 16:49:45 +0100386 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000387 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100388 "lineno out of range");
389 return -1;
390 }
391 new_lineno = (int)l_new_lineno;
392
393 if (new_lineno < f->f_code->co_firstlineno) {
394 PyErr_Format(PyExc_ValueError,
395 "line %d comes before the current code block",
396 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 return -1;
398 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000399
Mark Shannon57697242020-04-29 16:49:45 +0100400 int len = PyBytes_GET_SIZE(f->f_code->co_code)/sizeof(_Py_CODEUNIT);
401 int *lines = marklines(f->f_code, len);
402 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 return -1;
404 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000405
Mark Shannon57697242020-04-29 16:49:45 +0100406 new_lineno = first_line_not_before(lines, len, new_lineno);
407 if (new_lineno < 0) {
408 PyErr_Format(PyExc_ValueError,
409 "line %d comes after the current code block",
410 (int)l_new_lineno);
411 PyMem_Free(lines);
412 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000413 }
414
Mark Shannon57697242020-04-29 16:49:45 +0100415 int64_t *blocks = markblocks(f->f_code, len);
416 if (blocks == NULL) {
417 PyMem_Free(lines);
418 return -1;
419 }
420
421 int64_t target_block_stack = -1;
422 int64_t best_block_stack = -1;
423 int best_addr = -1;
424 int64_t start_block_stack = blocks[f->f_lasti/sizeof(_Py_CODEUNIT)];
425 const char *msg = "cannot find bytecode for specified line";
426 for (int i = 0; i < len; i++) {
427 if (lines[i] == new_lineno) {
428 target_block_stack = blocks[i];
429 if (compatible_block_stack(start_block_stack, target_block_stack)) {
430 msg = NULL;
431 if (target_block_stack > best_block_stack) {
432 best_block_stack = target_block_stack;
433 best_addr = i*sizeof(_Py_CODEUNIT);
434 }
435 }
436 else if (msg) {
437 if (target_block_stack >= 0) {
438 msg = explain_incompatible_block_stack(target_block_stack);
439 }
440 else {
441 msg = "code may be unreachable.";
442 }
443 }
Mark Shannonfee55262019-11-21 09:11:43 +0000444 }
445 }
Mark Shannon57697242020-04-29 16:49:45 +0100446 PyMem_Free(blocks);
447 PyMem_Free(lines);
448 if (msg != NULL) {
449 PyErr_SetString(PyExc_ValueError, msg);
450 return -1;
451 }
Mark Shannonfee55262019-11-21 09:11:43 +0000452
453 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100454 while (start_block_stack > best_block_stack) {
455 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000456 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100457 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000458 frame_stack_pop(f);
459 break;
Mark Shannon57697242020-04-29 16:49:45 +0100460 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000461 frame_block_unwind(f);
462 break;
Mark Shannon57697242020-04-29 16:49:45 +0100463 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000464 frame_block_unwind(f);
465 // Pop the exit function
466 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 break;
Mark Shannon57697242020-04-29 16:49:45 +0100468 case Except:
469 PyErr_SetString(PyExc_ValueError,
470 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000471 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 }
Mark Shannon57697242020-04-29 16:49:45 +0100473 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 }
Mark Shannonfee55262019-11-21 09:11:43 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Finally set the new f_lineno and f_lasti and return OK. */
477 f->f_lineno = new_lineno;
Mark Shannon57697242020-04-29 16:49:45 +0100478 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000480}
481
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000482static PyObject *
483frame_gettrace(PyFrameObject *f, void *closure)
484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (trace == NULL)
488 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000493}
494
495static int
496frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* We rely on f_lineno being accurate when f_trace is set. */
499 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000500
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300501 if (v == Py_None)
502 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300504 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000507}
508
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000509
Guido van Rossum32d34c82001-09-20 21:45:26 +0000510static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 {"f_locals", (getter)frame_getlocals, NULL, NULL},
512 {"f_lineno", (getter)frame_getlineno,
513 (setter)frame_setlineno, NULL},
514 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
515 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000516};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000517
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000518/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000519 In an attempt to improve the speed of function calls, we:
520
521 1. Hold a single "zombie" frame on each code object. This retains
522 the allocated and initialised frame object from an invocation of
523 the code object. The zombie is reanimated the next time we need a
524 frame object for that code object. Doing this saves the malloc/
525 realloc required when using a free_list frame that isn't the
526 correct size. It also saves some field initialisation.
527
528 In zombie mode, no field of PyFrameObject holds a reference, but
529 the following fields are still valid:
530
531 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532
Mark Shannonae3087c2017-10-22 22:41:51 +0100533 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534
535 * f_localsplus does not require re-allocation and
536 the local variables in f_localsplus are NULL.
537
538 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000539 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 a stack frame is on the free list, only the following members have
541 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 ob_type == &Frametype
543 f_back next item on free list, or NULL
544 f_stacksize size of value stack
545 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000546 Note that the value and block stacks are preserved -- this can save
547 another malloc() call or two (and two free() calls as well!).
548 Also note that, unlike for integers, each frame object is a
549 malloc'ed object in its own right -- it is only the actual calls to
550 malloc() that we are trying to save here, not the administration.
551 After all, while a typical program may make millions of calls, a
552 call depth of more than 20 or 30 is probably already exceptional
553 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000554
Christian Heimes2202f872008-02-06 14:31:34 +0000555 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000556 free_list. Else programs creating lots of cyclic trash involving
557 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000558*/
559
Guido van Rossum18752471997-04-29 14:49:28 +0000560static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561static int numfree = 0; /* number of frames currently in free_list */
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{
Antoine Pitrou93963562013-05-14 20:37:52 +0200568 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000570
INADA Naoki5a625d02016-12-24 20:19:08 +0900571 if (_PyObject_GC_IS_TRACKED(f))
572 _PyObject_GC_UNTRACK(f);
573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200575 /* Kill all local variables */
576 valuestack = f->f_valuestack;
577 for (p = f->f_localsplus; p < valuestack; p++)
578 Py_CLEAR(*p);
579
580 /* Free stack */
581 if (f->f_stacktop != NULL) {
582 for (p = valuestack; p < f->f_stacktop; p++)
583 Py_XDECREF(*p);
584 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 Py_XDECREF(f->f_back);
587 Py_DECREF(f->f_builtins);
588 Py_DECREF(f->f_globals);
589 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200590 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 co = f->f_code;
593 if (co->co_zombieframe == NULL)
594 co->co_zombieframe = f;
595 else if (numfree < PyFrame_MAXFREELIST) {
596 ++numfree;
597 f->f_back = free_list;
598 free_list = f;
599 }
600 else
601 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 Py_DECREF(co);
604 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000605}
606
Victor Stinner6d86a232020-04-29 00:56:58 +0200607static inline Py_ssize_t
608frame_nslots(PyFrameObject *frame)
609{
610 PyCodeObject *code = frame->f_code;
611 return (code->co_nlocals
612 + PyTuple_GET_SIZE(code->co_cellvars)
613 + PyTuple_GET_SIZE(code->co_freevars));
614}
615
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000616static int
617frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 Py_VISIT(f->f_back);
620 Py_VISIT(f->f_code);
621 Py_VISIT(f->f_builtins);
622 Py_VISIT(f->f_globals);
623 Py_VISIT(f->f_locals);
624 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200627 PyObject **fastlocals = f->f_localsplus;
628 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200630 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 /* stack */
633 if (f->f_stacktop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200634 for (PyObject **p = f->f_valuestack; p < f->f_stacktop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 Py_VISIT(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200636 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
638 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000639}
640
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200641static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200642frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000643{
Antoine Pitrou93963562013-05-14 20:37:52 +0200644 /* Before anything else, make sure that this frame is clearly marked
645 * as being defunct! Else, e.g., a generator reachable from this
646 * frame may also point to this frame, believe itself to still be
647 * active, and try cleaning up this frame again.
648 */
Victor Stinner6d86a232020-04-29 00:56:58 +0200649 PyObject **oldtop = f->f_stacktop;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200651 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200656 PyObject **fastlocals = f->f_localsplus;
657 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200659 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 /* stack */
662 if (oldtop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200663 for (PyObject **p = f->f_valuestack; p < oldtop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 Py_CLEAR(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200667 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000668}
669
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000670static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530671frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200672{
673 if (f->f_executing) {
674 PyErr_SetString(PyExc_RuntimeError,
675 "cannot clear an executing frame");
676 return NULL;
677 }
678 if (f->f_gen) {
679 _PyGen_Finalize(f->f_gen);
680 assert(f->f_gen == NULL);
681 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200682 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200683 Py_RETURN_NONE;
684}
685
686PyDoc_STRVAR(clear__doc__,
687"F.clear(): clear most references held by the frame");
688
689static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530690frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000693
Victor Stinner6d86a232020-04-29 00:56:58 +0200694 PyCodeObject *code = f->f_code;
695 ncells = PyTuple_GET_SIZE(code->co_cellvars);
696 nfrees = PyTuple_GET_SIZE(code->co_freevars);
697 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 /* subtract one as it is already included in PyFrameObject */
699 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000702}
703
704PyDoc_STRVAR(sizeof__doc__,
705"F.__sizeof__() -> size of F in memory, in bytes");
706
Antoine Pitrou14709142017-12-31 22:35:22 +0100707static PyObject *
708frame_repr(PyFrameObject *f)
709{
710 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200711 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100712 return PyUnicode_FromFormat(
713 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200714 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100715}
716
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000717static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200718 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
719 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
721 sizeof__doc__},
722 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000723};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000724
Guido van Rossum18752471997-04-29 14:49:28 +0000725PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyVarObject_HEAD_INIT(&PyType_Type, 0)
727 "frame",
728 sizeof(PyFrameObject),
729 sizeof(PyObject *),
730 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200731 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 0, /* tp_getattr */
733 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200734 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100735 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 0, /* tp_as_number */
737 0, /* tp_as_sequence */
738 0, /* tp_as_mapping */
739 0, /* tp_hash */
740 0, /* tp_call */
741 0, /* tp_str */
742 PyObject_GenericGetAttr, /* tp_getattro */
743 PyObject_GenericSetAttr, /* tp_setattro */
744 0, /* tp_as_buffer */
745 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
746 0, /* tp_doc */
747 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200748 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 0, /* tp_richcompare */
750 0, /* tp_weaklistoffset */
751 0, /* tp_iter */
752 0, /* tp_iternext */
753 frame_methods, /* tp_methods */
754 frame_memberlist, /* tp_members */
755 frame_getsetlist, /* tp_getset */
756 0, /* tp_base */
757 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000758};
759
Victor Stinner07e9e382013-11-07 22:22:39 +0100760_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000761
Victor Stinnerc6944e72016-11-11 02:13:35 +0100762PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900763_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
764 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyFrameObject *back = tstate->frame;
767 PyFrameObject *f;
768 PyObject *builtins;
769 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000770
Michael W. Hudson69734a52002-08-19 16:54:08 +0000771#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
773 (locals != NULL && !PyMapping_Check(locals))) {
774 PyErr_BadInternalCall();
775 return NULL;
776 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000777#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (back == NULL || back->f_globals != globals) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200779 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (builtins) {
781 if (PyModule_Check(builtins)) {
782 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200783 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 }
786 if (builtins == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200787 if (PyErr_Occurred()) {
788 return NULL;
789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /* No builtins! Make up a minimal one
791 Give them 'None', at least. */
792 builtins = PyDict_New();
793 if (builtins == NULL ||
794 PyDict_SetItemString(
795 builtins, "None", Py_None) < 0)
796 return NULL;
797 }
798 else
799 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 }
802 else {
803 /* If we share the globals, we share the builtins.
804 Save a lookup and a call. */
805 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200806 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 Py_INCREF(builtins);
808 }
809 if (code->co_zombieframe != NULL) {
810 f = code->co_zombieframe;
811 code->co_zombieframe = NULL;
812 _Py_NewReference((PyObject *)f);
813 assert(f->f_code == code);
814 }
815 else {
816 Py_ssize_t extras, ncells, nfrees;
817 ncells = PyTuple_GET_SIZE(code->co_cellvars);
818 nfrees = PyTuple_GET_SIZE(code->co_freevars);
819 extras = code->co_stacksize + code->co_nlocals + ncells +
820 nfrees;
821 if (free_list == NULL) {
822 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
823 extras);
824 if (f == NULL) {
825 Py_DECREF(builtins);
826 return NULL;
827 }
828 }
829 else {
830 assert(numfree > 0);
831 --numfree;
832 f = free_list;
833 free_list = free_list->f_back;
834 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000835 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
836 if (new_f == NULL) {
837 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 Py_DECREF(builtins);
839 return NULL;
840 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000841 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
843 _Py_NewReference((PyObject *)f);
844 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 f->f_code = code;
847 extras = code->co_nlocals + ncells + nfrees;
848 f->f_valuestack = f->f_localsplus + extras;
849 for (i=0; i<extras; i++)
850 f->f_localsplus[i] = NULL;
851 f->f_locals = NULL;
852 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 }
854 f->f_stacktop = f->f_valuestack;
855 f->f_builtins = builtins;
856 Py_XINCREF(back);
857 f->f_back = back;
858 Py_INCREF(code);
859 Py_INCREF(globals);
860 f->f_globals = globals;
861 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
862 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
863 (CO_NEWLOCALS | CO_OPTIMIZED))
864 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
865 else if (code->co_flags & CO_NEWLOCALS) {
866 locals = PyDict_New();
867 if (locals == NULL) {
868 Py_DECREF(f);
869 return NULL;
870 }
871 f->f_locals = locals;
872 }
873 else {
874 if (locals == NULL)
875 locals = globals;
876 Py_INCREF(locals);
877 f->f_locals = locals;
878 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 f->f_lasti = -1;
881 f->f_lineno = code->co_firstlineno;
882 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200883 f->f_executing = 0;
884 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000885 f->f_trace_opcodes = 0;
886 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000887
Victor Stinner6d86a232020-04-29 00:56:58 +0200888 assert(f->f_code != NULL);
889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000891}
892
INADA Naoki5a625d02016-12-24 20:19:08 +0900893PyFrameObject*
894PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
895 PyObject *globals, PyObject *locals)
896{
897 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
898 if (f)
899 _PyObject_GC_TRACK(f);
900 return f;
901}
902
903
Guido van Rossum3f5da241990-12-20 15:06:42 +0000904/* Block management */
905
906void
Fred Drake1b190b42000-07-09 05:40:56 +0000907PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100910 if (f->f_iblock >= CO_MAXBLOCKS) {
911 Py_FatalError("block stack overflow");
912 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 b = &f->f_blockstack[f->f_iblock++];
914 b->b_type = type;
915 b->b_level = level;
916 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000917}
918
Guido van Rossum18752471997-04-29 14:49:28 +0000919PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000920PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100923 if (f->f_iblock <= 0) {
924 Py_FatalError("block stack underflow");
925 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 b = &f->f_blockstack[--f->f_iblock];
927 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000928}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000929
Guido van Rossumd8faa362007-04-27 19:54:29 +0000930/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931
932 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933 values is an array of PyObject*. At index i, map[i] is the name of
934 the variable with value values[i]. The function copies the first
935 nmap variable from map/values into dict. If values[i] is NULL,
936 the variable is deleted from dict.
937
938 If deref is true, then the values being copied are cell variables
939 and the value is extracted from the cell variable before being put
940 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000942
Victor Stinner41bb43a2013-10-29 01:19:37 +0100943static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000944map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 Py_ssize_t j;
948 assert(PyTuple_Check(map));
949 assert(PyDict_Check(dict));
950 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800951 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyObject *key = PyTuple_GET_ITEM(map, j);
953 PyObject *value = values[j];
954 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400955 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 assert(PyCell_Check(value));
957 value = PyCell_GET(value);
958 }
959 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100960 if (PyObject_DelItem(dict, key) != 0) {
961 if (PyErr_ExceptionMatches(PyExc_KeyError))
962 PyErr_Clear();
963 else
964 return -1;
965 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
967 else {
968 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100969 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 }
971 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100972 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000973}
974
Guido van Rossumd8faa362007-04-27 19:54:29 +0000975/* Copy values from the "locals" dict into the fast locals.
976
977 dict is an input argument containing string keys representing
978 variables names and arbitrary PyObject* as values.
979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 values is an array of PyObject*. At index i, map[i] is the name of
982 the variable with value values[i]. The function copies the first
983 nmap variable from map/values into dict. If values[i] is NULL,
984 the variable is deleted from dict.
985
986 If deref is true, then the values being copied are cell variables
987 and the value is extracted from the cell variable before being put
988 in dict. If clear is true, then variables in map but not in dict
989 are set to NULL in map; if clear is false, variables missing in
990 dict are ignored.
991
992 Exceptions raised while modifying the dict are silently ignored,
993 because there is no good way to report them.
994*/
995
Guido van Rossum6b356e72001-04-14 17:55:41 +0000996static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000997dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Py_ssize_t j;
1001 assert(PyTuple_Check(map));
1002 assert(PyDict_Check(dict));
1003 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001004 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyObject *key = PyTuple_GET_ITEM(map, j);
1006 PyObject *value = PyObject_GetItem(dict, key);
1007 assert(PyUnicode_Check(key));
1008 /* We only care about NULLs if clear is true. */
1009 if (value == NULL) {
1010 PyErr_Clear();
1011 if (!clear)
1012 continue;
1013 }
1014 if (deref) {
1015 assert(PyCell_Check(values[j]));
1016 if (PyCell_GET(values[j]) != value) {
1017 if (PyCell_Set(values[j], value) < 0)
1018 PyErr_Clear();
1019 }
1020 } else if (values[j] != value) {
1021 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001022 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 }
1024 Py_XDECREF(value);
1025 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001026}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001027
Victor Stinner41bb43a2013-10-29 01:19:37 +01001028int
1029PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 /* Merge fast locals into f->f_locals */
1032 PyObject *locals, *map;
1033 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyCodeObject *co;
1035 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001036 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001037
1038 if (f == NULL) {
1039 PyErr_BadInternalCall();
1040 return -1;
1041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 locals = f->f_locals;
1043 if (locals == NULL) {
1044 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001045 if (locals == NULL)
1046 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 }
1048 co = f->f_code;
1049 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001050 if (!PyTuple_Check(map)) {
1051 PyErr_Format(PyExc_SystemError,
1052 "co_varnames must be a tuple, not %s",
1053 Py_TYPE(map)->tp_name);
1054 return -1;
1055 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 fast = f->f_localsplus;
1057 j = PyTuple_GET_SIZE(map);
1058 if (j > co->co_nlocals)
1059 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001060 if (co->co_nlocals) {
1061 if (map_to_dict(map, j, locals, fast, 0) < 0)
1062 return -1;
1063 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1065 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1066 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001067 if (map_to_dict(co->co_cellvars, ncells,
1068 locals, fast + co->co_nlocals, 1))
1069 return -1;
1070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 /* If the namespace is unoptimized, then one of the
1072 following cases applies:
1073 1. It does not contain free variables, because it
1074 uses import * or is a top-level namespace.
1075 2. It is a class namespace.
1076 We don't want to accidentally copy free variables
1077 into the locals dict used by the class.
1078 */
1079 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001080 if (map_to_dict(co->co_freevars, nfreevars,
1081 locals, fast + co->co_nlocals + ncells, 1) < 0)
1082 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
1084 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001085 return 0;
1086}
1087
1088void
1089PyFrame_FastToLocals(PyFrameObject *f)
1090{
1091 int res;
1092
1093 assert(!PyErr_Occurred());
1094
1095 res = PyFrame_FastToLocalsWithError(f);
1096 if (res < 0)
1097 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001098}
1099
1100void
Fred Drake1b190b42000-07-09 05:40:56 +00001101PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 /* Merge f->f_locals into fast locals */
1104 PyObject *locals, *map;
1105 PyObject **fast;
1106 PyObject *error_type, *error_value, *error_traceback;
1107 PyCodeObject *co;
1108 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001109 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (f == NULL)
1111 return;
1112 locals = f->f_locals;
1113 co = f->f_code;
1114 map = co->co_varnames;
1115 if (locals == NULL)
1116 return;
1117 if (!PyTuple_Check(map))
1118 return;
1119 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1120 fast = f->f_localsplus;
1121 j = PyTuple_GET_SIZE(map);
1122 if (j > co->co_nlocals)
1123 j = co->co_nlocals;
1124 if (co->co_nlocals)
1125 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1126 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1127 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1128 if (ncells || nfreevars) {
1129 dict_to_map(co->co_cellvars, ncells,
1130 locals, fast + co->co_nlocals, 1, clear);
1131 /* Same test as in PyFrame_FastToLocals() above. */
1132 if (co->co_flags & CO_OPTIMIZED) {
1133 dict_to_map(co->co_freevars, nfreevars,
1134 locals, fast + co->co_nlocals + ncells, 1,
1135 clear);
1136 }
1137 }
1138 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001139}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001140
1141/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001142void
1143_PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 while (free_list != NULL) {
1146 PyFrameObject *f = free_list;
1147 free_list = free_list->f_back;
1148 PyObject_GC_Del(f);
1149 --numfree;
1150 }
1151 assert(numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001152}
1153
1154void
Victor Stinnerbed48172019-08-27 00:12:32 +02001155_PyFrame_Fini(void)
Christian Heimesa156e092008-02-16 07:38:31 +00001156{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001157 _PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001158}
David Malcolm49526f42012-06-22 14:55:41 -04001159
1160/* Print summary info about the state of the optimized allocator */
1161void
1162_PyFrame_DebugMallocStats(FILE *out)
1163{
1164 _PyDebugAllocatorStats(out,
1165 "free PyFrameObject",
1166 numfree, sizeof(PyFrameObject));
1167}
1168
Victor Stinnera42ca742020-04-28 19:01:31 +02001169
1170PyCodeObject *
1171PyFrame_GetCode(PyFrameObject *frame)
1172{
1173 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001174 PyCodeObject *code = frame->f_code;
1175 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001176 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001177 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001178}
Victor Stinner70364772020-04-29 03:28:46 +02001179
1180
1181PyFrameObject*
1182PyFrame_GetBack(PyFrameObject *frame)
1183{
1184 assert(frame != NULL);
1185 PyFrameObject *back = frame->f_back;
1186 Py_XINCREF(back);
1187 return back;
1188}