blob: 175874503bb2fdf7617ad5805e5462389e1fe198 [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"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00006#include "frameobject.h"
7#include "opcode.h"
8#include "structmember.h"
9
Neal Norwitz91787cb2002-12-18 23:33:35 +000010#undef MIN
11#undef MAX
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000012#define MIN(a, b) ((a) < (b) ? (a) : (b))
13#define MAX(a, b) ((a) > (b) ? (a) : (b))
14
Guido van Rossum18752471997-04-29 14:49:28 +000015#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000016
Guido van Rossum6f799372001-09-20 20:46:19 +000017static PyMemberDef frame_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000018 {"f_back", T_OBJECT, OFF(f_back), RO},
19 {"f_code", T_OBJECT, OFF(f_code), RO},
20 {"f_builtins", T_OBJECT, OFF(f_builtins),RO},
21 {"f_globals", T_OBJECT, OFF(f_globals), RO},
22 {"f_lasti", T_INT, OFF(f_lasti), RO},
23 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000024};
25
Benjamin Petersonf09925d2008-12-22 20:16:25 +000026#define WARN_GET_SET(NAME) \
27static PyObject * frame_get_ ## NAME(PyFrameObject *f) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000028 if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
29 return NULL; \
30 if (f->NAME) { \
31 Py_INCREF(f->NAME); \
32 return f->NAME; \
33 } \
34 Py_RETURN_NONE; \
Benjamin Petersonf09925d2008-12-22 20:16:25 +000035} \
36static int frame_set_ ## NAME(PyFrameObject *f, PyObject *new) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000037 if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
38 return -1; \
39 if (f->NAME) { \
40 Py_CLEAR(f->NAME); \
41 } \
42 if (new == Py_None) \
43 new = NULL; \
44 Py_XINCREF(new); \
45 f->NAME = new; \
46 return 0; \
Benjamin Petersonf09925d2008-12-22 20:16:25 +000047}
48
49
50WARN_GET_SET(f_exc_traceback)
51WARN_GET_SET(f_exc_type)
52WARN_GET_SET(f_exc_value)
53
54
Guido van Rossum18752471997-04-29 14:49:28 +000055static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000056frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000058 PyFrame_FastToLocals(f);
59 Py_INCREF(f->f_locals);
60 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000061}
62
Jeffrey Yasskinf7f858d2009-05-08 22:23:21 +000063int
64PyFrame_GetLineNumber(PyFrameObject *f)
65{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000066 if (f->f_trace)
67 return f->f_lineno;
68 else
69 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Jeffrey Yasskinf7f858d2009-05-08 22:23:21 +000070}
71
Michael W. Hudsondd32a912002-08-15 14:59:02 +000072static PyObject *
73frame_getlineno(PyFrameObject *f, void *closure)
74{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000075 return PyInt_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000076}
77
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000078/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouc83ea132010-05-09 14:46:46 +000079 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000080 * lines are OK to jump to because they don't make any assumptions about the
81 * state of the stack (obvious because you could remove the line and the code
82 * would still work without any stack errors), but there are some constructs
83 * that limit jumping:
84 *
85 * o Lines with an 'except' statement on them can't be jumped to, because
86 * they expect an exception to be on the top of the stack.
87 * o Lines that live in a 'finally' block can't be jumped from or to, since
88 * the END_FINALLY expects to clean up the stack after the 'try' block.
89 * o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
90 * needs to be set up before their code runs, and for 'for' loops the
91 * iterator needs to be on the stack.
xdegayebaca85f2018-03-13 22:06:14 +010092 * o Jumps cannot be made from within a trace function invoked with a
93 * 'return' or 'exception' event since the eval loop has been exited at
94 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000095 */
96static int
97frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
98{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000099 int new_lineno = 0; /* The new value of f_lineno */
100 int new_lasti = 0; /* The new value of f_lasti */
101 int new_iblock = 0; /* The new value of f_iblock */
102 unsigned char *code = NULL; /* The bytecode for the frame... */
103 Py_ssize_t code_len = 0; /* ...and its length */
104 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
105 Py_ssize_t lnotab_len = 0; /* (ditto) */
106 int offset = 0; /* (ditto) */
107 int line = 0; /* (ditto) */
108 int addr = 0; /* (ditto) */
109 int min_addr = 0; /* Scanning the SETUPs and POPs */
110 int max_addr = 0; /* (ditto) */
111 int delta_iblock = 0; /* (ditto) */
112 int min_delta_iblock = 0; /* (ditto) */
113 int min_iblock = 0; /* (ditto) */
114 int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
115 int new_lasti_setup_addr = 0; /* (ditto) */
116 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
117 int in_finally[CO_MAXBLOCKS]; /* (ditto) */
118 int blockstack_top = 0; /* (ditto) */
119 unsigned char setup_op = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000120
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000121 /* f_lineno must be an integer. */
122 if (!PyInt_Check(p_new_lineno)) {
123 PyErr_SetString(PyExc_ValueError,
124 "lineno must be an integer");
125 return -1;
126 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000127
xdegayebaca85f2018-03-13 22:06:14 +0100128 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
129 * f->f_trace is NULL, check first on the first condition.
130 * Forbidding jumps from the 'call' event of a new frame is a side effect
131 * of allowing to set f_lineno only from trace functions. */
132 if (f->f_lasti == -1) {
133 PyErr_Format(PyExc_ValueError,
134 "can't jump from the 'call' trace event of a new frame");
135 return -1;
136 }
137
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000138 /* You can only do this from within a trace function, not via
139 * _getframe or similar hackery. */
xdegayebaca85f2018-03-13 22:06:14 +0100140 if (!f->f_trace) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 PyErr_Format(PyExc_ValueError,
xdegayebaca85f2018-03-13 22:06:14 +0100142 "f_lineno can only be set by a trace function");
143 return -1;
144 }
145
146 /* Forbid jumps upon a 'return' trace event (except after executing a
147 * YIELD_VALUE opcode, f_stacktop is not NULL in that case) and upon an
148 * 'exception' trace event.
149 * Jumps from 'call' trace events have already been forbidden above for new
150 * frames, so this check does not change anything for 'call' events. */
151 if (f->f_stacktop == NULL) {
152 PyErr_SetString(PyExc_ValueError,
153 "can only jump from a 'line' trace event");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000154 return -1;
155 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000156
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157 /* Fail if the line comes before the start of the code block. */
158 new_lineno = (int) PyInt_AsLong(p_new_lineno);
159 if (new_lineno < f->f_code->co_firstlineno) {
160 PyErr_Format(PyExc_ValueError,
161 "line %d comes before the current code block",
162 new_lineno);
163 return -1;
164 }
165 else if (new_lineno == f->f_code->co_firstlineno) {
166 new_lasti = 0;
167 new_lineno = f->f_code->co_firstlineno;
168 }
169 else {
170 /* Find the bytecode offset for the start of the given
171 * line, or the first code-owning line after it. */
172 char *tmp;
173 PyString_AsStringAndSize(f->f_code->co_lnotab,
174 &tmp, &lnotab_len);
175 lnotab = (unsigned char *) tmp;
176 addr = 0;
177 line = f->f_code->co_firstlineno;
178 new_lasti = -1;
179 for (offset = 0; offset < lnotab_len; offset += 2) {
180 addr += lnotab[offset];
181 line += lnotab[offset+1];
182 if (line >= new_lineno) {
183 new_lasti = addr;
184 new_lineno = line;
185 break;
186 }
187 }
188 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000189
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000190 /* If we didn't reach the requested line, return an error. */
191 if (new_lasti == -1) {
192 PyErr_Format(PyExc_ValueError,
193 "line %d comes after the current code block",
194 new_lineno);
195 return -1;
196 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000197
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000198 /* We're now ready to look at the bytecode. */
199 PyString_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
200 min_addr = MIN(new_lasti, f->f_lasti);
201 max_addr = MAX(new_lasti, f->f_lasti);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000202
xdegayebaca85f2018-03-13 22:06:14 +0100203 /* The trace function is called with a 'return' trace event after the
204 * execution of a yield statement. */
205 assert(f->f_lasti != -1);
206 if (code[f->f_lasti] == YIELD_VALUE) {
207 PyErr_SetString(PyExc_ValueError,
208 "can't jump from a yield statement");
209 return -1;
210 }
211
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000212 /* You can't jump onto a line with an 'except' statement on it -
213 * they expect to have an exception on the top of the stack, which
214 * won't be true if you jump to them. They always start with code
215 * that either pops the exception using POP_TOP (plain 'except:'
216 * lines do this) or duplicates the exception on the stack using
217 * DUP_TOP (if there's an exception type specified). See compile.c,
218 * 'com_try_except' for the full details. There aren't any other
219 * cases (AFAIK) where a line's code can start with DUP_TOP or
220 * POP_TOP, but if any ever appear, they'll be subject to the same
221 * restriction (but with a different error message). */
222 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
223 PyErr_SetString(PyExc_ValueError,
224 "can't jump to 'except' line as there's no exception");
225 return -1;
226 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000227
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000228 /* You can't jump into or out of a 'finally' block because the 'try'
229 * block leaves something on the stack for the END_FINALLY to clean
230 * up. So we walk the bytecode, maintaining a simulated blockstack.
231 * When we reach the old or new address and it's in a 'finally' block
232 * we note the address of the corresponding SETUP_FINALLY. The jump
233 * is only legal if neither address is in a 'finally' block or
234 * they're both in the same one. 'blockstack' is a stack of the
235 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
236 * whether we're in a 'finally' block at each blockstack level. */
237 f_lasti_setup_addr = -1;
238 new_lasti_setup_addr = -1;
239 memset(blockstack, '\0', sizeof(blockstack));
240 memset(in_finally, '\0', sizeof(in_finally));
241 blockstack_top = 0;
242 for (addr = 0; addr < code_len; addr++) {
243 unsigned char op = code[addr];
244 switch (op) {
245 case SETUP_LOOP:
246 case SETUP_EXCEPT:
247 case SETUP_FINALLY:
Benjamin Peterson76605552012-04-18 11:14:31 -0400248 case SETUP_WITH:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000249 blockstack[blockstack_top++] = addr;
250 in_finally[blockstack_top-1] = 0;
251 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000252
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 case POP_BLOCK:
254 assert(blockstack_top > 0);
255 setup_op = code[blockstack[blockstack_top-1]];
Benjamin Peterson76605552012-04-18 11:14:31 -0400256 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 in_finally[blockstack_top-1] = 1;
258 }
259 else {
260 blockstack_top--;
261 }
262 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000263
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000264 case END_FINALLY:
265 /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
266 * in the bytecode but don't correspond to an actual
267 * 'finally' block. (If blockstack_top is 0, we must
268 * be seeing such an END_FINALLY.) */
269 if (blockstack_top > 0) {
270 setup_op = code[blockstack[blockstack_top-1]];
Benjamin Peterson76605552012-04-18 11:14:31 -0400271 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000272 blockstack_top--;
273 }
274 }
275 break;
276 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 /* For the addresses we're interested in, see whether they're
279 * within a 'finally' block and if so, remember the address
280 * of the SETUP_FINALLY. */
281 if (addr == new_lasti || addr == f->f_lasti) {
282 int i = 0;
283 int setup_addr = -1;
284 for (i = blockstack_top-1; i >= 0; i--) {
285 if (in_finally[i]) {
286 setup_addr = blockstack[i];
287 break;
288 }
289 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000290
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000291 if (setup_addr != -1) {
292 if (addr == new_lasti) {
293 new_lasti_setup_addr = setup_addr;
294 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000295
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000296 if (addr == f->f_lasti) {
297 f_lasti_setup_addr = setup_addr;
298 }
299 }
300 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000301
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000302 if (op >= HAVE_ARGUMENT) {
303 addr += 2;
304 }
305 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000306
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000307 /* Verify that the blockstack tracking code didn't get lost. */
308 assert(blockstack_top == 0);
Neal Norwitzee65e222002-12-19 18:16:57 +0000309
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000310 /* After all that, are we jumping into / out of a 'finally' block? */
311 if (new_lasti_setup_addr != f_lasti_setup_addr) {
312 PyErr_SetString(PyExc_ValueError,
313 "can't jump into or out of a 'finally' block");
314 return -1;
315 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000316
317
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000318 /* Police block-jumping (you can't jump into the middle of a block)
319 * and ensure that the blockstack finishes up in a sensible state (by
320 * popping any blocks we're jumping out of). We look at all the
321 * blockstack operations between the current position and the new
322 * one, and keep track of how many blocks we drop out of on the way.
323 * By also keeping track of the lowest blockstack position we see, we
324 * can tell whether the jump goes into any blocks without coming out
325 * again - in that case we raise an exception below. */
326 delta_iblock = 0;
327 for (addr = min_addr; addr < max_addr; addr++) {
328 unsigned char op = code[addr];
329 switch (op) {
330 case SETUP_LOOP:
331 case SETUP_EXCEPT:
332 case SETUP_FINALLY:
Benjamin Peterson76605552012-04-18 11:14:31 -0400333 case SETUP_WITH:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000334 delta_iblock++;
335 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000336
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 case POP_BLOCK:
338 delta_iblock--;
339 break;
340 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000341
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000342 min_delta_iblock = MIN(min_delta_iblock, delta_iblock);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000343
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000344 if (op >= HAVE_ARGUMENT) {
345 addr += 2;
346 }
347 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000348
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000349 /* Derive the absolute iblock values from the deltas. */
350 min_iblock = f->f_iblock + min_delta_iblock;
351 if (new_lasti > f->f_lasti) {
352 /* Forwards jump. */
353 new_iblock = f->f_iblock + delta_iblock;
354 }
355 else {
356 /* Backwards jump. */
357 new_iblock = f->f_iblock - delta_iblock;
358 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000359
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000360 /* Are we jumping into a block? */
361 if (new_iblock > min_iblock) {
362 PyErr_SetString(PyExc_ValueError,
363 "can't jump into the middle of a block");
364 return -1;
365 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000366
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000367 /* Pop any blocks that we're jumping out of. */
368 while (f->f_iblock > new_iblock) {
369 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
370 while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
371 PyObject *v = (*--f->f_stacktop);
372 Py_DECREF(v);
373 }
Miss Islington (bot)3854f582018-03-11 00:55:59 -0800374 if (b->b_type == SETUP_WITH) {
375 /* Pop the exit function. */
376 PyObject *v = (*--f->f_stacktop);
377 Py_DECREF(v);
378 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000379 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000380
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000381 /* Finally set the new f_lineno and f_lasti and return OK. */
382 f->f_lineno = new_lineno;
383 f->f_lasti = new_lasti;
384 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000385}
386
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000387static PyObject *
388frame_gettrace(PyFrameObject *f, void *closure)
389{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000390 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000391
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000392 if (trace == NULL)
393 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000394
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000395 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000396
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000397 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000398}
399
400static int
401frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
402{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000403 /* We rely on f_lineno being accurate when f_trace is set. */
404 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000405
Serhiy Storchakad37781e2016-06-04 20:30:43 +0300406 if (v == Py_None)
407 v = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000408 Py_XINCREF(v);
Serhiy Storchakad37781e2016-06-04 20:30:43 +0300409 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000410
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000411 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000412}
413
Neal Norwitzb9845e72006-06-12 02:11:18 +0000414static PyObject *
415frame_getrestricted(PyFrameObject *f, void *closure)
416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 return PyBool_FromLong(PyFrame_IsRestricted(f));
Neal Norwitzb9845e72006-06-12 02:11:18 +0000418}
419
Guido van Rossum32d34c82001-09-20 21:45:26 +0000420static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000421 {"f_locals", (getter)frame_getlocals, NULL, NULL},
422 {"f_lineno", (getter)frame_getlineno,
423 (setter)frame_setlineno, NULL},
424 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
425 {"f_restricted",(getter)frame_getrestricted,NULL, NULL},
426 {"f_exc_traceback", (getter)frame_get_f_exc_traceback,
427 (setter)frame_set_f_exc_traceback, NULL},
428 {"f_exc_type", (getter)frame_get_f_exc_type,
429 (setter)frame_set_f_exc_type, NULL},
430 {"f_exc_value", (getter)frame_get_f_exc_value,
431 (setter)frame_set_f_exc_value, NULL},
432 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000434
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000435/* Stack frames are allocated and deallocated at a considerable rate.
Richard Jones7c88dcc2006-05-23 10:37:38 +0000436 In an attempt to improve the speed of function calls, we:
437
438 1. Hold a single "zombie" frame on each code object. This retains
439 the allocated and initialised frame object from an invocation of
440 the code object. The zombie is reanimated the next time we need a
441 frame object for that code object. Doing this saves the malloc/
442 realloc required when using a free_list frame that isn't the
443 correct size. It also saves some field initialisation.
444
445 In zombie mode, no field of PyFrameObject holds a reference, but
446 the following fields are still valid:
447
Richard Jonesa3727112006-05-23 18:32:11 +0000448 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000449
Richard Jones7c88dcc2006-05-23 10:37:38 +0000450 * f_locals, f_trace,
451 f_exc_type, f_exc_value, f_exc_traceback are NULL;
452
453 * f_localsplus does not require re-allocation and
454 the local variables in f_localsplus are NULL.
455
456 2. We also maintain a separate free list of stack frames (just like
457 integers are allocated in a special way -- see intobject.c). When
458 a stack frame is on the free list, only the following members have
459 a meaning:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000460 ob_type == &Frametype
461 f_back next item on free list, or NULL
462 f_stacksize size of value stack
463 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000464 Note that the value and block stacks are preserved -- this can save
465 another malloc() call or two (and two free() calls as well!).
466 Also note that, unlike for integers, each frame object is a
467 malloc'ed object in its own right -- it is only the actual calls to
468 malloc() that we are trying to save here, not the administration.
469 After all, while a typical program may make millions of calls, a
470 call depth of more than 20 or 30 is probably already exceptional
471 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000472
Christian Heimes5b970ad2008-02-06 13:33:44 +0000473 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000474 free_list. Else programs creating lots of cyclic trash involving
475 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000476*/
477
Guido van Rossum18752471997-04-29 14:49:28 +0000478static PyFrameObject *free_list = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000479static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes5b970ad2008-02-06 13:33:44 +0000480/* max value for numfree */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000481#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000482
Guido van Rossum3f5da241990-12-20 15:06:42 +0000483static void
Fred Drake1b190b42000-07-09 05:40:56 +0000484frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000485{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 PyObject **p, **valuestack;
487 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000488
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000489 PyObject_GC_UnTrack(f);
490 Py_TRASHCAN_SAFE_BEGIN(f)
491 /* Kill all local variables */
492 valuestack = f->f_valuestack;
493 for (p = f->f_localsplus; p < valuestack; p++)
494 Py_CLEAR(*p);
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000495
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000496 /* Free stack */
497 if (f->f_stacktop != NULL) {
498 for (p = valuestack; p < f->f_stacktop; p++)
499 Py_XDECREF(*p);
500 }
Tim Petersa13131c2006-04-15 03:15:24 +0000501
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000502 Py_XDECREF(f->f_back);
503 Py_DECREF(f->f_builtins);
504 Py_DECREF(f->f_globals);
505 Py_CLEAR(f->f_locals);
506 Py_CLEAR(f->f_trace);
507 Py_CLEAR(f->f_exc_type);
508 Py_CLEAR(f->f_exc_value);
509 Py_CLEAR(f->f_exc_traceback);
Richard Jones7c88dcc2006-05-23 10:37:38 +0000510
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 co = f->f_code;
512 if (co->co_zombieframe == NULL)
513 co->co_zombieframe = f;
514 else if (numfree < PyFrame_MAXFREELIST) {
515 ++numfree;
516 f->f_back = free_list;
517 free_list = f;
518 }
519 else
520 PyObject_GC_Del(f);
Richard Jones7c88dcc2006-05-23 10:37:38 +0000521
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000522 Py_DECREF(co);
523 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000524}
525
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000526static int
527frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
528{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000529 PyObject **fastlocals, **p;
530 int i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000531
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000532 Py_VISIT(f->f_back);
533 Py_VISIT(f->f_code);
534 Py_VISIT(f->f_builtins);
535 Py_VISIT(f->f_globals);
536 Py_VISIT(f->f_locals);
537 Py_VISIT(f->f_trace);
538 Py_VISIT(f->f_exc_type);
539 Py_VISIT(f->f_exc_value);
540 Py_VISIT(f->f_exc_traceback);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000541
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 /* locals */
543 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
544 fastlocals = f->f_localsplus;
545 for (i = slots; --i >= 0; ++fastlocals)
546 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000547
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000548 /* stack */
549 if (f->f_stacktop != NULL) {
550 for (p = f->f_valuestack; p < f->f_stacktop; p++)
551 Py_VISIT(*p);
552 }
553 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000554}
555
556static void
557frame_clear(PyFrameObject *f)
558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000559 PyObject **fastlocals, **p, **oldtop;
560 int i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000561
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000562 /* Before anything else, make sure that this frame is clearly marked
563 * as being defunct! Else, e.g., a generator reachable from this
564 * frame may also point to this frame, believe itself to still be
565 * active, and try cleaning up this frame again.
566 */
567 oldtop = f->f_stacktop;
568 f->f_stacktop = NULL;
Phillip J. Eby8ebb28d2006-04-15 01:02:17 +0000569
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000570 Py_CLEAR(f->f_exc_type);
571 Py_CLEAR(f->f_exc_value);
572 Py_CLEAR(f->f_exc_traceback);
573 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000574
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000575 /* locals */
576 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
577 fastlocals = f->f_localsplus;
578 for (i = slots; --i >= 0; ++fastlocals)
579 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000580
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000581 /* stack */
582 if (oldtop != NULL) {
583 for (p = f->f_valuestack; p < oldtop; p++)
584 Py_CLEAR(*p);
585 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000586}
587
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000588static PyObject *
589frame_sizeof(PyFrameObject *f)
590{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000591 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000592
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000593 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
594 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
595 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
596 ncells + nfrees;
597 /* subtract one as it is already included in PyFrameObject */
598 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000599
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000600 return PyInt_FromSsize_t(res);
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000601}
602
603PyDoc_STRVAR(sizeof__doc__,
604"F.__sizeof__() -> size of F in memory, in bytes");
605
606static PyMethodDef frame_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000607 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
608 sizeof__doc__},
609 {NULL, NULL} /* sentinel */
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000610};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000611
Guido van Rossum18752471997-04-29 14:49:28 +0000612PyTypeObject PyFrame_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000613 PyVarObject_HEAD_INIT(&PyType_Type, 0)
614 "frame",
615 sizeof(PyFrameObject),
616 sizeof(PyObject *),
617 (destructor)frame_dealloc, /* tp_dealloc */
618 0, /* tp_print */
619 0, /* tp_getattr */
620 0, /* tp_setattr */
621 0, /* tp_compare */
622 0, /* tp_repr */
623 0, /* tp_as_number */
624 0, /* tp_as_sequence */
625 0, /* tp_as_mapping */
626 0, /* tp_hash */
627 0, /* tp_call */
628 0, /* tp_str */
629 PyObject_GenericGetAttr, /* tp_getattro */
630 PyObject_GenericSetAttr, /* tp_setattro */
631 0, /* tp_as_buffer */
632 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
633 0, /* tp_doc */
634 (traverseproc)frame_traverse, /* tp_traverse */
635 (inquiry)frame_clear, /* tp_clear */
636 0, /* tp_richcompare */
637 0, /* tp_weaklistoffset */
638 0, /* tp_iter */
639 0, /* tp_iternext */
640 frame_methods, /* tp_methods */
641 frame_memberlist, /* tp_members */
642 frame_getsetlist, /* tp_getset */
643 0, /* tp_base */
644 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000645};
646
Neal Norwitzc91ed402002-12-30 22:29:22 +0000647static PyObject *builtin_object;
648
Neal Norwitzb2501f42002-12-31 03:42:13 +0000649int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000650{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 builtin_object = PyString_InternFromString("__builtins__");
652 if (builtin_object == NULL)
653 return 0;
654 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000655}
656
Guido van Rossum18752471997-04-29 14:49:28 +0000657PyFrameObject *
Tim Petersa13131c2006-04-15 03:15:24 +0000658PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000660{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000661 PyFrameObject *back = tstate->frame;
662 PyFrameObject *f;
663 PyObject *builtins;
664 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000665
Michael W. Hudson69734a52002-08-19 16:54:08 +0000666#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000667 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
668 (locals != NULL && !PyMapping_Check(locals))) {
669 PyErr_BadInternalCall();
670 return NULL;
671 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000672#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000673 if (back == NULL || back->f_globals != globals) {
674 builtins = PyDict_GetItem(globals, builtin_object);
675 if (builtins) {
676 if (PyModule_Check(builtins)) {
677 builtins = PyModule_GetDict(builtins);
678 assert(!builtins || PyDict_Check(builtins));
679 }
680 else if (!PyDict_Check(builtins))
681 builtins = NULL;
682 }
683 if (builtins == NULL) {
684 /* No builtins! Make up a minimal one
685 Give them 'None', at least. */
686 builtins = PyDict_New();
687 if (builtins == NULL ||
688 PyDict_SetItemString(
689 builtins, "None", Py_None) < 0)
690 return NULL;
691 }
692 else
693 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000694
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000695 }
696 else {
697 /* If we share the globals, we share the builtins.
698 Save a lookup and a call. */
699 builtins = back->f_builtins;
700 assert(builtins != NULL && PyDict_Check(builtins));
701 Py_INCREF(builtins);
702 }
703 if (code->co_zombieframe != NULL) {
704 f = code->co_zombieframe;
705 code->co_zombieframe = NULL;
706 _Py_NewReference((PyObject *)f);
707 assert(f->f_code == code);
708 }
709 else {
710 Py_ssize_t extras, ncells, nfrees;
711 ncells = PyTuple_GET_SIZE(code->co_cellvars);
712 nfrees = PyTuple_GET_SIZE(code->co_freevars);
713 extras = code->co_stacksize + code->co_nlocals + ncells +
714 nfrees;
715 if (free_list == NULL) {
716 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
717 extras);
718 if (f == NULL) {
719 Py_DECREF(builtins);
720 return NULL;
721 }
722 }
723 else {
724 assert(numfree > 0);
725 --numfree;
726 f = free_list;
727 free_list = free_list->f_back;
728 if (Py_SIZE(f) < extras) {
729 f = PyObject_GC_Resize(PyFrameObject, f, extras);
730 if (f == NULL) {
731 Py_DECREF(builtins);
732 return NULL;
733 }
734 }
735 _Py_NewReference((PyObject *)f);
736 }
Richard Jones7c88dcc2006-05-23 10:37:38 +0000737
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000738 f->f_code = code;
739 extras = code->co_nlocals + ncells + nfrees;
740 f->f_valuestack = f->f_localsplus + extras;
741 for (i=0; i<extras; i++)
742 f->f_localsplus[i] = NULL;
743 f->f_locals = NULL;
744 f->f_trace = NULL;
745 f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
746 }
747 f->f_stacktop = f->f_valuestack;
748 f->f_builtins = builtins;
749 Py_XINCREF(back);
750 f->f_back = back;
751 Py_INCREF(code);
752 Py_INCREF(globals);
753 f->f_globals = globals;
754 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
755 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
756 (CO_NEWLOCALS | CO_OPTIMIZED))
757 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
758 else if (code->co_flags & CO_NEWLOCALS) {
759 locals = PyDict_New();
760 if (locals == NULL) {
761 Py_DECREF(f);
762 return NULL;
763 }
764 f->f_locals = locals;
765 }
766 else {
767 if (locals == NULL)
768 locals = globals;
769 Py_INCREF(locals);
770 f->f_locals = locals;
771 }
772 f->f_tstate = tstate;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000773
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000774 f->f_lasti = -1;
775 f->f_lineno = code->co_firstlineno;
776 f->f_iblock = 0;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000777
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000778 _PyObject_GC_TRACK(f);
779 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000780}
781
Guido van Rossum3f5da241990-12-20 15:06:42 +0000782/* Block management */
783
784void
Fred Drake1b190b42000-07-09 05:40:56 +0000785PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000786{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 PyTryBlock *b;
788 if (f->f_iblock >= CO_MAXBLOCKS)
789 Py_FatalError("XXX block stack overflow");
790 b = &f->f_blockstack[f->f_iblock++];
791 b->b_type = type;
792 b->b_level = level;
793 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000794}
795
Guido van Rossum18752471997-04-29 14:49:28 +0000796PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000797PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000798{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000799 PyTryBlock *b;
800 if (f->f_iblock <= 0)
801 Py_FatalError("XXX block stack underflow");
802 b = &f->f_blockstack[--f->f_iblock];
803 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000804}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000805
Jeremy Hylton759410b2007-02-26 18:41:18 +0000806/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000807
808 map and values are input arguments. map is a tuple of strings.
Jeremy Hylton759410b2007-02-26 18:41:18 +0000809 values is an array of PyObject*. At index i, map[i] is the name of
810 the variable with value values[i]. The function copies the first
811 nmap variable from map/values into dict. If values[i] is NULL,
812 the variable is deleted from dict.
813
814 If deref is true, then the values being copied are cell variables
815 and the value is extracted from the cell variable before being put
816 in dict.
817
818 Exceptions raised while modifying the dict are silently ignored,
819 because there is no good way to report them.
820 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000821
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000822static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000823map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000825{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000826 Py_ssize_t j;
827 assert(PyTuple_Check(map));
828 assert(PyDict_Check(dict));
829 assert(PyTuple_Size(map) >= nmap);
830 for (j = nmap; --j >= 0; ) {
831 PyObject *key = PyTuple_GET_ITEM(map, j);
832 PyObject *value = values[j];
833 assert(PyString_Check(key));
834 if (deref) {
835 assert(PyCell_Check(value));
836 value = PyCell_GET(value);
837 }
838 if (value == NULL) {
839 if (PyObject_DelItem(dict, key) != 0)
840 PyErr_Clear();
841 }
842 else {
843 if (PyObject_SetItem(dict, key, value) != 0)
844 PyErr_Clear();
845 }
846 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000847}
848
Jeremy Hylton759410b2007-02-26 18:41:18 +0000849/* Copy values from the "locals" dict into the fast locals.
850
851 dict is an input argument containing string keys representing
852 variables names and arbitrary PyObject* as values.
853
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000854 map and values are input arguments. map is a tuple of strings.
Jeremy Hylton759410b2007-02-26 18:41:18 +0000855 values is an array of PyObject*. At index i, map[i] is the name of
856 the variable with value values[i]. The function copies the first
857 nmap variable from map/values into dict. If values[i] is NULL,
858 the variable is deleted from dict.
859
860 If deref is true, then the values being copied are cell variables
861 and the value is extracted from the cell variable before being put
862 in dict. If clear is true, then variables in map but not in dict
863 are set to NULL in map; if clear is false, variables missing in
864 dict are ignored.
865
866 Exceptions raised while modifying the dict are silently ignored,
867 because there is no good way to report them.
868*/
869
Guido van Rossum6b356e72001-04-14 17:55:41 +0000870static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000871dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000872 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000873{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 Py_ssize_t j;
875 assert(PyTuple_Check(map));
876 assert(PyDict_Check(dict));
877 assert(PyTuple_Size(map) >= nmap);
878 for (j = nmap; --j >= 0; ) {
879 PyObject *key = PyTuple_GET_ITEM(map, j);
880 PyObject *value = PyObject_GetItem(dict, key);
881 assert(PyString_Check(key));
882 /* We only care about NULLs if clear is true. */
883 if (value == NULL) {
884 PyErr_Clear();
885 if (!clear)
886 continue;
887 }
888 if (deref) {
889 assert(PyCell_Check(values[j]));
890 if (PyCell_GET(values[j]) != value) {
891 if (PyCell_Set(values[j], value) < 0)
892 PyErr_Clear();
893 }
894 } else if (values[j] != value) {
895 Py_XINCREF(value);
Serhiy Storchakabc62af12016-04-06 09:51:18 +0300896 Py_XSETREF(values[j], value);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 }
898 Py_XDECREF(value);
899 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000900}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000901
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000902void
Fred Drake1b190b42000-07-09 05:40:56 +0000903PyFrame_FastToLocals(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000904{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000905 /* Merge fast locals into f->f_locals */
906 PyObject *locals, *map;
907 PyObject **fast;
908 PyObject *error_type, *error_value, *error_traceback;
909 PyCodeObject *co;
910 Py_ssize_t j;
911 int ncells, nfreevars;
912 if (f == NULL)
913 return;
914 locals = f->f_locals;
915 if (locals == NULL) {
916 locals = f->f_locals = PyDict_New();
917 if (locals == NULL) {
918 PyErr_Clear(); /* Can't report it :-( */
919 return;
920 }
921 }
922 co = f->f_code;
923 map = co->co_varnames;
924 if (!PyTuple_Check(map))
925 return;
926 PyErr_Fetch(&error_type, &error_value, &error_traceback);
927 fast = f->f_localsplus;
928 j = PyTuple_GET_SIZE(map);
929 if (j > co->co_nlocals)
930 j = co->co_nlocals;
931 if (co->co_nlocals)
932 map_to_dict(map, j, locals, fast, 0);
933 ncells = PyTuple_GET_SIZE(co->co_cellvars);
934 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
935 if (ncells || nfreevars) {
936 map_to_dict(co->co_cellvars, ncells,
937 locals, fast + co->co_nlocals, 1);
938 /* If the namespace is unoptimized, then one of the
939 following cases applies:
940 1. It does not contain free variables, because it
941 uses import * or is a top-level namespace.
942 2. It is a class namespace.
943 We don't want to accidentally copy free variables
944 into the locals dict used by the class.
945 */
946 if (co->co_flags & CO_OPTIMIZED) {
947 map_to_dict(co->co_freevars, nfreevars,
948 locals, fast + co->co_nlocals + ncells, 1);
949 }
950 }
951 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000952}
953
954void
Fred Drake1b190b42000-07-09 05:40:56 +0000955PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000956{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000957 /* Merge f->f_locals into fast locals */
958 PyObject *locals, *map;
959 PyObject **fast;
960 PyObject *error_type, *error_value, *error_traceback;
961 PyCodeObject *co;
962 Py_ssize_t j;
963 int ncells, nfreevars;
964 if (f == NULL)
965 return;
966 locals = f->f_locals;
967 co = f->f_code;
968 map = co->co_varnames;
969 if (locals == NULL)
970 return;
971 if (!PyTuple_Check(map))
972 return;
973 PyErr_Fetch(&error_type, &error_value, &error_traceback);
974 fast = f->f_localsplus;
975 j = PyTuple_GET_SIZE(map);
976 if (j > co->co_nlocals)
977 j = co->co_nlocals;
978 if (co->co_nlocals)
979 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
980 ncells = PyTuple_GET_SIZE(co->co_cellvars);
981 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
982 if (ncells || nfreevars) {
983 dict_to_map(co->co_cellvars, ncells,
984 locals, fast + co->co_nlocals, 1, clear);
985 /* Same test as in PyFrame_FastToLocals() above. */
986 if (co->co_flags & CO_OPTIMIZED) {
987 dict_to_map(co->co_freevars, nfreevars,
988 locals, fast + co->co_nlocals + ncells, 1,
989 clear);
990 }
991 }
992 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000993}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000994
995/* Clear out the free list */
Christian Heimes3b718a72008-02-14 12:47:33 +0000996int
997PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000998{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000999 int freelist_size = numfree;
1000
1001 while (free_list != NULL) {
1002 PyFrameObject *f = free_list;
1003 free_list = free_list->f_back;
1004 PyObject_GC_Del(f);
1005 --numfree;
1006 }
1007 assert(numfree == 0);
1008 return freelist_size;
Christian Heimes3b718a72008-02-14 12:47:33 +00001009}
1010
1011void
1012PyFrame_Fini(void)
1013{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001014 (void)PyFrame_ClearFreeList();
1015 Py_XDECREF(builtin_object);
1016 builtin_object = NULL;
Guido van Rossum404b95d1997-08-05 02:09:46 +00001017}