blob: f518dc4856162efb6589af9866f2ed3b852a9a23 [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.
xdegayee32bbaf2018-03-13 09:52:35 +010062 * o Jumps cannot be made from within a trace function invoked with a
63 * 'return' or 'exception' event since the eval loop has been exited at
64 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000065 */
66static int
67frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
68{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 int new_lineno = 0; /* The new value of f_lineno */
70 long l_new_lineno;
71 int overflow;
72 int new_lasti = 0; /* The new value of f_lasti */
73 int new_iblock = 0; /* The new value of f_iblock */
74 unsigned char *code = NULL; /* The bytecode for the frame... */
75 Py_ssize_t code_len = 0; /* ...and its length */
76 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
77 Py_ssize_t lnotab_len = 0; /* (ditto) */
78 int offset = 0; /* (ditto) */
79 int line = 0; /* (ditto) */
80 int addr = 0; /* (ditto) */
81 int min_addr = 0; /* Scanning the SETUPs and POPs */
82 int max_addr = 0; /* (ditto) */
83 int delta_iblock = 0; /* (ditto) */
84 int min_delta_iblock = 0; /* (ditto) */
85 int min_iblock = 0; /* (ditto) */
86 int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
87 int new_lasti_setup_addr = 0; /* (ditto) */
88 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
89 int in_finally[CO_MAXBLOCKS]; /* (ditto) */
90 int blockstack_top = 0; /* (ditto) */
91 unsigned char setup_op = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 /* f_lineno must be an integer. */
94 if (!PyLong_CheckExact(p_new_lineno)) {
95 PyErr_SetString(PyExc_ValueError,
96 "lineno must be an integer");
97 return -1;
98 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000099
xdegayee32bbaf2018-03-13 09:52:35 +0100100 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
101 * f->f_trace is NULL, check first on the first condition.
102 * Forbidding jumps from the 'call' event of a new frame is a side effect
103 * of allowing to set f_lineno only from trace functions. */
104 if (f->f_lasti == -1) {
105 PyErr_Format(PyExc_ValueError,
106 "can't jump from the 'call' trace event of a new frame");
107 return -1;
108 }
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* You can only do this from within a trace function, not via
111 * _getframe or similar hackery. */
xdegayee32bbaf2018-03-13 09:52:35 +0100112 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PyErr_Format(PyExc_ValueError,
xdegayee32bbaf2018-03-13 09:52:35 +0100114 "f_lineno can only be set by a trace function");
115 return -1;
116 }
117
118 /* Forbid jumps upon a 'return' trace event (except after executing a
119 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
120 * and upon an 'exception' trace event.
121 * Jumps from 'call' trace events have already been forbidden above for new
122 * frames, so this check does not change anything for 'call' events. */
123 if (f->f_stacktop == NULL) {
124 PyErr_SetString(PyExc_ValueError,
125 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 return -1;
127 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 /* Fail if the line comes before the start of the code block. */
130 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
131 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000132#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 || l_new_lineno > INT_MAX
134 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000135#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 ) {
137 PyErr_SetString(PyExc_ValueError,
138 "lineno out of range");
139 return -1;
140 }
141 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (new_lineno < f->f_code->co_firstlineno) {
144 PyErr_Format(PyExc_ValueError,
145 "line %d comes before the current code block",
146 new_lineno);
147 return -1;
148 }
149 else if (new_lineno == f->f_code->co_firstlineno) {
150 new_lasti = 0;
151 new_lineno = f->f_code->co_firstlineno;
152 }
153 else {
154 /* Find the bytecode offset for the start of the given
155 * line, or the first code-owning line after it. */
156 char *tmp;
157 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
158 &tmp, &lnotab_len);
159 lnotab = (unsigned char *) tmp;
160 addr = 0;
161 line = f->f_code->co_firstlineno;
162 new_lasti = -1;
163 for (offset = 0; offset < lnotab_len; offset += 2) {
164 addr += lnotab[offset];
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100165 line += (signed char)lnotab[offset+1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (line >= new_lineno) {
167 new_lasti = addr;
168 new_lineno = line;
169 break;
170 }
171 }
172 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 /* If we didn't reach the requested line, return an error. */
175 if (new_lasti == -1) {
176 PyErr_Format(PyExc_ValueError,
177 "line %d comes after the current code block",
178 new_lineno);
179 return -1;
180 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 /* We're now ready to look at the bytecode. */
183 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
xdegayee32bbaf2018-03-13 09:52:35 +0100184
185 /* The trace function is called with a 'return' trace event after the
186 * execution of a yield statement. */
187 assert(f->f_lasti != -1);
188 if (code[f->f_lasti] == YIELD_VALUE || code[f->f_lasti] == YIELD_FROM) {
189 PyErr_SetString(PyExc_ValueError,
190 "can't jump from a yield statement");
191 return -1;
192 }
193
Victor Stinner640c35c2013-06-04 23:14:37 +0200194 min_addr = Py_MIN(new_lasti, f->f_lasti);
195 max_addr = Py_MAX(new_lasti, f->f_lasti);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 /* You can't jump onto a line with an 'except' statement on it -
198 * they expect to have an exception on the top of the stack, which
199 * won't be true if you jump to them. They always start with code
200 * that either pops the exception using POP_TOP (plain 'except:'
201 * lines do this) or duplicates the exception on the stack using
202 * DUP_TOP (if there's an exception type specified). See compile.c,
203 * 'com_try_except' for the full details. There aren't any other
204 * cases (AFAIK) where a line's code can start with DUP_TOP or
205 * POP_TOP, but if any ever appear, they'll be subject to the same
206 * restriction (but with a different error message). */
207 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
208 PyErr_SetString(PyExc_ValueError,
209 "can't jump to 'except' line as there's no exception");
210 return -1;
211 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* You can't jump into or out of a 'finally' block because the 'try'
214 * block leaves something on the stack for the END_FINALLY to clean
215 * up. So we walk the bytecode, maintaining a simulated blockstack.
216 * When we reach the old or new address and it's in a 'finally' block
217 * we note the address of the corresponding SETUP_FINALLY. The jump
218 * is only legal if neither address is in a 'finally' block or
219 * they're both in the same one. 'blockstack' is a stack of the
220 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
221 * whether we're in a 'finally' block at each blockstack level. */
222 f_lasti_setup_addr = -1;
223 new_lasti_setup_addr = -1;
224 memset(blockstack, '\0', sizeof(blockstack));
225 memset(in_finally, '\0', sizeof(in_finally));
226 blockstack_top = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300227 for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 unsigned char op = code[addr];
229 switch (op) {
230 case SETUP_LOOP:
231 case SETUP_EXCEPT:
232 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400233 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400234 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 blockstack[blockstack_top++] = addr;
236 in_finally[blockstack_top-1] = 0;
237 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 case POP_BLOCK:
240 assert(blockstack_top > 0);
241 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400242 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
243 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 in_finally[blockstack_top-1] = 1;
245 }
246 else {
247 blockstack_top--;
248 }
249 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 case END_FINALLY:
252 /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
253 * in the bytecode but don't correspond to an actual
254 * 'finally' block. (If blockstack_top is 0, we must
255 * be seeing such an END_FINALLY.) */
256 if (blockstack_top > 0) {
257 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400258 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
259 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 blockstack_top--;
261 }
262 }
263 break;
264 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 /* For the addresses we're interested in, see whether they're
267 * within a 'finally' block and if so, remember the address
268 * of the SETUP_FINALLY. */
269 if (addr == new_lasti || addr == f->f_lasti) {
270 int i = 0;
271 int setup_addr = -1;
272 for (i = blockstack_top-1; i >= 0; i--) {
273 if (in_finally[i]) {
274 setup_addr = blockstack[i];
275 break;
276 }
277 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (setup_addr != -1) {
280 if (addr == new_lasti) {
281 new_lasti_setup_addr = setup_addr;
282 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 if (addr == f->f_lasti) {
285 f_lasti_setup_addr = setup_addr;
286 }
287 }
288 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 /* Verify that the blockstack tracking code didn't get lost. */
292 assert(blockstack_top == 0);
293
294 /* After all that, are we jumping into / out of a 'finally' block? */
295 if (new_lasti_setup_addr != f_lasti_setup_addr) {
296 PyErr_SetString(PyExc_ValueError,
297 "can't jump into or out of a 'finally' block");
298 return -1;
299 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000300
301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* Police block-jumping (you can't jump into the middle of a block)
303 * and ensure that the blockstack finishes up in a sensible state (by
304 * popping any blocks we're jumping out of). We look at all the
305 * blockstack operations between the current position and the new
306 * one, and keep track of how many blocks we drop out of on the way.
307 * By also keeping track of the lowest blockstack position we see, we
308 * can tell whether the jump goes into any blocks without coming out
309 * again - in that case we raise an exception below. */
310 delta_iblock = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300311 for (addr = min_addr; addr < max_addr; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 unsigned char op = code[addr];
313 switch (op) {
314 case SETUP_LOOP:
315 case SETUP_EXCEPT:
316 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400317 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400318 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 delta_iblock++;
320 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 case POP_BLOCK:
323 delta_iblock--;
324 break;
325 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000326
Victor Stinner640c35c2013-06-04 23:14:37 +0200327 min_delta_iblock = Py_MIN(min_delta_iblock, delta_iblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 /* Derive the absolute iblock values from the deltas. */
331 min_iblock = f->f_iblock + min_delta_iblock;
332 if (new_lasti > f->f_lasti) {
333 /* Forwards jump. */
334 new_iblock = f->f_iblock + delta_iblock;
335 }
336 else {
337 /* Backwards jump. */
338 new_iblock = f->f_iblock - delta_iblock;
339 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 /* Are we jumping into a block? */
342 if (new_iblock > min_iblock) {
343 PyErr_SetString(PyExc_ValueError,
344 "can't jump into the middle of a block");
345 return -1;
346 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 /* Pop any blocks that we're jumping out of. */
349 while (f->f_iblock > new_iblock) {
350 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
351 while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
352 PyObject *v = (*--f->f_stacktop);
353 Py_DECREF(v);
354 }
Serhiy Storchaka04aadf22018-03-11 09:30:13 +0200355 if (b->b_type == SETUP_FINALLY &&
356 code[b->b_handler] == WITH_CLEANUP_START)
357 {
358 /* Pop the exit function. */
359 PyObject *v = (*--f->f_stacktop);
360 Py_DECREF(v);
361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 /* Finally set the new f_lineno and f_lasti and return OK. */
365 f->f_lineno = new_lineno;
366 f->f_lasti = new_lasti;
367 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000368}
369
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000370static PyObject *
371frame_gettrace(PyFrameObject *f, void *closure)
372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (trace == NULL)
376 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000381}
382
383static int
384frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* We rely on f_lineno being accurate when f_trace is set. */
387 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000388
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300389 if (v == Py_None)
390 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300392 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000395}
396
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000397
Guido van Rossum32d34c82001-09-20 21:45:26 +0000398static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 {"f_locals", (getter)frame_getlocals, NULL, NULL},
400 {"f_lineno", (getter)frame_getlineno,
401 (setter)frame_setlineno, NULL},
402 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
403 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000404};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000405
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000406/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000407 In an attempt to improve the speed of function calls, we:
408
409 1. Hold a single "zombie" frame on each code object. This retains
410 the allocated and initialised frame object from an invocation of
411 the code object. The zombie is reanimated the next time we need a
412 frame object for that code object. Doing this saves the malloc/
413 realloc required when using a free_list frame that isn't the
414 correct size. It also saves some field initialisation.
415
416 In zombie mode, no field of PyFrameObject holds a reference, but
417 the following fields are still valid:
418
419 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420
Mark Shannonae3087c2017-10-22 22:41:51 +0100421 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000422
423 * f_localsplus does not require re-allocation and
424 the local variables in f_localsplus are NULL.
425
426 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000427 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000428 a stack frame is on the free list, only the following members have
429 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 ob_type == &Frametype
431 f_back next item on free list, or NULL
432 f_stacksize size of value stack
433 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000434 Note that the value and block stacks are preserved -- this can save
435 another malloc() call or two (and two free() calls as well!).
436 Also note that, unlike for integers, each frame object is a
437 malloc'ed object in its own right -- it is only the actual calls to
438 malloc() that we are trying to save here, not the administration.
439 After all, while a typical program may make millions of calls, a
440 call depth of more than 20 or 30 is probably already exceptional
441 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000442
Christian Heimes2202f872008-02-06 14:31:34 +0000443 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000444 free_list. Else programs creating lots of cyclic trash involving
445 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000446*/
447
Guido van Rossum18752471997-04-29 14:49:28 +0000448static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000450/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000452
Victor Stinnerc6944e72016-11-11 02:13:35 +0100453static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000454frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000455{
Antoine Pitrou93963562013-05-14 20:37:52 +0200456 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000458
INADA Naoki5a625d02016-12-24 20:19:08 +0900459 if (_PyObject_GC_IS_TRACKED(f))
460 _PyObject_GC_UNTRACK(f);
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200463 /* Kill all local variables */
464 valuestack = f->f_valuestack;
465 for (p = f->f_localsplus; p < valuestack; p++)
466 Py_CLEAR(*p);
467
468 /* Free stack */
469 if (f->f_stacktop != NULL) {
470 for (p = valuestack; p < f->f_stacktop; p++)
471 Py_XDECREF(*p);
472 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 Py_XDECREF(f->f_back);
475 Py_DECREF(f->f_builtins);
476 Py_DECREF(f->f_globals);
477 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200478 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 co = f->f_code;
481 if (co->co_zombieframe == NULL)
482 co->co_zombieframe = f;
483 else if (numfree < PyFrame_MAXFREELIST) {
484 ++numfree;
485 f->f_back = free_list;
486 free_list = f;
487 }
488 else
489 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 Py_DECREF(co);
492 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000493}
494
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000495static int
496frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100499 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 Py_VISIT(f->f_back);
502 Py_VISIT(f->f_code);
503 Py_VISIT(f->f_builtins);
504 Py_VISIT(f->f_globals);
505 Py_VISIT(f->f_locals);
506 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* locals */
509 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
510 fastlocals = f->f_localsplus;
511 for (i = slots; --i >= 0; ++fastlocals)
512 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 /* stack */
515 if (f->f_stacktop != NULL) {
516 for (p = f->f_valuestack; p < f->f_stacktop; p++)
517 Py_VISIT(*p);
518 }
519 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000520}
521
522static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200523frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100526 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000527
Antoine Pitrou93963562013-05-14 20:37:52 +0200528 /* Before anything else, make sure that this frame is clearly marked
529 * as being defunct! Else, e.g., a generator reachable from this
530 * frame may also point to this frame, believe itself to still be
531 * active, and try cleaning up this frame again.
532 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 oldtop = f->f_stacktop;
534 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200535 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 /* locals */
540 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
541 fastlocals = f->f_localsplus;
542 for (i = slots; --i >= 0; ++fastlocals)
543 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* stack */
546 if (oldtop != NULL) {
547 for (p = f->f_valuestack; p < oldtop; p++)
548 Py_CLEAR(*p);
549 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000550}
551
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000552static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200553frame_clear(PyFrameObject *f)
554{
555 if (f->f_executing) {
556 PyErr_SetString(PyExc_RuntimeError,
557 "cannot clear an executing frame");
558 return NULL;
559 }
560 if (f->f_gen) {
561 _PyGen_Finalize(f->f_gen);
562 assert(f->f_gen == NULL);
563 }
564 frame_tp_clear(f);
565 Py_RETURN_NONE;
566}
567
568PyDoc_STRVAR(clear__doc__,
569"F.clear(): clear most references held by the frame");
570
571static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000572frame_sizeof(PyFrameObject *f)
573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
577 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
578 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
579 ncells + nfrees;
580 /* subtract one as it is already included in PyFrameObject */
581 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000584}
585
586PyDoc_STRVAR(sizeof__doc__,
587"F.__sizeof__() -> size of F in memory, in bytes");
588
Antoine Pitrou14709142017-12-31 22:35:22 +0100589static PyObject *
590frame_repr(PyFrameObject *f)
591{
592 int lineno = PyFrame_GetLineNumber(f);
593 return PyUnicode_FromFormat(
594 "<frame at %p, file %R, line %d, code %S>",
595 f, f->f_code->co_filename, lineno, f->f_code->co_name);
596}
597
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000598static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200599 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
600 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
602 sizeof__doc__},
603 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000604};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000605
Guido van Rossum18752471997-04-29 14:49:28 +0000606PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyVarObject_HEAD_INIT(&PyType_Type, 0)
608 "frame",
609 sizeof(PyFrameObject),
610 sizeof(PyObject *),
611 (destructor)frame_dealloc, /* tp_dealloc */
612 0, /* tp_print */
613 0, /* tp_getattr */
614 0, /* tp_setattr */
615 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100616 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 0, /* tp_as_number */
618 0, /* tp_as_sequence */
619 0, /* tp_as_mapping */
620 0, /* tp_hash */
621 0, /* tp_call */
622 0, /* tp_str */
623 PyObject_GenericGetAttr, /* tp_getattro */
624 PyObject_GenericSetAttr, /* tp_setattro */
625 0, /* tp_as_buffer */
626 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
627 0, /* tp_doc */
628 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200629 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 0, /* tp_richcompare */
631 0, /* tp_weaklistoffset */
632 0, /* tp_iter */
633 0, /* tp_iternext */
634 frame_methods, /* tp_methods */
635 frame_memberlist, /* tp_members */
636 frame_getsetlist, /* tp_getset */
637 0, /* tp_base */
638 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000639};
640
Victor Stinner07e9e382013-11-07 22:22:39 +0100641_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000642
Neal Norwitzb2501f42002-12-31 03:42:13 +0000643int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000644{
Victor Stinner07e9e382013-11-07 22:22:39 +0100645 /* Before, PyId___builtins__ was a string created explicitly in
646 this function. Now there is nothing to initialize anymore, but
647 the function is kept for backward compatibility. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000649}
650
Victor Stinnerc6944e72016-11-11 02:13:35 +0100651PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900652_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
653 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyFrameObject *back = tstate->frame;
656 PyFrameObject *f;
657 PyObject *builtins;
658 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000659
Michael W. Hudson69734a52002-08-19 16:54:08 +0000660#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
662 (locals != NULL && !PyMapping_Check(locals))) {
663 PyErr_BadInternalCall();
664 return NULL;
665 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000666#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100668 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (builtins) {
670 if (PyModule_Check(builtins)) {
671 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200672 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 }
675 if (builtins == NULL) {
676 /* No builtins! Make up a minimal one
677 Give them 'None', at least. */
678 builtins = PyDict_New();
679 if (builtins == NULL ||
680 PyDict_SetItemString(
681 builtins, "None", Py_None) < 0)
682 return NULL;
683 }
684 else
685 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 }
688 else {
689 /* If we share the globals, we share the builtins.
690 Save a lookup and a call. */
691 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200692 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_INCREF(builtins);
694 }
695 if (code->co_zombieframe != NULL) {
696 f = code->co_zombieframe;
697 code->co_zombieframe = NULL;
698 _Py_NewReference((PyObject *)f);
699 assert(f->f_code == code);
700 }
701 else {
702 Py_ssize_t extras, ncells, nfrees;
703 ncells = PyTuple_GET_SIZE(code->co_cellvars);
704 nfrees = PyTuple_GET_SIZE(code->co_freevars);
705 extras = code->co_stacksize + code->co_nlocals + ncells +
706 nfrees;
707 if (free_list == NULL) {
708 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
709 extras);
710 if (f == NULL) {
711 Py_DECREF(builtins);
712 return NULL;
713 }
714 }
715 else {
716 assert(numfree > 0);
717 --numfree;
718 f = free_list;
719 free_list = free_list->f_back;
720 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000721 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
722 if (new_f == NULL) {
723 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 Py_DECREF(builtins);
725 return NULL;
726 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000727 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 }
729 _Py_NewReference((PyObject *)f);
730 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 f->f_code = code;
733 extras = code->co_nlocals + ncells + nfrees;
734 f->f_valuestack = f->f_localsplus + extras;
735 for (i=0; i<extras; i++)
736 f->f_localsplus[i] = NULL;
737 f->f_locals = NULL;
738 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
740 f->f_stacktop = f->f_valuestack;
741 f->f_builtins = builtins;
742 Py_XINCREF(back);
743 f->f_back = back;
744 Py_INCREF(code);
745 Py_INCREF(globals);
746 f->f_globals = globals;
747 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
748 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
749 (CO_NEWLOCALS | CO_OPTIMIZED))
750 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
751 else if (code->co_flags & CO_NEWLOCALS) {
752 locals = PyDict_New();
753 if (locals == NULL) {
754 Py_DECREF(f);
755 return NULL;
756 }
757 f->f_locals = locals;
758 }
759 else {
760 if (locals == NULL)
761 locals = globals;
762 Py_INCREF(locals);
763 f->f_locals = locals;
764 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 f->f_lasti = -1;
767 f->f_lineno = code->co_firstlineno;
768 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200769 f->f_executing = 0;
770 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000771 f->f_trace_opcodes = 0;
772 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000775}
776
INADA Naoki5a625d02016-12-24 20:19:08 +0900777PyFrameObject*
778PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
779 PyObject *globals, PyObject *locals)
780{
781 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
782 if (f)
783 _PyObject_GC_TRACK(f);
784 return f;
785}
786
787
Guido van Rossum3f5da241990-12-20 15:06:42 +0000788/* Block management */
789
790void
Fred Drake1b190b42000-07-09 05:40:56 +0000791PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 PyTryBlock *b;
794 if (f->f_iblock >= CO_MAXBLOCKS)
795 Py_FatalError("XXX block stack overflow");
796 b = &f->f_blockstack[f->f_iblock++];
797 b->b_type = type;
798 b->b_level = level;
799 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000800}
801
Guido van Rossum18752471997-04-29 14:49:28 +0000802PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000803PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 PyTryBlock *b;
806 if (f->f_iblock <= 0)
807 Py_FatalError("XXX block stack underflow");
808 b = &f->f_blockstack[--f->f_iblock];
809 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000810}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000811
Guido van Rossumd8faa362007-04-27 19:54:29 +0000812/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813
814 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815 values is an array of PyObject*. At index i, map[i] is the name of
816 the variable with value values[i]. The function copies the first
817 nmap variable from map/values into dict. If values[i] is NULL,
818 the variable is deleted from dict.
819
820 If deref is true, then the values being copied are cell variables
821 and the value is extracted from the cell variable before being put
822 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000823 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000824
Victor Stinner41bb43a2013-10-29 01:19:37 +0100825static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000826map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_ssize_t j;
830 assert(PyTuple_Check(map));
831 assert(PyDict_Check(dict));
832 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800833 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *key = PyTuple_GET_ITEM(map, j);
835 PyObject *value = values[j];
836 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400837 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 assert(PyCell_Check(value));
839 value = PyCell_GET(value);
840 }
841 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100842 if (PyObject_DelItem(dict, key) != 0) {
843 if (PyErr_ExceptionMatches(PyExc_KeyError))
844 PyErr_Clear();
845 else
846 return -1;
847 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
849 else {
850 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100851 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 }
853 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100854 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000855}
856
Guido van Rossumd8faa362007-04-27 19:54:29 +0000857/* Copy values from the "locals" dict into the fast locals.
858
859 dict is an input argument containing string keys representing
860 variables names and arbitrary PyObject* as values.
861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000863 values is an array of PyObject*. At index i, map[i] is the name of
864 the variable with value values[i]. The function copies the first
865 nmap variable from map/values into dict. If values[i] is NULL,
866 the variable is deleted from dict.
867
868 If deref is true, then the values being copied are cell variables
869 and the value is extracted from the cell variable before being put
870 in dict. If clear is true, then variables in map but not in dict
871 are set to NULL in map; if clear is false, variables missing in
872 dict are ignored.
873
874 Exceptions raised while modifying the dict are silently ignored,
875 because there is no good way to report them.
876*/
877
Guido van Rossum6b356e72001-04-14 17:55:41 +0000878static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000879dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_ssize_t j;
883 assert(PyTuple_Check(map));
884 assert(PyDict_Check(dict));
885 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800886 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 PyObject *key = PyTuple_GET_ITEM(map, j);
888 PyObject *value = PyObject_GetItem(dict, key);
889 assert(PyUnicode_Check(key));
890 /* We only care about NULLs if clear is true. */
891 if (value == NULL) {
892 PyErr_Clear();
893 if (!clear)
894 continue;
895 }
896 if (deref) {
897 assert(PyCell_Check(values[j]));
898 if (PyCell_GET(values[j]) != value) {
899 if (PyCell_Set(values[j], value) < 0)
900 PyErr_Clear();
901 }
902 } else if (values[j] != value) {
903 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300904 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 }
906 Py_XDECREF(value);
907 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000908}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000909
Victor Stinner41bb43a2013-10-29 01:19:37 +0100910int
911PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Merge fast locals into f->f_locals */
914 PyObject *locals, *map;
915 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyCodeObject *co;
917 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100918 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100919
920 if (f == NULL) {
921 PyErr_BadInternalCall();
922 return -1;
923 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 locals = f->f_locals;
925 if (locals == NULL) {
926 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100927 if (locals == NULL)
928 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 }
930 co = f->f_code;
931 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100932 if (!PyTuple_Check(map)) {
933 PyErr_Format(PyExc_SystemError,
934 "co_varnames must be a tuple, not %s",
935 Py_TYPE(map)->tp_name);
936 return -1;
937 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 fast = f->f_localsplus;
939 j = PyTuple_GET_SIZE(map);
940 if (j > co->co_nlocals)
941 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100942 if (co->co_nlocals) {
943 if (map_to_dict(map, j, locals, fast, 0) < 0)
944 return -1;
945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 ncells = PyTuple_GET_SIZE(co->co_cellvars);
947 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
948 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100949 if (map_to_dict(co->co_cellvars, ncells,
950 locals, fast + co->co_nlocals, 1))
951 return -1;
952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* If the namespace is unoptimized, then one of the
954 following cases applies:
955 1. It does not contain free variables, because it
956 uses import * or is a top-level namespace.
957 2. It is a class namespace.
958 We don't want to accidentally copy free variables
959 into the locals dict used by the class.
960 */
961 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100962 if (map_to_dict(co->co_freevars, nfreevars,
963 locals, fast + co->co_nlocals + ncells, 1) < 0)
964 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 }
966 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100967 return 0;
968}
969
970void
971PyFrame_FastToLocals(PyFrameObject *f)
972{
973 int res;
974
975 assert(!PyErr_Occurred());
976
977 res = PyFrame_FastToLocalsWithError(f);
978 if (res < 0)
979 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000980}
981
982void
Fred Drake1b190b42000-07-09 05:40:56 +0000983PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 /* Merge f->f_locals into fast locals */
986 PyObject *locals, *map;
987 PyObject **fast;
988 PyObject *error_type, *error_value, *error_traceback;
989 PyCodeObject *co;
990 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100991 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (f == NULL)
993 return;
994 locals = f->f_locals;
995 co = f->f_code;
996 map = co->co_varnames;
997 if (locals == NULL)
998 return;
999 if (!PyTuple_Check(map))
1000 return;
1001 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1002 fast = f->f_localsplus;
1003 j = PyTuple_GET_SIZE(map);
1004 if (j > co->co_nlocals)
1005 j = co->co_nlocals;
1006 if (co->co_nlocals)
1007 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1008 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1009 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1010 if (ncells || nfreevars) {
1011 dict_to_map(co->co_cellvars, ncells,
1012 locals, fast + co->co_nlocals, 1, clear);
1013 /* Same test as in PyFrame_FastToLocals() above. */
1014 if (co->co_flags & CO_OPTIMIZED) {
1015 dict_to_map(co->co_freevars, nfreevars,
1016 locals, fast + co->co_nlocals + ncells, 1,
1017 clear);
1018 }
1019 }
1020 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001021}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001022
1023/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +00001024int
1025PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 int freelist_size = numfree;
1028
1029 while (free_list != NULL) {
1030 PyFrameObject *f = free_list;
1031 free_list = free_list->f_back;
1032 PyObject_GC_Del(f);
1033 --numfree;
1034 }
1035 assert(numfree == 0);
1036 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +00001037}
1038
1039void
1040PyFrame_Fini(void)
1041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001043}
David Malcolm49526f42012-06-22 14:55:41 -04001044
1045/* Print summary info about the state of the optimized allocator */
1046void
1047_PyFrame_DebugMallocStats(FILE *out)
1048{
1049 _PyDebugAllocatorStats(out,
1050 "free PyFrameObject",
1051 numfree, sizeof(PyFrameObject));
1052}
1053