blob: 2825041e6310275b411228930b090c901e39461e [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06004#include "internal/pystate.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00007#include "frameobject.h"
8#include "opcode.h"
9#include "structmember.h"
10
Guido van Rossum18752471997-04-29 14:49:28 +000011#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012
Guido van Rossum6f799372001-09-20 20:46:19 +000013static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100014 {"f_back", T_OBJECT, OFF(f_back), READONLY},
15 {"f_code", T_OBJECT, OFF(f_code), READONLY},
16 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
17 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
18 {"f_lasti", T_INT, OFF(f_lasti), READONLY},
Nick Coghlan5a851672017-09-08 10:14:16 +100019 {"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
20 {"f_trace_opcodes", T_BOOL, OFF(f_trace_opcodes), 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000022};
23
Guido van Rossum18752471997-04-29 14:49:28 +000024static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000025frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000026{
Victor Stinner41bb43a2013-10-29 01:19:37 +010027 if (PyFrame_FastToLocalsWithError(f) < 0)
28 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 Py_INCREF(f->f_locals);
30 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000031}
32
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000033int
34PyFrame_GetLineNumber(PyFrameObject *f)
35{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 if (f->f_trace)
37 return f->f_lineno;
38 else
39 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000040}
41
Michael W. Hudsondd32a912002-08-15 14:59:02 +000042static PyObject *
43frame_getlineno(PyFrameObject *f, void *closure)
44{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000046}
47
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000048/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000050 * lines are OK to jump to because they don't make any assumptions about the
51 * state of the stack (obvious because you could remove the line and the code
52 * would still work without any stack errors), but there are some constructs
53 * that limit jumping:
54 *
55 * o Lines with an 'except' statement on them can't be jumped to, because
56 * they expect an exception to be on the top of the stack.
57 * o Lines that live in a 'finally' block can't be jumped from or to, since
58 * the END_FINALLY expects to clean up the stack after the 'try' block.
59 * o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
60 * needs to be set up before their code runs, and for 'for' loops the
61 * iterator needs to be on the stack.
62 */
63static int
64frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
65{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 int new_lineno = 0; /* The new value of f_lineno */
67 long l_new_lineno;
68 int overflow;
69 int new_lasti = 0; /* The new value of f_lasti */
70 int new_iblock = 0; /* The new value of f_iblock */
71 unsigned char *code = NULL; /* The bytecode for the frame... */
72 Py_ssize_t code_len = 0; /* ...and its length */
73 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
74 Py_ssize_t lnotab_len = 0; /* (ditto) */
75 int offset = 0; /* (ditto) */
76 int line = 0; /* (ditto) */
77 int addr = 0; /* (ditto) */
78 int min_addr = 0; /* Scanning the SETUPs and POPs */
79 int max_addr = 0; /* (ditto) */
80 int delta_iblock = 0; /* (ditto) */
81 int min_delta_iblock = 0; /* (ditto) */
82 int min_iblock = 0; /* (ditto) */
83 int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
84 int new_lasti_setup_addr = 0; /* (ditto) */
85 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
86 int in_finally[CO_MAXBLOCKS]; /* (ditto) */
87 int blockstack_top = 0; /* (ditto) */
88 unsigned char setup_op = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 /* f_lineno must be an integer. */
91 if (!PyLong_CheckExact(p_new_lineno)) {
92 PyErr_SetString(PyExc_ValueError,
93 "lineno must be an integer");
94 return -1;
95 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 /* You can only do this from within a trace function, not via
98 * _getframe or similar hackery. */
99 if (!f->f_trace)
100 {
101 PyErr_Format(PyExc_ValueError,
102 "f_lineno can only be set by a"
103 " line trace function");
104 return -1;
105 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 /* Fail if the line comes before the start of the code block. */
108 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
109 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000110#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 || l_new_lineno > INT_MAX
112 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000113#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 ) {
115 PyErr_SetString(PyExc_ValueError,
116 "lineno out of range");
117 return -1;
118 }
119 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (new_lineno < f->f_code->co_firstlineno) {
122 PyErr_Format(PyExc_ValueError,
123 "line %d comes before the current code block",
124 new_lineno);
125 return -1;
126 }
127 else if (new_lineno == f->f_code->co_firstlineno) {
128 new_lasti = 0;
129 new_lineno = f->f_code->co_firstlineno;
130 }
131 else {
132 /* Find the bytecode offset for the start of the given
133 * line, or the first code-owning line after it. */
134 char *tmp;
135 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
136 &tmp, &lnotab_len);
137 lnotab = (unsigned char *) tmp;
138 addr = 0;
139 line = f->f_code->co_firstlineno;
140 new_lasti = -1;
141 for (offset = 0; offset < lnotab_len; offset += 2) {
142 addr += lnotab[offset];
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100143 line += (signed char)lnotab[offset+1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (line >= new_lineno) {
145 new_lasti = addr;
146 new_lineno = line;
147 break;
148 }
149 }
150 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 /* If we didn't reach the requested line, return an error. */
153 if (new_lasti == -1) {
154 PyErr_Format(PyExc_ValueError,
155 "line %d comes after the current code block",
156 new_lineno);
157 return -1;
158 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 /* We're now ready to look at the bytecode. */
161 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
Victor Stinner640c35c2013-06-04 23:14:37 +0200162 min_addr = Py_MIN(new_lasti, f->f_lasti);
163 max_addr = Py_MAX(new_lasti, f->f_lasti);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 /* You can't jump onto a line with an 'except' statement on it -
166 * they expect to have an exception on the top of the stack, which
167 * won't be true if you jump to them. They always start with code
168 * that either pops the exception using POP_TOP (plain 'except:'
169 * lines do this) or duplicates the exception on the stack using
170 * DUP_TOP (if there's an exception type specified). See compile.c,
171 * 'com_try_except' for the full details. There aren't any other
172 * cases (AFAIK) where a line's code can start with DUP_TOP or
173 * POP_TOP, but if any ever appear, they'll be subject to the same
174 * restriction (but with a different error message). */
175 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
176 PyErr_SetString(PyExc_ValueError,
177 "can't jump to 'except' line as there's no exception");
178 return -1;
179 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 /* You can't jump into or out of a 'finally' block because the 'try'
182 * block leaves something on the stack for the END_FINALLY to clean
183 * up. So we walk the bytecode, maintaining a simulated blockstack.
184 * When we reach the old or new address and it's in a 'finally' block
185 * we note the address of the corresponding SETUP_FINALLY. The jump
186 * is only legal if neither address is in a 'finally' block or
187 * they're both in the same one. 'blockstack' is a stack of the
188 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
189 * whether we're in a 'finally' block at each blockstack level. */
190 f_lasti_setup_addr = -1;
191 new_lasti_setup_addr = -1;
192 memset(blockstack, '\0', sizeof(blockstack));
193 memset(in_finally, '\0', sizeof(in_finally));
194 blockstack_top = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300195 for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 unsigned char op = code[addr];
197 switch (op) {
198 case SETUP_LOOP:
199 case SETUP_EXCEPT:
200 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400201 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400202 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 blockstack[blockstack_top++] = addr;
204 in_finally[blockstack_top-1] = 0;
205 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 case POP_BLOCK:
208 assert(blockstack_top > 0);
209 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400210 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
211 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 in_finally[blockstack_top-1] = 1;
213 }
214 else {
215 blockstack_top--;
216 }
217 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 case END_FINALLY:
220 /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
221 * in the bytecode but don't correspond to an actual
222 * 'finally' block. (If blockstack_top is 0, we must
223 * be seeing such an END_FINALLY.) */
224 if (blockstack_top > 0) {
225 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400226 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
227 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 blockstack_top--;
229 }
230 }
231 break;
232 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 /* For the addresses we're interested in, see whether they're
235 * within a 'finally' block and if so, remember the address
236 * of the SETUP_FINALLY. */
237 if (addr == new_lasti || addr == f->f_lasti) {
238 int i = 0;
239 int setup_addr = -1;
240 for (i = blockstack_top-1; i >= 0; i--) {
241 if (in_finally[i]) {
242 setup_addr = blockstack[i];
243 break;
244 }
245 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (setup_addr != -1) {
248 if (addr == new_lasti) {
249 new_lasti_setup_addr = setup_addr;
250 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (addr == f->f_lasti) {
253 f_lasti_setup_addr = setup_addr;
254 }
255 }
256 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 /* Verify that the blockstack tracking code didn't get lost. */
260 assert(blockstack_top == 0);
261
262 /* After all that, are we jumping into / out of a 'finally' block? */
263 if (new_lasti_setup_addr != f_lasti_setup_addr) {
264 PyErr_SetString(PyExc_ValueError,
265 "can't jump into or out of a 'finally' block");
266 return -1;
267 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000268
269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* Police block-jumping (you can't jump into the middle of a block)
271 * and ensure that the blockstack finishes up in a sensible state (by
272 * popping any blocks we're jumping out of). We look at all the
273 * blockstack operations between the current position and the new
274 * one, and keep track of how many blocks we drop out of on the way.
275 * By also keeping track of the lowest blockstack position we see, we
276 * can tell whether the jump goes into any blocks without coming out
277 * again - in that case we raise an exception below. */
278 delta_iblock = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300279 for (addr = min_addr; addr < max_addr; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 unsigned char op = code[addr];
281 switch (op) {
282 case SETUP_LOOP:
283 case SETUP_EXCEPT:
284 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400285 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400286 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 delta_iblock++;
288 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 case POP_BLOCK:
291 delta_iblock--;
292 break;
293 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000294
Victor Stinner640c35c2013-06-04 23:14:37 +0200295 min_delta_iblock = Py_MIN(min_delta_iblock, delta_iblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* Derive the absolute iblock values from the deltas. */
299 min_iblock = f->f_iblock + min_delta_iblock;
300 if (new_lasti > f->f_lasti) {
301 /* Forwards jump. */
302 new_iblock = f->f_iblock + delta_iblock;
303 }
304 else {
305 /* Backwards jump. */
306 new_iblock = f->f_iblock - delta_iblock;
307 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 /* Are we jumping into a block? */
310 if (new_iblock > min_iblock) {
311 PyErr_SetString(PyExc_ValueError,
312 "can't jump into the middle of a block");
313 return -1;
314 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 /* Pop any blocks that we're jumping out of. */
317 while (f->f_iblock > new_iblock) {
318 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
319 while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
320 PyObject *v = (*--f->f_stacktop);
321 Py_DECREF(v);
322 }
Serhiy Storchaka04aadf22018-03-11 09:30:13 +0200323 if (b->b_type == SETUP_FINALLY &&
324 code[b->b_handler] == WITH_CLEANUP_START)
325 {
326 /* Pop the exit function. */
327 PyObject *v = (*--f->f_stacktop);
328 Py_DECREF(v);
329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* Finally set the new f_lineno and f_lasti and return OK. */
333 f->f_lineno = new_lineno;
334 f->f_lasti = new_lasti;
335 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000336}
337
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000338static PyObject *
339frame_gettrace(PyFrameObject *f, void *closure)
340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (trace == NULL)
344 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000349}
350
351static int
352frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 /* We rely on f_lineno being accurate when f_trace is set. */
355 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000356
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300357 if (v == Py_None)
358 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300360 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000363}
364
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000365
Guido van Rossum32d34c82001-09-20 21:45:26 +0000366static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 {"f_locals", (getter)frame_getlocals, NULL, NULL},
368 {"f_lineno", (getter)frame_getlineno,
369 (setter)frame_setlineno, NULL},
370 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
371 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000372};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000373
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000374/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000375 In an attempt to improve the speed of function calls, we:
376
377 1. Hold a single "zombie" frame on each code object. This retains
378 the allocated and initialised frame object from an invocation of
379 the code object. The zombie is reanimated the next time we need a
380 frame object for that code object. Doing this saves the malloc/
381 realloc required when using a free_list frame that isn't the
382 correct size. It also saves some field initialisation.
383
384 In zombie mode, no field of PyFrameObject holds a reference, but
385 the following fields are still valid:
386
387 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388
Mark Shannonae3087c2017-10-22 22:41:51 +0100389 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000390
391 * f_localsplus does not require re-allocation and
392 the local variables in f_localsplus are NULL.
393
394 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000395 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000396 a stack frame is on the free list, only the following members have
397 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 ob_type == &Frametype
399 f_back next item on free list, or NULL
400 f_stacksize size of value stack
401 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000402 Note that the value and block stacks are preserved -- this can save
403 another malloc() call or two (and two free() calls as well!).
404 Also note that, unlike for integers, each frame object is a
405 malloc'ed object in its own right -- it is only the actual calls to
406 malloc() that we are trying to save here, not the administration.
407 After all, while a typical program may make millions of calls, a
408 call depth of more than 20 or 30 is probably already exceptional
409 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000410
Christian Heimes2202f872008-02-06 14:31:34 +0000411 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000412 free_list. Else programs creating lots of cyclic trash involving
413 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000414*/
415
Guido van Rossum18752471997-04-29 14:49:28 +0000416static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000418/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000420
Victor Stinnerc6944e72016-11-11 02:13:35 +0100421static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000422frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000423{
Antoine Pitrou93963562013-05-14 20:37:52 +0200424 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000426
INADA Naoki5a625d02016-12-24 20:19:08 +0900427 if (_PyObject_GC_IS_TRACKED(f))
428 _PyObject_GC_UNTRACK(f);
429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200431 /* Kill all local variables */
432 valuestack = f->f_valuestack;
433 for (p = f->f_localsplus; p < valuestack; p++)
434 Py_CLEAR(*p);
435
436 /* Free stack */
437 if (f->f_stacktop != NULL) {
438 for (p = valuestack; p < f->f_stacktop; p++)
439 Py_XDECREF(*p);
440 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 Py_XDECREF(f->f_back);
443 Py_DECREF(f->f_builtins);
444 Py_DECREF(f->f_globals);
445 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200446 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 co = f->f_code;
449 if (co->co_zombieframe == NULL)
450 co->co_zombieframe = f;
451 else if (numfree < PyFrame_MAXFREELIST) {
452 ++numfree;
453 f->f_back = free_list;
454 free_list = f;
455 }
456 else
457 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 Py_DECREF(co);
460 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000461}
462
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000463static int
464frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100467 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_VISIT(f->f_back);
470 Py_VISIT(f->f_code);
471 Py_VISIT(f->f_builtins);
472 Py_VISIT(f->f_globals);
473 Py_VISIT(f->f_locals);
474 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* locals */
477 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
478 fastlocals = f->f_localsplus;
479 for (i = slots; --i >= 0; ++fastlocals)
480 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* stack */
483 if (f->f_stacktop != NULL) {
484 for (p = f->f_valuestack; p < f->f_stacktop; p++)
485 Py_VISIT(*p);
486 }
487 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000488}
489
490static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200491frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100494 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000495
Antoine Pitrou93963562013-05-14 20:37:52 +0200496 /* Before anything else, make sure that this frame is clearly marked
497 * as being defunct! Else, e.g., a generator reachable from this
498 * frame may also point to this frame, believe itself to still be
499 * active, and try cleaning up this frame again.
500 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 oldtop = f->f_stacktop;
502 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200503 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* locals */
508 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
509 fastlocals = f->f_localsplus;
510 for (i = slots; --i >= 0; ++fastlocals)
511 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 /* stack */
514 if (oldtop != NULL) {
515 for (p = f->f_valuestack; p < oldtop; p++)
516 Py_CLEAR(*p);
517 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000518}
519
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000520static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200521frame_clear(PyFrameObject *f)
522{
523 if (f->f_executing) {
524 PyErr_SetString(PyExc_RuntimeError,
525 "cannot clear an executing frame");
526 return NULL;
527 }
528 if (f->f_gen) {
529 _PyGen_Finalize(f->f_gen);
530 assert(f->f_gen == NULL);
531 }
532 frame_tp_clear(f);
533 Py_RETURN_NONE;
534}
535
536PyDoc_STRVAR(clear__doc__,
537"F.clear(): clear most references held by the frame");
538
539static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000540frame_sizeof(PyFrameObject *f)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
545 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
546 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
547 ncells + nfrees;
548 /* subtract one as it is already included in PyFrameObject */
549 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000552}
553
554PyDoc_STRVAR(sizeof__doc__,
555"F.__sizeof__() -> size of F in memory, in bytes");
556
Antoine Pitrou14709142017-12-31 22:35:22 +0100557static PyObject *
558frame_repr(PyFrameObject *f)
559{
560 int lineno = PyFrame_GetLineNumber(f);
561 return PyUnicode_FromFormat(
562 "<frame at %p, file %R, line %d, code %S>",
563 f, f->f_code->co_filename, lineno, f->f_code->co_name);
564}
565
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000566static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200567 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
568 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
570 sizeof__doc__},
571 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000572};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000573
Guido van Rossum18752471997-04-29 14:49:28 +0000574PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 PyVarObject_HEAD_INIT(&PyType_Type, 0)
576 "frame",
577 sizeof(PyFrameObject),
578 sizeof(PyObject *),
579 (destructor)frame_dealloc, /* tp_dealloc */
580 0, /* tp_print */
581 0, /* tp_getattr */
582 0, /* tp_setattr */
583 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100584 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 0, /* tp_as_number */
586 0, /* tp_as_sequence */
587 0, /* tp_as_mapping */
588 0, /* tp_hash */
589 0, /* tp_call */
590 0, /* tp_str */
591 PyObject_GenericGetAttr, /* tp_getattro */
592 PyObject_GenericSetAttr, /* tp_setattro */
593 0, /* tp_as_buffer */
594 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
595 0, /* tp_doc */
596 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200597 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 0, /* tp_richcompare */
599 0, /* tp_weaklistoffset */
600 0, /* tp_iter */
601 0, /* tp_iternext */
602 frame_methods, /* tp_methods */
603 frame_memberlist, /* tp_members */
604 frame_getsetlist, /* tp_getset */
605 0, /* tp_base */
606 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000607};
608
Victor Stinner07e9e382013-11-07 22:22:39 +0100609_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000610
Neal Norwitzb2501f42002-12-31 03:42:13 +0000611int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000612{
Victor Stinner07e9e382013-11-07 22:22:39 +0100613 /* Before, PyId___builtins__ was a string created explicitly in
614 this function. Now there is nothing to initialize anymore, but
615 the function is kept for backward compatibility. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000617}
618
Victor Stinnerc6944e72016-11-11 02:13:35 +0100619PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900620_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
621 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyFrameObject *back = tstate->frame;
624 PyFrameObject *f;
625 PyObject *builtins;
626 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000627
Michael W. Hudson69734a52002-08-19 16:54:08 +0000628#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
630 (locals != NULL && !PyMapping_Check(locals))) {
631 PyErr_BadInternalCall();
632 return NULL;
633 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000634#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100636 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (builtins) {
638 if (PyModule_Check(builtins)) {
639 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200640 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 }
643 if (builtins == NULL) {
644 /* No builtins! Make up a minimal one
645 Give them 'None', at least. */
646 builtins = PyDict_New();
647 if (builtins == NULL ||
648 PyDict_SetItemString(
649 builtins, "None", Py_None) < 0)
650 return NULL;
651 }
652 else
653 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 }
656 else {
657 /* If we share the globals, we share the builtins.
658 Save a lookup and a call. */
659 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200660 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_INCREF(builtins);
662 }
663 if (code->co_zombieframe != NULL) {
664 f = code->co_zombieframe;
665 code->co_zombieframe = NULL;
666 _Py_NewReference((PyObject *)f);
667 assert(f->f_code == code);
668 }
669 else {
670 Py_ssize_t extras, ncells, nfrees;
671 ncells = PyTuple_GET_SIZE(code->co_cellvars);
672 nfrees = PyTuple_GET_SIZE(code->co_freevars);
673 extras = code->co_stacksize + code->co_nlocals + ncells +
674 nfrees;
675 if (free_list == NULL) {
676 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
677 extras);
678 if (f == NULL) {
679 Py_DECREF(builtins);
680 return NULL;
681 }
682 }
683 else {
684 assert(numfree > 0);
685 --numfree;
686 f = free_list;
687 free_list = free_list->f_back;
688 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000689 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
690 if (new_f == NULL) {
691 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 Py_DECREF(builtins);
693 return NULL;
694 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000695 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 }
697 _Py_NewReference((PyObject *)f);
698 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 f->f_code = code;
701 extras = code->co_nlocals + ncells + nfrees;
702 f->f_valuestack = f->f_localsplus + extras;
703 for (i=0; i<extras; i++)
704 f->f_localsplus[i] = NULL;
705 f->f_locals = NULL;
706 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 }
708 f->f_stacktop = f->f_valuestack;
709 f->f_builtins = builtins;
710 Py_XINCREF(back);
711 f->f_back = back;
712 Py_INCREF(code);
713 Py_INCREF(globals);
714 f->f_globals = globals;
715 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
716 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
717 (CO_NEWLOCALS | CO_OPTIMIZED))
718 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
719 else if (code->co_flags & CO_NEWLOCALS) {
720 locals = PyDict_New();
721 if (locals == NULL) {
722 Py_DECREF(f);
723 return NULL;
724 }
725 f->f_locals = locals;
726 }
727 else {
728 if (locals == NULL)
729 locals = globals;
730 Py_INCREF(locals);
731 f->f_locals = locals;
732 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 f->f_lasti = -1;
735 f->f_lineno = code->co_firstlineno;
736 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200737 f->f_executing = 0;
738 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000739 f->f_trace_opcodes = 0;
740 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000743}
744
INADA Naoki5a625d02016-12-24 20:19:08 +0900745PyFrameObject*
746PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
747 PyObject *globals, PyObject *locals)
748{
749 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
750 if (f)
751 _PyObject_GC_TRACK(f);
752 return f;
753}
754
755
Guido van Rossum3f5da241990-12-20 15:06:42 +0000756/* Block management */
757
758void
Fred Drake1b190b42000-07-09 05:40:56 +0000759PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyTryBlock *b;
762 if (f->f_iblock >= CO_MAXBLOCKS)
763 Py_FatalError("XXX block stack overflow");
764 b = &f->f_blockstack[f->f_iblock++];
765 b->b_type = type;
766 b->b_level = level;
767 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000768}
769
Guido van Rossum18752471997-04-29 14:49:28 +0000770PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000771PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 PyTryBlock *b;
774 if (f->f_iblock <= 0)
775 Py_FatalError("XXX block stack underflow");
776 b = &f->f_blockstack[--f->f_iblock];
777 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000778}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000779
Guido van Rossumd8faa362007-04-27 19:54:29 +0000780/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781
782 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000783 values is an array of PyObject*. At index i, map[i] is the name of
784 the variable with value values[i]. The function copies the first
785 nmap variable from map/values into dict. If values[i] is NULL,
786 the variable is deleted from dict.
787
788 If deref is true, then the values being copied are cell variables
789 and the value is extracted from the cell variable before being put
790 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000791 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000792
Victor Stinner41bb43a2013-10-29 01:19:37 +0100793static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000794map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 Py_ssize_t j;
798 assert(PyTuple_Check(map));
799 assert(PyDict_Check(dict));
800 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800801 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyObject *key = PyTuple_GET_ITEM(map, j);
803 PyObject *value = values[j];
804 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400805 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 assert(PyCell_Check(value));
807 value = PyCell_GET(value);
808 }
809 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100810 if (PyObject_DelItem(dict, key) != 0) {
811 if (PyErr_ExceptionMatches(PyExc_KeyError))
812 PyErr_Clear();
813 else
814 return -1;
815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 }
817 else {
818 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100819 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 }
821 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100822 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000823}
824
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825/* Copy values from the "locals" dict into the fast locals.
826
827 dict is an input argument containing string keys representing
828 variables names and arbitrary PyObject* as values.
829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831 values is an array of PyObject*. At index i, map[i] is the name of
832 the variable with value values[i]. The function copies the first
833 nmap variable from map/values into dict. If values[i] is NULL,
834 the variable is deleted from dict.
835
836 If deref is true, then the values being copied are cell variables
837 and the value is extracted from the cell variable before being put
838 in dict. If clear is true, then variables in map but not in dict
839 are set to NULL in map; if clear is false, variables missing in
840 dict are ignored.
841
842 Exceptions raised while modifying the dict are silently ignored,
843 because there is no good way to report them.
844*/
845
Guido van Rossum6b356e72001-04-14 17:55:41 +0000846static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000847dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 Py_ssize_t j;
851 assert(PyTuple_Check(map));
852 assert(PyDict_Check(dict));
853 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800854 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 PyObject *key = PyTuple_GET_ITEM(map, j);
856 PyObject *value = PyObject_GetItem(dict, key);
857 assert(PyUnicode_Check(key));
858 /* We only care about NULLs if clear is true. */
859 if (value == NULL) {
860 PyErr_Clear();
861 if (!clear)
862 continue;
863 }
864 if (deref) {
865 assert(PyCell_Check(values[j]));
866 if (PyCell_GET(values[j]) != value) {
867 if (PyCell_Set(values[j], value) < 0)
868 PyErr_Clear();
869 }
870 } else if (values[j] != value) {
871 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300872 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 }
874 Py_XDECREF(value);
875 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000876}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000877
Victor Stinner41bb43a2013-10-29 01:19:37 +0100878int
879PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Merge fast locals into f->f_locals */
882 PyObject *locals, *map;
883 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 PyCodeObject *co;
885 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100886 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100887
888 if (f == NULL) {
889 PyErr_BadInternalCall();
890 return -1;
891 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 locals = f->f_locals;
893 if (locals == NULL) {
894 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100895 if (locals == NULL)
896 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 }
898 co = f->f_code;
899 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100900 if (!PyTuple_Check(map)) {
901 PyErr_Format(PyExc_SystemError,
902 "co_varnames must be a tuple, not %s",
903 Py_TYPE(map)->tp_name);
904 return -1;
905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 fast = f->f_localsplus;
907 j = PyTuple_GET_SIZE(map);
908 if (j > co->co_nlocals)
909 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100910 if (co->co_nlocals) {
911 if (map_to_dict(map, j, locals, fast, 0) < 0)
912 return -1;
913 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 ncells = PyTuple_GET_SIZE(co->co_cellvars);
915 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
916 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100917 if (map_to_dict(co->co_cellvars, ncells,
918 locals, fast + co->co_nlocals, 1))
919 return -1;
920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* If the namespace is unoptimized, then one of the
922 following cases applies:
923 1. It does not contain free variables, because it
924 uses import * or is a top-level namespace.
925 2. It is a class namespace.
926 We don't want to accidentally copy free variables
927 into the locals dict used by the class.
928 */
929 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100930 if (map_to_dict(co->co_freevars, nfreevars,
931 locals, fast + co->co_nlocals + ncells, 1) < 0)
932 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 }
934 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100935 return 0;
936}
937
938void
939PyFrame_FastToLocals(PyFrameObject *f)
940{
941 int res;
942
943 assert(!PyErr_Occurred());
944
945 res = PyFrame_FastToLocalsWithError(f);
946 if (res < 0)
947 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000948}
949
950void
Fred Drake1b190b42000-07-09 05:40:56 +0000951PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Merge f->f_locals into fast locals */
954 PyObject *locals, *map;
955 PyObject **fast;
956 PyObject *error_type, *error_value, *error_traceback;
957 PyCodeObject *co;
958 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100959 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (f == NULL)
961 return;
962 locals = f->f_locals;
963 co = f->f_code;
964 map = co->co_varnames;
965 if (locals == NULL)
966 return;
967 if (!PyTuple_Check(map))
968 return;
969 PyErr_Fetch(&error_type, &error_value, &error_traceback);
970 fast = f->f_localsplus;
971 j = PyTuple_GET_SIZE(map);
972 if (j > co->co_nlocals)
973 j = co->co_nlocals;
974 if (co->co_nlocals)
975 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
976 ncells = PyTuple_GET_SIZE(co->co_cellvars);
977 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
978 if (ncells || nfreevars) {
979 dict_to_map(co->co_cellvars, ncells,
980 locals, fast + co->co_nlocals, 1, clear);
981 /* Same test as in PyFrame_FastToLocals() above. */
982 if (co->co_flags & CO_OPTIMIZED) {
983 dict_to_map(co->co_freevars, nfreevars,
984 locals, fast + co->co_nlocals + ncells, 1,
985 clear);
986 }
987 }
988 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000989}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000990
991/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000992int
993PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 int freelist_size = numfree;
996
997 while (free_list != NULL) {
998 PyFrameObject *f = free_list;
999 free_list = free_list->f_back;
1000 PyObject_GC_Del(f);
1001 --numfree;
1002 }
1003 assert(numfree == 0);
1004 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +00001005}
1006
1007void
1008PyFrame_Fini(void)
1009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001011}
David Malcolm49526f42012-06-22 14:55:41 -04001012
1013/* Print summary info about the state of the optimized allocator */
1014void
1015_PyFrame_DebugMallocStats(FILE *out)
1016{
1017 _PyDebugAllocatorStats(out,
1018 "free PyFrameObject",
1019 numfree, sizeof(PyFrameObject));
1020}
1021