blob: 9aadd61019e0abb7f290fff26a801e81de4f739c [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
Guido van Rossum18752471997-04-29 14:49:28 +000010#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000011
Guido van Rossum6f799372001-09-20 20:46:19 +000012static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100013 {"f_back", T_OBJECT, OFF(f_back), READONLY},
14 {"f_code", T_OBJECT, OFF(f_code), READONLY},
15 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
16 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
17 {"f_lasti", T_INT, OFF(f_lasti), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000019};
20
Guido van Rossum18752471997-04-29 14:49:28 +000021static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000022frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000023{
Victor Stinner41bb43a2013-10-29 01:19:37 +010024 if (PyFrame_FastToLocalsWithError(f) < 0)
25 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 Py_INCREF(f->f_locals);
27 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000028}
29
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000030int
31PyFrame_GetLineNumber(PyFrameObject *f)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 if (f->f_trace)
34 return f->f_lineno;
35 else
36 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000037}
38
Michael W. Hudsondd32a912002-08-15 14:59:02 +000039static PyObject *
40frame_getlineno(PyFrameObject *f, void *closure)
41{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000043}
44
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000045/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000047 * lines are OK to jump to because they don't make any assumptions about the
48 * state of the stack (obvious because you could remove the line and the code
49 * would still work without any stack errors), but there are some constructs
50 * that limit jumping:
51 *
52 * o Lines with an 'except' statement on them can't be jumped to, because
53 * they expect an exception to be on the top of the stack.
54 * o Lines that live in a 'finally' block can't be jumped from or to, since
55 * the END_FINALLY expects to clean up the stack after the 'try' block.
56 * o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
57 * needs to be set up before their code runs, and for 'for' loops the
58 * iterator needs to be on the stack.
59 */
60static int
61frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
62{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 int new_lineno = 0; /* The new value of f_lineno */
64 long l_new_lineno;
65 int overflow;
66 int new_lasti = 0; /* The new value of f_lasti */
67 int new_iblock = 0; /* The new value of f_iblock */
68 unsigned char *code = NULL; /* The bytecode for the frame... */
69 Py_ssize_t code_len = 0; /* ...and its length */
70 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
71 Py_ssize_t lnotab_len = 0; /* (ditto) */
72 int offset = 0; /* (ditto) */
73 int line = 0; /* (ditto) */
74 int addr = 0; /* (ditto) */
75 int min_addr = 0; /* Scanning the SETUPs and POPs */
76 int max_addr = 0; /* (ditto) */
77 int delta_iblock = 0; /* (ditto) */
78 int min_delta_iblock = 0; /* (ditto) */
79 int min_iblock = 0; /* (ditto) */
80 int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
81 int new_lasti_setup_addr = 0; /* (ditto) */
82 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
83 int in_finally[CO_MAXBLOCKS]; /* (ditto) */
84 int blockstack_top = 0; /* (ditto) */
85 unsigned char setup_op = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 /* f_lineno must be an integer. */
88 if (!PyLong_CheckExact(p_new_lineno)) {
89 PyErr_SetString(PyExc_ValueError,
90 "lineno must be an integer");
91 return -1;
92 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 /* You can only do this from within a trace function, not via
95 * _getframe or similar hackery. */
96 if (!f->f_trace)
97 {
98 PyErr_Format(PyExc_ValueError,
99 "f_lineno can only be set by a"
100 " line trace function");
101 return -1;
102 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 /* Fail if the line comes before the start of the code block. */
105 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
106 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000107#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 || l_new_lineno > INT_MAX
109 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000110#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 ) {
112 PyErr_SetString(PyExc_ValueError,
113 "lineno out of range");
114 return -1;
115 }
116 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 if (new_lineno < f->f_code->co_firstlineno) {
119 PyErr_Format(PyExc_ValueError,
120 "line %d comes before the current code block",
121 new_lineno);
122 return -1;
123 }
124 else if (new_lineno == f->f_code->co_firstlineno) {
125 new_lasti = 0;
126 new_lineno = f->f_code->co_firstlineno;
127 }
128 else {
129 /* Find the bytecode offset for the start of the given
130 * line, or the first code-owning line after it. */
131 char *tmp;
132 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
133 &tmp, &lnotab_len);
134 lnotab = (unsigned char *) tmp;
135 addr = 0;
136 line = f->f_code->co_firstlineno;
137 new_lasti = -1;
138 for (offset = 0; offset < lnotab_len; offset += 2) {
139 addr += lnotab[offset];
140 line += lnotab[offset+1];
141 if (line >= new_lineno) {
142 new_lasti = addr;
143 new_lineno = line;
144 break;
145 }
146 }
147 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 /* If we didn't reach the requested line, return an error. */
150 if (new_lasti == -1) {
151 PyErr_Format(PyExc_ValueError,
152 "line %d comes after the current code block",
153 new_lineno);
154 return -1;
155 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 /* We're now ready to look at the bytecode. */
158 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
Victor Stinner640c35c2013-06-04 23:14:37 +0200159 min_addr = Py_MIN(new_lasti, f->f_lasti);
160 max_addr = Py_MAX(new_lasti, f->f_lasti);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* You can't jump onto a line with an 'except' statement on it -
163 * they expect to have an exception on the top of the stack, which
164 * won't be true if you jump to them. They always start with code
165 * that either pops the exception using POP_TOP (plain 'except:'
166 * lines do this) or duplicates the exception on the stack using
167 * DUP_TOP (if there's an exception type specified). See compile.c,
168 * 'com_try_except' for the full details. There aren't any other
169 * cases (AFAIK) where a line's code can start with DUP_TOP or
170 * POP_TOP, but if any ever appear, they'll be subject to the same
171 * restriction (but with a different error message). */
172 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
173 PyErr_SetString(PyExc_ValueError,
174 "can't jump to 'except' line as there's no exception");
175 return -1;
176 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* You can't jump into or out of a 'finally' block because the 'try'
179 * block leaves something on the stack for the END_FINALLY to clean
180 * up. So we walk the bytecode, maintaining a simulated blockstack.
181 * When we reach the old or new address and it's in a 'finally' block
182 * we note the address of the corresponding SETUP_FINALLY. The jump
183 * is only legal if neither address is in a 'finally' block or
184 * they're both in the same one. 'blockstack' is a stack of the
185 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
186 * whether we're in a 'finally' block at each blockstack level. */
187 f_lasti_setup_addr = -1;
188 new_lasti_setup_addr = -1;
189 memset(blockstack, '\0', sizeof(blockstack));
190 memset(in_finally, '\0', sizeof(in_finally));
191 blockstack_top = 0;
192 for (addr = 0; addr < code_len; addr++) {
193 unsigned char op = code[addr];
194 switch (op) {
195 case SETUP_LOOP:
196 case SETUP_EXCEPT:
197 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400198 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400199 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 blockstack[blockstack_top++] = addr;
201 in_finally[blockstack_top-1] = 0;
202 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 case POP_BLOCK:
205 assert(blockstack_top > 0);
206 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400207 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
208 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 in_finally[blockstack_top-1] = 1;
210 }
211 else {
212 blockstack_top--;
213 }
214 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 case END_FINALLY:
217 /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
218 * in the bytecode but don't correspond to an actual
219 * 'finally' block. (If blockstack_top is 0, we must
220 * be seeing such an END_FINALLY.) */
221 if (blockstack_top > 0) {
222 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400223 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
224 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 blockstack_top--;
226 }
227 }
228 break;
229 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* For the addresses we're interested in, see whether they're
232 * within a 'finally' block and if so, remember the address
233 * of the SETUP_FINALLY. */
234 if (addr == new_lasti || addr == f->f_lasti) {
235 int i = 0;
236 int setup_addr = -1;
237 for (i = blockstack_top-1; i >= 0; i--) {
238 if (in_finally[i]) {
239 setup_addr = blockstack[i];
240 break;
241 }
242 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (setup_addr != -1) {
245 if (addr == new_lasti) {
246 new_lasti_setup_addr = setup_addr;
247 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (addr == f->f_lasti) {
250 f_lasti_setup_addr = setup_addr;
251 }
252 }
253 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (op >= HAVE_ARGUMENT) {
256 addr += 2;
257 }
258 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 /* Verify that the blockstack tracking code didn't get lost. */
261 assert(blockstack_top == 0);
262
263 /* After all that, are we jumping into / out of a 'finally' block? */
264 if (new_lasti_setup_addr != f_lasti_setup_addr) {
265 PyErr_SetString(PyExc_ValueError,
266 "can't jump into or out of a 'finally' block");
267 return -1;
268 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000269
270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 /* Police block-jumping (you can't jump into the middle of a block)
272 * and ensure that the blockstack finishes up in a sensible state (by
273 * popping any blocks we're jumping out of). We look at all the
274 * blockstack operations between the current position and the new
275 * one, and keep track of how many blocks we drop out of on the way.
276 * By also keeping track of the lowest blockstack position we see, we
277 * can tell whether the jump goes into any blocks without coming out
278 * again - in that case we raise an exception below. */
279 delta_iblock = 0;
280 for (addr = min_addr; addr < max_addr; addr++) {
281 unsigned char op = code[addr];
282 switch (op) {
283 case SETUP_LOOP:
284 case SETUP_EXCEPT:
285 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400286 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400287 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 delta_iblock++;
289 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 case POP_BLOCK:
292 delta_iblock--;
293 break;
294 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000295
Victor Stinner640c35c2013-06-04 23:14:37 +0200296 min_delta_iblock = Py_MIN(min_delta_iblock, delta_iblock);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (op >= HAVE_ARGUMENT) {
299 addr += 2;
300 }
301 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 /* Derive the absolute iblock values from the deltas. */
304 min_iblock = f->f_iblock + min_delta_iblock;
305 if (new_lasti > f->f_lasti) {
306 /* Forwards jump. */
307 new_iblock = f->f_iblock + delta_iblock;
308 }
309 else {
310 /* Backwards jump. */
311 new_iblock = f->f_iblock - delta_iblock;
312 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 /* Are we jumping into a block? */
315 if (new_iblock > min_iblock) {
316 PyErr_SetString(PyExc_ValueError,
317 "can't jump into the middle of a block");
318 return -1;
319 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 /* Pop any blocks that we're jumping out of. */
322 while (f->f_iblock > new_iblock) {
323 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
324 while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
325 PyObject *v = (*--f->f_stacktop);
326 Py_DECREF(v);
327 }
328 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 /* Finally set the new f_lineno and f_lasti and return OK. */
331 f->f_lineno = new_lineno;
332 f->f_lasti = new_lasti;
333 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000334}
335
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000336static PyObject *
337frame_gettrace(PyFrameObject *f, void *closure)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (trace == NULL)
342 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000347}
348
349static int
350frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* We rely on f_lineno being accurate when f_trace is set. */
353 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000354
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300355 if (v == Py_None)
356 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 Py_XINCREF(v);
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300358 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000361}
362
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000363
Guido van Rossum32d34c82001-09-20 21:45:26 +0000364static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 {"f_locals", (getter)frame_getlocals, NULL, NULL},
366 {"f_lineno", (getter)frame_getlineno,
367 (setter)frame_setlineno, NULL},
368 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
369 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000370};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000371
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000372/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 In an attempt to improve the speed of function calls, we:
374
375 1. Hold a single "zombie" frame on each code object. This retains
376 the allocated and initialised frame object from an invocation of
377 the code object. The zombie is reanimated the next time we need a
378 frame object for that code object. Doing this saves the malloc/
379 realloc required when using a free_list frame that isn't the
380 correct size. It also saves some field initialisation.
381
382 In zombie mode, no field of PyFrameObject holds a reference, but
383 the following fields are still valid:
384
385 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386
Thomas Wouters477c8d52006-05-27 19:21:47 +0000387 * f_locals, f_trace,
388 f_exc_type, f_exc_value, f_exc_traceback are NULL;
389
390 * f_localsplus does not require re-allocation and
391 the local variables in f_localsplus are NULL.
392
393 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000394 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000395 a stack frame is on the free list, only the following members have
396 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 ob_type == &Frametype
398 f_back next item on free list, or NULL
399 f_stacksize size of value stack
400 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000401 Note that the value and block stacks are preserved -- this can save
402 another malloc() call or two (and two free() calls as well!).
403 Also note that, unlike for integers, each frame object is a
404 malloc'ed object in its own right -- it is only the actual calls to
405 malloc() that we are trying to save here, not the administration.
406 After all, while a typical program may make millions of calls, a
407 call depth of more than 20 or 30 is probably already exceptional
408 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000409
Christian Heimes2202f872008-02-06 14:31:34 +0000410 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000411 free_list. Else programs creating lots of cyclic trash involving
412 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000413*/
414
Guido van Rossum18752471997-04-29 14:49:28 +0000415static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000417/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000419
Guido van Rossum3f5da241990-12-20 15:06:42 +0000420static void
Fred Drake1b190b42000-07-09 05:40:56 +0000421frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000422{
Antoine Pitrou93963562013-05-14 20:37:52 +0200423 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyObject_GC_UnTrack(f);
427 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200428 /* Kill all local variables */
429 valuestack = f->f_valuestack;
430 for (p = f->f_localsplus; p < valuestack; p++)
431 Py_CLEAR(*p);
432
433 /* Free stack */
434 if (f->f_stacktop != NULL) {
435 for (p = valuestack; p < f->f_stacktop; p++)
436 Py_XDECREF(*p);
437 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 Py_XDECREF(f->f_back);
440 Py_DECREF(f->f_builtins);
441 Py_DECREF(f->f_globals);
442 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200443 Py_CLEAR(f->f_trace);
444 Py_CLEAR(f->f_exc_type);
445 Py_CLEAR(f->f_exc_value);
446 Py_CLEAR(f->f_exc_traceback);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 co = f->f_code;
449 if (co->co_zombieframe == NULL)
450 co->co_zombieframe = f;
451 else if (numfree < PyFrame_MAXFREELIST) {
452 ++numfree;
453 f->f_back = free_list;
454 free_list = f;
455 }
456 else
457 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 Py_DECREF(co);
460 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000461}
462
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000463static int
464frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100467 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_VISIT(f->f_back);
470 Py_VISIT(f->f_code);
471 Py_VISIT(f->f_builtins);
472 Py_VISIT(f->f_globals);
473 Py_VISIT(f->f_locals);
474 Py_VISIT(f->f_trace);
475 Py_VISIT(f->f_exc_type);
476 Py_VISIT(f->f_exc_value);
477 Py_VISIT(f->f_exc_traceback);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 /* locals */
480 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
481 fastlocals = f->f_localsplus;
482 for (i = slots; --i >= 0; ++fastlocals)
483 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* stack */
486 if (f->f_stacktop != NULL) {
487 for (p = f->f_valuestack; p < f->f_stacktop; p++)
488 Py_VISIT(*p);
489 }
490 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000491}
492
493static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200494frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100497 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000498
Antoine Pitrou93963562013-05-14 20:37:52 +0200499 /* Before anything else, make sure that this frame is clearly marked
500 * as being defunct! Else, e.g., a generator reachable from this
501 * frame may also point to this frame, believe itself to still be
502 * active, and try cleaning up this frame again.
503 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 oldtop = f->f_stacktop;
505 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200506 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 Py_CLEAR(f->f_exc_type);
509 Py_CLEAR(f->f_exc_value);
510 Py_CLEAR(f->f_exc_traceback);
511 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 /* locals */
514 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
515 fastlocals = f->f_localsplus;
516 for (i = slots; --i >= 0; ++fastlocals)
517 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 /* stack */
520 if (oldtop != NULL) {
521 for (p = f->f_valuestack; p < oldtop; p++)
522 Py_CLEAR(*p);
523 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000524}
525
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000526static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200527frame_clear(PyFrameObject *f)
528{
529 if (f->f_executing) {
530 PyErr_SetString(PyExc_RuntimeError,
531 "cannot clear an executing frame");
532 return NULL;
533 }
534 if (f->f_gen) {
535 _PyGen_Finalize(f->f_gen);
536 assert(f->f_gen == NULL);
537 }
538 frame_tp_clear(f);
539 Py_RETURN_NONE;
540}
541
542PyDoc_STRVAR(clear__doc__,
543"F.clear(): clear most references held by the frame");
544
545static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000546frame_sizeof(PyFrameObject *f)
547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
551 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
552 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
553 ncells + nfrees;
554 /* subtract one as it is already included in PyFrameObject */
555 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000558}
559
560PyDoc_STRVAR(sizeof__doc__,
561"F.__sizeof__() -> size of F in memory, in bytes");
562
563static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200564 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
565 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
567 sizeof__doc__},
568 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000569};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000570
Guido van Rossum18752471997-04-29 14:49:28 +0000571PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 PyVarObject_HEAD_INIT(&PyType_Type, 0)
573 "frame",
574 sizeof(PyFrameObject),
575 sizeof(PyObject *),
576 (destructor)frame_dealloc, /* tp_dealloc */
577 0, /* tp_print */
578 0, /* tp_getattr */
579 0, /* tp_setattr */
580 0, /* tp_reserved */
581 0, /* tp_repr */
582 0, /* tp_as_number */
583 0, /* tp_as_sequence */
584 0, /* tp_as_mapping */
585 0, /* tp_hash */
586 0, /* tp_call */
587 0, /* tp_str */
588 PyObject_GenericGetAttr, /* tp_getattro */
589 PyObject_GenericSetAttr, /* tp_setattro */
590 0, /* tp_as_buffer */
591 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
592 0, /* tp_doc */
593 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200594 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 0, /* tp_richcompare */
596 0, /* tp_weaklistoffset */
597 0, /* tp_iter */
598 0, /* tp_iternext */
599 frame_methods, /* tp_methods */
600 frame_memberlist, /* tp_members */
601 frame_getsetlist, /* tp_getset */
602 0, /* tp_base */
603 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000604};
605
Victor Stinner07e9e382013-11-07 22:22:39 +0100606_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000607
Neal Norwitzb2501f42002-12-31 03:42:13 +0000608int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000609{
Victor Stinner07e9e382013-11-07 22:22:39 +0100610 /* Before, PyId___builtins__ was a string created explicitly in
611 this function. Now there is nothing to initialize anymore, but
612 the function is kept for backward compatibility. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000614}
615
Guido van Rossum18752471997-04-29 14:49:28 +0000616PyFrameObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000617PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 PyFrameObject *back = tstate->frame;
621 PyFrameObject *f;
622 PyObject *builtins;
623 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000624
Michael W. Hudson69734a52002-08-19 16:54:08 +0000625#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
627 (locals != NULL && !PyMapping_Check(locals))) {
628 PyErr_BadInternalCall();
629 return NULL;
630 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000631#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100633 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (builtins) {
635 if (PyModule_Check(builtins)) {
636 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200637 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 }
640 if (builtins == NULL) {
641 /* No builtins! Make up a minimal one
642 Give them 'None', at least. */
643 builtins = PyDict_New();
644 if (builtins == NULL ||
645 PyDict_SetItemString(
646 builtins, "None", Py_None) < 0)
647 return NULL;
648 }
649 else
650 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 }
653 else {
654 /* If we share the globals, we share the builtins.
655 Save a lookup and a call. */
656 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200657 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 Py_INCREF(builtins);
659 }
660 if (code->co_zombieframe != NULL) {
661 f = code->co_zombieframe;
662 code->co_zombieframe = NULL;
663 _Py_NewReference((PyObject *)f);
664 assert(f->f_code == code);
665 }
666 else {
667 Py_ssize_t extras, ncells, nfrees;
668 ncells = PyTuple_GET_SIZE(code->co_cellvars);
669 nfrees = PyTuple_GET_SIZE(code->co_freevars);
670 extras = code->co_stacksize + code->co_nlocals + ncells +
671 nfrees;
672 if (free_list == NULL) {
673 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
674 extras);
675 if (f == NULL) {
676 Py_DECREF(builtins);
677 return NULL;
678 }
679 }
680 else {
681 assert(numfree > 0);
682 --numfree;
683 f = free_list;
684 free_list = free_list->f_back;
685 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000686 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
687 if (new_f == NULL) {
688 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_DECREF(builtins);
690 return NULL;
691 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000692 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 }
694 _Py_NewReference((PyObject *)f);
695 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 f->f_code = code;
698 extras = code->co_nlocals + ncells + nfrees;
699 f->f_valuestack = f->f_localsplus + extras;
700 for (i=0; i<extras; i++)
701 f->f_localsplus[i] = NULL;
702 f->f_locals = NULL;
703 f->f_trace = NULL;
704 f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
705 }
706 f->f_stacktop = f->f_valuestack;
707 f->f_builtins = builtins;
708 Py_XINCREF(back);
709 f->f_back = back;
710 Py_INCREF(code);
711 Py_INCREF(globals);
712 f->f_globals = globals;
713 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
714 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
715 (CO_NEWLOCALS | CO_OPTIMIZED))
716 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
717 else if (code->co_flags & CO_NEWLOCALS) {
718 locals = PyDict_New();
719 if (locals == NULL) {
720 Py_DECREF(f);
721 return NULL;
722 }
723 f->f_locals = locals;
724 }
725 else {
726 if (locals == NULL)
727 locals = globals;
728 Py_INCREF(locals);
729 f->f_locals = locals;
730 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 f->f_lasti = -1;
733 f->f_lineno = code->co_firstlineno;
734 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200735 f->f_executing = 0;
736 f->f_gen = NULL;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 _PyObject_GC_TRACK(f);
739 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000740}
741
Guido van Rossum3f5da241990-12-20 15:06:42 +0000742/* Block management */
743
744void
Fred Drake1b190b42000-07-09 05:40:56 +0000745PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyTryBlock *b;
748 if (f->f_iblock >= CO_MAXBLOCKS)
749 Py_FatalError("XXX block stack overflow");
750 b = &f->f_blockstack[f->f_iblock++];
751 b->b_type = type;
752 b->b_level = level;
753 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000754}
755
Guido van Rossum18752471997-04-29 14:49:28 +0000756PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000757PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 PyTryBlock *b;
760 if (f->f_iblock <= 0)
761 Py_FatalError("XXX block stack underflow");
762 b = &f->f_blockstack[--f->f_iblock];
763 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000764}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000765
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767
768 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769 values is an array of PyObject*. At index i, map[i] is the name of
770 the variable with value values[i]. The function copies the first
771 nmap variable from map/values into dict. If values[i] is NULL,
772 the variable is deleted from dict.
773
774 If deref is true, then the values being copied are cell variables
775 and the value is extracted from the cell variable before being put
776 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000778
Victor Stinner41bb43a2013-10-29 01:19:37 +0100779static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000780map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 Py_ssize_t j;
784 assert(PyTuple_Check(map));
785 assert(PyDict_Check(dict));
786 assert(PyTuple_Size(map) >= nmap);
787 for (j = nmap; --j >= 0; ) {
788 PyObject *key = PyTuple_GET_ITEM(map, j);
789 PyObject *value = values[j];
790 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400791 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(PyCell_Check(value));
793 value = PyCell_GET(value);
794 }
795 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100796 if (PyObject_DelItem(dict, key) != 0) {
797 if (PyErr_ExceptionMatches(PyExc_KeyError))
798 PyErr_Clear();
799 else
800 return -1;
801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 }
803 else {
804 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100805 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 }
807 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100808 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000809}
810
Guido van Rossumd8faa362007-04-27 19:54:29 +0000811/* Copy values from the "locals" dict into the fast locals.
812
813 dict is an input argument containing string keys representing
814 variables names and arbitrary PyObject* as values.
815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000817 values is an array of PyObject*. At index i, map[i] is the name of
818 the variable with value values[i]. The function copies the first
819 nmap variable from map/values into dict. If values[i] is NULL,
820 the variable is deleted from dict.
821
822 If deref is true, then the values being copied are cell variables
823 and the value is extracted from the cell variable before being put
824 in dict. If clear is true, then variables in map but not in dict
825 are set to NULL in map; if clear is false, variables missing in
826 dict are ignored.
827
828 Exceptions raised while modifying the dict are silently ignored,
829 because there is no good way to report them.
830*/
831
Guido van Rossum6b356e72001-04-14 17:55:41 +0000832static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000833dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 Py_ssize_t j;
837 assert(PyTuple_Check(map));
838 assert(PyDict_Check(dict));
839 assert(PyTuple_Size(map) >= nmap);
840 for (j = nmap; --j >= 0; ) {
841 PyObject *key = PyTuple_GET_ITEM(map, j);
842 PyObject *value = PyObject_GetItem(dict, key);
843 assert(PyUnicode_Check(key));
844 /* We only care about NULLs if clear is true. */
845 if (value == NULL) {
846 PyErr_Clear();
847 if (!clear)
848 continue;
849 }
850 if (deref) {
851 assert(PyCell_Check(values[j]));
852 if (PyCell_GET(values[j]) != value) {
853 if (PyCell_Set(values[j], value) < 0)
854 PyErr_Clear();
855 }
856 } else if (values[j] != value) {
857 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300858 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 }
860 Py_XDECREF(value);
861 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000862}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000863
Victor Stinner41bb43a2013-10-29 01:19:37 +0100864int
865PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Merge fast locals into f->f_locals */
868 PyObject *locals, *map;
869 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyCodeObject *co;
871 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100872 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100873
874 if (f == NULL) {
875 PyErr_BadInternalCall();
876 return -1;
877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 locals = f->f_locals;
879 if (locals == NULL) {
880 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100881 if (locals == NULL)
882 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 }
884 co = f->f_code;
885 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100886 if (!PyTuple_Check(map)) {
887 PyErr_Format(PyExc_SystemError,
888 "co_varnames must be a tuple, not %s",
889 Py_TYPE(map)->tp_name);
890 return -1;
891 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 fast = f->f_localsplus;
893 j = PyTuple_GET_SIZE(map);
894 if (j > co->co_nlocals)
895 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100896 if (co->co_nlocals) {
897 if (map_to_dict(map, j, locals, fast, 0) < 0)
898 return -1;
899 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 ncells = PyTuple_GET_SIZE(co->co_cellvars);
901 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
902 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100903 if (map_to_dict(co->co_cellvars, ncells,
904 locals, fast + co->co_nlocals, 1))
905 return -1;
906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* If the namespace is unoptimized, then one of the
908 following cases applies:
909 1. It does not contain free variables, because it
910 uses import * or is a top-level namespace.
911 2. It is a class namespace.
912 We don't want to accidentally copy free variables
913 into the locals dict used by the class.
914 */
915 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100916 if (map_to_dict(co->co_freevars, nfreevars,
917 locals, fast + co->co_nlocals + ncells, 1) < 0)
918 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 }
920 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100921 return 0;
922}
923
924void
925PyFrame_FastToLocals(PyFrameObject *f)
926{
927 int res;
928
929 assert(!PyErr_Occurred());
930
931 res = PyFrame_FastToLocalsWithError(f);
932 if (res < 0)
933 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000934}
935
936void
Fred Drake1b190b42000-07-09 05:40:56 +0000937PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* Merge f->f_locals into fast locals */
940 PyObject *locals, *map;
941 PyObject **fast;
942 PyObject *error_type, *error_value, *error_traceback;
943 PyCodeObject *co;
944 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100945 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (f == NULL)
947 return;
948 locals = f->f_locals;
949 co = f->f_code;
950 map = co->co_varnames;
951 if (locals == NULL)
952 return;
953 if (!PyTuple_Check(map))
954 return;
955 PyErr_Fetch(&error_type, &error_value, &error_traceback);
956 fast = f->f_localsplus;
957 j = PyTuple_GET_SIZE(map);
958 if (j > co->co_nlocals)
959 j = co->co_nlocals;
960 if (co->co_nlocals)
961 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
962 ncells = PyTuple_GET_SIZE(co->co_cellvars);
963 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
964 if (ncells || nfreevars) {
965 dict_to_map(co->co_cellvars, ncells,
966 locals, fast + co->co_nlocals, 1, clear);
967 /* Same test as in PyFrame_FastToLocals() above. */
968 if (co->co_flags & CO_OPTIMIZED) {
969 dict_to_map(co->co_freevars, nfreevars,
970 locals, fast + co->co_nlocals + ncells, 1,
971 clear);
972 }
973 }
974 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000975}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000976
977/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000978int
979PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 int freelist_size = numfree;
982
983 while (free_list != NULL) {
984 PyFrameObject *f = free_list;
985 free_list = free_list->f_back;
986 PyObject_GC_Del(f);
987 --numfree;
988 }
989 assert(numfree == 0);
990 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000991}
992
993void
994PyFrame_Fini(void)
995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000997}
David Malcolm49526f42012-06-22 14:55:41 -0400998
999/* Print summary info about the state of the optimized allocator */
1000void
1001_PyFrame_DebugMallocStats(FILE *out)
1002{
1003 _PyDebugAllocatorStats(out,
1004 "free PyFrameObject",
1005 numfree, sizeof(PyFrameObject));
1006}
1007