blob: 31ad8d0be226cee60a9e2c52c4fcd15bf608296c [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 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 unsigned char *code = NULL; /* The bytecode for the frame... */
93 Py_ssize_t code_len = 0; /* ...and its length */
94 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
95 Py_ssize_t lnotab_len = 0; /* (ditto) */
96 int offset = 0; /* (ditto) */
97 int line = 0; /* (ditto) */
98 int addr = 0; /* (ditto) */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020099 int delta_iblock = 0; /* Scanning the SETUPs and POPs */
100 int for_loop_delta = 0; /* (ditto) */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200101 int delta;
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 Storchaka26c9f562018-03-11 08:32:47 +0200261 delta = 0;
262 if (delta_iblock > 0) {
263 f->f_iblock -= delta_iblock;
264 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
265 delta = (f->f_stacktop - f->f_valuestack) - b->b_level;
266 if (b->b_type == SETUP_FINALLY &&
267 code[b->b_handler] == WITH_CLEANUP_START)
268 {
269 /* Pop the exit function. */
270 delta++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 }
272 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200273 /* Pop the iterators of any 'for' loop we're jumping out of. */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200274 delta += for_loop_delta;
275
276 while (delta > 0) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200277 PyObject *v = (*--f->f_stacktop);
278 Py_DECREF(v);
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200279 delta--;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200280 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 /* Finally set the new f_lineno and f_lasti and return OK. */
283 f->f_lineno = new_lineno;
284 f->f_lasti = new_lasti;
285 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000286}
287
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000288static PyObject *
289frame_gettrace(PyFrameObject *f, void *closure)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 if (trace == NULL)
294 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000299}
300
301static int
302frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* We rely on f_lineno being accurate when f_trace is set. */
305 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000306
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300307 if (v == Py_None)
308 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300310 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000313}
314
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000315
Guido van Rossum32d34c82001-09-20 21:45:26 +0000316static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 {"f_locals", (getter)frame_getlocals, NULL, NULL},
318 {"f_lineno", (getter)frame_getlineno,
319 (setter)frame_setlineno, NULL},
320 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
321 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000322};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000323
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000324/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325 In an attempt to improve the speed of function calls, we:
326
327 1. Hold a single "zombie" frame on each code object. This retains
328 the allocated and initialised frame object from an invocation of
329 the code object. The zombie is reanimated the next time we need a
330 frame object for that code object. Doing this saves the malloc/
331 realloc required when using a free_list frame that isn't the
332 correct size. It also saves some field initialisation.
333
334 In zombie mode, no field of PyFrameObject holds a reference, but
335 the following fields are still valid:
336
337 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338
Mark Shannonae3087c2017-10-22 22:41:51 +0100339 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340
341 * f_localsplus does not require re-allocation and
342 the local variables in f_localsplus are NULL.
343
344 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000345 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000346 a stack frame is on the free list, only the following members have
347 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 ob_type == &Frametype
349 f_back next item on free list, or NULL
350 f_stacksize size of value stack
351 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000352 Note that the value and block stacks are preserved -- this can save
353 another malloc() call or two (and two free() calls as well!).
354 Also note that, unlike for integers, each frame object is a
355 malloc'ed object in its own right -- it is only the actual calls to
356 malloc() that we are trying to save here, not the administration.
357 After all, while a typical program may make millions of calls, a
358 call depth of more than 20 or 30 is probably already exceptional
359 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000360
Christian Heimes2202f872008-02-06 14:31:34 +0000361 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000362 free_list. Else programs creating lots of cyclic trash involving
363 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000364*/
365
Guido van Rossum18752471997-04-29 14:49:28 +0000366static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000368/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000370
Victor Stinnerc6944e72016-11-11 02:13:35 +0100371static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000372frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000373{
Antoine Pitrou93963562013-05-14 20:37:52 +0200374 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000376
INADA Naoki5a625d02016-12-24 20:19:08 +0900377 if (_PyObject_GC_IS_TRACKED(f))
378 _PyObject_GC_UNTRACK(f);
379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200381 /* Kill all local variables */
382 valuestack = f->f_valuestack;
383 for (p = f->f_localsplus; p < valuestack; p++)
384 Py_CLEAR(*p);
385
386 /* Free stack */
387 if (f->f_stacktop != NULL) {
388 for (p = valuestack; p < f->f_stacktop; p++)
389 Py_XDECREF(*p);
390 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 Py_XDECREF(f->f_back);
393 Py_DECREF(f->f_builtins);
394 Py_DECREF(f->f_globals);
395 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200396 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 co = f->f_code;
399 if (co->co_zombieframe == NULL)
400 co->co_zombieframe = f;
401 else if (numfree < PyFrame_MAXFREELIST) {
402 ++numfree;
403 f->f_back = free_list;
404 free_list = f;
405 }
406 else
407 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 Py_DECREF(co);
410 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000411}
412
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000413static int
414frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100417 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 Py_VISIT(f->f_back);
420 Py_VISIT(f->f_code);
421 Py_VISIT(f->f_builtins);
422 Py_VISIT(f->f_globals);
423 Py_VISIT(f->f_locals);
424 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 /* locals */
427 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
428 fastlocals = f->f_localsplus;
429 for (i = slots; --i >= 0; ++fastlocals)
430 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 /* stack */
433 if (f->f_stacktop != NULL) {
434 for (p = f->f_valuestack; p < f->f_stacktop; p++)
435 Py_VISIT(*p);
436 }
437 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000438}
439
440static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200441frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100444 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000445
Antoine Pitrou93963562013-05-14 20:37:52 +0200446 /* Before anything else, make sure that this frame is clearly marked
447 * as being defunct! Else, e.g., a generator reachable from this
448 * frame may also point to this frame, believe itself to still be
449 * active, and try cleaning up this frame again.
450 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 oldtop = f->f_stacktop;
452 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200453 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* locals */
458 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
459 fastlocals = f->f_localsplus;
460 for (i = slots; --i >= 0; ++fastlocals)
461 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* stack */
464 if (oldtop != NULL) {
465 for (p = f->f_valuestack; p < oldtop; p++)
466 Py_CLEAR(*p);
467 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000468}
469
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000470static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200471frame_clear(PyFrameObject *f)
472{
473 if (f->f_executing) {
474 PyErr_SetString(PyExc_RuntimeError,
475 "cannot clear an executing frame");
476 return NULL;
477 }
478 if (f->f_gen) {
479 _PyGen_Finalize(f->f_gen);
480 assert(f->f_gen == NULL);
481 }
482 frame_tp_clear(f);
483 Py_RETURN_NONE;
484}
485
486PyDoc_STRVAR(clear__doc__,
487"F.clear(): clear most references held by the frame");
488
489static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000490frame_sizeof(PyFrameObject *f)
491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
495 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
496 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
497 ncells + nfrees;
498 /* subtract one as it is already included in PyFrameObject */
499 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000502}
503
504PyDoc_STRVAR(sizeof__doc__,
505"F.__sizeof__() -> size of F in memory, in bytes");
506
Antoine Pitrou14709142017-12-31 22:35:22 +0100507static PyObject *
508frame_repr(PyFrameObject *f)
509{
510 int lineno = PyFrame_GetLineNumber(f);
511 return PyUnicode_FromFormat(
512 "<frame at %p, file %R, line %d, code %S>",
513 f, f->f_code->co_filename, lineno, f->f_code->co_name);
514}
515
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000516static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200517 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
518 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
520 sizeof__doc__},
521 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000522};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000523
Guido van Rossum18752471997-04-29 14:49:28 +0000524PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyVarObject_HEAD_INIT(&PyType_Type, 0)
526 "frame",
527 sizeof(PyFrameObject),
528 sizeof(PyObject *),
529 (destructor)frame_dealloc, /* tp_dealloc */
530 0, /* tp_print */
531 0, /* tp_getattr */
532 0, /* tp_setattr */
533 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100534 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 0, /* tp_as_number */
536 0, /* tp_as_sequence */
537 0, /* tp_as_mapping */
538 0, /* tp_hash */
539 0, /* tp_call */
540 0, /* tp_str */
541 PyObject_GenericGetAttr, /* tp_getattro */
542 PyObject_GenericSetAttr, /* tp_setattro */
543 0, /* tp_as_buffer */
544 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
545 0, /* tp_doc */
546 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200547 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 0, /* tp_richcompare */
549 0, /* tp_weaklistoffset */
550 0, /* tp_iter */
551 0, /* tp_iternext */
552 frame_methods, /* tp_methods */
553 frame_memberlist, /* tp_members */
554 frame_getsetlist, /* tp_getset */
555 0, /* tp_base */
556 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000557};
558
Victor Stinner07e9e382013-11-07 22:22:39 +0100559_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000560
Victor Stinnerc6944e72016-11-11 02:13:35 +0100561PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900562_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
563 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 PyFrameObject *back = tstate->frame;
566 PyFrameObject *f;
567 PyObject *builtins;
568 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000569
Michael W. Hudson69734a52002-08-19 16:54:08 +0000570#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
572 (locals != NULL && !PyMapping_Check(locals))) {
573 PyErr_BadInternalCall();
574 return NULL;
575 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000576#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100578 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (builtins) {
580 if (PyModule_Check(builtins)) {
581 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200582 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 }
585 if (builtins == NULL) {
586 /* No builtins! Make up a minimal one
587 Give them 'None', at least. */
588 builtins = PyDict_New();
589 if (builtins == NULL ||
590 PyDict_SetItemString(
591 builtins, "None", Py_None) < 0)
592 return NULL;
593 }
594 else
595 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 }
598 else {
599 /* If we share the globals, we share the builtins.
600 Save a lookup and a call. */
601 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200602 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 Py_INCREF(builtins);
604 }
605 if (code->co_zombieframe != NULL) {
606 f = code->co_zombieframe;
607 code->co_zombieframe = NULL;
608 _Py_NewReference((PyObject *)f);
609 assert(f->f_code == code);
610 }
611 else {
612 Py_ssize_t extras, ncells, nfrees;
613 ncells = PyTuple_GET_SIZE(code->co_cellvars);
614 nfrees = PyTuple_GET_SIZE(code->co_freevars);
615 extras = code->co_stacksize + code->co_nlocals + ncells +
616 nfrees;
617 if (free_list == NULL) {
618 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
619 extras);
620 if (f == NULL) {
621 Py_DECREF(builtins);
622 return NULL;
623 }
624 }
625 else {
626 assert(numfree > 0);
627 --numfree;
628 f = free_list;
629 free_list = free_list->f_back;
630 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000631 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
632 if (new_f == NULL) {
633 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_DECREF(builtins);
635 return NULL;
636 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000637 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
639 _Py_NewReference((PyObject *)f);
640 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 f->f_code = code;
643 extras = code->co_nlocals + ncells + nfrees;
644 f->f_valuestack = f->f_localsplus + extras;
645 for (i=0; i<extras; i++)
646 f->f_localsplus[i] = NULL;
647 f->f_locals = NULL;
648 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 }
650 f->f_stacktop = f->f_valuestack;
651 f->f_builtins = builtins;
652 Py_XINCREF(back);
653 f->f_back = back;
654 Py_INCREF(code);
655 Py_INCREF(globals);
656 f->f_globals = globals;
657 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
658 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
659 (CO_NEWLOCALS | CO_OPTIMIZED))
660 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
661 else if (code->co_flags & CO_NEWLOCALS) {
662 locals = PyDict_New();
663 if (locals == NULL) {
664 Py_DECREF(f);
665 return NULL;
666 }
667 f->f_locals = locals;
668 }
669 else {
670 if (locals == NULL)
671 locals = globals;
672 Py_INCREF(locals);
673 f->f_locals = locals;
674 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 f->f_lasti = -1;
677 f->f_lineno = code->co_firstlineno;
678 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200679 f->f_executing = 0;
680 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000681 f->f_trace_opcodes = 0;
682 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000685}
686
INADA Naoki5a625d02016-12-24 20:19:08 +0900687PyFrameObject*
688PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
689 PyObject *globals, PyObject *locals)
690{
691 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
692 if (f)
693 _PyObject_GC_TRACK(f);
694 return f;
695}
696
697
Guido van Rossum3f5da241990-12-20 15:06:42 +0000698/* Block management */
699
700void
Fred Drake1b190b42000-07-09 05:40:56 +0000701PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyTryBlock *b;
704 if (f->f_iblock >= CO_MAXBLOCKS)
705 Py_FatalError("XXX block stack overflow");
706 b = &f->f_blockstack[f->f_iblock++];
707 b->b_type = type;
708 b->b_level = level;
709 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000710}
711
Guido van Rossum18752471997-04-29 14:49:28 +0000712PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000713PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyTryBlock *b;
716 if (f->f_iblock <= 0)
717 Py_FatalError("XXX block stack underflow");
718 b = &f->f_blockstack[--f->f_iblock];
719 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000720}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000721
Guido van Rossumd8faa362007-04-27 19:54:29 +0000722/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723
724 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000725 values is an array of PyObject*. At index i, map[i] is the name of
726 the variable with value values[i]. The function copies the first
727 nmap variable from map/values into dict. If values[i] is NULL,
728 the variable is deleted from dict.
729
730 If deref is true, then the values being copied are cell variables
731 and the value is extracted from the cell variable before being put
732 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000734
Victor Stinner41bb43a2013-10-29 01:19:37 +0100735static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000736map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 Py_ssize_t j;
740 assert(PyTuple_Check(map));
741 assert(PyDict_Check(dict));
742 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800743 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyObject *key = PyTuple_GET_ITEM(map, j);
745 PyObject *value = values[j];
746 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400747 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 assert(PyCell_Check(value));
749 value = PyCell_GET(value);
750 }
751 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100752 if (PyObject_DelItem(dict, key) != 0) {
753 if (PyErr_ExceptionMatches(PyExc_KeyError))
754 PyErr_Clear();
755 else
756 return -1;
757 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 }
759 else {
760 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100761 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 }
763 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100764 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000765}
766
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767/* Copy values from the "locals" dict into the fast locals.
768
769 dict is an input argument containing string keys representing
770 variables names and arbitrary PyObject* as values.
771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000773 values is an array of PyObject*. At index i, map[i] is the name of
774 the variable with value values[i]. The function copies the first
775 nmap variable from map/values into dict. If values[i] is NULL,
776 the variable is deleted from dict.
777
778 If deref is true, then the values being copied are cell variables
779 and the value is extracted from the cell variable before being put
780 in dict. If clear is true, then variables in map but not in dict
781 are set to NULL in map; if clear is false, variables missing in
782 dict are ignored.
783
784 Exceptions raised while modifying the dict are silently ignored,
785 because there is no good way to report them.
786*/
787
Guido van Rossum6b356e72001-04-14 17:55:41 +0000788static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000789dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 Py_ssize_t j;
793 assert(PyTuple_Check(map));
794 assert(PyDict_Check(dict));
795 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800796 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyObject *key = PyTuple_GET_ITEM(map, j);
798 PyObject *value = PyObject_GetItem(dict, key);
799 assert(PyUnicode_Check(key));
800 /* We only care about NULLs if clear is true. */
801 if (value == NULL) {
802 PyErr_Clear();
803 if (!clear)
804 continue;
805 }
806 if (deref) {
807 assert(PyCell_Check(values[j]));
808 if (PyCell_GET(values[j]) != value) {
809 if (PyCell_Set(values[j], value) < 0)
810 PyErr_Clear();
811 }
812 } else if (values[j] != value) {
813 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300814 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 }
816 Py_XDECREF(value);
817 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000818}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000819
Victor Stinner41bb43a2013-10-29 01:19:37 +0100820int
821PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 /* Merge fast locals into f->f_locals */
824 PyObject *locals, *map;
825 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyCodeObject *co;
827 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100828 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100829
830 if (f == NULL) {
831 PyErr_BadInternalCall();
832 return -1;
833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 locals = f->f_locals;
835 if (locals == NULL) {
836 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100837 if (locals == NULL)
838 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
840 co = f->f_code;
841 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100842 if (!PyTuple_Check(map)) {
843 PyErr_Format(PyExc_SystemError,
844 "co_varnames must be a tuple, not %s",
845 Py_TYPE(map)->tp_name);
846 return -1;
847 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 fast = f->f_localsplus;
849 j = PyTuple_GET_SIZE(map);
850 if (j > co->co_nlocals)
851 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100852 if (co->co_nlocals) {
853 if (map_to_dict(map, j, locals, fast, 0) < 0)
854 return -1;
855 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 ncells = PyTuple_GET_SIZE(co->co_cellvars);
857 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
858 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100859 if (map_to_dict(co->co_cellvars, ncells,
860 locals, fast + co->co_nlocals, 1))
861 return -1;
862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 /* If the namespace is unoptimized, then one of the
864 following cases applies:
865 1. It does not contain free variables, because it
866 uses import * or is a top-level namespace.
867 2. It is a class namespace.
868 We don't want to accidentally copy free variables
869 into the locals dict used by the class.
870 */
871 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100872 if (map_to_dict(co->co_freevars, nfreevars,
873 locals, fast + co->co_nlocals + ncells, 1) < 0)
874 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 }
876 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100877 return 0;
878}
879
880void
881PyFrame_FastToLocals(PyFrameObject *f)
882{
883 int res;
884
885 assert(!PyErr_Occurred());
886
887 res = PyFrame_FastToLocalsWithError(f);
888 if (res < 0)
889 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000890}
891
892void
Fred Drake1b190b42000-07-09 05:40:56 +0000893PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Merge f->f_locals into fast locals */
896 PyObject *locals, *map;
897 PyObject **fast;
898 PyObject *error_type, *error_value, *error_traceback;
899 PyCodeObject *co;
900 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100901 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (f == NULL)
903 return;
904 locals = f->f_locals;
905 co = f->f_code;
906 map = co->co_varnames;
907 if (locals == NULL)
908 return;
909 if (!PyTuple_Check(map))
910 return;
911 PyErr_Fetch(&error_type, &error_value, &error_traceback);
912 fast = f->f_localsplus;
913 j = PyTuple_GET_SIZE(map);
914 if (j > co->co_nlocals)
915 j = co->co_nlocals;
916 if (co->co_nlocals)
917 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
918 ncells = PyTuple_GET_SIZE(co->co_cellvars);
919 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
920 if (ncells || nfreevars) {
921 dict_to_map(co->co_cellvars, ncells,
922 locals, fast + co->co_nlocals, 1, clear);
923 /* Same test as in PyFrame_FastToLocals() above. */
924 if (co->co_flags & CO_OPTIMIZED) {
925 dict_to_map(co->co_freevars, nfreevars,
926 locals, fast + co->co_nlocals + ncells, 1,
927 clear);
928 }
929 }
930 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000931}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000932
933/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000934int
935PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 int freelist_size = numfree;
938
939 while (free_list != NULL) {
940 PyFrameObject *f = free_list;
941 free_list = free_list->f_back;
942 PyObject_GC_Del(f);
943 --numfree;
944 }
945 assert(numfree == 0);
946 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000947}
948
949void
950PyFrame_Fini(void)
951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000953}
David Malcolm49526f42012-06-22 14:55:41 -0400954
955/* Print summary info about the state of the optimized allocator */
956void
957_PyFrame_DebugMallocStats(FILE *out)
958{
959 _PyDebugAllocatorStats(out,
960 "free PyFrameObject",
961 numfree, sizeof(PyFrameObject));
962}
963