blob: 9d37935c2f79b798816ae2fd56b840954e046636 [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.
xdegayeb8e9d6c2018-03-13 18:31:31 +010084 * o Jumps cannot be made from within a trace function invoked with a
85 * 'return' or 'exception' event since the eval loop has been exited at
86 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000087 */
88static int
89frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
90{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 int new_lineno = 0; /* The new value of f_lineno */
92 long l_new_lineno;
93 int overflow;
94 int new_lasti = 0; /* The new value of f_lasti */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 unsigned char *code = NULL; /* The bytecode for the frame... */
96 Py_ssize_t code_len = 0; /* ...and its length */
97 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
98 Py_ssize_t lnotab_len = 0; /* (ditto) */
99 int offset = 0; /* (ditto) */
100 int line = 0; /* (ditto) */
101 int addr = 0; /* (ditto) */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200102 int delta_iblock = 0; /* Scanning the SETUPs and POPs */
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200103 int delta = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 int blockstack_top = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 /* f_lineno must be an integer. */
108 if (!PyLong_CheckExact(p_new_lineno)) {
109 PyErr_SetString(PyExc_ValueError,
110 "lineno must be an integer");
111 return -1;
112 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000113
xdegayeb8e9d6c2018-03-13 18:31:31 +0100114 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
115 * f->f_trace is NULL, check first on the first condition.
116 * Forbidding jumps from the 'call' event of a new frame is a side effect
117 * of allowing to set f_lineno only from trace functions. */
118 if (f->f_lasti == -1) {
119 PyErr_Format(PyExc_ValueError,
120 "can't jump from the 'call' trace event of a new frame");
121 return -1;
122 }
123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* You can only do this from within a trace function, not via
125 * _getframe or similar hackery. */
xdegayeb8e9d6c2018-03-13 18:31:31 +0100126 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100128 "f_lineno can only be set by a trace function");
129 return -1;
130 }
131
132 /* Forbid jumps upon a 'return' trace event (except after executing a
133 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
134 * and upon an 'exception' trace event.
135 * Jumps from 'call' trace events have already been forbidden above for new
136 * frames, so this check does not change anything for 'call' events. */
137 if (f->f_stacktop == NULL) {
138 PyErr_SetString(PyExc_ValueError,
139 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 return -1;
141 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 /* Fail if the line comes before the start of the code block. */
144 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
145 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000146#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 || l_new_lineno > INT_MAX
148 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000149#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 ) {
151 PyErr_SetString(PyExc_ValueError,
152 "lineno out of range");
153 return -1;
154 }
155 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 if (new_lineno < f->f_code->co_firstlineno) {
158 PyErr_Format(PyExc_ValueError,
159 "line %d comes before the current code block",
160 new_lineno);
161 return -1;
162 }
163 else if (new_lineno == f->f_code->co_firstlineno) {
164 new_lasti = 0;
165 new_lineno = f->f_code->co_firstlineno;
166 }
167 else {
168 /* Find the bytecode offset for the start of the given
169 * line, or the first code-owning line after it. */
170 char *tmp;
171 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
172 &tmp, &lnotab_len);
173 lnotab = (unsigned char *) tmp;
174 addr = 0;
175 line = f->f_code->co_firstlineno;
176 new_lasti = -1;
177 for (offset = 0; offset < lnotab_len; offset += 2) {
178 addr += lnotab[offset];
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100179 line += (signed char)lnotab[offset+1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 if (line >= new_lineno) {
181 new_lasti = addr;
182 new_lineno = line;
183 break;
184 }
185 }
186 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 /* If we didn't reach the requested line, return an error. */
189 if (new_lasti == -1) {
190 PyErr_Format(PyExc_ValueError,
191 "line %d comes after the current code block",
192 new_lineno);
193 return -1;
194 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* We're now ready to look at the bytecode. */
197 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000198
xdegayeb8e9d6c2018-03-13 18:31:31 +0100199 /* The trace function is called with a 'return' trace event after the
200 * execution of a yield statement. */
201 assert(f->f_lasti != -1);
202 if (code[f->f_lasti] == YIELD_VALUE || code[f->f_lasti] == YIELD_FROM) {
203 PyErr_SetString(PyExc_ValueError,
204 "can't jump from a yield statement");
205 return -1;
206 }
207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* You can't jump onto a line with an 'except' statement on it -
209 * they expect to have an exception on the top of the stack, which
210 * won't be true if you jump to them. They always start with code
211 * that either pops the exception using POP_TOP (plain 'except:'
212 * lines do this) or duplicates the exception on the stack using
213 * DUP_TOP (if there's an exception type specified). See compile.c,
214 * 'com_try_except' for the full details. There aren't any other
215 * cases (AFAIK) where a line's code can start with DUP_TOP or
216 * POP_TOP, but if any ever appear, they'll be subject to the same
217 * restriction (but with a different error message). */
218 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
219 PyErr_SetString(PyExc_ValueError,
220 "can't jump to 'except' line as there's no exception");
221 return -1;
222 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 /* You can't jump into or out of a 'finally' block because the 'try'
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200225 * block leaves something on the stack for the END_FINALLY to clean up.
226 * So we walk the bytecode, maintaining a simulated blockstack.
227 * 'blockstack' is a stack of the bytecode addresses of the starts of
228 * the 'finally' blocks. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 memset(blockstack, '\0', sizeof(blockstack));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 blockstack_top = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300231 for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 unsigned char op = code[addr];
233 switch (op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400235 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400236 case SETUP_ASYNC_WITH:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200237 case FOR_ITER: {
238 unsigned int oparg = get_arg((const _Py_CODEUNIT *)code,
239 addr / sizeof(_Py_CODEUNIT));
240 int target_addr = addr + oparg + sizeof(_Py_CODEUNIT);
241 assert(target_addr < code_len);
242 /* Police block-jumping (you can't jump into the middle of a block)
243 * and ensure that the blockstack finishes up in a sensible state (by
244 * popping any blocks we're jumping out of). We look at all the
245 * blockstack operations between the current position and the new
246 * one, and keep track of how many blocks we drop out of on the way.
247 * By also keeping track of the lowest blockstack position we see, we
248 * can tell whether the jump goes into any blocks without coming out
249 * again - in that case we raise an exception below. */
250 int first_in = addr < f->f_lasti && f->f_lasti < target_addr;
251 int second_in = addr < new_lasti && new_lasti < target_addr;
252 if (!first_in && second_in) {
253 PyErr_SetString(PyExc_ValueError,
254 "can't jump into the middle of a block");
255 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200257 if (first_in && !second_in) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200258 if (op != FOR_ITER && code[target_addr] != END_ASYNC_FOR) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200259 delta_iblock++;
260 }
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200261 else if (!delta_iblock) {
262 /* Pop the iterators of any 'for' and 'async for' loop
263 * we're jumping out of. */
264 delta++;
265 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200266 }
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200267 if (op != FOR_ITER && code[target_addr] != END_ASYNC_FOR) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200268 blockstack[blockstack_top++] = target_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 }
270 break;
271 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000272
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200273 case END_FINALLY: {
274 assert(blockstack_top > 0);
275 int target_addr = blockstack[--blockstack_top];
276 assert(target_addr <= addr);
277 int first_in = target_addr <= f->f_lasti && f->f_lasti <= addr;
278 int second_in = target_addr <= new_lasti && new_lasti <= addr;
279 if (first_in != second_in) {
280 PyErr_SetString(PyExc_ValueError,
281 "can't jump into or out of a 'finally' block");
282 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200284 break;
285 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 /* Verify that the blockstack tracking code didn't get lost. */
290 assert(blockstack_top == 0);
291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 /* Pop any blocks that we're jumping out of. */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200293 if (delta_iblock > 0) {
294 f->f_iblock -= delta_iblock;
295 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200296 delta += (f->f_stacktop - f->f_valuestack) - b->b_level;
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200297 if (b->b_type == SETUP_FINALLY &&
298 code[b->b_handler] == WITH_CLEANUP_START)
299 {
300 /* Pop the exit function. */
301 delta++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 }
303 }
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200304 while (delta > 0) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200305 PyObject *v = (*--f->f_stacktop);
306 Py_DECREF(v);
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200307 delta--;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200308 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 /* Finally set the new f_lineno and f_lasti and return OK. */
311 f->f_lineno = new_lineno;
312 f->f_lasti = new_lasti;
313 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000314}
315
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000316static PyObject *
317frame_gettrace(PyFrameObject *f, void *closure)
318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (trace == NULL)
322 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000327}
328
329static int
330frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* We rely on f_lineno being accurate when f_trace is set. */
333 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000334
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300335 if (v == Py_None)
336 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300338 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000341}
342
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000343
Guido van Rossum32d34c82001-09-20 21:45:26 +0000344static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 {"f_locals", (getter)frame_getlocals, NULL, NULL},
346 {"f_lineno", (getter)frame_getlineno,
347 (setter)frame_setlineno, NULL},
348 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
349 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000350};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000351
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000352/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000353 In an attempt to improve the speed of function calls, we:
354
355 1. Hold a single "zombie" frame on each code object. This retains
356 the allocated and initialised frame object from an invocation of
357 the code object. The zombie is reanimated the next time we need a
358 frame object for that code object. Doing this saves the malloc/
359 realloc required when using a free_list frame that isn't the
360 correct size. It also saves some field initialisation.
361
362 In zombie mode, no field of PyFrameObject holds a reference, but
363 the following fields are still valid:
364
365 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366
Mark Shannonae3087c2017-10-22 22:41:51 +0100367 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000368
369 * f_localsplus does not require re-allocation and
370 the local variables in f_localsplus are NULL.
371
372 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000373 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000374 a stack frame is on the free list, only the following members have
375 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 ob_type == &Frametype
377 f_back next item on free list, or NULL
378 f_stacksize size of value stack
379 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000380 Note that the value and block stacks are preserved -- this can save
381 another malloc() call or two (and two free() calls as well!).
382 Also note that, unlike for integers, each frame object is a
383 malloc'ed object in its own right -- it is only the actual calls to
384 malloc() that we are trying to save here, not the administration.
385 After all, while a typical program may make millions of calls, a
386 call depth of more than 20 or 30 is probably already exceptional
387 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000388
Christian Heimes2202f872008-02-06 14:31:34 +0000389 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000390 free_list. Else programs creating lots of cyclic trash involving
391 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000392*/
393
Guido van Rossum18752471997-04-29 14:49:28 +0000394static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000396/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000398
Victor Stinnerc6944e72016-11-11 02:13:35 +0100399static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000400frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000401{
Antoine Pitrou93963562013-05-14 20:37:52 +0200402 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000404
INADA Naoki5a625d02016-12-24 20:19:08 +0900405 if (_PyObject_GC_IS_TRACKED(f))
406 _PyObject_GC_UNTRACK(f);
407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200409 /* Kill all local variables */
410 valuestack = f->f_valuestack;
411 for (p = f->f_localsplus; p < valuestack; p++)
412 Py_CLEAR(*p);
413
414 /* Free stack */
415 if (f->f_stacktop != NULL) {
416 for (p = valuestack; p < f->f_stacktop; p++)
417 Py_XDECREF(*p);
418 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_XDECREF(f->f_back);
421 Py_DECREF(f->f_builtins);
422 Py_DECREF(f->f_globals);
423 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200424 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 co = f->f_code;
427 if (co->co_zombieframe == NULL)
428 co->co_zombieframe = f;
429 else if (numfree < PyFrame_MAXFREELIST) {
430 ++numfree;
431 f->f_back = free_list;
432 free_list = f;
433 }
434 else
435 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_DECREF(co);
438 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000439}
440
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000441static int
442frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100445 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 Py_VISIT(f->f_back);
448 Py_VISIT(f->f_code);
449 Py_VISIT(f->f_builtins);
450 Py_VISIT(f->f_globals);
451 Py_VISIT(f->f_locals);
452 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* locals */
455 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
456 fastlocals = f->f_localsplus;
457 for (i = slots; --i >= 0; ++fastlocals)
458 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* stack */
461 if (f->f_stacktop != NULL) {
462 for (p = f->f_valuestack; p < f->f_stacktop; p++)
463 Py_VISIT(*p);
464 }
465 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000466}
467
468static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200469frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100472 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000473
Antoine Pitrou93963562013-05-14 20:37:52 +0200474 /* Before anything else, make sure that this frame is clearly marked
475 * as being defunct! Else, e.g., a generator reachable from this
476 * frame may also point to this frame, believe itself to still be
477 * active, and try cleaning up this frame again.
478 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 oldtop = f->f_stacktop;
480 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200481 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* locals */
486 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
487 fastlocals = f->f_localsplus;
488 for (i = slots; --i >= 0; ++fastlocals)
489 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 /* stack */
492 if (oldtop != NULL) {
493 for (p = f->f_valuestack; p < oldtop; p++)
494 Py_CLEAR(*p);
495 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000496}
497
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000498static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200499frame_clear(PyFrameObject *f)
500{
501 if (f->f_executing) {
502 PyErr_SetString(PyExc_RuntimeError,
503 "cannot clear an executing frame");
504 return NULL;
505 }
506 if (f->f_gen) {
507 _PyGen_Finalize(f->f_gen);
508 assert(f->f_gen == NULL);
509 }
510 frame_tp_clear(f);
511 Py_RETURN_NONE;
512}
513
514PyDoc_STRVAR(clear__doc__,
515"F.clear(): clear most references held by the frame");
516
517static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000518frame_sizeof(PyFrameObject *f)
519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
523 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
524 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
525 ncells + nfrees;
526 /* subtract one as it is already included in PyFrameObject */
527 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000530}
531
532PyDoc_STRVAR(sizeof__doc__,
533"F.__sizeof__() -> size of F in memory, in bytes");
534
Antoine Pitrou14709142017-12-31 22:35:22 +0100535static PyObject *
536frame_repr(PyFrameObject *f)
537{
538 int lineno = PyFrame_GetLineNumber(f);
539 return PyUnicode_FromFormat(
540 "<frame at %p, file %R, line %d, code %S>",
541 f, f->f_code->co_filename, lineno, f->f_code->co_name);
542}
543
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000544static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200545 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
546 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
548 sizeof__doc__},
549 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000550};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000551
Guido van Rossum18752471997-04-29 14:49:28 +0000552PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 PyVarObject_HEAD_INIT(&PyType_Type, 0)
554 "frame",
555 sizeof(PyFrameObject),
556 sizeof(PyObject *),
557 (destructor)frame_dealloc, /* tp_dealloc */
558 0, /* tp_print */
559 0, /* tp_getattr */
560 0, /* tp_setattr */
561 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100562 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 0, /* tp_as_number */
564 0, /* tp_as_sequence */
565 0, /* tp_as_mapping */
566 0, /* tp_hash */
567 0, /* tp_call */
568 0, /* tp_str */
569 PyObject_GenericGetAttr, /* tp_getattro */
570 PyObject_GenericSetAttr, /* tp_setattro */
571 0, /* tp_as_buffer */
572 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
573 0, /* tp_doc */
574 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200575 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 0, /* tp_richcompare */
577 0, /* tp_weaklistoffset */
578 0, /* tp_iter */
579 0, /* tp_iternext */
580 frame_methods, /* tp_methods */
581 frame_memberlist, /* tp_members */
582 frame_getsetlist, /* tp_getset */
583 0, /* tp_base */
584 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000585};
586
Victor Stinner07e9e382013-11-07 22:22:39 +0100587_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000588
Victor Stinnerc6944e72016-11-11 02:13:35 +0100589PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900590_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
591 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 PyFrameObject *back = tstate->frame;
594 PyFrameObject *f;
595 PyObject *builtins;
596 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000597
Michael W. Hudson69734a52002-08-19 16:54:08 +0000598#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
600 (locals != NULL && !PyMapping_Check(locals))) {
601 PyErr_BadInternalCall();
602 return NULL;
603 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000604#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100606 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (builtins) {
608 if (PyModule_Check(builtins)) {
609 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200610 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 }
613 if (builtins == NULL) {
614 /* No builtins! Make up a minimal one
615 Give them 'None', at least. */
616 builtins = PyDict_New();
617 if (builtins == NULL ||
618 PyDict_SetItemString(
619 builtins, "None", Py_None) < 0)
620 return NULL;
621 }
622 else
623 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 }
626 else {
627 /* If we share the globals, we share the builtins.
628 Save a lookup and a call. */
629 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200630 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 Py_INCREF(builtins);
632 }
633 if (code->co_zombieframe != NULL) {
634 f = code->co_zombieframe;
635 code->co_zombieframe = NULL;
636 _Py_NewReference((PyObject *)f);
637 assert(f->f_code == code);
638 }
639 else {
640 Py_ssize_t extras, ncells, nfrees;
641 ncells = PyTuple_GET_SIZE(code->co_cellvars);
642 nfrees = PyTuple_GET_SIZE(code->co_freevars);
643 extras = code->co_stacksize + code->co_nlocals + ncells +
644 nfrees;
645 if (free_list == NULL) {
646 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
647 extras);
648 if (f == NULL) {
649 Py_DECREF(builtins);
650 return NULL;
651 }
652 }
653 else {
654 assert(numfree > 0);
655 --numfree;
656 f = free_list;
657 free_list = free_list->f_back;
658 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000659 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
660 if (new_f == NULL) {
661 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 Py_DECREF(builtins);
663 return NULL;
664 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000665 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
667 _Py_NewReference((PyObject *)f);
668 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 f->f_code = code;
671 extras = code->co_nlocals + ncells + nfrees;
672 f->f_valuestack = f->f_localsplus + extras;
673 for (i=0; i<extras; i++)
674 f->f_localsplus[i] = NULL;
675 f->f_locals = NULL;
676 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 }
678 f->f_stacktop = f->f_valuestack;
679 f->f_builtins = builtins;
680 Py_XINCREF(back);
681 f->f_back = back;
682 Py_INCREF(code);
683 Py_INCREF(globals);
684 f->f_globals = globals;
685 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
686 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
687 (CO_NEWLOCALS | CO_OPTIMIZED))
688 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
689 else if (code->co_flags & CO_NEWLOCALS) {
690 locals = PyDict_New();
691 if (locals == NULL) {
692 Py_DECREF(f);
693 return NULL;
694 }
695 f->f_locals = locals;
696 }
697 else {
698 if (locals == NULL)
699 locals = globals;
700 Py_INCREF(locals);
701 f->f_locals = locals;
702 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 f->f_lasti = -1;
705 f->f_lineno = code->co_firstlineno;
706 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200707 f->f_executing = 0;
708 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000709 f->f_trace_opcodes = 0;
710 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000713}
714
INADA Naoki5a625d02016-12-24 20:19:08 +0900715PyFrameObject*
716PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
717 PyObject *globals, PyObject *locals)
718{
719 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
720 if (f)
721 _PyObject_GC_TRACK(f);
722 return f;
723}
724
725
Guido van Rossum3f5da241990-12-20 15:06:42 +0000726/* Block management */
727
728void
Fred Drake1b190b42000-07-09 05:40:56 +0000729PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyTryBlock *b;
732 if (f->f_iblock >= CO_MAXBLOCKS)
733 Py_FatalError("XXX block stack overflow");
734 b = &f->f_blockstack[f->f_iblock++];
735 b->b_type = type;
736 b->b_level = level;
737 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000738}
739
Guido van Rossum18752471997-04-29 14:49:28 +0000740PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000741PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyTryBlock *b;
744 if (f->f_iblock <= 0)
745 Py_FatalError("XXX block stack underflow");
746 b = &f->f_blockstack[--f->f_iblock];
747 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000748}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000749
Guido van Rossumd8faa362007-04-27 19:54:29 +0000750/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751
752 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753 values is an array of PyObject*. At index i, map[i] is the name of
754 the variable with value values[i]. The function copies the first
755 nmap variable from map/values into dict. If values[i] is NULL,
756 the variable is deleted from dict.
757
758 If deref is true, then the values being copied are cell variables
759 and the value is extracted from the cell variable before being put
760 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000761 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000762
Victor Stinner41bb43a2013-10-29 01:19:37 +0100763static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000764map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 Py_ssize_t j;
768 assert(PyTuple_Check(map));
769 assert(PyDict_Check(dict));
770 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800771 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 PyObject *key = PyTuple_GET_ITEM(map, j);
773 PyObject *value = values[j];
774 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400775 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 assert(PyCell_Check(value));
777 value = PyCell_GET(value);
778 }
779 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100780 if (PyObject_DelItem(dict, key) != 0) {
781 if (PyErr_ExceptionMatches(PyExc_KeyError))
782 PyErr_Clear();
783 else
784 return -1;
785 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 }
787 else {
788 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100789 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 }
791 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100792 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000793}
794
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795/* Copy values from the "locals" dict into the fast locals.
796
797 dict is an input argument containing string keys representing
798 variables names and arbitrary PyObject* as values.
799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000801 values is an array of PyObject*. At index i, map[i] is the name of
802 the variable with value values[i]. The function copies the first
803 nmap variable from map/values into dict. If values[i] is NULL,
804 the variable is deleted from dict.
805
806 If deref is true, then the values being copied are cell variables
807 and the value is extracted from the cell variable before being put
808 in dict. If clear is true, then variables in map but not in dict
809 are set to NULL in map; if clear is false, variables missing in
810 dict are ignored.
811
812 Exceptions raised while modifying the dict are silently ignored,
813 because there is no good way to report them.
814*/
815
Guido van Rossum6b356e72001-04-14 17:55:41 +0000816static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000817dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 Py_ssize_t j;
821 assert(PyTuple_Check(map));
822 assert(PyDict_Check(dict));
823 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800824 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyObject *key = PyTuple_GET_ITEM(map, j);
826 PyObject *value = PyObject_GetItem(dict, key);
827 assert(PyUnicode_Check(key));
828 /* We only care about NULLs if clear is true. */
829 if (value == NULL) {
830 PyErr_Clear();
831 if (!clear)
832 continue;
833 }
834 if (deref) {
835 assert(PyCell_Check(values[j]));
836 if (PyCell_GET(values[j]) != value) {
837 if (PyCell_Set(values[j], value) < 0)
838 PyErr_Clear();
839 }
840 } else if (values[j] != value) {
841 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300842 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 }
844 Py_XDECREF(value);
845 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000846}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000847
Victor Stinner41bb43a2013-10-29 01:19:37 +0100848int
849PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Merge fast locals into f->f_locals */
852 PyObject *locals, *map;
853 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 PyCodeObject *co;
855 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100856 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100857
858 if (f == NULL) {
859 PyErr_BadInternalCall();
860 return -1;
861 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 locals = f->f_locals;
863 if (locals == NULL) {
864 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100865 if (locals == NULL)
866 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 }
868 co = f->f_code;
869 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100870 if (!PyTuple_Check(map)) {
871 PyErr_Format(PyExc_SystemError,
872 "co_varnames must be a tuple, not %s",
873 Py_TYPE(map)->tp_name);
874 return -1;
875 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 fast = f->f_localsplus;
877 j = PyTuple_GET_SIZE(map);
878 if (j > co->co_nlocals)
879 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100880 if (co->co_nlocals) {
881 if (map_to_dict(map, j, locals, fast, 0) < 0)
882 return -1;
883 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 ncells = PyTuple_GET_SIZE(co->co_cellvars);
885 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
886 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100887 if (map_to_dict(co->co_cellvars, ncells,
888 locals, fast + co->co_nlocals, 1))
889 return -1;
890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* If the namespace is unoptimized, then one of the
892 following cases applies:
893 1. It does not contain free variables, because it
894 uses import * or is a top-level namespace.
895 2. It is a class namespace.
896 We don't want to accidentally copy free variables
897 into the locals dict used by the class.
898 */
899 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100900 if (map_to_dict(co->co_freevars, nfreevars,
901 locals, fast + co->co_nlocals + ncells, 1) < 0)
902 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 }
904 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100905 return 0;
906}
907
908void
909PyFrame_FastToLocals(PyFrameObject *f)
910{
911 int res;
912
913 assert(!PyErr_Occurred());
914
915 res = PyFrame_FastToLocalsWithError(f);
916 if (res < 0)
917 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000918}
919
920void
Fred Drake1b190b42000-07-09 05:40:56 +0000921PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Merge f->f_locals into fast locals */
924 PyObject *locals, *map;
925 PyObject **fast;
926 PyObject *error_type, *error_value, *error_traceback;
927 PyCodeObject *co;
928 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100929 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 if (f == NULL)
931 return;
932 locals = f->f_locals;
933 co = f->f_code;
934 map = co->co_varnames;
935 if (locals == NULL)
936 return;
937 if (!PyTuple_Check(map))
938 return;
939 PyErr_Fetch(&error_type, &error_value, &error_traceback);
940 fast = f->f_localsplus;
941 j = PyTuple_GET_SIZE(map);
942 if (j > co->co_nlocals)
943 j = co->co_nlocals;
944 if (co->co_nlocals)
945 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
946 ncells = PyTuple_GET_SIZE(co->co_cellvars);
947 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
948 if (ncells || nfreevars) {
949 dict_to_map(co->co_cellvars, ncells,
950 locals, fast + co->co_nlocals, 1, clear);
951 /* Same test as in PyFrame_FastToLocals() above. */
952 if (co->co_flags & CO_OPTIMIZED) {
953 dict_to_map(co->co_freevars, nfreevars,
954 locals, fast + co->co_nlocals + ncells, 1,
955 clear);
956 }
957 }
958 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000959}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000960
961/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000962int
963PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 int freelist_size = numfree;
966
967 while (free_list != NULL) {
968 PyFrameObject *f = free_list;
969 free_list = free_list->f_back;
970 PyObject_GC_Del(f);
971 --numfree;
972 }
973 assert(numfree == 0);
974 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000975}
976
977void
978PyFrame_Fini(void)
979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000981}
David Malcolm49526f42012-06-22 14:55:41 -0400982
983/* Print summary info about the state of the optimized allocator */
984void
985_PyFrame_DebugMallocStats(FILE *out)
986{
987 _PyDebugAllocatorStats(out,
988 "free PyFrameObject",
989 numfree, sizeof(PyFrameObject));
990}
991