blob: d308457b7547d16da6c88a0c91dfbc13ed819d66 [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
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020048
49/* Given the index of the effective opcode,
50 scan back to construct the oparg with EXTENDED_ARG */
51static unsigned int
52get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
53{
54 _Py_CODEUNIT word;
55 unsigned int oparg = _Py_OPARG(codestr[i]);
56 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
57 oparg |= _Py_OPARG(word) << 8;
58 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
59 oparg |= _Py_OPARG(word) << 16;
60 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
61 oparg |= _Py_OPARG(word) << 24;
62 }
63 }
64 }
65 return oparg;
66}
67
68
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000069/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000071 * lines are OK to jump to because they don't make any assumptions about the
72 * state of the stack (obvious because you could remove the line and the code
73 * would still work without any stack errors), but there are some constructs
74 * that limit jumping:
75 *
76 * o Lines with an 'except' statement on them can't be jumped to, because
77 * they expect an exception to be on the top of the stack.
78 * o Lines that live in a 'finally' block can't be jumped from or to, since
79 * the END_FINALLY expects to clean up the stack after the 'try' block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020080 * o 'try', 'with' and 'async with' blocks can't be jumped into because
81 * the blockstack needs to be set up before their code runs.
82 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000083 * iterator needs to be on the stack.
84 */
85static int
86frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
87{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 int new_lineno = 0; /* The new value of f_lineno */
89 long l_new_lineno;
90 int overflow;
91 int new_lasti = 0; /* The new value of f_lasti */
92 int new_iblock = 0; /* The new value of f_iblock */
93 unsigned char *code = NULL; /* The bytecode for the frame... */
94 Py_ssize_t code_len = 0; /* ...and its length */
95 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
96 Py_ssize_t lnotab_len = 0; /* (ditto) */
97 int offset = 0; /* (ditto) */
98 int line = 0; /* (ditto) */
99 int addr = 0; /* (ditto) */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200100 int delta_iblock = 0; /* Scanning the SETUPs and POPs */
101 int for_loop_delta = 0; /* (ditto) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 int blockstack_top = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 /* f_lineno must be an integer. */
106 if (!PyLong_CheckExact(p_new_lineno)) {
107 PyErr_SetString(PyExc_ValueError,
108 "lineno must be an integer");
109 return -1;
110 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 /* You can only do this from within a trace function, not via
113 * _getframe or similar hackery. */
114 if (!f->f_trace)
115 {
116 PyErr_Format(PyExc_ValueError,
117 "f_lineno can only be set by a"
118 " line trace function");
119 return -1;
120 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 /* Fail if the line comes before the start of the code block. */
123 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
124 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000125#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 || l_new_lineno > INT_MAX
127 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000128#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 ) {
130 PyErr_SetString(PyExc_ValueError,
131 "lineno out of range");
132 return -1;
133 }
134 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 if (new_lineno < f->f_code->co_firstlineno) {
137 PyErr_Format(PyExc_ValueError,
138 "line %d comes before the current code block",
139 new_lineno);
140 return -1;
141 }
142 else if (new_lineno == f->f_code->co_firstlineno) {
143 new_lasti = 0;
144 new_lineno = f->f_code->co_firstlineno;
145 }
146 else {
147 /* Find the bytecode offset for the start of the given
148 * line, or the first code-owning line after it. */
149 char *tmp;
150 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
151 &tmp, &lnotab_len);
152 lnotab = (unsigned char *) tmp;
153 addr = 0;
154 line = f->f_code->co_firstlineno;
155 new_lasti = -1;
156 for (offset = 0; offset < lnotab_len; offset += 2) {
157 addr += lnotab[offset];
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100158 line += (signed char)lnotab[offset+1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 if (line >= new_lineno) {
160 new_lasti = addr;
161 new_lineno = line;
162 break;
163 }
164 }
165 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 /* If we didn't reach the requested line, return an error. */
168 if (new_lasti == -1) {
169 PyErr_Format(PyExc_ValueError,
170 "line %d comes after the current code block",
171 new_lineno);
172 return -1;
173 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 /* We're now ready to look at the bytecode. */
176 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* You can't jump onto a line with an 'except' statement on it -
179 * they expect to have an exception on the top of the stack, which
180 * won't be true if you jump to them. They always start with code
181 * that either pops the exception using POP_TOP (plain 'except:'
182 * lines do this) or duplicates the exception on the stack using
183 * DUP_TOP (if there's an exception type specified). See compile.c,
184 * 'com_try_except' for the full details. There aren't any other
185 * cases (AFAIK) where a line's code can start with DUP_TOP or
186 * POP_TOP, but if any ever appear, they'll be subject to the same
187 * restriction (but with a different error message). */
188 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
189 PyErr_SetString(PyExc_ValueError,
190 "can't jump to 'except' line as there's no exception");
191 return -1;
192 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* You can't jump into or out of a 'finally' block because the 'try'
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200195 * block leaves something on the stack for the END_FINALLY to clean up.
196 * So we walk the bytecode, maintaining a simulated blockstack.
197 * 'blockstack' is a stack of the bytecode addresses of the starts of
198 * the 'finally' blocks. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 memset(blockstack, '\0', sizeof(blockstack));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 blockstack_top = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300201 for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 unsigned char op = code[addr];
203 switch (op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400205 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400206 case SETUP_ASYNC_WITH:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200207 case FOR_ITER: {
208 unsigned int oparg = get_arg((const _Py_CODEUNIT *)code,
209 addr / sizeof(_Py_CODEUNIT));
210 int target_addr = addr + oparg + sizeof(_Py_CODEUNIT);
211 assert(target_addr < code_len);
212 /* Police block-jumping (you can't jump into the middle of a block)
213 * and ensure that the blockstack finishes up in a sensible state (by
214 * popping any blocks we're jumping out of). We look at all the
215 * blockstack operations between the current position and the new
216 * one, and keep track of how many blocks we drop out of on the way.
217 * By also keeping track of the lowest blockstack position we see, we
218 * can tell whether the jump goes into any blocks without coming out
219 * again - in that case we raise an exception below. */
220 int first_in = addr < f->f_lasti && f->f_lasti < target_addr;
221 int second_in = addr < new_lasti && new_lasti < target_addr;
222 if (!first_in && second_in) {
223 PyErr_SetString(PyExc_ValueError,
224 "can't jump into the middle of a block");
225 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200227 if (first_in && !second_in) {
228 if (op == FOR_ITER && !delta_iblock) {
229 for_loop_delta++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200231 if (op != FOR_ITER) {
232 delta_iblock++;
233 }
234 }
235 if (op != FOR_ITER) {
236 blockstack[blockstack_top++] = target_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 }
238 break;
239 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000240
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200241 case END_FINALLY: {
242 assert(blockstack_top > 0);
243 int target_addr = blockstack[--blockstack_top];
244 assert(target_addr <= addr);
245 int first_in = target_addr <= f->f_lasti && f->f_lasti <= addr;
246 int second_in = target_addr <= new_lasti && new_lasti <= addr;
247 if (first_in != second_in) {
248 PyErr_SetString(PyExc_ValueError,
249 "can't jump into or out of a 'finally' block");
250 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200252 break;
253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 /* Verify that the blockstack tracking code didn't get lost. */
258 assert(blockstack_top == 0);
259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 /* Pop any blocks that we're jumping out of. */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200261 new_iblock = f->f_iblock - delta_iblock;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 while (f->f_iblock > new_iblock) {
263 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
264 while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
265 PyObject *v = (*--f->f_stacktop);
266 Py_DECREF(v);
267 }
268 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200269 /* Pop the iterators of any 'for' loop we're jumping out of. */
270 while (for_loop_delta > 0) {
271 PyObject *v = (*--f->f_stacktop);
272 Py_DECREF(v);
273 for_loop_delta--;
274 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Finally set the new f_lineno and f_lasti and return OK. */
277 f->f_lineno = new_lineno;
278 f->f_lasti = new_lasti;
279 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000280}
281
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000282static PyObject *
283frame_gettrace(PyFrameObject *f, void *closure)
284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 if (trace == NULL)
288 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000293}
294
295static int
296frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* We rely on f_lineno being accurate when f_trace is set. */
299 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000300
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300301 if (v == Py_None)
302 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300304 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000307}
308
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000309
Guido van Rossum32d34c82001-09-20 21:45:26 +0000310static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 {"f_locals", (getter)frame_getlocals, NULL, NULL},
312 {"f_lineno", (getter)frame_getlineno,
313 (setter)frame_setlineno, NULL},
314 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
315 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000316};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000317
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000318/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000319 In an attempt to improve the speed of function calls, we:
320
321 1. Hold a single "zombie" frame on each code object. This retains
322 the allocated and initialised frame object from an invocation of
323 the code object. The zombie is reanimated the next time we need a
324 frame object for that code object. Doing this saves the malloc/
325 realloc required when using a free_list frame that isn't the
326 correct size. It also saves some field initialisation.
327
328 In zombie mode, no field of PyFrameObject holds a reference, but
329 the following fields are still valid:
330
331 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332
Mark Shannonae3087c2017-10-22 22:41:51 +0100333 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000334
335 * f_localsplus does not require re-allocation and
336 the local variables in f_localsplus are NULL.
337
338 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000339 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340 a stack frame is on the free list, only the following members have
341 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 ob_type == &Frametype
343 f_back next item on free list, or NULL
344 f_stacksize size of value stack
345 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000346 Note that the value and block stacks are preserved -- this can save
347 another malloc() call or two (and two free() calls as well!).
348 Also note that, unlike for integers, each frame object is a
349 malloc'ed object in its own right -- it is only the actual calls to
350 malloc() that we are trying to save here, not the administration.
351 After all, while a typical program may make millions of calls, a
352 call depth of more than 20 or 30 is probably already exceptional
353 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000354
Christian Heimes2202f872008-02-06 14:31:34 +0000355 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000356 free_list. Else programs creating lots of cyclic trash involving
357 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000358*/
359
Guido van Rossum18752471997-04-29 14:49:28 +0000360static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000362/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000364
Victor Stinnerc6944e72016-11-11 02:13:35 +0100365static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000366frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000367{
Antoine Pitrou93963562013-05-14 20:37:52 +0200368 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000370
INADA Naoki5a625d02016-12-24 20:19:08 +0900371 if (_PyObject_GC_IS_TRACKED(f))
372 _PyObject_GC_UNTRACK(f);
373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200375 /* Kill all local variables */
376 valuestack = f->f_valuestack;
377 for (p = f->f_localsplus; p < valuestack; p++)
378 Py_CLEAR(*p);
379
380 /* Free stack */
381 if (f->f_stacktop != NULL) {
382 for (p = valuestack; p < f->f_stacktop; p++)
383 Py_XDECREF(*p);
384 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 Py_XDECREF(f->f_back);
387 Py_DECREF(f->f_builtins);
388 Py_DECREF(f->f_globals);
389 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200390 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 co = f->f_code;
393 if (co->co_zombieframe == NULL)
394 co->co_zombieframe = f;
395 else if (numfree < PyFrame_MAXFREELIST) {
396 ++numfree;
397 f->f_back = free_list;
398 free_list = f;
399 }
400 else
401 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 Py_DECREF(co);
404 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000405}
406
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000407static int
408frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100411 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 Py_VISIT(f->f_back);
414 Py_VISIT(f->f_code);
415 Py_VISIT(f->f_builtins);
416 Py_VISIT(f->f_globals);
417 Py_VISIT(f->f_locals);
418 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 /* locals */
421 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
422 fastlocals = f->f_localsplus;
423 for (i = slots; --i >= 0; ++fastlocals)
424 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 /* stack */
427 if (f->f_stacktop != NULL) {
428 for (p = f->f_valuestack; p < f->f_stacktop; p++)
429 Py_VISIT(*p);
430 }
431 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000432}
433
434static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200435frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100438 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000439
Antoine Pitrou93963562013-05-14 20:37:52 +0200440 /* Before anything else, make sure that this frame is clearly marked
441 * as being defunct! Else, e.g., a generator reachable from this
442 * frame may also point to this frame, believe itself to still be
443 * active, and try cleaning up this frame again.
444 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 oldtop = f->f_stacktop;
446 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200447 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* locals */
452 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
453 fastlocals = f->f_localsplus;
454 for (i = slots; --i >= 0; ++fastlocals)
455 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* stack */
458 if (oldtop != NULL) {
459 for (p = f->f_valuestack; p < oldtop; p++)
460 Py_CLEAR(*p);
461 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000462}
463
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000464static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200465frame_clear(PyFrameObject *f)
466{
467 if (f->f_executing) {
468 PyErr_SetString(PyExc_RuntimeError,
469 "cannot clear an executing frame");
470 return NULL;
471 }
472 if (f->f_gen) {
473 _PyGen_Finalize(f->f_gen);
474 assert(f->f_gen == NULL);
475 }
476 frame_tp_clear(f);
477 Py_RETURN_NONE;
478}
479
480PyDoc_STRVAR(clear__doc__,
481"F.clear(): clear most references held by the frame");
482
483static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000484frame_sizeof(PyFrameObject *f)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
489 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
490 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
491 ncells + nfrees;
492 /* subtract one as it is already included in PyFrameObject */
493 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000496}
497
498PyDoc_STRVAR(sizeof__doc__,
499"F.__sizeof__() -> size of F in memory, in bytes");
500
Antoine Pitrou14709142017-12-31 22:35:22 +0100501static PyObject *
502frame_repr(PyFrameObject *f)
503{
504 int lineno = PyFrame_GetLineNumber(f);
505 return PyUnicode_FromFormat(
506 "<frame at %p, file %R, line %d, code %S>",
507 f, f->f_code->co_filename, lineno, f->f_code->co_name);
508}
509
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000510static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200511 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
512 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
514 sizeof__doc__},
515 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000516};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000517
Guido van Rossum18752471997-04-29 14:49:28 +0000518PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 PyVarObject_HEAD_INIT(&PyType_Type, 0)
520 "frame",
521 sizeof(PyFrameObject),
522 sizeof(PyObject *),
523 (destructor)frame_dealloc, /* tp_dealloc */
524 0, /* tp_print */
525 0, /* tp_getattr */
526 0, /* tp_setattr */
527 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100528 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 0, /* tp_as_number */
530 0, /* tp_as_sequence */
531 0, /* tp_as_mapping */
532 0, /* tp_hash */
533 0, /* tp_call */
534 0, /* tp_str */
535 PyObject_GenericGetAttr, /* tp_getattro */
536 PyObject_GenericSetAttr, /* tp_setattro */
537 0, /* tp_as_buffer */
538 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
539 0, /* tp_doc */
540 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200541 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 0, /* tp_richcompare */
543 0, /* tp_weaklistoffset */
544 0, /* tp_iter */
545 0, /* tp_iternext */
546 frame_methods, /* tp_methods */
547 frame_memberlist, /* tp_members */
548 frame_getsetlist, /* tp_getset */
549 0, /* tp_base */
550 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000551};
552
Victor Stinner07e9e382013-11-07 22:22:39 +0100553_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000554
Neal Norwitzb2501f42002-12-31 03:42:13 +0000555int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000556{
Victor Stinner07e9e382013-11-07 22:22:39 +0100557 /* Before, PyId___builtins__ was a string created explicitly in
558 this function. Now there is nothing to initialize anymore, but
559 the function is kept for backward compatibility. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000561}
562
Victor Stinnerc6944e72016-11-11 02:13:35 +0100563PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900564_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
565 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyFrameObject *back = tstate->frame;
568 PyFrameObject *f;
569 PyObject *builtins;
570 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000571
Michael W. Hudson69734a52002-08-19 16:54:08 +0000572#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
574 (locals != NULL && !PyMapping_Check(locals))) {
575 PyErr_BadInternalCall();
576 return NULL;
577 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000578#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100580 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (builtins) {
582 if (PyModule_Check(builtins)) {
583 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200584 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 }
587 if (builtins == NULL) {
588 /* No builtins! Make up a minimal one
589 Give them 'None', at least. */
590 builtins = PyDict_New();
591 if (builtins == NULL ||
592 PyDict_SetItemString(
593 builtins, "None", Py_None) < 0)
594 return NULL;
595 }
596 else
597 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 }
600 else {
601 /* If we share the globals, we share the builtins.
602 Save a lookup and a call. */
603 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200604 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 Py_INCREF(builtins);
606 }
607 if (code->co_zombieframe != NULL) {
608 f = code->co_zombieframe;
609 code->co_zombieframe = NULL;
610 _Py_NewReference((PyObject *)f);
611 assert(f->f_code == code);
612 }
613 else {
614 Py_ssize_t extras, ncells, nfrees;
615 ncells = PyTuple_GET_SIZE(code->co_cellvars);
616 nfrees = PyTuple_GET_SIZE(code->co_freevars);
617 extras = code->co_stacksize + code->co_nlocals + ncells +
618 nfrees;
619 if (free_list == NULL) {
620 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
621 extras);
622 if (f == NULL) {
623 Py_DECREF(builtins);
624 return NULL;
625 }
626 }
627 else {
628 assert(numfree > 0);
629 --numfree;
630 f = free_list;
631 free_list = free_list->f_back;
632 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000633 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
634 if (new_f == NULL) {
635 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_DECREF(builtins);
637 return NULL;
638 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000639 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 }
641 _Py_NewReference((PyObject *)f);
642 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 f->f_code = code;
645 extras = code->co_nlocals + ncells + nfrees;
646 f->f_valuestack = f->f_localsplus + extras;
647 for (i=0; i<extras; i++)
648 f->f_localsplus[i] = NULL;
649 f->f_locals = NULL;
650 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
652 f->f_stacktop = f->f_valuestack;
653 f->f_builtins = builtins;
654 Py_XINCREF(back);
655 f->f_back = back;
656 Py_INCREF(code);
657 Py_INCREF(globals);
658 f->f_globals = globals;
659 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
660 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
661 (CO_NEWLOCALS | CO_OPTIMIZED))
662 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
663 else if (code->co_flags & CO_NEWLOCALS) {
664 locals = PyDict_New();
665 if (locals == NULL) {
666 Py_DECREF(f);
667 return NULL;
668 }
669 f->f_locals = locals;
670 }
671 else {
672 if (locals == NULL)
673 locals = globals;
674 Py_INCREF(locals);
675 f->f_locals = locals;
676 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 f->f_lasti = -1;
679 f->f_lineno = code->co_firstlineno;
680 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200681 f->f_executing = 0;
682 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000683 f->f_trace_opcodes = 0;
684 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000687}
688
INADA Naoki5a625d02016-12-24 20:19:08 +0900689PyFrameObject*
690PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
691 PyObject *globals, PyObject *locals)
692{
693 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
694 if (f)
695 _PyObject_GC_TRACK(f);
696 return f;
697}
698
699
Guido van Rossum3f5da241990-12-20 15:06:42 +0000700/* Block management */
701
702void
Fred Drake1b190b42000-07-09 05:40:56 +0000703PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyTryBlock *b;
706 if (f->f_iblock >= CO_MAXBLOCKS)
707 Py_FatalError("XXX block stack overflow");
708 b = &f->f_blockstack[f->f_iblock++];
709 b->b_type = type;
710 b->b_level = level;
711 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000712}
713
Guido van Rossum18752471997-04-29 14:49:28 +0000714PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000715PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyTryBlock *b;
718 if (f->f_iblock <= 0)
719 Py_FatalError("XXX block stack underflow");
720 b = &f->f_blockstack[--f->f_iblock];
721 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000722}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000723
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725
726 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727 values is an array of PyObject*. At index i, map[i] is the name of
728 the variable with value values[i]. The function copies the first
729 nmap variable from map/values into dict. If values[i] is NULL,
730 the variable is deleted from dict.
731
732 If deref is true, then the values being copied are cell variables
733 and the value is extracted from the cell variable before being put
734 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000736
Victor Stinner41bb43a2013-10-29 01:19:37 +0100737static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000738map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 Py_ssize_t j;
742 assert(PyTuple_Check(map));
743 assert(PyDict_Check(dict));
744 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800745 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyObject *key = PyTuple_GET_ITEM(map, j);
747 PyObject *value = values[j];
748 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400749 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 assert(PyCell_Check(value));
751 value = PyCell_GET(value);
752 }
753 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100754 if (PyObject_DelItem(dict, key) != 0) {
755 if (PyErr_ExceptionMatches(PyExc_KeyError))
756 PyErr_Clear();
757 else
758 return -1;
759 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 }
761 else {
762 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100763 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 }
765 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100766 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000767}
768
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769/* Copy values from the "locals" dict into the fast locals.
770
771 dict is an input argument containing string keys representing
772 variables names and arbitrary PyObject* as values.
773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775 values is an array of PyObject*. At index i, map[i] is the name of
776 the variable with value values[i]. The function copies the first
777 nmap variable from map/values into dict. If values[i] is NULL,
778 the variable is deleted from dict.
779
780 If deref is true, then the values being copied are cell variables
781 and the value is extracted from the cell variable before being put
782 in dict. If clear is true, then variables in map but not in dict
783 are set to NULL in map; if clear is false, variables missing in
784 dict are ignored.
785
786 Exceptions raised while modifying the dict are silently ignored,
787 because there is no good way to report them.
788*/
789
Guido van Rossum6b356e72001-04-14 17:55:41 +0000790static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000791dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 Py_ssize_t j;
795 assert(PyTuple_Check(map));
796 assert(PyDict_Check(dict));
797 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800798 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyObject *key = PyTuple_GET_ITEM(map, j);
800 PyObject *value = PyObject_GetItem(dict, key);
801 assert(PyUnicode_Check(key));
802 /* We only care about NULLs if clear is true. */
803 if (value == NULL) {
804 PyErr_Clear();
805 if (!clear)
806 continue;
807 }
808 if (deref) {
809 assert(PyCell_Check(values[j]));
810 if (PyCell_GET(values[j]) != value) {
811 if (PyCell_Set(values[j], value) < 0)
812 PyErr_Clear();
813 }
814 } else if (values[j] != value) {
815 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300816 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 }
818 Py_XDECREF(value);
819 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000820}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000821
Victor Stinner41bb43a2013-10-29 01:19:37 +0100822int
823PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 /* Merge fast locals into f->f_locals */
826 PyObject *locals, *map;
827 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyCodeObject *co;
829 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100830 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100831
832 if (f == NULL) {
833 PyErr_BadInternalCall();
834 return -1;
835 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 locals = f->f_locals;
837 if (locals == NULL) {
838 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100839 if (locals == NULL)
840 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 }
842 co = f->f_code;
843 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100844 if (!PyTuple_Check(map)) {
845 PyErr_Format(PyExc_SystemError,
846 "co_varnames must be a tuple, not %s",
847 Py_TYPE(map)->tp_name);
848 return -1;
849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 fast = f->f_localsplus;
851 j = PyTuple_GET_SIZE(map);
852 if (j > co->co_nlocals)
853 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100854 if (co->co_nlocals) {
855 if (map_to_dict(map, j, locals, fast, 0) < 0)
856 return -1;
857 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 ncells = PyTuple_GET_SIZE(co->co_cellvars);
859 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
860 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100861 if (map_to_dict(co->co_cellvars, ncells,
862 locals, fast + co->co_nlocals, 1))
863 return -1;
864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* If the namespace is unoptimized, then one of the
866 following cases applies:
867 1. It does not contain free variables, because it
868 uses import * or is a top-level namespace.
869 2. It is a class namespace.
870 We don't want to accidentally copy free variables
871 into the locals dict used by the class.
872 */
873 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100874 if (map_to_dict(co->co_freevars, nfreevars,
875 locals, fast + co->co_nlocals + ncells, 1) < 0)
876 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 }
878 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100879 return 0;
880}
881
882void
883PyFrame_FastToLocals(PyFrameObject *f)
884{
885 int res;
886
887 assert(!PyErr_Occurred());
888
889 res = PyFrame_FastToLocalsWithError(f);
890 if (res < 0)
891 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000892}
893
894void
Fred Drake1b190b42000-07-09 05:40:56 +0000895PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* Merge f->f_locals into fast locals */
898 PyObject *locals, *map;
899 PyObject **fast;
900 PyObject *error_type, *error_value, *error_traceback;
901 PyCodeObject *co;
902 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100903 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (f == NULL)
905 return;
906 locals = f->f_locals;
907 co = f->f_code;
908 map = co->co_varnames;
909 if (locals == NULL)
910 return;
911 if (!PyTuple_Check(map))
912 return;
913 PyErr_Fetch(&error_type, &error_value, &error_traceback);
914 fast = f->f_localsplus;
915 j = PyTuple_GET_SIZE(map);
916 if (j > co->co_nlocals)
917 j = co->co_nlocals;
918 if (co->co_nlocals)
919 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
920 ncells = PyTuple_GET_SIZE(co->co_cellvars);
921 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
922 if (ncells || nfreevars) {
923 dict_to_map(co->co_cellvars, ncells,
924 locals, fast + co->co_nlocals, 1, clear);
925 /* Same test as in PyFrame_FastToLocals() above. */
926 if (co->co_flags & CO_OPTIMIZED) {
927 dict_to_map(co->co_freevars, nfreevars,
928 locals, fast + co->co_nlocals + ncells, 1,
929 clear);
930 }
931 }
932 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000933}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000934
935/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000936int
937PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 int freelist_size = numfree;
940
941 while (free_list != NULL) {
942 PyFrameObject *f = free_list;
943 free_list = free_list->f_back;
944 PyObject_GC_Del(f);
945 --numfree;
946 }
947 assert(numfree == 0);
948 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000949}
950
951void
952PyFrame_Fini(void)
953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000955}
David Malcolm49526f42012-06-22 14:55:41 -0400956
957/* Print summary info about the state of the optimized allocator */
958void
959_PyFrame_DebugMallocStats(FILE *out)
960{
961 _PyDebugAllocatorStats(out,
962 "free PyFrameObject",
963 numfree, sizeof(PyFrameObject));
964}
965