blob: 340267bd4790794db9eb0fc9c8045dc33ea44501 [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 Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pystate.h"
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"
10#include "structmember.h"
11
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 if (f->f_trace)
38 return f->f_lineno;
39 else
40 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000041}
42
Michael W. Hudsondd32a912002-08-15 14:59:02 +000043static PyObject *
44frame_getlineno(PyFrameObject *f, void *closure)
45{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000047}
48
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020049
50/* Given the index of the effective opcode,
51 scan back to construct the oparg with EXTENDED_ARG */
52static unsigned int
53get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
54{
55 _Py_CODEUNIT word;
56 unsigned int oparg = _Py_OPARG(codestr[i]);
57 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
58 oparg |= _Py_OPARG(word) << 8;
59 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
60 oparg |= _Py_OPARG(word) << 16;
61 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
62 oparg |= _Py_OPARG(word) << 24;
63 }
64 }
65 }
66 return oparg;
67}
68
Mark Shannonfee55262019-11-21 09:11:43 +000069typedef struct _codetracker {
70 unsigned char *code;
71 Py_ssize_t code_len;
72 unsigned char *lnotab;
73 Py_ssize_t lnotab_len;
74 int start_line;
75 int offset;
76 int line;
77 int addr;
78 int line_addr;
79} codetracker;
80
81/* Reset the mutable parts of the tracker */
82static void
83reset(codetracker *tracker)
84{
85 tracker->offset = 0;
86 tracker->addr = 0;
87 tracker->line_addr = 0;
88 tracker->line = tracker->start_line;
89}
90
91/* Initialise the tracker */
92static void
93init_codetracker(codetracker *tracker, PyCodeObject *code_obj)
94{
95 PyBytes_AsStringAndSize(code_obj->co_code,
96 (char **)&tracker->code, &tracker->code_len);
97 PyBytes_AsStringAndSize(code_obj->co_lnotab,
98 (char **)&tracker->lnotab, &tracker->lnotab_len);
99 tracker->start_line = code_obj->co_firstlineno;
100 reset(tracker);
101}
102
103static void
104advance_tracker(codetracker *tracker)
105{
106 tracker->addr += sizeof(_Py_CODEUNIT);
107 if (tracker->offset >= tracker->lnotab_len) {
108 return;
109 }
110 while (tracker->offset < tracker->lnotab_len &&
111 tracker->addr >= tracker->line_addr + tracker->lnotab[tracker->offset]) {
112 tracker->line_addr += tracker->lnotab[tracker->offset];
113 tracker->line += (signed char)tracker->lnotab[tracker->offset+1];
114 tracker->offset += 2;
115 }
116}
117
118
119static void
120retreat_tracker(codetracker *tracker)
121{
122 tracker->addr -= sizeof(_Py_CODEUNIT);
123 while (tracker->addr < tracker->line_addr) {
124 tracker->offset -= 2;
125 tracker->line_addr -= tracker->lnotab[tracker->offset];
126 tracker->line -= (signed char)tracker->lnotab[tracker->offset+1];
127 }
128}
129
130static int
131move_to_addr(codetracker *tracker, int addr)
132{
133 while (addr > tracker->addr) {
134 advance_tracker(tracker);
135 if (tracker->addr >= tracker->code_len) {
136 return -1;
137 }
138 }
139 while (addr < tracker->addr) {
140 retreat_tracker(tracker);
141 if (tracker->addr < 0) {
142 return -1;
143 }
144 }
145 return 0;
146}
147
148static int
149first_line_not_before(codetracker *tracker, int line)
150{
151 int result = INT_MAX;
152 reset(tracker);
153 while (tracker->addr < tracker->code_len) {
154 if (tracker->line == line) {
155 return line;
156 }
157 if (tracker->line > line && tracker->line < result) {
158 result = tracker->line;
159 }
160 advance_tracker(tracker);
161 }
162 if (result == INT_MAX) {
163 return -1;
164 }
165 return result;
166}
167
168static int
169move_to_nearest_start_of_line(codetracker *tracker, int line)
170{
171 if (line > tracker->line) {
172 while (line != tracker->line) {
173 advance_tracker(tracker);
174 if (tracker->addr >= tracker->code_len) {
175 return -1;
176 }
177 }
178 }
179 else {
180 while (line != tracker->line) {
181 retreat_tracker(tracker);
182 if (tracker->addr < 0) {
183 return -1;
184 }
185 }
186 while (tracker->addr > tracker->line_addr) {
187 retreat_tracker(tracker);
188 }
189 }
190 return 0;
191}
192
193typedef struct _blockitem
194{
195 unsigned char kind;
196 int end_addr;
197 int start_line;
198} blockitem;
199
200typedef struct _blockstack
201{
202 blockitem stack[CO_MAXBLOCKS];
203 int depth;
204} blockstack;
205
206
207static void
208init_blockstack(blockstack *blocks)
209{
210 blocks->depth = 0;
211}
212
213static void
214push_block(blockstack *blocks, unsigned char kind,
215 int end_addr, int start_line)
216{
217 assert(blocks->depth < CO_MAXBLOCKS);
218 blocks->stack[blocks->depth].kind = kind;
219 blocks->stack[blocks->depth].end_addr = end_addr;
220 blocks->stack[blocks->depth].start_line = start_line;
221 blocks->depth++;
222}
223
224static unsigned char
225pop_block(blockstack *blocks)
226{
227 assert(blocks->depth > 0);
228 blocks->depth--;
229 return blocks->stack[blocks->depth].kind;
230}
231
232static blockitem *
233top_block(blockstack *blocks)
234{
235 assert(blocks->depth > 0);
236 return &blocks->stack[blocks->depth-1];
237}
238
239static inline int
240is_try_except(unsigned char op, int target_op)
241{
242 return op == SETUP_FINALLY && (target_op == DUP_TOP || target_op == POP_TOP);
243}
244
245static inline int
246is_async_for(unsigned char op, int target_op)
247{
248 return op == SETUP_FINALLY && target_op == END_ASYNC_FOR;
249}
250
251static inline int
252is_try_finally(unsigned char op, int target_op)
253{
254 return op == SETUP_FINALLY && !is_try_except(op, target_op) && !is_async_for(op, target_op);
255}
256
257/* Kind for finding except blocks in the jump to line code */
258#define TRY_EXCEPT 250
259
260static int
261block_stack_for_line(codetracker *tracker, int line, blockstack *blocks)
262{
263 if (line < tracker->start_line) {
264 return -1;
265 }
266 init_blockstack(blocks);
267 reset(tracker);
268 while (tracker->addr < tracker->code_len) {
269 if (tracker->line == line) {
270 return 0;
271 }
272 if (blocks->depth > 0 && tracker->addr == top_block(blocks)->end_addr) {
273 unsigned char kind = pop_block(blocks);
274 assert(kind != SETUP_FINALLY);
275 if (kind == TRY_EXCEPT) {
276 push_block(blocks, POP_EXCEPT, -1, tracker->line);
277 }
278 if (kind == SETUP_WITH || kind == SETUP_ASYNC_WITH) {
279 push_block(blocks, WITH_EXCEPT_START, -1, tracker->line);
280 }
281 }
282 unsigned char op = tracker->code[tracker->addr];
283 if (op == SETUP_FINALLY || op == SETUP_ASYNC_WITH || op == SETUP_WITH || op == FOR_ITER) {
284 unsigned int oparg = get_arg((const _Py_CODEUNIT *)tracker->code,
285 tracker->addr / sizeof(_Py_CODEUNIT));
286 int target_addr = tracker->addr + oparg + sizeof(_Py_CODEUNIT);
287 int target_op = tracker->code[target_addr];
288 if (is_async_for(op, target_op)) {
289 push_block(blocks, FOR_ITER, target_addr, tracker->line);
290 }
291 else if (op == FOR_ITER) {
292 push_block(blocks, FOR_ITER, target_addr-sizeof(_Py_CODEUNIT), tracker->line);
293 }
294 else if (is_try_except(op, target_op)) {
295 push_block(blocks, TRY_EXCEPT, target_addr-sizeof(_Py_CODEUNIT), tracker->line);
296 }
297 else if (is_try_finally(op, target_op)) {
298 int addr = tracker->addr;
299 // Skip over duplicate 'finally' blocks if line is after body.
300 move_to_addr(tracker, target_addr);
301 if (tracker->line > line) {
302 // Target is in body, rewind to start.
303 move_to_addr(tracker, addr);
304 push_block(blocks, op, target_addr, tracker->line);
305 }
306 else {
307 // Now in finally block.
308 push_block(blocks, RERAISE, -1, tracker->line);
309 }
310 }
311 else {
312 push_block(blocks, op, target_addr, tracker->line);
313 }
314 }
315 else if (op == RERAISE) {
316 assert(blocks->depth > 0);
317 unsigned char kind = top_block(blocks)->kind;
318 if (kind == RERAISE || kind == WITH_EXCEPT_START || kind == POP_EXCEPT) {
319 pop_block(blocks);
320 }
321
322 }
323 advance_tracker(tracker);
324 }
325 return -1;
326}
327
328static void
329frame_stack_pop(PyFrameObject *f)
330{
331 PyObject *v = (*--f->f_stacktop);
332 Py_DECREF(v);
333}
334
335static void
336frame_block_unwind(PyFrameObject *f)
337{
338 assert(f->f_iblock > 0);
339 f->f_iblock--;
340 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Victor Stinner629023c2020-01-21 12:47:29 +0100341 intptr_t delta = (f->f_stacktop - f->f_valuestack) - b->b_level;
Mark Shannonfee55262019-11-21 09:11:43 +0000342 while (delta > 0) {
343 frame_stack_pop(f);
344 delta--;
345 }
346}
347
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200348
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000349/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000351 * lines are OK to jump to because they don't make any assumptions about the
352 * state of the stack (obvious because you could remove the line and the code
353 * would still work without any stack errors), but there are some constructs
354 * that limit jumping:
355 *
356 * o Lines with an 'except' statement on them can't be jumped to, because
357 * they expect an exception to be on the top of the stack.
358 * o Lines that live in a 'finally' block can't be jumped from or to, since
Mark Shannonfee55262019-11-21 09:11:43 +0000359 * we cannot be sure which state the interpreter was in or would be in
360 * during execution of the finally block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200361 * o 'try', 'with' and 'async with' blocks can't be jumped into because
362 * the blockstack needs to be set up before their code runs.
363 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000364 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +0100365 * o Jumps cannot be made from within a trace function invoked with a
366 * 'return' or 'exception' event since the eval loop has been exited at
367 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000368 */
369static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200370frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000371{
Zackery Spytz842acaa2018-12-17 07:52:45 -0700372 if (p_new_lineno == NULL) {
373 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
374 return -1;
375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 /* f_lineno must be an integer. */
377 if (!PyLong_CheckExact(p_new_lineno)) {
378 PyErr_SetString(PyExc_ValueError,
379 "lineno must be an integer");
380 return -1;
381 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000382
xdegayeb8e9d6c2018-03-13 18:31:31 +0100383 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
384 * f->f_trace is NULL, check first on the first condition.
385 * Forbidding jumps from the 'call' event of a new frame is a side effect
386 * of allowing to set f_lineno only from trace functions. */
387 if (f->f_lasti == -1) {
388 PyErr_Format(PyExc_ValueError,
389 "can't jump from the 'call' trace event of a new frame");
390 return -1;
391 }
392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* You can only do this from within a trace function, not via
394 * _getframe or similar hackery. */
xdegayeb8e9d6c2018-03-13 18:31:31 +0100395 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100397 "f_lineno can only be set by a trace function");
398 return -1;
399 }
400
401 /* Forbid jumps upon a 'return' trace event (except after executing a
402 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
403 * and upon an 'exception' trace event.
404 * Jumps from 'call' trace events have already been forbidden above for new
405 * frames, so this check does not change anything for 'call' events. */
406 if (f->f_stacktop == NULL) {
407 PyErr_SetString(PyExc_ValueError,
408 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 return -1;
410 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000411
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000412
Mark Shannonfee55262019-11-21 09:11:43 +0000413 codetracker tracker;
414 init_codetracker(&tracker, f->f_code);
415 move_to_addr(&tracker, f->f_lasti);
416 int current_line = tracker.line;
417 assert(current_line >= 0);
418 int new_lineno;
419
420 {
421 /* Fail if the line falls outside the code block and
422 select first line with actual code. */
423 int overflow;
424 long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
425 if (overflow
426#if SIZEOF_LONG > SIZEOF_INT
427 || l_new_lineno > INT_MAX
428 || l_new_lineno < INT_MIN
429#endif
430 ) {
431 PyErr_SetString(PyExc_ValueError,
432 "lineno out of range");
433 return -1;
434 }
435 new_lineno = (int)l_new_lineno;
436
437 if (new_lineno < f->f_code->co_firstlineno) {
438 PyErr_Format(PyExc_ValueError,
439 "line %d comes before the current code block",
440 new_lineno);
441 return -1;
442 }
443
444 new_lineno = first_line_not_before(&tracker, new_lineno);
445 if (new_lineno < 0) {
446 PyErr_Format(PyExc_ValueError,
447 "line %d comes after the current code block",
448 (int)l_new_lineno);
449 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 }
451 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000452
Mark Shannonfee55262019-11-21 09:11:43 +0000453 if (tracker.code[f->f_lasti] == YIELD_VALUE || tracker.code[f->f_lasti] == YIELD_FROM) {
454 PyErr_SetString(PyExc_ValueError,
455 "can't jump from a 'yield' statement");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return -1;
457 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000458
Mark Shannonfee55262019-11-21 09:11:43 +0000459 /* Find block stack for current line and target line. */
460 blockstack current_stack, new_stack;
461 block_stack_for_line(&tracker, new_lineno, &new_stack);
462 block_stack_for_line(&tracker, current_line, &current_stack);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000463
xdegayeb8e9d6c2018-03-13 18:31:31 +0100464 /* The trace function is called with a 'return' trace event after the
465 * execution of a yield statement. */
Mark Shannonfee55262019-11-21 09:11:43 +0000466 if (tracker.code[tracker.addr] == DUP_TOP || tracker.code[tracker.addr] == POP_TOP) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyErr_SetString(PyExc_ValueError,
468 "can't jump to 'except' line as there's no exception");
469 return -1;
470 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000471
Mark Shannonfee55262019-11-21 09:11:43 +0000472 /* Validate change of block stack. */
473 if (new_stack.depth > 0) {
474 blockitem *current_block_at_new_depth = &(current_stack.stack[new_stack.depth-1]);
475 if (new_stack.depth > current_stack.depth ||
476 top_block(&new_stack)->start_line != current_block_at_new_depth->start_line) {
477 unsigned char target_kind = top_block(&new_stack)->kind;
Andy Lester7386a702020-02-13 22:42:56 -0600478 const char *msg;
Mark Shannonfee55262019-11-21 09:11:43 +0000479 if (target_kind == POP_EXCEPT) {
480 msg = "can't jump into an 'except' block as there's no exception";
481 }
482 else if (target_kind == RERAISE) {
483 msg = "can't jump into a 'finally' block";
484 }
485 else {
486 msg = "can't jump into the middle of a block";
487 }
488 PyErr_SetString(PyExc_ValueError, msg);
489 return -1;
490 }
491 }
492
493 /* Check for illegal jumps out of finally or except blocks. */
494 for (int depth = new_stack.depth; depth < current_stack.depth; depth++) {
495 switch(current_stack.stack[depth].kind) {
496 case RERAISE:
497 PyErr_SetString(PyExc_ValueError,
498 "can't jump out of a 'finally' block");
499 return -1;
500 case POP_EXCEPT:
501 PyErr_SetString(PyExc_ValueError,
502 "can't jump out of an 'except' block");
503 return -1;
504 }
505 }
506
507 /* Unwind block stack. */
508 while (current_stack.depth > new_stack.depth) {
509 unsigned char kind = pop_block(&current_stack);
510 switch(kind) {
511 case FOR_ITER:
512 frame_stack_pop(f);
513 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 case SETUP_FINALLY:
Mark Shannonfee55262019-11-21 09:11:43 +0000515 case TRY_EXCEPT:
516 frame_block_unwind(f);
517 break;
Benjamin Petersone42fb302012-04-18 11:14:31 -0400518 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400519 case SETUP_ASYNC_WITH:
Mark Shannonfee55262019-11-21 09:11:43 +0000520 frame_block_unwind(f);
521 // Pop the exit function
522 frame_stack_pop(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 break;
Mark Shannonfee55262019-11-21 09:11:43 +0000524 default:
525 PyErr_SetString(PyExc_SystemError,
526 "unexpected block kind");
527 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 }
529 }
Mark Shannonfee55262019-11-21 09:11:43 +0000530
531 move_to_addr(&tracker, f->f_lasti);
532 move_to_nearest_start_of_line(&tracker, new_lineno);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* Finally set the new f_lineno and f_lasti and return OK. */
535 f->f_lineno = new_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +0000536 f->f_lasti = tracker.addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000538}
539
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000540static PyObject *
541frame_gettrace(PyFrameObject *f, void *closure)
542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (trace == NULL)
546 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000551}
552
553static int
554frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 /* We rely on f_lineno being accurate when f_trace is set. */
557 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000558
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300559 if (v == Py_None)
560 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300562 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000565}
566
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000567
Guido van Rossum32d34c82001-09-20 21:45:26 +0000568static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 {"f_locals", (getter)frame_getlocals, NULL, NULL},
570 {"f_lineno", (getter)frame_getlineno,
571 (setter)frame_setlineno, NULL},
572 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
573 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000574};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000575
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000576/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577 In an attempt to improve the speed of function calls, we:
578
579 1. Hold a single "zombie" frame on each code object. This retains
580 the allocated and initialised frame object from an invocation of
581 the code object. The zombie is reanimated the next time we need a
582 frame object for that code object. Doing this saves the malloc/
583 realloc required when using a free_list frame that isn't the
584 correct size. It also saves some field initialisation.
585
586 In zombie mode, no field of PyFrameObject holds a reference, but
587 the following fields are still valid:
588
589 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590
Mark Shannonae3087c2017-10-22 22:41:51 +0100591 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000592
593 * f_localsplus does not require re-allocation and
594 the local variables in f_localsplus are NULL.
595
596 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000597 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 a stack frame is on the free list, only the following members have
599 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 ob_type == &Frametype
601 f_back next item on free list, or NULL
602 f_stacksize size of value stack
603 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000604 Note that the value and block stacks are preserved -- this can save
605 another malloc() call or two (and two free() calls as well!).
606 Also note that, unlike for integers, each frame object is a
607 malloc'ed object in its own right -- it is only the actual calls to
608 malloc() that we are trying to save here, not the administration.
609 After all, while a typical program may make millions of calls, a
610 call depth of more than 20 or 30 is probably already exceptional
611 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000612
Christian Heimes2202f872008-02-06 14:31:34 +0000613 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000614 free_list. Else programs creating lots of cyclic trash involving
615 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000616*/
617
Guido van Rossum18752471997-04-29 14:49:28 +0000618static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000620/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000622
Victor Stinnerc6944e72016-11-11 02:13:35 +0100623static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000624frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000625{
Antoine Pitrou93963562013-05-14 20:37:52 +0200626 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000628
INADA Naoki5a625d02016-12-24 20:19:08 +0900629 if (_PyObject_GC_IS_TRACKED(f))
630 _PyObject_GC_UNTRACK(f);
631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200633 /* Kill all local variables */
634 valuestack = f->f_valuestack;
635 for (p = f->f_localsplus; p < valuestack; p++)
636 Py_CLEAR(*p);
637
638 /* Free stack */
639 if (f->f_stacktop != NULL) {
640 for (p = valuestack; p < f->f_stacktop; p++)
641 Py_XDECREF(*p);
642 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 Py_XDECREF(f->f_back);
645 Py_DECREF(f->f_builtins);
646 Py_DECREF(f->f_globals);
647 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200648 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 co = f->f_code;
651 if (co->co_zombieframe == NULL)
652 co->co_zombieframe = f;
653 else if (numfree < PyFrame_MAXFREELIST) {
654 ++numfree;
655 f->f_back = free_list;
656 free_list = f;
657 }
658 else
659 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_DECREF(co);
662 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000663}
664
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000665static int
666frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100669 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 Py_VISIT(f->f_back);
672 Py_VISIT(f->f_code);
673 Py_VISIT(f->f_builtins);
674 Py_VISIT(f->f_globals);
675 Py_VISIT(f->f_locals);
676 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 /* locals */
679 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
680 fastlocals = f->f_localsplus;
681 for (i = slots; --i >= 0; ++fastlocals)
682 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 /* stack */
685 if (f->f_stacktop != NULL) {
686 for (p = f->f_valuestack; p < f->f_stacktop; p++)
687 Py_VISIT(*p);
688 }
689 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000690}
691
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200692static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200693frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100696 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000697
Antoine Pitrou93963562013-05-14 20:37:52 +0200698 /* Before anything else, make sure that this frame is clearly marked
699 * as being defunct! Else, e.g., a generator reachable from this
700 * frame may also point to this frame, believe itself to still be
701 * active, and try cleaning up this frame again.
702 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 oldtop = f->f_stacktop;
704 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200705 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 /* locals */
710 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
711 fastlocals = f->f_localsplus;
712 for (i = slots; --i >= 0; ++fastlocals)
713 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 /* stack */
716 if (oldtop != NULL) {
717 for (p = f->f_valuestack; p < oldtop; p++)
718 Py_CLEAR(*p);
719 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200720 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000721}
722
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000723static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530724frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200725{
726 if (f->f_executing) {
727 PyErr_SetString(PyExc_RuntimeError,
728 "cannot clear an executing frame");
729 return NULL;
730 }
731 if (f->f_gen) {
732 _PyGen_Finalize(f->f_gen);
733 assert(f->f_gen == NULL);
734 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200735 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200736 Py_RETURN_NONE;
737}
738
739PyDoc_STRVAR(clear__doc__,
740"F.clear(): clear most references held by the frame");
741
742static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530743frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
748 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
749 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
750 ncells + nfrees;
751 /* subtract one as it is already included in PyFrameObject */
752 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000755}
756
757PyDoc_STRVAR(sizeof__doc__,
758"F.__sizeof__() -> size of F in memory, in bytes");
759
Antoine Pitrou14709142017-12-31 22:35:22 +0100760static PyObject *
761frame_repr(PyFrameObject *f)
762{
763 int lineno = PyFrame_GetLineNumber(f);
764 return PyUnicode_FromFormat(
765 "<frame at %p, file %R, line %d, code %S>",
766 f, f->f_code->co_filename, lineno, f->f_code->co_name);
767}
768
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000769static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200770 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
771 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
773 sizeof__doc__},
774 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000775};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000776
Guido van Rossum18752471997-04-29 14:49:28 +0000777PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyVarObject_HEAD_INIT(&PyType_Type, 0)
779 "frame",
780 sizeof(PyFrameObject),
781 sizeof(PyObject *),
782 (destructor)frame_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200783 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 0, /* tp_getattr */
785 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200786 0, /* tp_as_async */
Antoine Pitrou14709142017-12-31 22:35:22 +0100787 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 0, /* tp_as_number */
789 0, /* tp_as_sequence */
790 0, /* tp_as_mapping */
791 0, /* tp_hash */
792 0, /* tp_call */
793 0, /* tp_str */
794 PyObject_GenericGetAttr, /* tp_getattro */
795 PyObject_GenericSetAttr, /* tp_setattro */
796 0, /* tp_as_buffer */
797 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
798 0, /* tp_doc */
799 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200800 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 0, /* tp_richcompare */
802 0, /* tp_weaklistoffset */
803 0, /* tp_iter */
804 0, /* tp_iternext */
805 frame_methods, /* tp_methods */
806 frame_memberlist, /* tp_members */
807 frame_getsetlist, /* tp_getset */
808 0, /* tp_base */
809 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000810};
811
Victor Stinner07e9e382013-11-07 22:22:39 +0100812_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000813
Victor Stinnerc6944e72016-11-11 02:13:35 +0100814PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900815_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
816 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyFrameObject *back = tstate->frame;
819 PyFrameObject *f;
820 PyObject *builtins;
821 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000822
Michael W. Hudson69734a52002-08-19 16:54:08 +0000823#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
825 (locals != NULL && !PyMapping_Check(locals))) {
826 PyErr_BadInternalCall();
827 return NULL;
828 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000829#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (back == NULL || back->f_globals != globals) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200831 builtins = _PyDict_GetItemIdWithError(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (builtins) {
833 if (PyModule_Check(builtins)) {
834 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200835 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 }
838 if (builtins == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200839 if (PyErr_Occurred()) {
840 return NULL;
841 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 /* No builtins! Make up a minimal one
843 Give them 'None', at least. */
844 builtins = PyDict_New();
845 if (builtins == NULL ||
846 PyDict_SetItemString(
847 builtins, "None", Py_None) < 0)
848 return NULL;
849 }
850 else
851 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 }
854 else {
855 /* If we share the globals, we share the builtins.
856 Save a lookup and a call. */
857 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200858 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_INCREF(builtins);
860 }
861 if (code->co_zombieframe != NULL) {
862 f = code->co_zombieframe;
863 code->co_zombieframe = NULL;
864 _Py_NewReference((PyObject *)f);
865 assert(f->f_code == code);
866 }
867 else {
868 Py_ssize_t extras, ncells, nfrees;
869 ncells = PyTuple_GET_SIZE(code->co_cellvars);
870 nfrees = PyTuple_GET_SIZE(code->co_freevars);
871 extras = code->co_stacksize + code->co_nlocals + ncells +
872 nfrees;
873 if (free_list == NULL) {
874 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
875 extras);
876 if (f == NULL) {
877 Py_DECREF(builtins);
878 return NULL;
879 }
880 }
881 else {
882 assert(numfree > 0);
883 --numfree;
884 f = free_list;
885 free_list = free_list->f_back;
886 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000887 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
888 if (new_f == NULL) {
889 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 Py_DECREF(builtins);
891 return NULL;
892 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000893 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 }
895 _Py_NewReference((PyObject *)f);
896 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 f->f_code = code;
899 extras = code->co_nlocals + ncells + nfrees;
900 f->f_valuestack = f->f_localsplus + extras;
901 for (i=0; i<extras; i++)
902 f->f_localsplus[i] = NULL;
903 f->f_locals = NULL;
904 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 }
906 f->f_stacktop = f->f_valuestack;
907 f->f_builtins = builtins;
908 Py_XINCREF(back);
909 f->f_back = back;
910 Py_INCREF(code);
911 Py_INCREF(globals);
912 f->f_globals = globals;
913 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
914 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
915 (CO_NEWLOCALS | CO_OPTIMIZED))
916 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
917 else if (code->co_flags & CO_NEWLOCALS) {
918 locals = PyDict_New();
919 if (locals == NULL) {
920 Py_DECREF(f);
921 return NULL;
922 }
923 f->f_locals = locals;
924 }
925 else {
926 if (locals == NULL)
927 locals = globals;
928 Py_INCREF(locals);
929 f->f_locals = locals;
930 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 f->f_lasti = -1;
933 f->f_lineno = code->co_firstlineno;
934 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200935 f->f_executing = 0;
936 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000937 f->f_trace_opcodes = 0;
938 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000941}
942
INADA Naoki5a625d02016-12-24 20:19:08 +0900943PyFrameObject*
944PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
945 PyObject *globals, PyObject *locals)
946{
947 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
948 if (f)
949 _PyObject_GC_TRACK(f);
950 return f;
951}
952
953
Guido van Rossum3f5da241990-12-20 15:06:42 +0000954/* Block management */
955
956void
Fred Drake1b190b42000-07-09 05:40:56 +0000957PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100960 if (f->f_iblock >= CO_MAXBLOCKS) {
961 Py_FatalError("block stack overflow");
962 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 b = &f->f_blockstack[f->f_iblock++];
964 b->b_type = type;
965 b->b_level = level;
966 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000967}
968
Guido van Rossum18752471997-04-29 14:49:28 +0000969PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000970PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 PyTryBlock *b;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100973 if (f->f_iblock <= 0) {
974 Py_FatalError("block stack underflow");
975 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 b = &f->f_blockstack[--f->f_iblock];
977 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000978}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000979
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981
982 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 values is an array of PyObject*. At index i, map[i] is the name of
984 the variable with value values[i]. The function copies the first
985 nmap variable from map/values into dict. If values[i] is NULL,
986 the variable is deleted from dict.
987
988 If deref is true, then the values being copied are cell variables
989 and the value is extracted from the cell variable before being put
990 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000991 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000992
Victor Stinner41bb43a2013-10-29 01:19:37 +0100993static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000994map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 Py_ssize_t j;
998 assert(PyTuple_Check(map));
999 assert(PyDict_Check(dict));
1000 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001001 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyObject *key = PyTuple_GET_ITEM(map, j);
1003 PyObject *value = values[j];
1004 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -04001005 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 assert(PyCell_Check(value));
1007 value = PyCell_GET(value);
1008 }
1009 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001010 if (PyObject_DelItem(dict, key) != 0) {
1011 if (PyErr_ExceptionMatches(PyExc_KeyError))
1012 PyErr_Clear();
1013 else
1014 return -1;
1015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 }
1017 else {
1018 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +01001019 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 }
1021 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001022 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001023}
1024
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025/* Copy values from the "locals" dict into the fast locals.
1026
1027 dict is an input argument containing string keys representing
1028 variables names and arbitrary PyObject* as values.
1029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031 values is an array of PyObject*. At index i, map[i] is the name of
1032 the variable with value values[i]. The function copies the first
1033 nmap variable from map/values into dict. If values[i] is NULL,
1034 the variable is deleted from dict.
1035
1036 If deref is true, then the values being copied are cell variables
1037 and the value is extracted from the cell variable before being put
1038 in dict. If clear is true, then variables in map but not in dict
1039 are set to NULL in map; if clear is false, variables missing in
1040 dict are ignored.
1041
1042 Exceptions raised while modifying the dict are silently ignored,
1043 because there is no good way to report them.
1044*/
1045
Guido van Rossum6b356e72001-04-14 17:55:41 +00001046static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001047dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 Py_ssize_t j;
1051 assert(PyTuple_Check(map));
1052 assert(PyDict_Check(dict));
1053 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -08001054 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 PyObject *key = PyTuple_GET_ITEM(map, j);
1056 PyObject *value = PyObject_GetItem(dict, key);
1057 assert(PyUnicode_Check(key));
1058 /* We only care about NULLs if clear is true. */
1059 if (value == NULL) {
1060 PyErr_Clear();
1061 if (!clear)
1062 continue;
1063 }
1064 if (deref) {
1065 assert(PyCell_Check(values[j]));
1066 if (PyCell_GET(values[j]) != value) {
1067 if (PyCell_Set(values[j], value) < 0)
1068 PyErr_Clear();
1069 }
1070 } else if (values[j] != value) {
1071 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001072 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 }
1074 Py_XDECREF(value);
1075 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001076}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001077
Victor Stinner41bb43a2013-10-29 01:19:37 +01001078int
1079PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* Merge fast locals into f->f_locals */
1082 PyObject *locals, *map;
1083 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyCodeObject *co;
1085 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001086 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001087
1088 if (f == NULL) {
1089 PyErr_BadInternalCall();
1090 return -1;
1091 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 locals = f->f_locals;
1093 if (locals == NULL) {
1094 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001095 if (locals == NULL)
1096 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 }
1098 co = f->f_code;
1099 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001100 if (!PyTuple_Check(map)) {
1101 PyErr_Format(PyExc_SystemError,
1102 "co_varnames must be a tuple, not %s",
1103 Py_TYPE(map)->tp_name);
1104 return -1;
1105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 fast = f->f_localsplus;
1107 j = PyTuple_GET_SIZE(map);
1108 if (j > co->co_nlocals)
1109 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001110 if (co->co_nlocals) {
1111 if (map_to_dict(map, j, locals, fast, 0) < 0)
1112 return -1;
1113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1115 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1116 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001117 if (map_to_dict(co->co_cellvars, ncells,
1118 locals, fast + co->co_nlocals, 1))
1119 return -1;
1120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 /* If the namespace is unoptimized, then one of the
1122 following cases applies:
1123 1. It does not contain free variables, because it
1124 uses import * or is a top-level namespace.
1125 2. It is a class namespace.
1126 We don't want to accidentally copy free variables
1127 into the locals dict used by the class.
1128 */
1129 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +01001130 if (map_to_dict(co->co_freevars, nfreevars,
1131 locals, fast + co->co_nlocals + ncells, 1) < 0)
1132 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
1134 }
Victor Stinner41bb43a2013-10-29 01:19:37 +01001135 return 0;
1136}
1137
1138void
1139PyFrame_FastToLocals(PyFrameObject *f)
1140{
1141 int res;
1142
1143 assert(!PyErr_Occurred());
1144
1145 res = PyFrame_FastToLocalsWithError(f);
1146 if (res < 0)
1147 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001148}
1149
1150void
Fred Drake1b190b42000-07-09 05:40:56 +00001151PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Merge f->f_locals into fast locals */
1154 PyObject *locals, *map;
1155 PyObject **fast;
1156 PyObject *error_type, *error_value, *error_traceback;
1157 PyCodeObject *co;
1158 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001159 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (f == NULL)
1161 return;
1162 locals = f->f_locals;
1163 co = f->f_code;
1164 map = co->co_varnames;
1165 if (locals == NULL)
1166 return;
1167 if (!PyTuple_Check(map))
1168 return;
1169 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1170 fast = f->f_localsplus;
1171 j = PyTuple_GET_SIZE(map);
1172 if (j > co->co_nlocals)
1173 j = co->co_nlocals;
1174 if (co->co_nlocals)
1175 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1176 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1177 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1178 if (ncells || nfreevars) {
1179 dict_to_map(co->co_cellvars, ncells,
1180 locals, fast + co->co_nlocals, 1, clear);
1181 /* Same test as in PyFrame_FastToLocals() above. */
1182 if (co->co_flags & CO_OPTIMIZED) {
1183 dict_to_map(co->co_freevars, nfreevars,
1184 locals, fast + co->co_nlocals + ncells, 1,
1185 clear);
1186 }
1187 }
1188 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001189}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001190
1191/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +00001192int
1193PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 int freelist_size = numfree;
1196
1197 while (free_list != NULL) {
1198 PyFrameObject *f = free_list;
1199 free_list = free_list->f_back;
1200 PyObject_GC_Del(f);
1201 --numfree;
1202 }
1203 assert(numfree == 0);
1204 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +00001205}
1206
1207void
Victor Stinnerbed48172019-08-27 00:12:32 +02001208_PyFrame_Fini(void)
Christian Heimesa156e092008-02-16 07:38:31 +00001209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001211}
David Malcolm49526f42012-06-22 14:55:41 -04001212
1213/* Print summary info about the state of the optimized allocator */
1214void
1215_PyFrame_DebugMallocStats(FILE *out)
1216{
1217 _PyDebugAllocatorStats(out,
1218 "free PyFrameObject",
1219 numfree, sizeof(PyFrameObject));
1220}
1221