blob: 4ef10d0eb7bcd6c4097f8029db11222f87fdff9d [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
Miss Islington (bot)5ceb7012018-11-27 09:58:07 -080067frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000068{
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
Miss Islington (bot)5ceb7012018-11-27 09:58:07 -0800522static int
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 }
Miss Islington (bot)5ceb7012018-11-27 09:58:07 -0800550 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000551}
552
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000553static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200554frame_clear(PyFrameObject *f)
555{
556 if (f->f_executing) {
557 PyErr_SetString(PyExc_RuntimeError,
558 "cannot clear an executing frame");
559 return NULL;
560 }
561 if (f->f_gen) {
562 _PyGen_Finalize(f->f_gen);
563 assert(f->f_gen == NULL);
564 }
Miss Islington (bot)5ceb7012018-11-27 09:58:07 -0800565 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200566 Py_RETURN_NONE;
567}
568
569PyDoc_STRVAR(clear__doc__,
570"F.clear(): clear most references held by the frame");
571
572static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000573frame_sizeof(PyFrameObject *f)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
578 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
579 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
580 ncells + nfrees;
581 /* subtract one as it is already included in PyFrameObject */
582 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000585}
586
587PyDoc_STRVAR(sizeof__doc__,
588"F.__sizeof__() -> size of F in memory, in bytes");
589
Antoine Pitrou14709142017-12-31 22:35:22 +0100590static PyObject *
591frame_repr(PyFrameObject *f)
592{
593 int lineno = PyFrame_GetLineNumber(f);
594 return PyUnicode_FromFormat(
595 "<frame at %p, file %R, line %d, code %S>",
596 f, f->f_code->co_filename, lineno, f->f_code->co_name);
597}
598
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000599static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200600 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
601 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
603 sizeof__doc__},
604 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000605};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000606
Guido van Rossum18752471997-04-29 14:49:28 +0000607PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyVarObject_HEAD_INIT(&PyType_Type, 0)
609 "frame",
610 sizeof(PyFrameObject),
611 sizeof(PyObject *),
612 (destructor)frame_dealloc, /* tp_dealloc */
613 0, /* tp_print */
614 0, /* tp_getattr */
615 0, /* tp_setattr */
616 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100617 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 0, /* tp_as_number */
619 0, /* tp_as_sequence */
620 0, /* tp_as_mapping */
621 0, /* tp_hash */
622 0, /* tp_call */
623 0, /* tp_str */
624 PyObject_GenericGetAttr, /* tp_getattro */
625 PyObject_GenericSetAttr, /* tp_setattro */
626 0, /* tp_as_buffer */
627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
628 0, /* tp_doc */
629 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200630 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 0, /* tp_richcompare */
632 0, /* tp_weaklistoffset */
633 0, /* tp_iter */
634 0, /* tp_iternext */
635 frame_methods, /* tp_methods */
636 frame_memberlist, /* tp_members */
637 frame_getsetlist, /* tp_getset */
638 0, /* tp_base */
639 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000640};
641
Victor Stinner07e9e382013-11-07 22:22:39 +0100642_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000643
Neal Norwitzb2501f42002-12-31 03:42:13 +0000644int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000645{
Victor Stinner07e9e382013-11-07 22:22:39 +0100646 /* Before, PyId___builtins__ was a string created explicitly in
647 this function. Now there is nothing to initialize anymore, but
648 the function is kept for backward compatibility. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000650}
651
Victor Stinnerc6944e72016-11-11 02:13:35 +0100652PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900653_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
654 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyFrameObject *back = tstate->frame;
657 PyFrameObject *f;
658 PyObject *builtins;
659 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000660
Michael W. Hudson69734a52002-08-19 16:54:08 +0000661#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
663 (locals != NULL && !PyMapping_Check(locals))) {
664 PyErr_BadInternalCall();
665 return NULL;
666 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000667#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100669 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (builtins) {
671 if (PyModule_Check(builtins)) {
672 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200673 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
676 if (builtins == NULL) {
677 /* No builtins! Make up a minimal one
678 Give them 'None', at least. */
679 builtins = PyDict_New();
680 if (builtins == NULL ||
681 PyDict_SetItemString(
682 builtins, "None", Py_None) < 0)
683 return NULL;
684 }
685 else
686 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 }
689 else {
690 /* If we share the globals, we share the builtins.
691 Save a lookup and a call. */
692 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200693 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 Py_INCREF(builtins);
695 }
696 if (code->co_zombieframe != NULL) {
697 f = code->co_zombieframe;
698 code->co_zombieframe = NULL;
699 _Py_NewReference((PyObject *)f);
700 assert(f->f_code == code);
701 }
702 else {
703 Py_ssize_t extras, ncells, nfrees;
704 ncells = PyTuple_GET_SIZE(code->co_cellvars);
705 nfrees = PyTuple_GET_SIZE(code->co_freevars);
706 extras = code->co_stacksize + code->co_nlocals + ncells +
707 nfrees;
708 if (free_list == NULL) {
709 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
710 extras);
711 if (f == NULL) {
712 Py_DECREF(builtins);
713 return NULL;
714 }
715 }
716 else {
717 assert(numfree > 0);
718 --numfree;
719 f = free_list;
720 free_list = free_list->f_back;
721 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000722 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
723 if (new_f == NULL) {
724 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 Py_DECREF(builtins);
726 return NULL;
727 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000728 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 }
730 _Py_NewReference((PyObject *)f);
731 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 f->f_code = code;
734 extras = code->co_nlocals + ncells + nfrees;
735 f->f_valuestack = f->f_localsplus + extras;
736 for (i=0; i<extras; i++)
737 f->f_localsplus[i] = NULL;
738 f->f_locals = NULL;
739 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 }
741 f->f_stacktop = f->f_valuestack;
742 f->f_builtins = builtins;
743 Py_XINCREF(back);
744 f->f_back = back;
745 Py_INCREF(code);
746 Py_INCREF(globals);
747 f->f_globals = globals;
748 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
749 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
750 (CO_NEWLOCALS | CO_OPTIMIZED))
751 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
752 else if (code->co_flags & CO_NEWLOCALS) {
753 locals = PyDict_New();
754 if (locals == NULL) {
755 Py_DECREF(f);
756 return NULL;
757 }
758 f->f_locals = locals;
759 }
760 else {
761 if (locals == NULL)
762 locals = globals;
763 Py_INCREF(locals);
764 f->f_locals = locals;
765 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 f->f_lasti = -1;
768 f->f_lineno = code->co_firstlineno;
769 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200770 f->f_executing = 0;
771 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000772 f->f_trace_opcodes = 0;
773 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000776}
777
INADA Naoki5a625d02016-12-24 20:19:08 +0900778PyFrameObject*
779PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
780 PyObject *globals, PyObject *locals)
781{
782 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
783 if (f)
784 _PyObject_GC_TRACK(f);
785 return f;
786}
787
788
Guido van Rossum3f5da241990-12-20 15:06:42 +0000789/* Block management */
790
791void
Fred Drake1b190b42000-07-09 05:40:56 +0000792PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyTryBlock *b;
795 if (f->f_iblock >= CO_MAXBLOCKS)
796 Py_FatalError("XXX block stack overflow");
797 b = &f->f_blockstack[f->f_iblock++];
798 b->b_type = type;
799 b->b_level = level;
800 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000801}
802
Guido van Rossum18752471997-04-29 14:49:28 +0000803PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000804PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyTryBlock *b;
807 if (f->f_iblock <= 0)
808 Py_FatalError("XXX block stack underflow");
809 b = &f->f_blockstack[--f->f_iblock];
810 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000811}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000812
Guido van Rossumd8faa362007-04-27 19:54:29 +0000813/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814
815 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000816 values is an array of PyObject*. At index i, map[i] is the name of
817 the variable with value values[i]. The function copies the first
818 nmap variable from map/values into dict. If values[i] is NULL,
819 the variable is deleted from dict.
820
821 If deref is true, then the values being copied are cell variables
822 and the value is extracted from the cell variable before being put
823 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000824 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000825
Victor Stinner41bb43a2013-10-29 01:19:37 +0100826static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000827map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_ssize_t j;
831 assert(PyTuple_Check(map));
832 assert(PyDict_Check(dict));
833 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800834 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *key = PyTuple_GET_ITEM(map, j);
836 PyObject *value = values[j];
837 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400838 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 assert(PyCell_Check(value));
840 value = PyCell_GET(value);
841 }
842 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100843 if (PyObject_DelItem(dict, key) != 0) {
844 if (PyErr_ExceptionMatches(PyExc_KeyError))
845 PyErr_Clear();
846 else
847 return -1;
848 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 }
850 else {
851 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100852 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 }
854 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100855 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000856}
857
Guido van Rossumd8faa362007-04-27 19:54:29 +0000858/* Copy values from the "locals" dict into the fast locals.
859
860 dict is an input argument containing string keys representing
861 variables names and arbitrary PyObject* as values.
862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864 values is an array of PyObject*. At index i, map[i] is the name of
865 the variable with value values[i]. The function copies the first
866 nmap variable from map/values into dict. If values[i] is NULL,
867 the variable is deleted from dict.
868
869 If deref is true, then the values being copied are cell variables
870 and the value is extracted from the cell variable before being put
871 in dict. If clear is true, then variables in map but not in dict
872 are set to NULL in map; if clear is false, variables missing in
873 dict are ignored.
874
875 Exceptions raised while modifying the dict are silently ignored,
876 because there is no good way to report them.
877*/
878
Guido van Rossum6b356e72001-04-14 17:55:41 +0000879static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000880dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 Py_ssize_t j;
884 assert(PyTuple_Check(map));
885 assert(PyDict_Check(dict));
886 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800887 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 PyObject *key = PyTuple_GET_ITEM(map, j);
889 PyObject *value = PyObject_GetItem(dict, key);
890 assert(PyUnicode_Check(key));
891 /* We only care about NULLs if clear is true. */
892 if (value == NULL) {
893 PyErr_Clear();
894 if (!clear)
895 continue;
896 }
897 if (deref) {
898 assert(PyCell_Check(values[j]));
899 if (PyCell_GET(values[j]) != value) {
900 if (PyCell_Set(values[j], value) < 0)
901 PyErr_Clear();
902 }
903 } else if (values[j] != value) {
904 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300905 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
907 Py_XDECREF(value);
908 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000909}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000910
Victor Stinner41bb43a2013-10-29 01:19:37 +0100911int
912PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Merge fast locals into f->f_locals */
915 PyObject *locals, *map;
916 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 PyCodeObject *co;
918 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100919 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100920
921 if (f == NULL) {
922 PyErr_BadInternalCall();
923 return -1;
924 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 locals = f->f_locals;
926 if (locals == NULL) {
927 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100928 if (locals == NULL)
929 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 }
931 co = f->f_code;
932 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100933 if (!PyTuple_Check(map)) {
934 PyErr_Format(PyExc_SystemError,
935 "co_varnames must be a tuple, not %s",
936 Py_TYPE(map)->tp_name);
937 return -1;
938 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 fast = f->f_localsplus;
940 j = PyTuple_GET_SIZE(map);
941 if (j > co->co_nlocals)
942 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100943 if (co->co_nlocals) {
944 if (map_to_dict(map, j, locals, fast, 0) < 0)
945 return -1;
946 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 ncells = PyTuple_GET_SIZE(co->co_cellvars);
948 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
949 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100950 if (map_to_dict(co->co_cellvars, ncells,
951 locals, fast + co->co_nlocals, 1))
952 return -1;
953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* If the namespace is unoptimized, then one of the
955 following cases applies:
956 1. It does not contain free variables, because it
957 uses import * or is a top-level namespace.
958 2. It is a class namespace.
959 We don't want to accidentally copy free variables
960 into the locals dict used by the class.
961 */
962 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100963 if (map_to_dict(co->co_freevars, nfreevars,
964 locals, fast + co->co_nlocals + ncells, 1) < 0)
965 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
967 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100968 return 0;
969}
970
971void
972PyFrame_FastToLocals(PyFrameObject *f)
973{
974 int res;
975
976 assert(!PyErr_Occurred());
977
978 res = PyFrame_FastToLocalsWithError(f);
979 if (res < 0)
980 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000981}
982
983void
Fred Drake1b190b42000-07-09 05:40:56 +0000984PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* Merge f->f_locals into fast locals */
987 PyObject *locals, *map;
988 PyObject **fast;
989 PyObject *error_type, *error_value, *error_traceback;
990 PyCodeObject *co;
991 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100992 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (f == NULL)
994 return;
995 locals = f->f_locals;
996 co = f->f_code;
997 map = co->co_varnames;
998 if (locals == NULL)
999 return;
1000 if (!PyTuple_Check(map))
1001 return;
1002 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1003 fast = f->f_localsplus;
1004 j = PyTuple_GET_SIZE(map);
1005 if (j > co->co_nlocals)
1006 j = co->co_nlocals;
1007 if (co->co_nlocals)
1008 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1009 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1010 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1011 if (ncells || nfreevars) {
1012 dict_to_map(co->co_cellvars, ncells,
1013 locals, fast + co->co_nlocals, 1, clear);
1014 /* Same test as in PyFrame_FastToLocals() above. */
1015 if (co->co_flags & CO_OPTIMIZED) {
1016 dict_to_map(co->co_freevars, nfreevars,
1017 locals, fast + co->co_nlocals + ncells, 1,
1018 clear);
1019 }
1020 }
1021 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001022}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001023
1024/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +00001025int
1026PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 int freelist_size = numfree;
1029
1030 while (free_list != NULL) {
1031 PyFrameObject *f = free_list;
1032 free_list = free_list->f_back;
1033 PyObject_GC_Del(f);
1034 --numfree;
1035 }
1036 assert(numfree == 0);
1037 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +00001038}
1039
1040void
1041PyFrame_Fini(void)
1042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001044}
David Malcolm49526f42012-06-22 14:55:41 -04001045
1046/* Print summary info about the state of the optimized allocator */
1047void
1048_PyFrame_DebugMallocStats(FILE *out)
1049{
1050 _PyDebugAllocatorStats(out,
1051 "free PyFrameObject",
1052 numfree, sizeof(PyFrameObject));
1053}
1054