blob: 7c2bce3615860777add5e7dc4921416f2760d0f7 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Frame object implementation */
2
Guido van Rossum18752471997-04-29 14:49:28 +00003#include "Python.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +01004#include "pycore_object.h"
Victor Stinnere5014be2020-04-14 17:52:15 +02005#include "pycore_gc.h" // _PyObject_GC_IS_TRACKED()
Guido van Rossum3f5da241990-12-20 15:06:42 +00006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#include "frameobject.h"
9#include "opcode.h"
Victor Stinner4a21e572020-04-15 02:35:41 +020010#include "structmember.h" // PyMemberDef
Guido van Rossum3f5da241990-12-20 15:06:42 +000011
Guido van Rossum18752471997-04-29 14:49:28 +000012#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000013
Guido van Rossum6f799372001-09-20 20:46:19 +000014static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100015 {"f_back", T_OBJECT, OFF(f_back), READONLY},
16 {"f_code", T_OBJECT, OFF(f_code), READONLY},
17 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
18 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
19 {"f_lasti", T_INT, OFF(f_lasti), READONLY},
Nick Coghlan5a851672017-09-08 10:14:16 +100020 {"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
21 {"f_trace_opcodes", T_BOOL, OFF(f_trace_opcodes), 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000023};
24
Victor Stinner522691c2020-06-23 16:40:40 +020025
26static struct _Py_frame_state *
27get_frame_state(void)
28{
29 PyInterpreterState *interp = _PyInterpreterState_GET();
30 return &interp->frame;
31}
32
33
Guido van Rossum18752471997-04-29 14:49:28 +000034static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000035frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000036{
Victor Stinner41bb43a2013-10-29 01:19:37 +010037 if (PyFrame_FastToLocalsWithError(f) < 0)
38 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 Py_INCREF(f->f_locals);
40 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000041}
42
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000043int
44PyFrame_GetLineNumber(PyFrameObject *f)
45{
Victor Stinner7c59d7c2020-04-28 16:32:48 +020046 assert(f != NULL);
47 if (f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return f->f_lineno;
Victor Stinner7c59d7c2020-04-28 16:32:48 +020049 }
50 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Victor Stinner7c59d7c2020-04-28 16:32:48 +020052 }
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000053}
54
Michael W. Hudsondd32a912002-08-15 14:59:02 +000055static PyObject *
56frame_getlineno(PyFrameObject *f, void *closure)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000059}
60
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020061
62/* Given the index of the effective opcode,
63 scan back to construct the oparg with EXTENDED_ARG */
64static unsigned int
65get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
66{
67 _Py_CODEUNIT word;
68 unsigned int oparg = _Py_OPARG(codestr[i]);
69 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
70 oparg |= _Py_OPARG(word) << 8;
71 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
72 oparg |= _Py_OPARG(word) << 16;
73 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
74 oparg |= _Py_OPARG(word) << 24;
75 }
76 }
77 }
78 return oparg;
79}
80
Mark Shannon57697242020-04-29 16:49:45 +010081typedef enum kind {
82 With = 1,
83 Loop = 2,
84 Try = 3,
85 Except = 4,
86} Kind;
Mark Shannonfee55262019-11-21 09:11:43 +000087
Mark Shannon57697242020-04-29 16:49:45 +010088#define BITS_PER_BLOCK 3
89
90static inline int64_t
91push_block(int64_t stack, Kind kind)
Mark Shannonfee55262019-11-21 09:11:43 +000092{
Mark Shannon57697242020-04-29 16:49:45 +010093 assert(stack < ((int64_t)1)<<(BITS_PER_BLOCK*CO_MAXBLOCKS));
94 return (stack << BITS_PER_BLOCK) | kind;
Mark Shannonfee55262019-11-21 09:11:43 +000095}
96
Mark Shannon57697242020-04-29 16:49:45 +010097static inline int64_t
98pop_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +000099{
Mark Shannon57697242020-04-29 16:49:45 +0100100 assert(stack > 0);
101 return stack >> BITS_PER_BLOCK;
Mark Shannonfee55262019-11-21 09:11:43 +0000102}
103
Mark Shannon57697242020-04-29 16:49:45 +0100104static inline Kind
105top_block(int64_t stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000106{
Mark Shannon57697242020-04-29 16:49:45 +0100107 return stack & ((1<<BITS_PER_BLOCK)-1);
Mark Shannonfee55262019-11-21 09:11:43 +0000108}
109
Mark Shannon57697242020-04-29 16:49:45 +0100110static int64_t *
111markblocks(PyCodeObject *code_obj, int len)
Mark Shannonfee55262019-11-21 09:11:43 +0000112{
Mark Shannon57697242020-04-29 16:49:45 +0100113 const _Py_CODEUNIT *code =
114 (const _Py_CODEUNIT *)PyBytes_AS_STRING(code_obj->co_code);
115 int64_t *blocks = PyMem_New(int64_t, len+1);
116 int i, j, opcode;
117
118 if (blocks == NULL) {
119 PyErr_NoMemory();
120 return NULL;
Mark Shannonfee55262019-11-21 09:11:43 +0000121 }
Mark Shannon57697242020-04-29 16:49:45 +0100122 memset(blocks, -1, (len+1)*sizeof(int64_t));
123 blocks[0] = 0;
124 int todo = 1;
125 while (todo) {
126 todo = 0;
127 for (i = 0; i < len; i++) {
128 int64_t block_stack = blocks[i];
129 int64_t except_stack;
130 if (block_stack == -1) {
131 continue;
132 }
133 opcode = _Py_OPCODE(code[i]);
134 switch (opcode) {
135 case JUMP_IF_FALSE_OR_POP:
136 case JUMP_IF_TRUE_OR_POP:
137 case POP_JUMP_IF_FALSE:
138 case POP_JUMP_IF_TRUE:
139 case JUMP_IF_NOT_EXC_MATCH:
140 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
141 assert(j < len);
142 if (blocks[j] == -1 && j < i) {
143 todo = 1;
144 }
145 assert(blocks[j] == -1 || blocks[j] == block_stack);
146 blocks[j] = block_stack;
147 blocks[i+1] = block_stack;
148 break;
149 case JUMP_ABSOLUTE:
150 j = get_arg(code, i) / sizeof(_Py_CODEUNIT);
151 assert(j < len);
152 if (blocks[j] == -1 && j < i) {
153 todo = 1;
154 }
155 assert(blocks[j] == -1 || blocks[j] == block_stack);
156 blocks[j] = block_stack;
157 break;
158 case SETUP_FINALLY:
159 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
160 assert(j < len);
161 except_stack = push_block(block_stack, Except);
162 assert(blocks[j] == -1 || blocks[j] == except_stack);
163 blocks[j] = except_stack;
164 block_stack = push_block(block_stack, Try);
165 blocks[i+1] = block_stack;
166 break;
167 case SETUP_WITH:
168 case SETUP_ASYNC_WITH:
169 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
170 assert(j < len);
171 except_stack = push_block(block_stack, Except);
172 assert(blocks[j] == -1 || blocks[j] == except_stack);
173 blocks[j] = except_stack;
174 block_stack = push_block(block_stack, With);
175 blocks[i+1] = block_stack;
176 break;
177 case JUMP_FORWARD:
178 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
179 assert(j < len);
180 assert(blocks[j] == -1 || blocks[j] == block_stack);
181 blocks[j] = block_stack;
182 break;
183 case GET_ITER:
184 case GET_AITER:
185 block_stack = push_block(block_stack, Loop);
186 blocks[i+1] = block_stack;
187 break;
188 case FOR_ITER:
189 blocks[i+1] = block_stack;
190 block_stack = pop_block(block_stack);
191 j = get_arg(code, i) / sizeof(_Py_CODEUNIT) + i + 1;
192 assert(j < len);
193 assert(blocks[j] == -1 || blocks[j] == block_stack);
194 blocks[j] = block_stack;
195 break;
196 case POP_BLOCK:
197 case POP_EXCEPT:
198 block_stack = pop_block(block_stack);
199 blocks[i+1] = block_stack;
200 break;
201 case END_ASYNC_FOR:
202 block_stack = pop_block(pop_block(block_stack));
203 blocks[i+1] = block_stack;
204 break;
205 case RETURN_VALUE:
206 case RAISE_VARARGS:
207 case RERAISE:
208 /* End of block */
209 break;
210 default:
211 blocks[i+1] = block_stack;
212
213 }
214 }
215 }
216 return blocks;
Mark Shannonfee55262019-11-21 09:11:43 +0000217}
218
219static int
Mark Shannon57697242020-04-29 16:49:45 +0100220compatible_block_stack(int64_t from_stack, int64_t to_stack)
Mark Shannonfee55262019-11-21 09:11:43 +0000221{
Mark Shannon57697242020-04-29 16:49:45 +0100222 if (to_stack < 0) {
223 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +0000224 }
Mark Shannon57697242020-04-29 16:49:45 +0100225 while(from_stack > to_stack) {
226 from_stack = pop_block(from_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000227 }
Mark Shannon57697242020-04-29 16:49:45 +0100228 return from_stack == to_stack;
229}
230
231static const char *
232explain_incompatible_block_stack(int64_t to_stack)
233{
234 Kind target_kind = top_block(to_stack);
235 switch(target_kind) {
236 case Except:
237 return "can't jump into an 'except' block as there's no exception";
238 case Try:
239 return "can't jump into the body of a try statement";
240 case With:
241 return "can't jump into the body of a with statement";
242 case Loop:
243 return "can't jump into the body of a for loop";
244 default:
245 Py_UNREACHABLE();
246 }
247}
248
249static int *
250marklines(PyCodeObject *code, int len)
251{
252 int *linestarts = PyMem_New(int, len);
253 if (linestarts == NULL) {
254 return NULL;
255 }
256 Py_ssize_t size = PyBytes_GET_SIZE(code->co_lnotab) / 2;
257 unsigned char *p = (unsigned char*)PyBytes_AS_STRING(code->co_lnotab);
258 int line = code->co_firstlineno;
259 int addr = 0;
260 int index = 0;
261 while (--size >= 0) {
262 addr += *p++;
263 if (index*2 < addr) {
264 linestarts[index++] = line;
265 }
266 while (index*2 < addr) {
267 linestarts[index++] = -1;
268 if (index >= len) {
269 break;
270 }
271 }
272 line += (signed char)*p;
273 p++;
274 }
275 if (index < len) {
276 linestarts[index++] = line;
277 }
278 while (index < len) {
279 linestarts[index++] = -1;
280 }
281 assert(index == len);
282 return linestarts;
Mark Shannonfee55262019-11-21 09:11:43 +0000283}
284
285static int
Mark Shannon57697242020-04-29 16:49:45 +0100286first_line_not_before(int *lines, int len, int line)
Mark Shannonfee55262019-11-21 09:11:43 +0000287{
288 int result = INT_MAX;
Mark Shannon57697242020-04-29 16:49:45 +0100289 for (int i = 0; i < len; i++) {
290 if (lines[i] < result && lines[i] >= line) {
291 result = lines[i];
Mark Shannonfee55262019-11-21 09:11:43 +0000292 }
Mark Shannonfee55262019-11-21 09:11:43 +0000293 }
294 if (result == INT_MAX) {
295 return -1;
296 }
297 return result;
298}
299
Mark Shannonfee55262019-11-21 09:11:43 +0000300static void
301frame_stack_pop(PyFrameObject *f)
302{
303 PyObject *v = (*--f->f_stacktop);
304 Py_DECREF(v);
305}
306
307static void
308frame_block_unwind(PyFrameObject *f)
309{
310 assert(f->f_iblock > 0);
311 f->f_iblock--;
312 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Victor Stinner629023c2020-01-21 12:47:29 +0100313 intptr_t delta = (f->f_stacktop - f->f_valuestack) - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000314 while (delta > 0) {
315 frame_stack_pop(f);
316 delta--;
317 }
318}
319
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200320
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000321/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000323 * lines are OK to jump to because they don't make any assumptions about the
324 * state of the stack (obvious because you could remove the line and the code
325 * would still work without any stack errors), but there are some constructs
326 * that limit jumping:
327 *
328 * o Lines with an 'except' statement on them can't be jumped to, because
329 * they expect an exception to be on the top of the stack.
330 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000331 * we cannot be sure which state the interpreter was in or would be in
332 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200333 * o 'try', 'with' and 'async with' blocks can't be jumped into because
334 * the blockstack needs to be set up before their code runs.
335 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000336 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100337 * o Jumps cannot be made from within a trace function invoked with a
338 * 'return' or 'exception' event since the eval loop has been exited at
339 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000340 */
341static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200342frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000343{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700344 if (p_new_lineno == NULL) {
345 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
346 return -1;
347 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 /* f_lineno must be an integer. */
349 if (!PyLong_CheckExact(p_new_lineno)) {
350 PyErr_SetString(PyExc_ValueError,
351 "lineno must be an integer");
352 return -1;
353 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000354
xdegayeb8e9d6c2018-03-13 18:31:31 +0100355 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
356 * f->f_trace is NULL, check first on the first condition.
357 * Forbidding jumps from the 'call' event of a new frame is a side effect
358 * of allowing to set f_lineno only from trace functions. */
359 if (f->f_lasti == -1) {
360 PyErr_Format(PyExc_ValueError,
361 "can't jump from the 'call' trace event of a new frame");
362 return -1;
363 }
364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 /* You can only do this from within a trace function, not via
366 * _getframe or similar hackery. */
xdegayeb8e9d6c2018-03-13 18:31:31 +0100367 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100369 "f_lineno can only be set by a trace function");
370 return -1;
371 }
372
373 /* Forbid jumps upon a 'return' trace event (except after executing a
374 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
375 * and upon an 'exception' trace event.
376 * Jumps from 'call' trace events have already been forbidden above for new
377 * frames, so this check does not change anything for 'call' events. */
378 if (f->f_stacktop == NULL) {
379 PyErr_SetString(PyExc_ValueError,
380 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 return -1;
382 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000383
Mark Shannonfee55262019-11-21 09:11:43 +0000384 int new_lineno;
385
Mark Shannon57697242020-04-29 16:49:45 +0100386 /* Fail if the line falls outside the code block and
387 select first line with actual code. */
388 int overflow;
389 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
390 if (overflow
Mark Shannonfee55262019-11-21 09:11:43 +0000391#if SIZEOF_LONG > SIZEOF_INT
Mark Shannon57697242020-04-29 16:49:45 +0100392 || l_new_lineno > INT_MAX
393 || l_new_lineno < INT_MIN
Mark Shannonfee55262019-11-21 09:11:43 +0000394#endif
Mark Shannon57697242020-04-29 16:49:45 +0100395 ) {
Mark Shannonfee55262019-11-21 09:11:43 +0000396 PyErr_SetString(PyExc_ValueError,
Mark Shannon57697242020-04-29 16:49:45 +0100397 "lineno out of range");
398 return -1;
399 }
400 new_lineno = (int)l_new_lineno;
401
402 if (new_lineno < f->f_code->co_firstlineno) {
403 PyErr_Format(PyExc_ValueError,
404 "line %d comes before the current code block",
405 new_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return -1;
407 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000408
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000409 /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
410 * should never overflow. */
411 int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT));
Mark Shannon57697242020-04-29 16:49:45 +0100412 int *lines = marklines(f->f_code, len);
413 if (lines == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 return -1;
415 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000416
Mark Shannon57697242020-04-29 16:49:45 +0100417 new_lineno = first_line_not_before(lines, len, new_lineno);
418 if (new_lineno < 0) {
419 PyErr_Format(PyExc_ValueError,
420 "line %d comes after the current code block",
421 (int)l_new_lineno);
422 PyMem_Free(lines);
423 return -1;
Mark Shannonfee55262019-11-21 09:11:43 +0000424 }
425
Mark Shannon57697242020-04-29 16:49:45 +0100426 int64_t *blocks = markblocks(f->f_code, len);
427 if (blocks == NULL) {
428 PyMem_Free(lines);
429 return -1;
430 }
431
432 int64_t target_block_stack = -1;
433 int64_t best_block_stack = -1;
434 int best_addr = -1;
435 int64_t start_block_stack = blocks[f->f_lasti/sizeof(_Py_CODEUNIT)];
436 const char *msg = "cannot find bytecode for specified line";
437 for (int i = 0; i < len; i++) {
438 if (lines[i] == new_lineno) {
439 target_block_stack = blocks[i];
440 if (compatible_block_stack(start_block_stack, target_block_stack)) {
441 msg = NULL;
442 if (target_block_stack > best_block_stack) {
443 best_block_stack = target_block_stack;
444 best_addr = i*sizeof(_Py_CODEUNIT);
445 }
446 }
447 else if (msg) {
448 if (target_block_stack >= 0) {
449 msg = explain_incompatible_block_stack(target_block_stack);
450 }
451 else {
452 msg = "code may be unreachable.";
453 }
454 }
Mark Shannonfee55262019-11-21 09:11:43 +0000455 }
456 }
Mark Shannon57697242020-04-29 16:49:45 +0100457 PyMem_Free(blocks);
458 PyMem_Free(lines);
459 if (msg != NULL) {
460 PyErr_SetString(PyExc_ValueError, msg);
461 return -1;
462 }
Mark Shannonfee55262019-11-21 09:11:43 +0000463
464 /* Unwind block stack. */
Mark Shannon57697242020-04-29 16:49:45 +0100465 while (start_block_stack > best_block_stack) {
466 Kind kind = top_block(start_block_stack);
Mark Shannonfee55262019-11-21 09:11:43 +0000467 switch(kind) {
Mark Shannon57697242020-04-29 16:49:45 +0100468 case Loop:
Mark Shannonfee55262019-11-21 09:11:43 +0000469 frame_stack_pop(f);
470 break;
Mark Shannon57697242020-04-29 16:49:45 +0100471 case Try:
Mark Shannonfee55262019-11-21 09:11:43 +0000472 frame_block_unwind(f);
473 break;
Mark Shannon57697242020-04-29 16:49:45 +0100474 case With:
Mark Shannonfee55262019-11-21 09:11:43 +0000475 frame_block_unwind(f);
476 // Pop the exit function
477 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 break;
Mark Shannon57697242020-04-29 16:49:45 +0100479 case Except:
480 PyErr_SetString(PyExc_ValueError,
481 "can't jump out of an 'except' block");
Mark Shannonfee55262019-11-21 09:11:43 +0000482 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 }
Mark Shannon57697242020-04-29 16:49:45 +0100484 start_block_stack = pop_block(start_block_stack);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 }
Mark Shannonfee55262019-11-21 09:11:43 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* Finally set the new f_lineno and f_lasti and return OK. */
488 f->f_lineno = new_lineno;
Mark Shannon57697242020-04-29 16:49:45 +0100489 f->f_lasti = best_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000491}
492
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000493static PyObject *
494frame_gettrace(PyFrameObject *f, void *closure)
495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (trace == NULL)
499 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000504}
505
506static int
507frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* We rely on f_lineno being accurate when f_trace is set. */
510 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000511
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300512 if (v == Py_None)
513 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300515 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000518}
519
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000520
Guido van Rossum32d34c82001-09-20 21:45:26 +0000521static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 {"f_locals", (getter)frame_getlocals, NULL, NULL},
523 {"f_lineno", (getter)frame_getlineno,
524 (setter)frame_setlineno, NULL},
525 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
526 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000527};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000528
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000529/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000530 In an attempt to improve the speed of function calls, we:
531
532 1. Hold a single "zombie" frame on each code object. This retains
533 the allocated and initialised frame object from an invocation of
534 the code object. The zombie is reanimated the next time we need a
535 frame object for that code object. Doing this saves the malloc/
536 realloc required when using a free_list frame that isn't the
537 correct size. It also saves some field initialisation.
538
539 In zombie mode, no field of PyFrameObject holds a reference, but
540 the following fields are still valid:
541
542 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543
Mark Shannonae3087c2017-10-22 22:41:51 +0100544 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
546 * f_localsplus does not require re-allocation and
547 the local variables in f_localsplus are NULL.
548
549 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000550 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551 a stack frame is on the free list, only the following members have
552 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 ob_type == &Frametype
554 f_back next item on free list, or NULL
555 f_stacksize size of value stack
556 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000557 Note that the value and block stacks are preserved -- this can save
558 another malloc() call or two (and two free() calls as well!).
559 Also note that, unlike for integers, each frame object is a
560 malloc'ed object in its own right -- it is only the actual calls to
561 malloc() that we are trying to save here, not the administration.
562 After all, while a typical program may make millions of calls, a
563 call depth of more than 20 or 30 is probably already exceptional
564 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000565
Christian Heimes2202f872008-02-06 14:31:34 +0000566 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000567 free_list. Else programs creating lots of cyclic trash involving
568 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000569*/
Christian Heimes2202f872008-02-06 14:31:34 +0000570/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000572
Victor Stinnerc6944e72016-11-11 02:13:35 +0100573static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000574frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000575{
Victor Stinner3744ed22020-06-05 01:39:24 +0200576 if (_PyObject_GC_IS_TRACKED(f)) {
INADA Naoki5a625d02016-12-24 20:19:08 +0900577 _PyObject_GC_UNTRACK(f);
Victor Stinner3744ed22020-06-05 01:39:24 +0200578 }
INADA Naoki5a625d02016-12-24 20:19:08 +0900579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200581 /* Kill all local variables */
Victor Stinner3744ed22020-06-05 01:39:24 +0200582 PyObject **valuestack = f->f_valuestack;
583 for (PyObject **p = f->f_localsplus; p < valuestack; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200584 Py_CLEAR(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200585 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200586
587 /* Free stack */
588 if (f->f_stacktop != NULL) {
Victor Stinner3744ed22020-06-05 01:39:24 +0200589 for (PyObject **p = valuestack; p < f->f_stacktop; p++) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200590 Py_XDECREF(*p);
Victor Stinner3744ed22020-06-05 01:39:24 +0200591 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200592 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 Py_XDECREF(f->f_back);
595 Py_DECREF(f->f_builtins);
596 Py_DECREF(f->f_globals);
597 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200598 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599
Victor Stinner3744ed22020-06-05 01:39:24 +0200600 PyCodeObject *co = f->f_code;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200601 if (co->co_zombieframe == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 co->co_zombieframe = f;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200603 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200604 else {
Victor Stinner522691c2020-06-23 16:40:40 +0200605 struct _Py_frame_state *state = get_frame_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200606#ifdef Py_DEBUG
607 // frame_dealloc() must not be called after _PyFrame_Fini()
608 assert(state->numfree != -1);
609#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200610 if (state->numfree < PyFrame_MAXFREELIST) {
611 ++state->numfree;
612 f->f_back = state->free_list;
613 state->free_list = f;
614 }
615 else {
616 PyObject_GC_Del(f);
617 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200618 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 Py_DECREF(co);
621 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000622}
623
Victor Stinner6d86a232020-04-29 00:56:58 +0200624static inline Py_ssize_t
625frame_nslots(PyFrameObject *frame)
626{
627 PyCodeObject *code = frame->f_code;
628 return (code->co_nlocals
629 + PyTuple_GET_SIZE(code->co_cellvars)
630 + PyTuple_GET_SIZE(code->co_freevars));
631}
632
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000633static int
634frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_VISIT(f->f_back);
637 Py_VISIT(f->f_code);
638 Py_VISIT(f->f_builtins);
639 Py_VISIT(f->f_globals);
640 Py_VISIT(f->f_locals);
641 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200644 PyObject **fastlocals = f->f_localsplus;
645 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200647 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 /* stack */
650 if (f->f_stacktop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200651 for (PyObject **p = f->f_valuestack; p < f->f_stacktop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 Py_VISIT(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200653 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 }
655 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000656}
657
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200658static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200659frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000660{
Antoine Pitrou93963562013-05-14 20:37:52 +0200661 /* Before anything else, make sure that this frame is clearly marked
662 * as being defunct! Else, e.g., a generator reachable from this
663 * frame may also point to this frame, believe itself to still be
664 * active, and try cleaning up this frame again.
665 */
Victor Stinner6d86a232020-04-29 00:56:58 +0200666 PyObject **oldtop = f->f_stacktop;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200668 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200673 PyObject **fastlocals = f->f_localsplus;
674 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200676 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 /* stack */
679 if (oldtop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200680 for (PyObject **p = f->f_valuestack; p < oldtop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 Py_CLEAR(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200682 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200684 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000685}
686
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000687static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530688frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200689{
690 if (f->f_executing) {
691 PyErr_SetString(PyExc_RuntimeError,
692 "cannot clear an executing frame");
693 return NULL;
694 }
695 if (f->f_gen) {
696 _PyGen_Finalize(f->f_gen);
697 assert(f->f_gen == NULL);
698 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200699 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200700 Py_RETURN_NONE;
701}
702
703PyDoc_STRVAR(clear__doc__,
704"F.clear(): clear most references held by the frame");
705
706static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530707frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000710
Victor Stinner6d86a232020-04-29 00:56:58 +0200711 PyCodeObject *code = f->f_code;
712 ncells = PyTuple_GET_SIZE(code->co_cellvars);
713 nfrees = PyTuple_GET_SIZE(code->co_freevars);
714 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 /* subtract one as it is already included in PyFrameObject */
716 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000719}
720
721PyDoc_STRVAR(sizeof__doc__,
722"F.__sizeof__() -> size of F in memory, in bytes");
723
Antoine Pitrou14709142017-12-31 22:35:22 +0100724static PyObject *
725frame_repr(PyFrameObject *f)
726{
727 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200728 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100729 return PyUnicode_FromFormat(
730 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200731 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100732}
733
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000734static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200735 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
736 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
738 sizeof__doc__},
739 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000740};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000741
Guido van Rossum18752471997-04-29 14:49:28 +0000742PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyVarObject_HEAD_INIT(&PyType_Type, 0)
744 "frame",
745 sizeof(PyFrameObject),
746 sizeof(PyObject *),
747 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200748 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 0, /* tp_getattr */
750 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200751 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100752 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 0, /* tp_as_number */
754 0, /* tp_as_sequence */
755 0, /* tp_as_mapping */
756 0, /* tp_hash */
757 0, /* tp_call */
758 0, /* tp_str */
759 PyObject_GenericGetAttr, /* tp_getattro */
760 PyObject_GenericSetAttr, /* tp_setattro */
761 0, /* tp_as_buffer */
762 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
763 0, /* tp_doc */
764 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200765 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 0, /* tp_richcompare */
767 0, /* tp_weaklistoffset */
768 0, /* tp_iter */
769 0, /* tp_iternext */
770 frame_methods, /* tp_methods */
771 frame_memberlist, /* tp_members */
772 frame_getsetlist, /* tp_getset */
773 0, /* tp_base */
774 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000775};
776
Victor Stinner07e9e382013-11-07 22:22:39 +0100777_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000778
Victor Stinnerb4b53862020-05-05 19:55:29 +0200779static inline PyFrameObject*
780frame_alloc(PyCodeObject *code)
781{
782 PyFrameObject *f;
783
784 f = code->co_zombieframe;
785 if (f != NULL) {
786 code->co_zombieframe = NULL;
787 _Py_NewReference((PyObject *)f);
788 assert(f->f_code == code);
789 return f;
790 }
791
792 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
793 Py_ssize_t nfrees = PyTuple_GET_SIZE(code->co_freevars);
794 Py_ssize_t extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Victor Stinner522691c2020-06-23 16:40:40 +0200795 struct _Py_frame_state *state = get_frame_state();
Victor Stinner3744ed22020-06-05 01:39:24 +0200796 if (state->free_list == NULL)
Victor Stinnerb4b53862020-05-05 19:55:29 +0200797 {
798 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
799 if (f == NULL) {
800 return NULL;
801 }
802 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200803 else {
Victor Stinnerbcb19832020-06-08 02:14:47 +0200804#ifdef Py_DEBUG
805 // frame_alloc() must not be called after _PyFrame_Fini()
806 assert(state->numfree != -1);
807#endif
Victor Stinner3744ed22020-06-05 01:39:24 +0200808 assert(state->numfree > 0);
809 --state->numfree;
810 f = state->free_list;
811 state->free_list = state->free_list->f_back;
Victor Stinnerb4b53862020-05-05 19:55:29 +0200812 if (Py_SIZE(f) < extras) {
813 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
814 if (new_f == NULL) {
815 PyObject_GC_Del(f);
816 return NULL;
817 }
818 f = new_f;
819 }
820 _Py_NewReference((PyObject *)f);
821 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200822
823 f->f_code = code;
824 extras = code->co_nlocals + ncells + nfrees;
825 f->f_valuestack = f->f_localsplus + extras;
826 for (Py_ssize_t i=0; i<extras; i++) {
827 f->f_localsplus[i] = NULL;
828 }
829 f->f_locals = NULL;
830 f->f_trace = NULL;
831 return f;
832}
833
834
835static inline PyObject *
836frame_get_builtins(PyFrameObject *back, PyObject *globals)
837{
838 PyObject *builtins;
839
840 if (back != NULL && back->f_globals == globals) {
841 /* If we share the globals, we share the builtins.
842 Save a lookup and a call. */
843 builtins = back->f_builtins;
844 assert(builtins != NULL);
845 Py_INCREF(builtins);
846 return builtins;
847 }
848
849 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
850 if (builtins != NULL && PyModule_Check(builtins)) {
851 builtins = PyModule_GetDict(builtins);
852 assert(builtins != NULL);
853 }
854 if (builtins != NULL) {
855 Py_INCREF(builtins);
856 return builtins;
857 }
858
859 if (PyErr_Occurred()) {
860 return NULL;
861 }
862
863 /* No builtins! Make up a minimal one.
864 Give them 'None', at least. */
865 builtins = PyDict_New();
866 if (builtins == NULL) {
867 return NULL;
868 }
869 if (PyDict_SetItemString(builtins, "None", Py_None) < 0) {
870 Py_DECREF(builtins);
871 return NULL;
872 }
873 return builtins;
874}
875
876
Victor Stinnerc6944e72016-11-11 02:13:35 +0100877PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900878_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
879 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000880{
Michael W. Hudson69734a52002-08-19 16:54:08 +0000881#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
883 (locals != NULL && !PyMapping_Check(locals))) {
884 PyErr_BadInternalCall();
885 return NULL;
886 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000887#endif
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000888
Victor Stinnerb4b53862020-05-05 19:55:29 +0200889 PyFrameObject *back = tstate->frame;
890 PyObject *builtins = frame_get_builtins(back, globals);
891 if (builtins == NULL) {
892 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000894
Victor Stinnerb4b53862020-05-05 19:55:29 +0200895 PyFrameObject *f = frame_alloc(code);
896 if (f == NULL) {
897 Py_DECREF(builtins);
898 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 }
Victor Stinnerb4b53862020-05-05 19:55:29 +0200900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 f->f_stacktop = f->f_valuestack;
902 f->f_builtins = builtins;
903 Py_XINCREF(back);
904 f->f_back = back;
905 Py_INCREF(code);
906 Py_INCREF(globals);
907 f->f_globals = globals;
908 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
909 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
910 (CO_NEWLOCALS | CO_OPTIMIZED))
911 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
912 else if (code->co_flags & CO_NEWLOCALS) {
913 locals = PyDict_New();
914 if (locals == NULL) {
915 Py_DECREF(f);
916 return NULL;
917 }
918 f->f_locals = locals;
919 }
920 else {
921 if (locals == NULL)
922 locals = globals;
923 Py_INCREF(locals);
924 f->f_locals = locals;
925 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 f->f_lasti = -1;
928 f->f_lineno = code->co_firstlineno;
929 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200930 f->f_executing = 0;
931 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000932 f->f_trace_opcodes = 0;
933 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000934
Victor Stinner6d86a232020-04-29 00:56:58 +0200935 assert(f->f_code != NULL);
936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000938}
939
INADA Naoki5a625d02016-12-24 20:19:08 +0900940PyFrameObject*
941PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
942 PyObject *globals, PyObject *locals)
943{
944 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
945 if (f)
946 _PyObject_GC_TRACK(f);
947 return f;
948}
949
950
Guido van Rossum3f5da241990-12-20 15:06:42 +0000951/* Block management */
952
953void
Fred Drake1b190b42000-07-09 05:40:56 +0000954PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100957 if (f->f_iblock >= CO_MAXBLOCKS) {
958 Py_FatalError("block stack overflow");
959 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 b = &f->f_blockstack[f->f_iblock++];
961 b->b_type = type;
962 b->b_level = level;
963 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000964}
965
Guido van Rossum18752471997-04-29 14:49:28 +0000966PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000967PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100970 if (f->f_iblock <= 0) {
971 Py_FatalError("block stack underflow");
972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 b = &f->f_blockstack[--f->f_iblock];
974 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000975}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000976
Guido van Rossumd8faa362007-04-27 19:54:29 +0000977/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978
979 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980 values is an array of PyObject*. At index i, map[i] is the name of
981 the variable with value values[i]. The function copies the first
982 nmap variable from map/values into dict. If values[i] is NULL,
983 the variable is deleted from dict.
984
985 If deref is true, then the values being copied are cell variables
986 and the value is extracted from the cell variable before being put
987 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000988 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000989
Victor Stinner41bb43a2013-10-29 01:19:37 +0100990static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000991map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 Py_ssize_t j;
995 assert(PyTuple_Check(map));
996 assert(PyDict_Check(dict));
997 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800998 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *key = PyTuple_GET_ITEM(map, j);
1000 PyObject *value = values[j];
1001 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -04001002 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 assert(PyCell_Check(value));
1004 value = PyCell_GET(value);
1005 }
1006 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001007 if (PyObject_DelItem(dict, key) != 0) {
1008 if (PyErr_ExceptionMatches(PyExc_KeyError))
1009 PyErr_Clear();
1010 else
1011 return -1;
1012 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 }
1014 else {
1015 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +01001016 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 }
1018 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001019 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001020}
1021
Guido van Rossumd8faa362007-04-27 19:54:29 +00001022/* Copy values from the "locals" dict into the fast locals.
1023
1024 dict is an input argument containing string keys representing
1025 variables names and arbitrary PyObject* as values.
1026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028 values is an array of PyObject*. At index i, map[i] is the name of
1029 the variable with value values[i]. The function copies the first
1030 nmap variable from map/values into dict. If values[i] is NULL,
1031 the variable is deleted from dict.
1032
1033 If deref is true, then the values being copied are cell variables
1034 and the value is extracted from the cell variable before being put
1035 in dict. If clear is true, then variables in map but not in dict
1036 are set to NULL in map; if clear is false, variables missing in
1037 dict are ignored.
1038
1039 Exceptions raised while modifying the dict are silently ignored,
1040 because there is no good way to report them.
1041*/
1042
Guido van Rossum6b356e72001-04-14 17:55:41 +00001043static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001044dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 Py_ssize_t j;
1048 assert(PyTuple_Check(map));
1049 assert(PyDict_Check(dict));
1050 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001051 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyObject *key = PyTuple_GET_ITEM(map, j);
1053 PyObject *value = PyObject_GetItem(dict, key);
1054 assert(PyUnicode_Check(key));
1055 /* We only care about NULLs if clear is true. */
1056 if (value == NULL) {
1057 PyErr_Clear();
1058 if (!clear)
1059 continue;
1060 }
1061 if (deref) {
1062 assert(PyCell_Check(values[j]));
1063 if (PyCell_GET(values[j]) != value) {
1064 if (PyCell_Set(values[j], value) < 0)
1065 PyErr_Clear();
1066 }
1067 } else if (values[j] != value) {
1068 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001069 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 }
1071 Py_XDECREF(value);
1072 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001073}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001074
Victor Stinner41bb43a2013-10-29 01:19:37 +01001075int
1076PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 /* Merge fast locals into f->f_locals */
1079 PyObject *locals, *map;
1080 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 PyCodeObject *co;
1082 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001083 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001084
1085 if (f == NULL) {
1086 PyErr_BadInternalCall();
1087 return -1;
1088 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 locals = f->f_locals;
1090 if (locals == NULL) {
1091 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001092 if (locals == NULL)
1093 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 }
1095 co = f->f_code;
1096 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001097 if (!PyTuple_Check(map)) {
1098 PyErr_Format(PyExc_SystemError,
1099 "co_varnames must be a tuple, not %s",
1100 Py_TYPE(map)->tp_name);
1101 return -1;
1102 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 fast = f->f_localsplus;
1104 j = PyTuple_GET_SIZE(map);
1105 if (j > co->co_nlocals)
1106 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001107 if (co->co_nlocals) {
1108 if (map_to_dict(map, j, locals, fast, 0) < 0)
1109 return -1;
1110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1112 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1113 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001114 if (map_to_dict(co->co_cellvars, ncells,
1115 locals, fast + co->co_nlocals, 1))
1116 return -1;
1117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 /* If the namespace is unoptimized, then one of the
1119 following cases applies:
1120 1. It does not contain free variables, because it
1121 uses import * or is a top-level namespace.
1122 2. It is a class namespace.
1123 We don't want to accidentally copy free variables
1124 into the locals dict used by the class.
1125 */
1126 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001127 if (map_to_dict(co->co_freevars, nfreevars,
1128 locals, fast + co->co_nlocals + ncells, 1) < 0)
1129 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
1131 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001132 return 0;
1133}
1134
1135void
1136PyFrame_FastToLocals(PyFrameObject *f)
1137{
1138 int res;
1139
1140 assert(!PyErr_Occurred());
1141
1142 res = PyFrame_FastToLocalsWithError(f);
1143 if (res < 0)
1144 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001145}
1146
1147void
Fred Drake1b190b42000-07-09 05:40:56 +00001148PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 /* Merge f->f_locals into fast locals */
1151 PyObject *locals, *map;
1152 PyObject **fast;
1153 PyObject *error_type, *error_value, *error_traceback;
1154 PyCodeObject *co;
1155 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001156 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (f == NULL)
1158 return;
1159 locals = f->f_locals;
1160 co = f->f_code;
1161 map = co->co_varnames;
1162 if (locals == NULL)
1163 return;
1164 if (!PyTuple_Check(map))
1165 return;
1166 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1167 fast = f->f_localsplus;
1168 j = PyTuple_GET_SIZE(map);
1169 if (j > co->co_nlocals)
1170 j = co->co_nlocals;
1171 if (co->co_nlocals)
1172 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1173 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1174 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1175 if (ncells || nfreevars) {
1176 dict_to_map(co->co_cellvars, ncells,
1177 locals, fast + co->co_nlocals, 1, clear);
1178 /* Same test as in PyFrame_FastToLocals() above. */
1179 if (co->co_flags & CO_OPTIMIZED) {
1180 dict_to_map(co->co_freevars, nfreevars,
1181 locals, fast + co->co_nlocals + ncells, 1,
1182 clear);
1183 }
1184 }
1185 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001186}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001187
1188/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001189void
Victor Stinner3744ed22020-06-05 01:39:24 +02001190_PyFrame_ClearFreeList(PyThreadState *tstate)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001191{
Victor Stinner3744ed22020-06-05 01:39:24 +02001192 struct _Py_frame_state *state = &tstate->interp->frame;
1193 while (state->free_list != NULL) {
1194 PyFrameObject *f = state->free_list;
1195 state->free_list = state->free_list->f_back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyObject_GC_Del(f);
Victor Stinner3744ed22020-06-05 01:39:24 +02001197 --state->numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 }
Victor Stinner3744ed22020-06-05 01:39:24 +02001199 assert(state->numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001200}
1201
1202void
Victor Stinner3744ed22020-06-05 01:39:24 +02001203_PyFrame_Fini(PyThreadState *tstate)
Christian Heimesa156e092008-02-16 07:38:31 +00001204{
Victor Stinner3744ed22020-06-05 01:39:24 +02001205 _PyFrame_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001206#ifdef Py_DEBUG
1207 struct _Py_frame_state *state = &tstate->interp->frame;
1208 state->numfree = -1;
1209#endif
Guido van Rossum404b95d1997-08-05 02:09:46 +00001210}
David Malcolm49526f42012-06-22 14:55:41 -04001211
1212/* Print summary info about the state of the optimized allocator */
1213void
1214_PyFrame_DebugMallocStats(FILE *out)
1215{
Victor Stinner522691c2020-06-23 16:40:40 +02001216 struct _Py_frame_state *state = get_frame_state();
David Malcolm49526f42012-06-22 14:55:41 -04001217 _PyDebugAllocatorStats(out,
1218 "free PyFrameObject",
Victor Stinner3744ed22020-06-05 01:39:24 +02001219 state->numfree, sizeof(PyFrameObject));
David Malcolm49526f42012-06-22 14:55:41 -04001220}
1221
Victor Stinnera42ca742020-04-28 19:01:31 +02001222
1223PyCodeObject *
1224PyFrame_GetCode(PyFrameObject *frame)
1225{
1226 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001227 PyCodeObject *code = frame->f_code;
1228 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001229 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001230 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001231}
Victor Stinner70364772020-04-29 03:28:46 +02001232
1233
1234PyFrameObject*
1235PyFrame_GetBack(PyFrameObject *frame)
1236{
1237 assert(frame != NULL);
1238 PyFrameObject *back = frame->f_back;
1239 Py_XINCREF(back);
1240 return back;
1241}