blob: 6d288b5b059d7ae500fe9362c411aeed93f94933 [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 Shannonfee55262019-11-21 09:11:43 +000072typedef struct _codetracker {
73 unsigned char *code;
74 Py_ssize_t code_len;
75 unsigned char *lnotab;
76 Py_ssize_t lnotab_len;
77 int start_line;
78 int offset;
79 int line;
80 int addr;
81 int line_addr;
82} codetracker;
83
84/* Reset the mutable parts of the tracker */
85static void
86reset(codetracker *tracker)
87{
88 tracker->offset = 0;
89 tracker->addr = 0;
90 tracker->line_addr = 0;
91 tracker->line = tracker->start_line;
92}
93
94/* Initialise the tracker */
95static void
96init_codetracker(codetracker *tracker, PyCodeObject *code_obj)
97{
98 PyBytes_AsStringAndSize(code_obj->co_code,
99 (char **)&tracker->code, &tracker->code_len);
100 PyBytes_AsStringAndSize(code_obj->co_lnotab,
101 (char **)&tracker->lnotab, &tracker->lnotab_len);
102 tracker->start_line = code_obj->co_firstlineno;
103 reset(tracker);
104}
105
106static void
107advance_tracker(codetracker *tracker)
108{
109 tracker->addr += sizeof(_Py_CODEUNIT);
110 if (tracker->offset >= tracker->lnotab_len) {
111 return;
112 }
113 while (tracker->offset < tracker->lnotab_len &&
114 tracker->addr >= tracker->line_addr + tracker->lnotab[tracker->offset]) {
115 tracker->line_addr += tracker->lnotab[tracker->offset];
116 tracker->line += (signed char)tracker->lnotab[tracker->offset+1];
117 tracker->offset += 2;
118 }
119}
120
121
122static void
123retreat_tracker(codetracker *tracker)
124{
125 tracker->addr -= sizeof(_Py_CODEUNIT);
126 while (tracker->addr < tracker->line_addr) {
127 tracker->offset -= 2;
128 tracker->line_addr -= tracker->lnotab[tracker->offset];
129 tracker->line -= (signed char)tracker->lnotab[tracker->offset+1];
130 }
131}
132
133static int
134move_to_addr(codetracker *tracker, int addr)
135{
136 while (addr > tracker->addr) {
137 advance_tracker(tracker);
138 if (tracker->addr >= tracker->code_len) {
139 return -1;
140 }
141 }
142 while (addr < tracker->addr) {
143 retreat_tracker(tracker);
144 if (tracker->addr < 0) {
145 return -1;
146 }
147 }
148 return 0;
149}
150
151static int
152first_line_not_before(codetracker *tracker, int line)
153{
154 int result = INT_MAX;
155 reset(tracker);
156 while (tracker->addr < tracker->code_len) {
157 if (tracker->line == line) {
158 return line;
159 }
160 if (tracker->line > line && tracker->line < result) {
161 result = tracker->line;
162 }
163 advance_tracker(tracker);
164 }
165 if (result == INT_MAX) {
166 return -1;
167 }
168 return result;
169}
170
171static int
172move_to_nearest_start_of_line(codetracker *tracker, int line)
173{
174 if (line > tracker->line) {
175 while (line != tracker->line) {
176 advance_tracker(tracker);
177 if (tracker->addr >= tracker->code_len) {
178 return -1;
179 }
180 }
181 }
182 else {
183 while (line != tracker->line) {
184 retreat_tracker(tracker);
185 if (tracker->addr < 0) {
186 return -1;
187 }
188 }
189 while (tracker->addr > tracker->line_addr) {
190 retreat_tracker(tracker);
191 }
192 }
193 return 0;
194}
195
196typedef struct _blockitem
197{
198 unsigned char kind;
199 int end_addr;
200 int start_line;
201} blockitem;
202
203typedef struct _blockstack
204{
205 blockitem stack[CO_MAXBLOCKS];
206 int depth;
207} blockstack;
208
209
210static void
211init_blockstack(blockstack *blocks)
212{
213 blocks->depth = 0;
214}
215
216static void
217push_block(blockstack *blocks, unsigned char kind,
218 int end_addr, int start_line)
219{
220 assert(blocks->depth < CO_MAXBLOCKS);
221 blocks->stack[blocks->depth].kind = kind;
222 blocks->stack[blocks->depth].end_addr = end_addr;
223 blocks->stack[blocks->depth].start_line = start_line;
224 blocks->depth++;
225}
226
227static unsigned char
228pop_block(blockstack *blocks)
229{
230 assert(blocks->depth > 0);
231 blocks->depth--;
232 return blocks->stack[blocks->depth].kind;
233}
234
235static blockitem *
236top_block(blockstack *blocks)
237{
238 assert(blocks->depth > 0);
239 return &blocks->stack[blocks->depth-1];
240}
241
242static inline int
243is_try_except(unsigned char op, int target_op)
244{
245 return op == SETUP_FINALLY && (target_op == DUP_TOP || target_op == POP_TOP);
246}
247
248static inline int
249is_async_for(unsigned char op, int target_op)
250{
251 return op == SETUP_FINALLY && target_op == END_ASYNC_FOR;
252}
253
254static inline int
255is_try_finally(unsigned char op, int target_op)
256{
257 return op == SETUP_FINALLY && !is_try_except(op, target_op) && !is_async_for(op, target_op);
258}
259
260/* Kind for finding except blocks in the jump to line code */
261#define TRY_EXCEPT 250
262
263static int
264block_stack_for_line(codetracker *tracker, int line, blockstack *blocks)
265{
266 if (line < tracker->start_line) {
267 return -1;
268 }
269 init_blockstack(blocks);
270 reset(tracker);
271 while (tracker->addr < tracker->code_len) {
272 if (tracker->line == line) {
273 return 0;
274 }
275 if (blocks->depth > 0 && tracker->addr == top_block(blocks)->end_addr) {
276 unsigned char kind = pop_block(blocks);
277 assert(kind != SETUP_FINALLY);
278 if (kind == TRY_EXCEPT) {
279 push_block(blocks, POP_EXCEPT, -1, tracker->line);
280 }
281 if (kind == SETUP_WITH || kind == SETUP_ASYNC_WITH) {
282 push_block(blocks, WITH_EXCEPT_START, -1, tracker->line);
283 }
284 }
285 unsigned char op = tracker->code[tracker->addr];
286 if (op == SETUP_FINALLY || op == SETUP_ASYNC_WITH || op == SETUP_WITH || op == FOR_ITER) {
287 unsigned int oparg = get_arg((const _Py_CODEUNIT *)tracker->code,
288 tracker->addr / sizeof(_Py_CODEUNIT));
289 int target_addr = tracker->addr + oparg + sizeof(_Py_CODEUNIT);
290 int target_op = tracker->code[target_addr];
291 if (is_async_for(op, target_op)) {
292 push_block(blocks, FOR_ITER, target_addr, tracker->line);
293 }
294 else if (op == FOR_ITER) {
295 push_block(blocks, FOR_ITER, target_addr-sizeof(_Py_CODEUNIT), tracker->line);
296 }
297 else if (is_try_except(op, target_op)) {
298 push_block(blocks, TRY_EXCEPT, target_addr-sizeof(_Py_CODEUNIT), tracker->line);
299 }
300 else if (is_try_finally(op, target_op)) {
301 int addr = tracker->addr;
302 // Skip over duplicate 'finally' blocks if line is after body.
303 move_to_addr(tracker, target_addr);
304 if (tracker->line > line) {
305 // Target is in body, rewind to start.
306 move_to_addr(tracker, addr);
307 push_block(blocks, op, target_addr, tracker->line);
308 }
309 else {
310 // Now in finally block.
311 push_block(blocks, RERAISE, -1, tracker->line);
312 }
313 }
314 else {
315 push_block(blocks, op, target_addr, tracker->line);
316 }
317 }
318 else if (op == RERAISE) {
319 assert(blocks->depth > 0);
320 unsigned char kind = top_block(blocks)->kind;
321 if (kind == RERAISE || kind == WITH_EXCEPT_START || kind == POP_EXCEPT) {
322 pop_block(blocks);
323 }
324
325 }
326 advance_tracker(tracker);
327 }
328 return -1;
329}
330
331static void
332frame_stack_pop(PyFrameObject *f)
333{
334 PyObject *v = (*--f->f_stacktop);
335 Py_DECREF(v);
336}
337
338static void
339frame_block_unwind(PyFrameObject *f)
340{
341 assert(f->f_iblock > 0);
342 f->f_iblock--;
343 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Victor Stinner629023c2020-01-21 12:47:29 +0100344 intptr_t delta = (f->f_stacktop - f->f_valuestack) - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000345 while (delta > 0) {
346 frame_stack_pop(f);
347 delta--;
348 }
349}
350
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200351
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000352/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000354 * lines are OK to jump to because they don't make any assumptions about the
355 * state of the stack (obvious because you could remove the line and the code
356 * would still work without any stack errors), but there are some constructs
357 * that limit jumping:
358 *
359 * o Lines with an 'except' statement on them can't be jumped to, because
360 * they expect an exception to be on the top of the stack.
361 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000362 * we cannot be sure which state the interpreter was in or would be in
363 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200364 * o 'try', 'with' and 'async with' blocks can't be jumped into because
365 * the blockstack needs to be set up before their code runs.
366 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000367 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100368 * o Jumps cannot be made from within a trace function invoked with a
369 * 'return' or 'exception' event since the eval loop has been exited at
370 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000371 */
372static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200373frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000374{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700375 if (p_new_lineno == NULL) {
376 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
377 return -1;
378 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* f_lineno must be an integer. */
380 if (!PyLong_CheckExact(p_new_lineno)) {
381 PyErr_SetString(PyExc_ValueError,
382 "lineno must be an integer");
383 return -1;
384 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000385
xdegayeb8e9d6c2018-03-13 18:31:31 +0100386 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
387 * f->f_trace is NULL, check first on the first condition.
388 * Forbidding jumps from the 'call' event of a new frame is a side effect
389 * of allowing to set f_lineno only from trace functions. */
390 if (f->f_lasti == -1) {
391 PyErr_Format(PyExc_ValueError,
392 "can't jump from the 'call' trace event of a new frame");
393 return -1;
394 }
395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* You can only do this from within a trace function, not via
397 * _getframe or similar hackery. */
xdegayeb8e9d6c2018-03-13 18:31:31 +0100398 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100400 "f_lineno can only be set by a trace function");
401 return -1;
402 }
403
404 /* Forbid jumps upon a 'return' trace event (except after executing a
405 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
406 * and upon an 'exception' trace event.
407 * Jumps from 'call' trace events have already been forbidden above for new
408 * frames, so this check does not change anything for 'call' events. */
409 if (f->f_stacktop == NULL) {
410 PyErr_SetString(PyExc_ValueError,
411 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 return -1;
413 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000414
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000415
Mark Shannonfee55262019-11-21 09:11:43 +0000416 codetracker tracker;
417 init_codetracker(&tracker, f->f_code);
418 move_to_addr(&tracker, f->f_lasti);
419 int current_line = tracker.line;
420 assert(current_line >= 0);
421 int new_lineno;
422
423 {
424 /* Fail if the line falls outside the code block and
425 select first line with actual code. */
426 int overflow;
427 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
428 if (overflow
429#if SIZEOF_LONG > SIZEOF_INT
430 || l_new_lineno > INT_MAX
431 || l_new_lineno < INT_MIN
432#endif
433 ) {
434 PyErr_SetString(PyExc_ValueError,
435 "lineno out of range");
436 return -1;
437 }
438 new_lineno = (int)l_new_lineno;
439
440 if (new_lineno < f->f_code->co_firstlineno) {
441 PyErr_Format(PyExc_ValueError,
442 "line %d comes before the current code block",
443 new_lineno);
444 return -1;
445 }
446
447 new_lineno = first_line_not_before(&tracker, new_lineno);
448 if (new_lineno < 0) {
449 PyErr_Format(PyExc_ValueError,
450 "line %d comes after the current code block",
451 (int)l_new_lineno);
452 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 }
454 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000455
Mark Shannonfee55262019-11-21 09:11:43 +0000456 if (tracker.code[f->f_lasti] == YIELD_VALUE || tracker.code[f->f_lasti] == YIELD_FROM) {
457 PyErr_SetString(PyExc_ValueError,
458 "can't jump from a 'yield' statement");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 return -1;
460 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000461
Mark Shannonfee55262019-11-21 09:11:43 +0000462 /* Find block stack for current line and target line. */
463 blockstack current_stack, new_stack;
464 block_stack_for_line(&tracker, new_lineno, &new_stack);
465 block_stack_for_line(&tracker, current_line, &current_stack);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000466
xdegayeb8e9d6c2018-03-13 18:31:31 +0100467 /* The trace function is called with a 'return' trace event after the
468 * execution of a yield statement. */
Mark Shannonfee55262019-11-21 09:11:43 +0000469 if (tracker.code[tracker.addr] == DUP_TOP || tracker.code[tracker.addr] == POP_TOP) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyErr_SetString(PyExc_ValueError,
471 "can't jump to 'except' line as there's no exception");
472 return -1;
473 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000474
Mark Shannonfee55262019-11-21 09:11:43 +0000475 /* Validate change of block stack. */
476 if (new_stack.depth > 0) {
477 blockitem *current_block_at_new_depth = &(current_stack.stack[new_stack.depth-1]);
478 if (new_stack.depth > current_stack.depth ||
479 top_block(&new_stack)->start_line != current_block_at_new_depth->start_line) {
480 unsigned char target_kind = top_block(&new_stack)->kind;
Andy Lester7386a702020-02-13 22:42:56 -0600481 const char *msg;
Mark Shannonfee55262019-11-21 09:11:43 +0000482 if (target_kind == POP_EXCEPT) {
483 msg = "can't jump into an 'except' block as there's no exception";
484 }
485 else if (target_kind == RERAISE) {
486 msg = "can't jump into a 'finally' block";
487 }
488 else {
489 msg = "can't jump into the middle of a block";
490 }
491 PyErr_SetString(PyExc_ValueError, msg);
492 return -1;
493 }
494 }
495
496 /* Check for illegal jumps out of finally or except blocks. */
497 for (int depth = new_stack.depth; depth < current_stack.depth; depth++) {
498 switch(current_stack.stack[depth].kind) {
499 case RERAISE:
500 PyErr_SetString(PyExc_ValueError,
501 "can't jump out of a 'finally' block");
502 return -1;
503 case POP_EXCEPT:
504 PyErr_SetString(PyExc_ValueError,
505 "can't jump out of an 'except' block");
506 return -1;
507 }
508 }
509
510 /* Unwind block stack. */
511 while (current_stack.depth > new_stack.depth) {
512 unsigned char kind = pop_block(&current_stack);
513 switch(kind) {
514 case FOR_ITER:
515 frame_stack_pop(f);
516 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 case SETUP_FINALLY:
Mark Shannonfee55262019-11-21 09:11:43 +0000518 case TRY_EXCEPT:
519 frame_block_unwind(f);
520 break;
Benjamin Petersone42fb302012-04-18 11:14:31 -0400521 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400522 case SETUP_ASYNC_WITH:
Mark Shannonfee55262019-11-21 09:11:43 +0000523 frame_block_unwind(f);
524 // Pop the exit function
525 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 break;
Mark Shannonfee55262019-11-21 09:11:43 +0000527 default:
528 PyErr_SetString(PyExc_SystemError,
529 "unexpected block kind");
530 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 }
532 }
Mark Shannonfee55262019-11-21 09:11:43 +0000533
534 move_to_addr(&tracker, f->f_lasti);
535 move_to_nearest_start_of_line(&tracker, new_lineno);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* Finally set the new f_lineno and f_lasti and return OK. */
538 f->f_lineno = new_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +0000539 f->f_lasti = tracker.addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000541}
542
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000543static PyObject *
544frame_gettrace(PyFrameObject *f, void *closure)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (trace == NULL)
549 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000554}
555
556static int
557frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* We rely on f_lineno being accurate when f_trace is set. */
560 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000561
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300562 if (v == Py_None)
563 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300565 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000568}
569
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570
Guido van Rossum32d34c82001-09-20 21:45:26 +0000571static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 {"f_locals", (getter)frame_getlocals, NULL, NULL},
573 {"f_lineno", (getter)frame_getlineno,
574 (setter)frame_setlineno, NULL},
575 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
576 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000578
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000579/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000580 In an attempt to improve the speed of function calls, we:
581
582 1. Hold a single "zombie" frame on each code object. This retains
583 the allocated and initialised frame object from an invocation of
584 the code object. The zombie is reanimated the next time we need a
585 frame object for that code object. Doing this saves the malloc/
586 realloc required when using a free_list frame that isn't the
587 correct size. It also saves some field initialisation.
588
589 In zombie mode, no field of PyFrameObject holds a reference, but
590 the following fields are still valid:
591
592 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593
Mark Shannonae3087c2017-10-22 22:41:51 +0100594 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000595
596 * f_localsplus does not require re-allocation and
597 the local variables in f_localsplus are NULL.
598
599 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000600 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000601 a stack frame is on the free list, only the following members have
602 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 ob_type == &Frametype
604 f_back next item on free list, or NULL
605 f_stacksize size of value stack
606 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000607 Note that the value and block stacks are preserved -- this can save
608 another malloc() call or two (and two free() calls as well!).
609 Also note that, unlike for integers, each frame object is a
610 malloc'ed object in its own right -- it is only the actual calls to
611 malloc() that we are trying to save here, not the administration.
612 After all, while a typical program may make millions of calls, a
613 call depth of more than 20 or 30 is probably already exceptional
614 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000615
Christian Heimes2202f872008-02-06 14:31:34 +0000616 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000617 free_list. Else programs creating lots of cyclic trash involving
618 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000619*/
620
Guido van Rossum18752471997-04-29 14:49:28 +0000621static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000623/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000625
Victor Stinnerc6944e72016-11-11 02:13:35 +0100626static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000627frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000628{
Antoine Pitrou93963562013-05-14 20:37:52 +0200629 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000631
INADA Naoki5a625d02016-12-24 20:19:08 +0900632 if (_PyObject_GC_IS_TRACKED(f))
633 _PyObject_GC_UNTRACK(f);
634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200636 /* Kill all local variables */
637 valuestack = f->f_valuestack;
638 for (p = f->f_localsplus; p < valuestack; p++)
639 Py_CLEAR(*p);
640
641 /* Free stack */
642 if (f->f_stacktop != NULL) {
643 for (p = valuestack; p < f->f_stacktop; p++)
644 Py_XDECREF(*p);
645 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 Py_XDECREF(f->f_back);
648 Py_DECREF(f->f_builtins);
649 Py_DECREF(f->f_globals);
650 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200651 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 co = f->f_code;
654 if (co->co_zombieframe == NULL)
655 co->co_zombieframe = f;
656 else if (numfree < PyFrame_MAXFREELIST) {
657 ++numfree;
658 f->f_back = free_list;
659 free_list = f;
660 }
661 else
662 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 Py_DECREF(co);
665 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000666}
667
Victor Stinner6d86a232020-04-29 00:56:58 +0200668static inline Py_ssize_t
669frame_nslots(PyFrameObject *frame)
670{
671 PyCodeObject *code = frame->f_code;
672 return (code->co_nlocals
673 + PyTuple_GET_SIZE(code->co_cellvars)
674 + PyTuple_GET_SIZE(code->co_freevars));
675}
676
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000677static int
678frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 Py_VISIT(f->f_back);
681 Py_VISIT(f->f_code);
682 Py_VISIT(f->f_builtins);
683 Py_VISIT(f->f_globals);
684 Py_VISIT(f->f_locals);
685 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200688 PyObject **fastlocals = f->f_localsplus;
689 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 Py_VISIT(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200691 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* stack */
694 if (f->f_stacktop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200695 for (PyObject **p = f->f_valuestack; p < f->f_stacktop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 Py_VISIT(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200697 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 }
699 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000700}
701
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200702static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200703frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000704{
Antoine Pitrou93963562013-05-14 20:37:52 +0200705 /* Before anything else, make sure that this frame is clearly marked
706 * as being defunct! Else, e.g., a generator reachable from this
707 * frame may also point to this frame, believe itself to still be
708 * active, and try cleaning up this frame again.
709 */
Victor Stinner6d86a232020-04-29 00:56:58 +0200710 PyObject **oldtop = f->f_stacktop;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200712 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 /* locals */
Victor Stinner6d86a232020-04-29 00:56:58 +0200717 PyObject **fastlocals = f->f_localsplus;
718 for (Py_ssize_t i = frame_nslots(f); --i >= 0; ++fastlocals) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 Py_CLEAR(*fastlocals);
Victor Stinner6d86a232020-04-29 00:56:58 +0200720 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 /* stack */
723 if (oldtop != NULL) {
Victor Stinner6d86a232020-04-29 00:56:58 +0200724 for (PyObject **p = f->f_valuestack; p < oldtop; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 Py_CLEAR(*p);
Victor Stinner6d86a232020-04-29 00:56:58 +0200726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200728 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000729}
730
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000731static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530732frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200733{
734 if (f->f_executing) {
735 PyErr_SetString(PyExc_RuntimeError,
736 "cannot clear an executing frame");
737 return NULL;
738 }
739 if (f->f_gen) {
740 _PyGen_Finalize(f->f_gen);
741 assert(f->f_gen == NULL);
742 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200743 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200744 Py_RETURN_NONE;
745}
746
747PyDoc_STRVAR(clear__doc__,
748"F.clear(): clear most references held by the frame");
749
750static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530751frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000754
Victor Stinner6d86a232020-04-29 00:56:58 +0200755 PyCodeObject *code = f->f_code;
756 ncells = PyTuple_GET_SIZE(code->co_cellvars);
757 nfrees = PyTuple_GET_SIZE(code->co_freevars);
758 extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* subtract one as it is already included in PyFrameObject */
760 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000763}
764
765PyDoc_STRVAR(sizeof__doc__,
766"F.__sizeof__() -> size of F in memory, in bytes");
767
Antoine Pitrou14709142017-12-31 22:35:22 +0100768static PyObject *
769frame_repr(PyFrameObject *f)
770{
771 int lineno = PyFrame_GetLineNumber(f);
Victor Stinner6d86a232020-04-29 00:56:58 +0200772 PyCodeObject *code = f->f_code;
Antoine Pitrou14709142017-12-31 22:35:22 +0100773 return PyUnicode_FromFormat(
774 "<frame at %p, file %R, line %d, code %S>",
Victor Stinner6d86a232020-04-29 00:56:58 +0200775 f, code->co_filename, lineno, code->co_name);
Antoine Pitrou14709142017-12-31 22:35:22 +0100776}
777
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000778static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200779 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
780 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
782 sizeof__doc__},
783 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000784};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000785
Guido van Rossum18752471997-04-29 14:49:28 +0000786PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyVarObject_HEAD_INIT(&PyType_Type, 0)
788 "frame",
789 sizeof(PyFrameObject),
790 sizeof(PyObject *),
791 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200792 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 0, /* tp_getattr */
794 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200795 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100796 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 0, /* tp_as_number */
798 0, /* tp_as_sequence */
799 0, /* tp_as_mapping */
800 0, /* tp_hash */
801 0, /* tp_call */
802 0, /* tp_str */
803 PyObject_GenericGetAttr, /* tp_getattro */
804 PyObject_GenericSetAttr, /* tp_setattro */
805 0, /* tp_as_buffer */
806 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
807 0, /* tp_doc */
808 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200809 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 0, /* tp_richcompare */
811 0, /* tp_weaklistoffset */
812 0, /* tp_iter */
813 0, /* tp_iternext */
814 frame_methods, /* tp_methods */
815 frame_memberlist, /* tp_members */
816 frame_getsetlist, /* tp_getset */
817 0, /* tp_base */
818 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000819};
820
Victor Stinner07e9e382013-11-07 22:22:39 +0100821_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000822
Victor Stinnerc6944e72016-11-11 02:13:35 +0100823PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900824_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
825 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyFrameObject *back = tstate->frame;
828 PyFrameObject *f;
829 PyObject *builtins;
830 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000831
Michael W. Hudson69734a52002-08-19 16:54:08 +0000832#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
834 (locals != NULL && !PyMapping_Check(locals))) {
835 PyErr_BadInternalCall();
836 return NULL;
837 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000838#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 if (back == NULL || back->f_globals != globals) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200840 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (builtins) {
842 if (PyModule_Check(builtins)) {
843 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200844 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 }
847 if (builtins == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200848 if (PyErr_Occurred()) {
849 return NULL;
850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* No builtins! Make up a minimal one
852 Give them 'None', at least. */
853 builtins = PyDict_New();
854 if (builtins == NULL ||
855 PyDict_SetItemString(
856 builtins, "None", Py_None) < 0)
857 return NULL;
858 }
859 else
860 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 }
863 else {
864 /* If we share the globals, we share the builtins.
865 Save a lookup and a call. */
866 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200867 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 Py_INCREF(builtins);
869 }
870 if (code->co_zombieframe != NULL) {
871 f = code->co_zombieframe;
872 code->co_zombieframe = NULL;
873 _Py_NewReference((PyObject *)f);
874 assert(f->f_code == code);
875 }
876 else {
877 Py_ssize_t extras, ncells, nfrees;
878 ncells = PyTuple_GET_SIZE(code->co_cellvars);
879 nfrees = PyTuple_GET_SIZE(code->co_freevars);
880 extras = code->co_stacksize + code->co_nlocals + ncells +
881 nfrees;
882 if (free_list == NULL) {
883 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
884 extras);
885 if (f == NULL) {
886 Py_DECREF(builtins);
887 return NULL;
888 }
889 }
890 else {
891 assert(numfree > 0);
892 --numfree;
893 f = free_list;
894 free_list = free_list->f_back;
895 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000896 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
897 if (new_f == NULL) {
898 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 Py_DECREF(builtins);
900 return NULL;
901 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000902 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 }
904 _Py_NewReference((PyObject *)f);
905 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 f->f_code = code;
908 extras = code->co_nlocals + ncells + nfrees;
909 f->f_valuestack = f->f_localsplus + extras;
910 for (i=0; i<extras; i++)
911 f->f_localsplus[i] = NULL;
912 f->f_locals = NULL;
913 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 }
915 f->f_stacktop = f->f_valuestack;
916 f->f_builtins = builtins;
917 Py_XINCREF(back);
918 f->f_back = back;
919 Py_INCREF(code);
920 Py_INCREF(globals);
921 f->f_globals = globals;
922 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
923 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
924 (CO_NEWLOCALS | CO_OPTIMIZED))
925 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
926 else if (code->co_flags & CO_NEWLOCALS) {
927 locals = PyDict_New();
928 if (locals == NULL) {
929 Py_DECREF(f);
930 return NULL;
931 }
932 f->f_locals = locals;
933 }
934 else {
935 if (locals == NULL)
936 locals = globals;
937 Py_INCREF(locals);
938 f->f_locals = locals;
939 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 f->f_lasti = -1;
942 f->f_lineno = code->co_firstlineno;
943 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200944 f->f_executing = 0;
945 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000946 f->f_trace_opcodes = 0;
947 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000948
Victor Stinner6d86a232020-04-29 00:56:58 +0200949 assert(f->f_code != NULL);
950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000952}
953
INADA Naoki5a625d02016-12-24 20:19:08 +0900954PyFrameObject*
955PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
956 PyObject *globals, PyObject *locals)
957{
958 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
959 if (f)
960 _PyObject_GC_TRACK(f);
961 return f;
962}
963
964
Guido van Rossum3f5da241990-12-20 15:06:42 +0000965/* Block management */
966
967void
Fred Drake1b190b42000-07-09 05:40:56 +0000968PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100971 if (f->f_iblock >= CO_MAXBLOCKS) {
972 Py_FatalError("block stack overflow");
973 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 b = &f->f_blockstack[f->f_iblock++];
975 b->b_type = type;
976 b->b_level = level;
977 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000978}
979
Guido van Rossum18752471997-04-29 14:49:28 +0000980PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000981PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100984 if (f->f_iblock <= 0) {
985 Py_FatalError("block stack underflow");
986 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 b = &f->f_blockstack[--f->f_iblock];
988 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000989}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000990
Guido van Rossumd8faa362007-04-27 19:54:29 +0000991/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992
993 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000994 values is an array of PyObject*. At index i, map[i] is the name of
995 the variable with value values[i]. The function copies the first
996 nmap variable from map/values into dict. If values[i] is NULL,
997 the variable is deleted from dict.
998
999 If deref is true, then the values being copied are cell variables
1000 and the value is extracted from the cell variable before being put
1001 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001002 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001003
Victor Stinner41bb43a2013-10-29 01:19:37 +01001004static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001005map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 Py_ssize_t j;
1009 assert(PyTuple_Check(map));
1010 assert(PyDict_Check(dict));
1011 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001012 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 PyObject *key = PyTuple_GET_ITEM(map, j);
1014 PyObject *value = values[j];
1015 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -04001016 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 assert(PyCell_Check(value));
1018 value = PyCell_GET(value);
1019 }
1020 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001021 if (PyObject_DelItem(dict, key) != 0) {
1022 if (PyErr_ExceptionMatches(PyExc_KeyError))
1023 PyErr_Clear();
1024 else
1025 return -1;
1026 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 }
1028 else {
1029 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +01001030 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 }
1032 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001033 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001034}
1035
Guido van Rossumd8faa362007-04-27 19:54:29 +00001036/* Copy values from the "locals" dict into the fast locals.
1037
1038 dict is an input argument containing string keys representing
1039 variables names and arbitrary PyObject* as values.
1040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042 values is an array of PyObject*. At index i, map[i] is the name of
1043 the variable with value values[i]. The function copies the first
1044 nmap variable from map/values into dict. If values[i] is NULL,
1045 the variable is deleted from dict.
1046
1047 If deref is true, then the values being copied are cell variables
1048 and the value is extracted from the cell variable before being put
1049 in dict. If clear is true, then variables in map but not in dict
1050 are set to NULL in map; if clear is false, variables missing in
1051 dict are ignored.
1052
1053 Exceptions raised while modifying the dict are silently ignored,
1054 because there is no good way to report them.
1055*/
1056
Guido van Rossum6b356e72001-04-14 17:55:41 +00001057static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001058dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 Py_ssize_t j;
1062 assert(PyTuple_Check(map));
1063 assert(PyDict_Check(dict));
1064 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001065 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyObject *key = PyTuple_GET_ITEM(map, j);
1067 PyObject *value = PyObject_GetItem(dict, key);
1068 assert(PyUnicode_Check(key));
1069 /* We only care about NULLs if clear is true. */
1070 if (value == NULL) {
1071 PyErr_Clear();
1072 if (!clear)
1073 continue;
1074 }
1075 if (deref) {
1076 assert(PyCell_Check(values[j]));
1077 if (PyCell_GET(values[j]) != value) {
1078 if (PyCell_Set(values[j], value) < 0)
1079 PyErr_Clear();
1080 }
1081 } else if (values[j] != value) {
1082 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001083 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
1085 Py_XDECREF(value);
1086 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001087}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001088
Victor Stinner41bb43a2013-10-29 01:19:37 +01001089int
1090PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 /* Merge fast locals into f->f_locals */
1093 PyObject *locals, *map;
1094 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyCodeObject *co;
1096 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001097 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001098
1099 if (f == NULL) {
1100 PyErr_BadInternalCall();
1101 return -1;
1102 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 locals = f->f_locals;
1104 if (locals == NULL) {
1105 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001106 if (locals == NULL)
1107 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 }
1109 co = f->f_code;
1110 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001111 if (!PyTuple_Check(map)) {
1112 PyErr_Format(PyExc_SystemError,
1113 "co_varnames must be a tuple, not %s",
1114 Py_TYPE(map)->tp_name);
1115 return -1;
1116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 fast = f->f_localsplus;
1118 j = PyTuple_GET_SIZE(map);
1119 if (j > co->co_nlocals)
1120 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001121 if (co->co_nlocals) {
1122 if (map_to_dict(map, j, locals, fast, 0) < 0)
1123 return -1;
1124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1126 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1127 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001128 if (map_to_dict(co->co_cellvars, ncells,
1129 locals, fast + co->co_nlocals, 1))
1130 return -1;
1131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 /* If the namespace is unoptimized, then one of the
1133 following cases applies:
1134 1. It does not contain free variables, because it
1135 uses import * or is a top-level namespace.
1136 2. It is a class namespace.
1137 We don't want to accidentally copy free variables
1138 into the locals dict used by the class.
1139 */
1140 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001141 if (map_to_dict(co->co_freevars, nfreevars,
1142 locals, fast + co->co_nlocals + ncells, 1) < 0)
1143 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 }
1145 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001146 return 0;
1147}
1148
1149void
1150PyFrame_FastToLocals(PyFrameObject *f)
1151{
1152 int res;
1153
1154 assert(!PyErr_Occurred());
1155
1156 res = PyFrame_FastToLocalsWithError(f);
1157 if (res < 0)
1158 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001159}
1160
1161void
Fred Drake1b190b42000-07-09 05:40:56 +00001162PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 /* Merge f->f_locals into fast locals */
1165 PyObject *locals, *map;
1166 PyObject **fast;
1167 PyObject *error_type, *error_value, *error_traceback;
1168 PyCodeObject *co;
1169 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001170 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (f == NULL)
1172 return;
1173 locals = f->f_locals;
1174 co = f->f_code;
1175 map = co->co_varnames;
1176 if (locals == NULL)
1177 return;
1178 if (!PyTuple_Check(map))
1179 return;
1180 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1181 fast = f->f_localsplus;
1182 j = PyTuple_GET_SIZE(map);
1183 if (j > co->co_nlocals)
1184 j = co->co_nlocals;
1185 if (co->co_nlocals)
1186 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1187 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1188 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1189 if (ncells || nfreevars) {
1190 dict_to_map(co->co_cellvars, ncells,
1191 locals, fast + co->co_nlocals, 1, clear);
1192 /* Same test as in PyFrame_FastToLocals() above. */
1193 if (co->co_flags & CO_OPTIMIZED) {
1194 dict_to_map(co->co_freevars, nfreevars,
1195 locals, fast + co->co_nlocals + ncells, 1,
1196 clear);
1197 }
1198 }
1199 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001200}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001201
1202/* Clear out the free list */
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001203void
1204_PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 while (free_list != NULL) {
1207 PyFrameObject *f = free_list;
1208 free_list = free_list->f_back;
1209 PyObject_GC_Del(f);
1210 --numfree;
1211 }
1212 assert(numfree == 0);
Christian Heimesa156e092008-02-16 07:38:31 +00001213}
1214
1215void
Victor Stinnerbed48172019-08-27 00:12:32 +02001216_PyFrame_Fini(void)
Christian Heimesa156e092008-02-16 07:38:31 +00001217{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001218 _PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001219}
David Malcolm49526f42012-06-22 14:55:41 -04001220
1221/* Print summary info about the state of the optimized allocator */
1222void
1223_PyFrame_DebugMallocStats(FILE *out)
1224{
1225 _PyDebugAllocatorStats(out,
1226 "free PyFrameObject",
1227 numfree, sizeof(PyFrameObject));
1228}
1229
Victor Stinnera42ca742020-04-28 19:01:31 +02001230
1231PyCodeObject *
1232PyFrame_GetCode(PyFrameObject *frame)
1233{
1234 assert(frame != NULL);
Victor Stinner6d86a232020-04-29 00:56:58 +02001235 PyCodeObject *code = frame->f_code;
1236 assert(code != NULL);
Victor Stinner8852ad42020-04-29 01:28:13 +02001237 Py_INCREF(code);
Victor Stinner6d86a232020-04-29 00:56:58 +02001238 return code;
Victor Stinnera42ca742020-04-28 19:01:31 +02001239}