blob: 92206c5f521086df8c5ef94393b8b7b9c5059a0f [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
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000668static int
669frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100672 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 Py_VISIT(f->f_back);
675 Py_VISIT(f->f_code);
676 Py_VISIT(f->f_builtins);
677 Py_VISIT(f->f_globals);
678 Py_VISIT(f->f_locals);
679 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 /* locals */
682 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
683 fastlocals = f->f_localsplus;
684 for (i = slots; --i >= 0; ++fastlocals)
685 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 /* stack */
688 if (f->f_stacktop != NULL) {
689 for (p = f->f_valuestack; p < f->f_stacktop; p++)
690 Py_VISIT(*p);
691 }
692 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000693}
694
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200695static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200696frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100699 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000700
Antoine Pitrou93963562013-05-14 20:37:52 +0200701 /* Before anything else, make sure that this frame is clearly marked
702 * as being defunct! Else, e.g., a generator reachable from this
703 * frame may also point to this frame, believe itself to still be
704 * active, and try cleaning up this frame again.
705 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 oldtop = f->f_stacktop;
707 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200708 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* locals */
713 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
714 fastlocals = f->f_localsplus;
715 for (i = slots; --i >= 0; ++fastlocals)
716 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 /* stack */
719 if (oldtop != NULL) {
720 for (p = f->f_valuestack; p < oldtop; p++)
721 Py_CLEAR(*p);
722 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200723 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000724}
725
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000726static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530727frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200728{
729 if (f->f_executing) {
730 PyErr_SetString(PyExc_RuntimeError,
731 "cannot clear an executing frame");
732 return NULL;
733 }
734 if (f->f_gen) {
735 _PyGen_Finalize(f->f_gen);
736 assert(f->f_gen == NULL);
737 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200738 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200739 Py_RETURN_NONE;
740}
741
742PyDoc_STRVAR(clear__doc__,
743"F.clear(): clear most references held by the frame");
744
745static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530746frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
751 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
752 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
753 ncells + nfrees;
754 /* subtract one as it is already included in PyFrameObject */
755 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000758}
759
760PyDoc_STRVAR(sizeof__doc__,
761"F.__sizeof__() -> size of F in memory, in bytes");
762
Antoine Pitrou14709142017-12-31 22:35:22 +0100763static PyObject *
764frame_repr(PyFrameObject *f)
765{
766 int lineno = PyFrame_GetLineNumber(f);
767 return PyUnicode_FromFormat(
768 "<frame at %p, file %R, line %d, code %S>",
769 f, f->f_code->co_filename, lineno, f->f_code->co_name);
770}
771
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000772static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200773 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
774 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
776 sizeof__doc__},
777 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000778};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000779
Guido van Rossum18752471997-04-29 14:49:28 +0000780PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyVarObject_HEAD_INIT(&PyType_Type, 0)
782 "frame",
783 sizeof(PyFrameObject),
784 sizeof(PyObject *),
785 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200786 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 0, /* tp_getattr */
788 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200789 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100790 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 0, /* tp_as_number */
792 0, /* tp_as_sequence */
793 0, /* tp_as_mapping */
794 0, /* tp_hash */
795 0, /* tp_call */
796 0, /* tp_str */
797 PyObject_GenericGetAttr, /* tp_getattro */
798 PyObject_GenericSetAttr, /* tp_setattro */
799 0, /* tp_as_buffer */
800 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
801 0, /* tp_doc */
802 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200803 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 0, /* tp_richcompare */
805 0, /* tp_weaklistoffset */
806 0, /* tp_iter */
807 0, /* tp_iternext */
808 frame_methods, /* tp_methods */
809 frame_memberlist, /* tp_members */
810 frame_getsetlist, /* tp_getset */
811 0, /* tp_base */
812 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000813};
814
Victor Stinner07e9e382013-11-07 22:22:39 +0100815_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000816
Victor Stinnerc6944e72016-11-11 02:13:35 +0100817PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900818_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
819 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyFrameObject *back = tstate->frame;
822 PyFrameObject *f;
823 PyObject *builtins;
824 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000825
Michael W. Hudson69734a52002-08-19 16:54:08 +0000826#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
828 (locals != NULL && !PyMapping_Check(locals))) {
829 PyErr_BadInternalCall();
830 return NULL;
831 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000832#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (back == NULL || back->f_globals != globals) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200834 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (builtins) {
836 if (PyModule_Check(builtins)) {
837 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200838 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
841 if (builtins == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200842 if (PyErr_Occurred()) {
843 return NULL;
844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 /* No builtins! Make up a minimal one
846 Give them 'None', at least. */
847 builtins = PyDict_New();
848 if (builtins == NULL ||
849 PyDict_SetItemString(
850 builtins, "None", Py_None) < 0)
851 return NULL;
852 }
853 else
854 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 }
857 else {
858 /* If we share the globals, we share the builtins.
859 Save a lookup and a call. */
860 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200861 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 Py_INCREF(builtins);
863 }
864 if (code->co_zombieframe != NULL) {
865 f = code->co_zombieframe;
866 code->co_zombieframe = NULL;
867 _Py_NewReference((PyObject *)f);
868 assert(f->f_code == code);
869 }
870 else {
871 Py_ssize_t extras, ncells, nfrees;
872 ncells = PyTuple_GET_SIZE(code->co_cellvars);
873 nfrees = PyTuple_GET_SIZE(code->co_freevars);
874 extras = code->co_stacksize + code->co_nlocals + ncells +
875 nfrees;
876 if (free_list == NULL) {
877 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
878 extras);
879 if (f == NULL) {
880 Py_DECREF(builtins);
881 return NULL;
882 }
883 }
884 else {
885 assert(numfree > 0);
886 --numfree;
887 f = free_list;
888 free_list = free_list->f_back;
889 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000890 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
891 if (new_f == NULL) {
892 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 Py_DECREF(builtins);
894 return NULL;
895 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000896 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 }
898 _Py_NewReference((PyObject *)f);
899 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 f->f_code = code;
902 extras = code->co_nlocals + ncells + nfrees;
903 f->f_valuestack = f->f_localsplus + extras;
904 for (i=0; i<extras; i++)
905 f->f_localsplus[i] = NULL;
906 f->f_locals = NULL;
907 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
909 f->f_stacktop = f->f_valuestack;
910 f->f_builtins = builtins;
911 Py_XINCREF(back);
912 f->f_back = back;
913 Py_INCREF(code);
914 Py_INCREF(globals);
915 f->f_globals = globals;
916 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
917 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
918 (CO_NEWLOCALS | CO_OPTIMIZED))
919 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
920 else if (code->co_flags & CO_NEWLOCALS) {
921 locals = PyDict_New();
922 if (locals == NULL) {
923 Py_DECREF(f);
924 return NULL;
925 }
926 f->f_locals = locals;
927 }
928 else {
929 if (locals == NULL)
930 locals = globals;
931 Py_INCREF(locals);
932 f->f_locals = locals;
933 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 f->f_lasti = -1;
936 f->f_lineno = code->co_firstlineno;
937 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200938 f->f_executing = 0;
939 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000940 f->f_trace_opcodes = 0;
941 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000944}
945
INADA Naoki5a625d02016-12-24 20:19:08 +0900946PyFrameObject*
947PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
948 PyObject *globals, PyObject *locals)
949{
950 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
951 if (f)
952 _PyObject_GC_TRACK(f);
953 return f;
954}
955
956
Guido van Rossum3f5da241990-12-20 15:06:42 +0000957/* Block management */
958
959void
Fred Drake1b190b42000-07-09 05:40:56 +0000960PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100963 if (f->f_iblock >= CO_MAXBLOCKS) {
964 Py_FatalError("block stack overflow");
965 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 b = &f->f_blockstack[f->f_iblock++];
967 b->b_type = type;
968 b->b_level = level;
969 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000970}
971
Guido van Rossum18752471997-04-29 14:49:28 +0000972PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000973PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100976 if (f->f_iblock <= 0) {
977 Py_FatalError("block stack underflow");
978 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 b = &f->f_blockstack[--f->f_iblock];
980 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000981}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000982
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984
985 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000986 values is an array of PyObject*. At index i, map[i] is the name of
987 the variable with value values[i]. The function copies the first
988 nmap variable from map/values into dict. If values[i] is NULL,
989 the variable is deleted from dict.
990
991 If deref is true, then the values being copied are cell variables
992 and the value is extracted from the cell variable before being put
993 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000994 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000995
Victor Stinner41bb43a2013-10-29 01:19:37 +0100996static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000997map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Py_ssize_t j;
1001 assert(PyTuple_Check(map));
1002 assert(PyDict_Check(dict));
1003 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001004 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyObject *key = PyTuple_GET_ITEM(map, j);
1006 PyObject *value = values[j];
1007 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -04001008 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 assert(PyCell_Check(value));
1010 value = PyCell_GET(value);
1011 }
1012 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001013 if (PyObject_DelItem(dict, key) != 0) {
1014 if (PyErr_ExceptionMatches(PyExc_KeyError))
1015 PyErr_Clear();
1016 else
1017 return -1;
1018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 }
1020 else {
1021 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +01001022 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 }
1024 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001025 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001026}
1027
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028/* Copy values from the "locals" dict into the fast locals.
1029
1030 dict is an input argument containing string keys representing
1031 variables names and arbitrary PyObject* as values.
1032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034 values is an array of PyObject*. At index i, map[i] is the name of
1035 the variable with value values[i]. The function copies the first
1036 nmap variable from map/values into dict. If values[i] is NULL,
1037 the variable is deleted from dict.
1038
1039 If deref is true, then the values being copied are cell variables
1040 and the value is extracted from the cell variable before being put
1041 in dict. If clear is true, then variables in map but not in dict
1042 are set to NULL in map; if clear is false, variables missing in
1043 dict are ignored.
1044
1045 Exceptions raised while modifying the dict are silently ignored,
1046 because there is no good way to report them.
1047*/
1048
Guido van Rossum6b356e72001-04-14 17:55:41 +00001049static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001050dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_ssize_t j;
1054 assert(PyTuple_Check(map));
1055 assert(PyDict_Check(dict));
1056 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001057 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 PyObject *key = PyTuple_GET_ITEM(map, j);
1059 PyObject *value = PyObject_GetItem(dict, key);
1060 assert(PyUnicode_Check(key));
1061 /* We only care about NULLs if clear is true. */
1062 if (value == NULL) {
1063 PyErr_Clear();
1064 if (!clear)
1065 continue;
1066 }
1067 if (deref) {
1068 assert(PyCell_Check(values[j]));
1069 if (PyCell_GET(values[j]) != value) {
1070 if (PyCell_Set(values[j], value) < 0)
1071 PyErr_Clear();
1072 }
1073 } else if (values[j] != value) {
1074 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001075 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 }
1077 Py_XDECREF(value);
1078 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001079}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001080
Victor Stinner41bb43a2013-10-29 01:19:37 +01001081int
1082PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 /* Merge fast locals into f->f_locals */
1085 PyObject *locals, *map;
1086 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyCodeObject *co;
1088 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001089 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001090
1091 if (f == NULL) {
1092 PyErr_BadInternalCall();
1093 return -1;
1094 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 locals = f->f_locals;
1096 if (locals == NULL) {
1097 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001098 if (locals == NULL)
1099 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
1101 co = f->f_code;
1102 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001103 if (!PyTuple_Check(map)) {
1104 PyErr_Format(PyExc_SystemError,
1105 "co_varnames must be a tuple, not %s",
1106 Py_TYPE(map)->tp_name);
1107 return -1;
1108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 fast = f->f_localsplus;
1110 j = PyTuple_GET_SIZE(map);
1111 if (j > co->co_nlocals)
1112 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001113 if (co->co_nlocals) {
1114 if (map_to_dict(map, j, locals, fast, 0) < 0)
1115 return -1;
1116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1118 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1119 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001120 if (map_to_dict(co->co_cellvars, ncells,
1121 locals, fast + co->co_nlocals, 1))
1122 return -1;
1123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* If the namespace is unoptimized, then one of the
1125 following cases applies:
1126 1. It does not contain free variables, because it
1127 uses import * or is a top-level namespace.
1128 2. It is a class namespace.
1129 We don't want to accidentally copy free variables
1130 into the locals dict used by the class.
1131 */
1132 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001133 if (map_to_dict(co->co_freevars, nfreevars,
1134 locals, fast + co->co_nlocals + ncells, 1) < 0)
1135 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 }
1137 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001138 return 0;
1139}
1140
1141void
1142PyFrame_FastToLocals(PyFrameObject *f)
1143{
1144 int res;
1145
1146 assert(!PyErr_Occurred());
1147
1148 res = PyFrame_FastToLocalsWithError(f);
1149 if (res < 0)
1150 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001151}
1152
1153void
Fred Drake1b190b42000-07-09 05:40:56 +00001154PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 /* Merge f->f_locals into fast locals */
1157 PyObject *locals, *map;
1158 PyObject **fast;
1159 PyObject *error_type, *error_value, *error_traceback;
1160 PyCodeObject *co;
1161 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001162 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (f == NULL)
1164 return;
1165 locals = f->f_locals;
1166 co = f->f_code;
1167 map = co->co_varnames;
1168 if (locals == NULL)
1169 return;
1170 if (!PyTuple_Check(map))
1171 return;
1172 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1173 fast = f->f_localsplus;
1174 j = PyTuple_GET_SIZE(map);
1175 if (j > co->co_nlocals)
1176 j = co->co_nlocals;
1177 if (co->co_nlocals)
1178 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1179 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1180 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1181 if (ncells || nfreevars) {
1182 dict_to_map(co->co_cellvars, ncells,
1183 locals, fast + co->co_nlocals, 1, clear);
1184 /* Same test as in PyFrame_FastToLocals() above. */
1185 if (co->co_flags & CO_OPTIMIZED) {
1186 dict_to_map(co->co_freevars, nfreevars,
1187 locals, fast + co->co_nlocals + ncells, 1,
1188 clear);
1189 }
1190 }
1191 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001192}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001193
1194/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +00001195int
1196PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 int freelist_size = numfree;
1199
1200 while (free_list != NULL) {
1201 PyFrameObject *f = free_list;
1202 free_list = free_list->f_back;
1203 PyObject_GC_Del(f);
1204 --numfree;
1205 }
1206 assert(numfree == 0);
1207 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +00001208}
1209
1210void
Victor Stinnerbed48172019-08-27 00:12:32 +02001211_PyFrame_Fini(void)
Christian Heimesa156e092008-02-16 07:38:31 +00001212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001214}
David Malcolm49526f42012-06-22 14:55:41 -04001215
1216/* Print summary info about the state of the optimized allocator */
1217void
1218_PyFrame_DebugMallocStats(FILE *out)
1219{
1220 _PyDebugAllocatorStats(out,
1221 "free PyFrameObject",
1222 numfree, sizeof(PyFrameObject));
1223}
1224
Victor Stinnera42ca742020-04-28 19:01:31 +02001225
1226PyCodeObject *
1227PyFrame_GetCode(PyFrameObject *frame)
1228{
1229 assert(frame != NULL);
1230 return frame->f_code;
1231}