blob: 0dad42ee7bff33c0005268267a78a165843549bb [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
Ammar Askar6e23a9c2020-06-04 05:19:23 +0000400 int len = Py_SAFE_DOWNCAST(
401 PyBytes_GET_SIZE(f->f_code->co_code)/sizeof(_Py_CODEUNIT),
402 Py_ssize_t, int);
Mark Shannon57697242020-04-29 16:49:45 +0100403 int *lines = marklines(f->f_code, len);
404 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return -1;
406 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000407
Mark Shannon57697242020-04-29 16:49:45 +0100408 new_lineno = first_line_not_before(lines, len, new_lineno);
409 if (new_lineno < 0) {
410 PyErr_Format(PyExc_ValueError,
411 "line %d comes after the current code block",
412 (int)l_new_lineno);
413 PyMem_Free(lines);
414 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000415 }
416
Mark Shannon57697242020-04-29 16:49:45 +0100417 int64_t *blocks = markblocks(f->f_code, len);
418 if (blocks == NULL) {
419 PyMem_Free(lines);
420 return -1;
421 }
422
423 int64_t target_block_stack = -1;
424 int64_t best_block_stack = -1;
425 int best_addr = -1;
426 int64_t start_block_stack = blocks[f->f_lasti/sizeof(_Py_CODEUNIT)];
427 const char *msg = "cannot find bytecode for specified line";
428 for (int i = 0; i < len; i++) {
429 if (lines[i] == new_lineno) {
430 target_block_stack = blocks[i];
431 if (compatible_block_stack(start_block_stack, target_block_stack)) {
432 msg = NULL;
433 if (target_block_stack > best_block_stack) {
434 best_block_stack = target_block_stack;
435 best_addr = i*sizeof(_Py_CODEUNIT);
436 }
437 }
438 else if (msg) {
439 if (target_block_stack >= 0) {
440 msg = explain_incompatible_block_stack(target_block_stack);
441 }
442 else {
443 msg = "code may be unreachable.";
444 }
445 }
Mark Shannonfee55262019-11-21 09:11:43 +0000446 }
447 }
Mark Shannon57697242020-04-29 16:49:45 +0100448 PyMem_Free(blocks);
449 PyMem_Free(lines);
450 if (msg != NULL) {
451 PyErr_SetString(PyExc_ValueError, msg);
452 return -1;
453 }
Mark Shannonfee55262019-11-21 09:11:43 +0000454
455 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100456 while (start_block_stack > best_block_stack) {
457 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000458 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100459 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000460 frame_stack_pop(f);
461 break;
Mark Shannon57697242020-04-29 16:49:45 +0100462 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000463 frame_block_unwind(f);
464 break;
Mark Shannon57697242020-04-29 16:49:45 +0100465 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000466 frame_block_unwind(f);
467 // Pop the exit function
468 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 break;
Mark Shannon57697242020-04-29 16:49:45 +0100470 case Except:
471 PyErr_SetString(PyExc_ValueError,
472 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000473 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 }
Mark Shannon57697242020-04-29 16:49:45 +0100475 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 }
Mark Shannonfee55262019-11-21 09:11:43 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Finally set the new f_lineno and f_lasti and return OK. */
479 f->f_lineno = new_lineno;
Mark Shannon57697242020-04-29 16:49:45 +0100480 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000482}
483
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000484static PyObject *
485frame_gettrace(PyFrameObject *f, void *closure)
486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (trace == NULL)
490 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000495}
496
497static int
498frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* We rely on f_lineno being accurate when f_trace is set. */
501 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000502
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300503 if (v == Py_None)
504 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300506 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000509}
510
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000511
Guido van Rossum32d34c82001-09-20 21:45:26 +0000512static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 {"f_locals", (getter)frame_getlocals, NULL, NULL},
514 {"f_lineno", (getter)frame_getlineno,
515 (setter)frame_setlineno, NULL},
516 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
517 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000518};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000519
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000520/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000521 In an attempt to improve the speed of function calls, we:
522
523 1. Hold a single "zombie" frame on each code object. This retains
524 the allocated and initialised frame object from an invocation of
525 the code object. The zombie is reanimated the next time we need a
526 frame object for that code object. Doing this saves the malloc/
527 realloc required when using a free_list frame that isn't the
528 correct size. It also saves some field initialisation.
529
530 In zombie mode, no field of PyFrameObject holds a reference, but
531 the following fields are still valid:
532
533 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534
Mark Shannonae3087c2017-10-22 22:41:51 +0100535 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536
537 * f_localsplus does not require re-allocation and
538 the local variables in f_localsplus are NULL.
539
540 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000541 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542 a stack frame is on the free list, only the following members have
543 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 ob_type == &Frametype
545 f_back next item on free list, or NULL
546 f_stacksize size of value stack
547 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000548 Note that the value and block stacks are preserved -- this can save
549 another malloc() call or two (and two free() calls as well!).
550 Also note that, unlike for integers, each frame object is a
551 malloc'ed object in its own right -- it is only the actual calls to
552 malloc() that we are trying to save here, not the administration.
553 After all, while a typical program may make millions of calls, a
554 call depth of more than 20 or 30 is probably already exceptional
555 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000556
Christian Heimes2202f872008-02-06 14:31:34 +0000557 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000558 free_list. Else programs creating lots of cyclic trash involving
559 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000560*/
Christian Heimes2202f872008-02-06 14:31:34 +0000561/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000563
Victor Stinnerc6944e72016-11-11 02:13:35 +0100564static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000565frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000566{
Victor Stinner3744ed22020-06-05 01:39:24 +0200567 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900568 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200569 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200572 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200573 PyObject **valuestack = f->f_valuestack;
574 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200575 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200576 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200577
578 /* Free stack */
579 if (f->f_stacktop != NULL) {
Victor Stinner3744ed22020-06-05 01:39:24 +0200580 for (PyObject **p = valuestack; p < f->f_stacktop; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200581 Py_XDECREF(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200582 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200583 }
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 Stinner3744ed22020-06-05 01:39:24 +0200596 PyInterpreterState *interp = _PyInterpreterState_GET();
597 struct _Py_frame_state *state = &interp->frame;
Victor Stinnerbcb19832020-06-08 02:14:47 +0200598#ifdef Py_DEBUG
599 // frame_dealloc() must not be called after _PyFrame_Fini()
600 assert(state->numfree != -1);
601#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200602 if (state->numfree < PyFrame_MAXFREELIST) {
603 ++state->numfree;
604 f->f_back = state->free_list;
605 state->free_list = f;
606 }
607 else {
608 PyObject_GC_Del(f);
609 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200610 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 Py_DECREF(co);
613 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000614}
615
Victor Stinner6d86a232020-04-29 00:56:58 +0200616static inline Py_ssize_t
617frame_nslots(PyFrameObject *frame)
618{
619 PyCodeObject *code = frame->f_code;
620 return (code->co_nlocals
621 + PyTuple_GET_SIZE(code->co_cellvars)
622 + PyTuple_GET_SIZE(code->co_freevars));
623}
624
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000625static int
626frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 Py_VISIT(f->f_back);
629 Py_VISIT(f->f_code);
630 Py_VISIT(f->f_builtins);
631 Py_VISIT(f->f_globals);
632 Py_VISIT(f->f_locals);
633 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200636 PyObject **fastlocals = f->f_localsplus;
637 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200639 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 /* stack */
642 if (f->f_stacktop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200643 for (PyObject **p = f->f_valuestack; p < f->f_stacktop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 Py_VISIT(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 }
647 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000648}
649
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200650static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200651frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000652{
Antoine Pitrou93963562013-05-14 20:37:52 +0200653 /* Before anything else, make sure that this frame is clearly marked
654 * as being defunct! Else, e.g., a generator reachable from this
655 * frame may also point to this frame, believe itself to still be
656 * active, and try cleaning up this frame again.
657 */
Victor Stinner6d86a232020-04-29 00:56:58 +0200658 PyObject **oldtop = f->f_stacktop;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200660 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200665 PyObject **fastlocals = f->f_localsplus;
666 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200668 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 /* stack */
671 if (oldtop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200672 for (PyObject **p = f->f_valuestack; p < oldtop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 Py_CLEAR(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200676 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000677}
678
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000679static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530680frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200681{
682 if (f->f_executing) {
683 PyErr_SetString(PyExc_RuntimeError,
684 "cannot clear an executing frame");
685 return NULL;
686 }
687 if (f->f_gen) {
688 _PyGen_Finalize(f->f_gen);
689 assert(f->f_gen == NULL);
690 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200691 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200692 Py_RETURN_NONE;
693}
694
695PyDoc_STRVAR(clear__doc__,
696"F.clear(): clear most references held by the frame");
697
698static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530699frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000702
Victor Stinner6d86a232020-04-29 00:56:58 +0200703 PyCodeObject *code = f->f_code;
704 ncells = PyTuple_GET_SIZE(code->co_cellvars);
705 nfrees = PyTuple_GET_SIZE(code->co_freevars);
706 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 /* subtract one as it is already included in PyFrameObject */
708 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000711}
712
713PyDoc_STRVAR(sizeof__doc__,
714"F.__sizeof__() -> size of F in memory, in bytes");
715
Antoine Pitrou14709142017-12-31 22:35:22 +0100716static PyObject *
717frame_repr(PyFrameObject *f)
718{
719 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200720 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100721 return PyUnicode_FromFormat(
722 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200723 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100724}
725
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000726static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200727 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
728 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
730 sizeof__doc__},
731 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000732};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000733
Guido van Rossum18752471997-04-29 14:49:28 +0000734PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyVarObject_HEAD_INIT(&PyType_Type, 0)
736 "frame",
737 sizeof(PyFrameObject),
738 sizeof(PyObject *),
739 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200740 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 0, /* tp_getattr */
742 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200743 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100744 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 0, /* tp_as_number */
746 0, /* tp_as_sequence */
747 0, /* tp_as_mapping */
748 0, /* tp_hash */
749 0, /* tp_call */
750 0, /* tp_str */
751 PyObject_GenericGetAttr, /* tp_getattro */
752 PyObject_GenericSetAttr, /* tp_setattro */
753 0, /* tp_as_buffer */
754 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
755 0, /* tp_doc */
756 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200757 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 0, /* tp_richcompare */
759 0, /* tp_weaklistoffset */
760 0, /* tp_iter */
761 0, /* tp_iternext */
762 frame_methods, /* tp_methods */
763 frame_memberlist, /* tp_members */
764 frame_getsetlist, /* tp_getset */
765 0, /* tp_base */
766 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000767};
768
Victor Stinner07e9e382013-11-07 22:22:39 +0100769_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000770
Victor Stinnerb4b53862020-05-05 19:55:29 +0200771static inline PyFrameObject*
772frame_alloc(PyCodeObject *code)
773{
774 PyFrameObject *f;
775
776 f = code->co_zombieframe;
777 if (f != NULL) {
778 code->co_zombieframe = NULL;
779 _Py_NewReference((PyObject *)f);
780 assert(f->f_code == code);
781 return f;
782 }
783
784 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
785 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
786 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner3744ed22020-06-05 01:39:24 +0200787 PyInterpreterState *interp = _PyInterpreterState_GET();
788 struct _Py_frame_state *state = &interp->frame;
789 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200790 {
791 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
792 if (f == NULL) {
793 return NULL;
794 }
795 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200796 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200797#ifdef Py_DEBUG
798 // frame_alloc() must not be called after _PyFrame_Fini()
799 assert(state->numfree != -1);
800#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200801 assert(state->numfree > 0);
802 --state->numfree;
803 f = state->free_list;
804 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200805 if (Py_SIZE(f) < extras) {
806 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
807 if (new_f == NULL) {
808 PyObject_GC_Del(f);
809 return NULL;
810 }
811 f = new_f;
812 }
813 _Py_NewReference((PyObject *)f);
814 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200815
816 f->f_code = code;
817 extras = code->co_nlocals + ncells + nfrees;
818 f->f_valuestack = f->f_localsplus + extras;
819 for (Py_ssize_t i=0; i<extras; i++) {
820 f->f_localsplus[i] = NULL;
821 }
822 f->f_locals = NULL;
823 f->f_trace = NULL;
824 return f;
825}
826
827
828static inline PyObject *
829frame_get_builtins(PyFrameObject *back, PyObject *globals)
830{
831 PyObject *builtins;
832
833 if (back != NULL && back->f_globals == globals) {
834 /* If we share the globals, we share the builtins.
835 Save a lookup and a call. */
836 builtins = back->f_builtins;
837 assert(builtins != NULL);
838 Py_INCREF(builtins);
839 return builtins;
840 }
841
842 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
843 if (builtins != NULL && PyModule_Check(builtins)) {
844 builtins = PyModule_GetDict(builtins);
845 assert(builtins != NULL);
846 }
847 if (builtins != NULL) {
848 Py_INCREF(builtins);
849 return builtins;
850 }
851
852 if (PyErr_Occurred()) {
853 return NULL;
854 }
855
856 /* No builtins! Make up a minimal one.
857 Give them 'None', at least. */
858 builtins = PyDict_New();
859 if (builtins == NULL) {
860 return NULL;
861 }
862 if (PyDict_SetItemString(builtins, "None", Py_None) < 0) {
863 Py_DECREF(builtins);
864 return NULL;
865 }
866 return builtins;
867}
868
869
Victor Stinnerc6944e72016-11-11 02:13:35 +0100870PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900871_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
872 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000873{
Michael W. Hudson69734a52002-08-19 16:54:08 +0000874#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
876 (locals != NULL && !PyMapping_Check(locals))) {
877 PyErr_BadInternalCall();
878 return NULL;
879 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000880#endif
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000881
Victor Stinnerb4b53862020-05-05 19:55:29 +0200882 PyFrameObject *back = tstate->frame;
883 PyObject *builtins = frame_get_builtins(back, globals);
884 if (builtins == NULL) {
885 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887
Victor Stinnerb4b53862020-05-05 19:55:29 +0200888 PyFrameObject *f = frame_alloc(code);
889 if (f == NULL) {
890 Py_DECREF(builtins);
891 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 f->f_stacktop = f->f_valuestack;
895 f->f_builtins = builtins;
896 Py_XINCREF(back);
897 f->f_back = back;
898 Py_INCREF(code);
899 Py_INCREF(globals);
900 f->f_globals = globals;
901 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
902 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
903 (CO_NEWLOCALS | CO_OPTIMIZED))
904 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
905 else if (code->co_flags & CO_NEWLOCALS) {
906 locals = PyDict_New();
907 if (locals == NULL) {
908 Py_DECREF(f);
909 return NULL;
910 }
911 f->f_locals = locals;
912 }
913 else {
914 if (locals == NULL)
915 locals = globals;
916 Py_INCREF(locals);
917 f->f_locals = locals;
918 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 f->f_lasti = -1;
921 f->f_lineno = code->co_firstlineno;
922 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200923 f->f_executing = 0;
924 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000925 f->f_trace_opcodes = 0;
926 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000927
Victor Stinner6d86a232020-04-29 00:56:58 +0200928 assert(f->f_code != NULL);
929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000931}
932
INADA Naoki5a625d02016-12-24 20:19:08 +0900933PyFrameObject*
934PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
935 PyObject *globals, PyObject *locals)
936{
937 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
938 if (f)
939 _PyObject_GC_TRACK(f);
940 return f;
941}
942
943
Guido van Rossum3f5da241990-12-20 15:06:42 +0000944/* Block management */
945
946void
Fred Drake1b190b42000-07-09 05:40:56 +0000947PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100950 if (f->f_iblock >= CO_MAXBLOCKS) {
951 Py_FatalError("block stack overflow");
952 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 b = &f->f_blockstack[f->f_iblock++];
954 b->b_type = type;
955 b->b_level = level;
956 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000957}
958
Guido van Rossum18752471997-04-29 14:49:28 +0000959PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000960PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100963 if (f->f_iblock <= 0) {
964 Py_FatalError("block stack underflow");
965 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 b = &f->f_blockstack[--f->f_iblock];
967 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000968}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000969
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971
972 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000973 values is an array of PyObject*. At index i, map[i] is the name of
974 the variable with value values[i]. The function copies the first
975 nmap variable from map/values into dict. If values[i] is NULL,
976 the variable is deleted from dict.
977
978 If deref is true, then the values being copied are cell variables
979 and the value is extracted from the cell variable before being put
980 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000982
Victor Stinner41bb43a2013-10-29 01:19:37 +0100983static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000984map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 Py_ssize_t j;
988 assert(PyTuple_Check(map));
989 assert(PyDict_Check(dict));
990 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800991 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 PyObject *key = PyTuple_GET_ITEM(map, j);
993 PyObject *value = values[j];
994 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400995 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 assert(PyCell_Check(value));
997 value = PyCell_GET(value);
998 }
999 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001000 if (PyObject_DelItem(dict, key) != 0) {
1001 if (PyErr_ExceptionMatches(PyExc_KeyError))
1002 PyErr_Clear();
1003 else
1004 return -1;
1005 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 }
1007 else {
1008 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +01001009 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 }
1011 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001012 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001013}
1014
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015/* Copy values from the "locals" dict into the fast locals.
1016
1017 dict is an input argument containing string keys representing
1018 variables names and arbitrary PyObject* as values.
1019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001021 values is an array of PyObject*. At index i, map[i] is the name of
1022 the variable with value values[i]. The function copies the first
1023 nmap variable from map/values into dict. If values[i] is NULL,
1024 the variable is deleted from dict.
1025
1026 If deref is true, then the values being copied are cell variables
1027 and the value is extracted from the cell variable before being put
1028 in dict. If clear is true, then variables in map but not in dict
1029 are set to NULL in map; if clear is false, variables missing in
1030 dict are ignored.
1031
1032 Exceptions raised while modifying the dict are silently ignored,
1033 because there is no good way to report them.
1034*/
1035
Guido van Rossum6b356e72001-04-14 17:55:41 +00001036static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001037dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 Py_ssize_t j;
1041 assert(PyTuple_Check(map));
1042 assert(PyDict_Check(dict));
1043 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001044 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyObject *key = PyTuple_GET_ITEM(map, j);
1046 PyObject *value = PyObject_GetItem(dict, key);
1047 assert(PyUnicode_Check(key));
1048 /* We only care about NULLs if clear is true. */
1049 if (value == NULL) {
1050 PyErr_Clear();
1051 if (!clear)
1052 continue;
1053 }
1054 if (deref) {
1055 assert(PyCell_Check(values[j]));
1056 if (PyCell_GET(values[j]) != value) {
1057 if (PyCell_Set(values[j], value) < 0)
1058 PyErr_Clear();
1059 }
1060 } else if (values[j] != value) {
1061 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001062 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 }
1064 Py_XDECREF(value);
1065 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001066}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001067
Victor Stinner41bb43a2013-10-29 01:19:37 +01001068int
1069PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 /* Merge fast locals into f->f_locals */
1072 PyObject *locals, *map;
1073 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyCodeObject *co;
1075 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001076 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001077
1078 if (f == NULL) {
1079 PyErr_BadInternalCall();
1080 return -1;
1081 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 locals = f->f_locals;
1083 if (locals == NULL) {
1084 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001085 if (locals == NULL)
1086 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
1088 co = f->f_code;
1089 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001090 if (!PyTuple_Check(map)) {
1091 PyErr_Format(PyExc_SystemError,
1092 "co_varnames must be a tuple, not %s",
1093 Py_TYPE(map)->tp_name);
1094 return -1;
1095 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 fast = f->f_localsplus;
1097 j = PyTuple_GET_SIZE(map);
1098 if (j > co->co_nlocals)
1099 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001100 if (co->co_nlocals) {
1101 if (map_to_dict(map, j, locals, fast, 0) < 0)
1102 return -1;
1103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1105 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1106 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001107 if (map_to_dict(co->co_cellvars, ncells,
1108 locals, fast + co->co_nlocals, 1))
1109 return -1;
1110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 /* If the namespace is unoptimized, then one of the
1112 following cases applies:
1113 1. It does not contain free variables, because it
1114 uses import * or is a top-level namespace.
1115 2. It is a class namespace.
1116 We don't want to accidentally copy free variables
1117 into the locals dict used by the class.
1118 */
1119 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001120 if (map_to_dict(co->co_freevars, nfreevars,
1121 locals, fast + co->co_nlocals + ncells, 1) < 0)
1122 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 }
1124 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001125 return 0;
1126}
1127
1128void
1129PyFrame_FastToLocals(PyFrameObject *f)
1130{
1131 int res;
1132
1133 assert(!PyErr_Occurred());
1134
1135 res = PyFrame_FastToLocalsWithError(f);
1136 if (res < 0)
1137 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001138}
1139
1140void
Fred Drake1b190b42000-07-09 05:40:56 +00001141PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 /* Merge f->f_locals into fast locals */
1144 PyObject *locals, *map;
1145 PyObject **fast;
1146 PyObject *error_type, *error_value, *error_traceback;
1147 PyCodeObject *co;
1148 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001149 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (f == NULL)
1151 return;
1152 locals = f->f_locals;
1153 co = f->f_code;
1154 map = co->co_varnames;
1155 if (locals == NULL)
1156 return;
1157 if (!PyTuple_Check(map))
1158 return;
1159 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1160 fast = f->f_localsplus;
1161 j = PyTuple_GET_SIZE(map);
1162 if (j > co->co_nlocals)
1163 j = co->co_nlocals;
1164 if (co->co_nlocals)
1165 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1166 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1167 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1168 if (ncells || nfreevars) {
1169 dict_to_map(co->co_cellvars, ncells,
1170 locals, fast + co->co_nlocals, 1, clear);
1171 /* Same test as in PyFrame_FastToLocals() above. */
1172 if (co->co_flags & CO_OPTIMIZED) {
1173 dict_to_map(co->co_freevars, nfreevars,
1174 locals, fast + co->co_nlocals + ncells, 1,
1175 clear);
1176 }
1177 }
1178 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001179}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001180
1181/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001182void
Victor Stinner3744ed22020-06-05 01:39:24 +02001183_PyFrame_ClearFreeList(PyThreadState *tstate)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001184{
Victor Stinner3744ed22020-06-05 01:39:24 +02001185 struct _Py_frame_state *state = &tstate->interp->frame;
1186 while (state->free_list != NULL) {
1187 PyFrameObject *f = state->free_list;
1188 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001190 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001192 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001193}
1194
1195void
Victor Stinner3744ed22020-06-05 01:39:24 +02001196_PyFrame_Fini(PyThreadState *tstate)
Christian Heimesa156e092008-02-16 07:38:31 +00001197{
Victor Stinner3744ed22020-06-05 01:39:24 +02001198 _PyFrame_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001199#ifdef Py_DEBUG
1200 struct _Py_frame_state *state = &tstate->interp->frame;
1201 state->numfree = -1;
1202#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001203}
David Malcolm49526f42012-06-22 14:55:41 -04001204
1205/* Print summary info about the state of the optimized allocator */
1206void
1207_PyFrame_DebugMallocStats(FILE *out)
1208{
Victor Stinner3744ed22020-06-05 01:39:24 +02001209 PyInterpreterState *interp = _PyInterpreterState_GET();
1210 struct _Py_frame_state *state = &interp->frame;
David Malcolm49526f42012-06-22 14:55:41 -04001211 _PyDebugAllocatorStats(out,
1212 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001213 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001214}
1215
Victor Stinnera42ca742020-04-28 19:01:31 +02001216
1217PyCodeObject *
1218PyFrame_GetCode(PyFrameObject *frame)
1219{
1220 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001221 PyCodeObject *code = frame->f_code;
1222 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001223 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001224 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001225}
Victor Stinner70364772020-04-29 03:28:46 +02001226
1227
1228PyFrameObject*
1229PyFrame_GetBack(PyFrameObject *frame)
1230{
1231 assert(frame != NULL);
1232 PyFrameObject *back = frame->f_back;
1233 Py_XINCREF(back);
1234 return back;
1235}