blob: 643be08fa18249af871a933e52a8daa909269b64 [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 */
103 int for_loop_delta = 0; /* (ditto) */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200104 int delta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 int blockstack_top = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 /* f_lineno must be an integer. */
109 if (!PyLong_CheckExact(p_new_lineno)) {
110 PyErr_SetString(PyExc_ValueError,
111 "lineno must be an integer");
112 return -1;
113 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000114
xdegayeb8e9d6c2018-03-13 18:31:31 +0100115 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
116 * f->f_trace is NULL, check first on the first condition.
117 * Forbidding jumps from the 'call' event of a new frame is a side effect
118 * of allowing to set f_lineno only from trace functions. */
119 if (f->f_lasti == -1) {
120 PyErr_Format(PyExc_ValueError,
121 "can't jump from the 'call' trace event of a new frame");
122 return -1;
123 }
124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 /* You can only do this from within a trace function, not via
126 * _getframe or similar hackery. */
xdegayeb8e9d6c2018-03-13 18:31:31 +0100127 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100129 "f_lineno can only be set by a trace function");
130 return -1;
131 }
132
133 /* Forbid jumps upon a 'return' trace event (except after executing a
134 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
135 * and upon an 'exception' trace event.
136 * Jumps from 'call' trace events have already been forbidden above for new
137 * frames, so this check does not change anything for 'call' events. */
138 if (f->f_stacktop == NULL) {
139 PyErr_SetString(PyExc_ValueError,
140 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 return -1;
142 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 /* Fail if the line comes before the start of the code block. */
145 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
146 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000147#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 || l_new_lineno > INT_MAX
149 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000150#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 ) {
152 PyErr_SetString(PyExc_ValueError,
153 "lineno out of range");
154 return -1;
155 }
156 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 if (new_lineno < f->f_code->co_firstlineno) {
159 PyErr_Format(PyExc_ValueError,
160 "line %d comes before the current code block",
161 new_lineno);
162 return -1;
163 }
164 else if (new_lineno == f->f_code->co_firstlineno) {
165 new_lasti = 0;
166 new_lineno = f->f_code->co_firstlineno;
167 }
168 else {
169 /* Find the bytecode offset for the start of the given
170 * line, or the first code-owning line after it. */
171 char *tmp;
172 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
173 &tmp, &lnotab_len);
174 lnotab = (unsigned char *) tmp;
175 addr = 0;
176 line = f->f_code->co_firstlineno;
177 new_lasti = -1;
178 for (offset = 0; offset < lnotab_len; offset += 2) {
179 addr += lnotab[offset];
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100180 line += (signed char)lnotab[offset+1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 if (line >= new_lineno) {
182 new_lasti = addr;
183 new_lineno = line;
184 break;
185 }
186 }
187 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 /* If we didn't reach the requested line, return an error. */
190 if (new_lasti == -1) {
191 PyErr_Format(PyExc_ValueError,
192 "line %d comes after the current code block",
193 new_lineno);
194 return -1;
195 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 /* We're now ready to look at the bytecode. */
198 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000199
xdegayeb8e9d6c2018-03-13 18:31:31 +0100200 /* The trace function is called with a 'return' trace event after the
201 * execution of a yield statement. */
202 assert(f->f_lasti != -1);
203 if (code[f->f_lasti] == YIELD_VALUE || code[f->f_lasti] == YIELD_FROM) {
204 PyErr_SetString(PyExc_ValueError,
205 "can't jump from a yield statement");
206 return -1;
207 }
208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 /* You can't jump onto a line with an 'except' statement on it -
210 * they expect to have an exception on the top of the stack, which
211 * won't be true if you jump to them. They always start with code
212 * that either pops the exception using POP_TOP (plain 'except:'
213 * lines do this) or duplicates the exception on the stack using
214 * DUP_TOP (if there's an exception type specified). See compile.c,
215 * 'com_try_except' for the full details. There aren't any other
216 * cases (AFAIK) where a line's code can start with DUP_TOP or
217 * POP_TOP, but if any ever appear, they'll be subject to the same
218 * restriction (but with a different error message). */
219 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
220 PyErr_SetString(PyExc_ValueError,
221 "can't jump to 'except' line as there's no exception");
222 return -1;
223 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* You can't jump into or out of a 'finally' block because the 'try'
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200226 * block leaves something on the stack for the END_FINALLY to clean up.
227 * So we walk the bytecode, maintaining a simulated blockstack.
228 * 'blockstack' is a stack of the bytecode addresses of the starts of
229 * the 'finally' blocks. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 memset(blockstack, '\0', sizeof(blockstack));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 blockstack_top = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300232 for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 unsigned char op = code[addr];
234 switch (op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400236 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400237 case SETUP_ASYNC_WITH:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200238 case FOR_ITER: {
239 unsigned int oparg = get_arg((const _Py_CODEUNIT *)code,
240 addr / sizeof(_Py_CODEUNIT));
241 int target_addr = addr + oparg + sizeof(_Py_CODEUNIT);
242 assert(target_addr < code_len);
243 /* Police block-jumping (you can't jump into the middle of a block)
244 * and ensure that the blockstack finishes up in a sensible state (by
245 * popping any blocks we're jumping out of). We look at all the
246 * blockstack operations between the current position and the new
247 * one, and keep track of how many blocks we drop out of on the way.
248 * By also keeping track of the lowest blockstack position we see, we
249 * can tell whether the jump goes into any blocks without coming out
250 * again - in that case we raise an exception below. */
251 int first_in = addr < f->f_lasti && f->f_lasti < target_addr;
252 int second_in = addr < new_lasti && new_lasti < target_addr;
253 if (!first_in && second_in) {
254 PyErr_SetString(PyExc_ValueError,
255 "can't jump into the middle of a block");
256 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200258 if (first_in && !second_in) {
259 if (op == FOR_ITER && !delta_iblock) {
260 for_loop_delta++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200262 if (op != FOR_ITER) {
263 delta_iblock++;
264 }
265 }
266 if (op != FOR_ITER) {
267 blockstack[blockstack_top++] = target_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 }
269 break;
270 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000271
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200272 case END_FINALLY: {
273 assert(blockstack_top > 0);
274 int target_addr = blockstack[--blockstack_top];
275 assert(target_addr <= addr);
276 int first_in = target_addr <= f->f_lasti && f->f_lasti <= addr;
277 int second_in = target_addr <= new_lasti && new_lasti <= addr;
278 if (first_in != second_in) {
279 PyErr_SetString(PyExc_ValueError,
280 "can't jump into or out of a 'finally' block");
281 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200283 break;
284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 /* Verify that the blockstack tracking code didn't get lost. */
289 assert(blockstack_top == 0);
290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 /* Pop any blocks that we're jumping out of. */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200292 delta = 0;
293 if (delta_iblock > 0) {
294 f->f_iblock -= delta_iblock;
295 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
296 delta = (f->f_stacktop - f->f_valuestack) - b->b_level;
297 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 Storchaka520b7ae2018-02-22 23:33:30 +0200304 /* Pop the iterators of any 'for' loop we're jumping out of. */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200305 delta += for_loop_delta;
306
307 while (delta > 0) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200308 PyObject *v = (*--f->f_stacktop);
309 Py_DECREF(v);
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200310 delta--;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200311 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 /* Finally set the new f_lineno and f_lasti and return OK. */
314 f->f_lineno = new_lineno;
315 f->f_lasti = new_lasti;
316 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000317}
318
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000319static PyObject *
320frame_gettrace(PyFrameObject *f, void *closure)
321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (trace == NULL)
325 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000330}
331
332static int
333frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* We rely on f_lineno being accurate when f_trace is set. */
336 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000337
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300338 if (v == Py_None)
339 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300341 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000344}
345
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000346
Guido van Rossum32d34c82001-09-20 21:45:26 +0000347static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 {"f_locals", (getter)frame_getlocals, NULL, NULL},
349 {"f_lineno", (getter)frame_getlineno,
350 (setter)frame_setlineno, NULL},
351 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
352 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000354
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000355/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 In an attempt to improve the speed of function calls, we:
357
358 1. Hold a single "zombie" frame on each code object. This retains
359 the allocated and initialised frame object from an invocation of
360 the code object. The zombie is reanimated the next time we need a
361 frame object for that code object. Doing this saves the malloc/
362 realloc required when using a free_list frame that isn't the
363 correct size. It also saves some field initialisation.
364
365 In zombie mode, no field of PyFrameObject holds a reference, but
366 the following fields are still valid:
367
368 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369
Mark Shannonae3087c2017-10-22 22:41:51 +0100370 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000371
372 * f_localsplus does not require re-allocation and
373 the local variables in f_localsplus are NULL.
374
375 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000376 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377 a stack frame is on the free list, only the following members have
378 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 ob_type == &Frametype
380 f_back next item on free list, or NULL
381 f_stacksize size of value stack
382 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000383 Note that the value and block stacks are preserved -- this can save
384 another malloc() call or two (and two free() calls as well!).
385 Also note that, unlike for integers, each frame object is a
386 malloc'ed object in its own right -- it is only the actual calls to
387 malloc() that we are trying to save here, not the administration.
388 After all, while a typical program may make millions of calls, a
389 call depth of more than 20 or 30 is probably already exceptional
390 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000391
Christian Heimes2202f872008-02-06 14:31:34 +0000392 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000393 free_list. Else programs creating lots of cyclic trash involving
394 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000395*/
396
Guido van Rossum18752471997-04-29 14:49:28 +0000397static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000399/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000401
Victor Stinnerc6944e72016-11-11 02:13:35 +0100402static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000403frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000404{
Antoine Pitrou93963562013-05-14 20:37:52 +0200405 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000407
INADA Naoki5a625d02016-12-24 20:19:08 +0900408 if (_PyObject_GC_IS_TRACKED(f))
409 _PyObject_GC_UNTRACK(f);
410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200412 /* Kill all local variables */
413 valuestack = f->f_valuestack;
414 for (p = f->f_localsplus; p < valuestack; p++)
415 Py_CLEAR(*p);
416
417 /* Free stack */
418 if (f->f_stacktop != NULL) {
419 for (p = valuestack; p < f->f_stacktop; p++)
420 Py_XDECREF(*p);
421 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_XDECREF(f->f_back);
424 Py_DECREF(f->f_builtins);
425 Py_DECREF(f->f_globals);
426 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200427 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 co = f->f_code;
430 if (co->co_zombieframe == NULL)
431 co->co_zombieframe = f;
432 else if (numfree < PyFrame_MAXFREELIST) {
433 ++numfree;
434 f->f_back = free_list;
435 free_list = f;
436 }
437 else
438 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 Py_DECREF(co);
441 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000442}
443
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000444static int
445frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100448 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 Py_VISIT(f->f_back);
451 Py_VISIT(f->f_code);
452 Py_VISIT(f->f_builtins);
453 Py_VISIT(f->f_globals);
454 Py_VISIT(f->f_locals);
455 Py_VISIT(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_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* stack */
464 if (f->f_stacktop != NULL) {
465 for (p = f->f_valuestack; p < f->f_stacktop; p++)
466 Py_VISIT(*p);
467 }
468 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000469}
470
471static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200472frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100475 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000476
Antoine Pitrou93963562013-05-14 20:37:52 +0200477 /* Before anything else, make sure that this frame is clearly marked
478 * as being defunct! Else, e.g., a generator reachable from this
479 * frame may also point to this frame, believe itself to still be
480 * active, and try cleaning up this frame again.
481 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 oldtop = f->f_stacktop;
483 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200484 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* locals */
489 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
490 fastlocals = f->f_localsplus;
491 for (i = slots; --i >= 0; ++fastlocals)
492 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* stack */
495 if (oldtop != NULL) {
496 for (p = f->f_valuestack; p < oldtop; p++)
497 Py_CLEAR(*p);
498 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000499}
500
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000501static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200502frame_clear(PyFrameObject *f)
503{
504 if (f->f_executing) {
505 PyErr_SetString(PyExc_RuntimeError,
506 "cannot clear an executing frame");
507 return NULL;
508 }
509 if (f->f_gen) {
510 _PyGen_Finalize(f->f_gen);
511 assert(f->f_gen == NULL);
512 }
513 frame_tp_clear(f);
514 Py_RETURN_NONE;
515}
516
517PyDoc_STRVAR(clear__doc__,
518"F.clear(): clear most references held by the frame");
519
520static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000521frame_sizeof(PyFrameObject *f)
522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
526 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
527 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
528 ncells + nfrees;
529 /* subtract one as it is already included in PyFrameObject */
530 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000533}
534
535PyDoc_STRVAR(sizeof__doc__,
536"F.__sizeof__() -> size of F in memory, in bytes");
537
Antoine Pitrou14709142017-12-31 22:35:22 +0100538static PyObject *
539frame_repr(PyFrameObject *f)
540{
541 int lineno = PyFrame_GetLineNumber(f);
542 return PyUnicode_FromFormat(
543 "<frame at %p, file %R, line %d, code %S>",
544 f, f->f_code->co_filename, lineno, f->f_code->co_name);
545}
546
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000547static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200548 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
549 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
551 sizeof__doc__},
552 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000553};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000554
Guido van Rossum18752471997-04-29 14:49:28 +0000555PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyVarObject_HEAD_INIT(&PyType_Type, 0)
557 "frame",
558 sizeof(PyFrameObject),
559 sizeof(PyObject *),
560 (destructor)frame_dealloc, /* tp_dealloc */
561 0, /* tp_print */
562 0, /* tp_getattr */
563 0, /* tp_setattr */
564 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100565 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 0, /* tp_as_number */
567 0, /* tp_as_sequence */
568 0, /* tp_as_mapping */
569 0, /* tp_hash */
570 0, /* tp_call */
571 0, /* tp_str */
572 PyObject_GenericGetAttr, /* tp_getattro */
573 PyObject_GenericSetAttr, /* tp_setattro */
574 0, /* tp_as_buffer */
575 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
576 0, /* tp_doc */
577 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200578 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 0, /* tp_richcompare */
580 0, /* tp_weaklistoffset */
581 0, /* tp_iter */
582 0, /* tp_iternext */
583 frame_methods, /* tp_methods */
584 frame_memberlist, /* tp_members */
585 frame_getsetlist, /* tp_getset */
586 0, /* tp_base */
587 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000588};
589
Victor Stinner07e9e382013-11-07 22:22:39 +0100590_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000591
Victor Stinnerc6944e72016-11-11 02:13:35 +0100592PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900593_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
594 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 PyFrameObject *back = tstate->frame;
597 PyFrameObject *f;
598 PyObject *builtins;
599 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000600
Michael W. Hudson69734a52002-08-19 16:54:08 +0000601#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
603 (locals != NULL && !PyMapping_Check(locals))) {
604 PyErr_BadInternalCall();
605 return NULL;
606 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000607#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100609 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (builtins) {
611 if (PyModule_Check(builtins)) {
612 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200613 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 }
616 if (builtins == NULL) {
617 /* No builtins! Make up a minimal one
618 Give them 'None', at least. */
619 builtins = PyDict_New();
620 if (builtins == NULL ||
621 PyDict_SetItemString(
622 builtins, "None", Py_None) < 0)
623 return NULL;
624 }
625 else
626 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 }
629 else {
630 /* If we share the globals, we share the builtins.
631 Save a lookup and a call. */
632 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200633 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_INCREF(builtins);
635 }
636 if (code->co_zombieframe != NULL) {
637 f = code->co_zombieframe;
638 code->co_zombieframe = NULL;
639 _Py_NewReference((PyObject *)f);
640 assert(f->f_code == code);
641 }
642 else {
643 Py_ssize_t extras, ncells, nfrees;
644 ncells = PyTuple_GET_SIZE(code->co_cellvars);
645 nfrees = PyTuple_GET_SIZE(code->co_freevars);
646 extras = code->co_stacksize + code->co_nlocals + ncells +
647 nfrees;
648 if (free_list == NULL) {
649 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
650 extras);
651 if (f == NULL) {
652 Py_DECREF(builtins);
653 return NULL;
654 }
655 }
656 else {
657 assert(numfree > 0);
658 --numfree;
659 f = free_list;
660 free_list = free_list->f_back;
661 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000662 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
663 if (new_f == NULL) {
664 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 Py_DECREF(builtins);
666 return NULL;
667 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000668 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 }
670 _Py_NewReference((PyObject *)f);
671 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 f->f_code = code;
674 extras = code->co_nlocals + ncells + nfrees;
675 f->f_valuestack = f->f_localsplus + extras;
676 for (i=0; i<extras; i++)
677 f->f_localsplus[i] = NULL;
678 f->f_locals = NULL;
679 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 }
681 f->f_stacktop = f->f_valuestack;
682 f->f_builtins = builtins;
683 Py_XINCREF(back);
684 f->f_back = back;
685 Py_INCREF(code);
686 Py_INCREF(globals);
687 f->f_globals = globals;
688 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
689 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
690 (CO_NEWLOCALS | CO_OPTIMIZED))
691 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
692 else if (code->co_flags & CO_NEWLOCALS) {
693 locals = PyDict_New();
694 if (locals == NULL) {
695 Py_DECREF(f);
696 return NULL;
697 }
698 f->f_locals = locals;
699 }
700 else {
701 if (locals == NULL)
702 locals = globals;
703 Py_INCREF(locals);
704 f->f_locals = locals;
705 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 f->f_lasti = -1;
708 f->f_lineno = code->co_firstlineno;
709 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200710 f->f_executing = 0;
711 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000712 f->f_trace_opcodes = 0;
713 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000716}
717
INADA Naoki5a625d02016-12-24 20:19:08 +0900718PyFrameObject*
719PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
720 PyObject *globals, PyObject *locals)
721{
722 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
723 if (f)
724 _PyObject_GC_TRACK(f);
725 return f;
726}
727
728
Guido van Rossum3f5da241990-12-20 15:06:42 +0000729/* Block management */
730
731void
Fred Drake1b190b42000-07-09 05:40:56 +0000732PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyTryBlock *b;
735 if (f->f_iblock >= CO_MAXBLOCKS)
736 Py_FatalError("XXX block stack overflow");
737 b = &f->f_blockstack[f->f_iblock++];
738 b->b_type = type;
739 b->b_level = level;
740 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000741}
742
Guido van Rossum18752471997-04-29 14:49:28 +0000743PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000744PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyTryBlock *b;
747 if (f->f_iblock <= 0)
748 Py_FatalError("XXX block stack underflow");
749 b = &f->f_blockstack[--f->f_iblock];
750 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000751}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000752
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754
755 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 values is an array of PyObject*. At index i, map[i] is the name of
757 the variable with value values[i]. The function copies the first
758 nmap variable from map/values into dict. If values[i] is NULL,
759 the variable is deleted from dict.
760
761 If deref is true, then the values being copied are cell variables
762 and the value is extracted from the cell variable before being put
763 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000764 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000765
Victor Stinner41bb43a2013-10-29 01:19:37 +0100766static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000767map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 Py_ssize_t j;
771 assert(PyTuple_Check(map));
772 assert(PyDict_Check(dict));
773 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800774 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 PyObject *key = PyTuple_GET_ITEM(map, j);
776 PyObject *value = values[j];
777 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400778 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(PyCell_Check(value));
780 value = PyCell_GET(value);
781 }
782 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100783 if (PyObject_DelItem(dict, key) != 0) {
784 if (PyErr_ExceptionMatches(PyExc_KeyError))
785 PyErr_Clear();
786 else
787 return -1;
788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 }
790 else {
791 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100792 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 }
794 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100795 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000796}
797
Guido van Rossumd8faa362007-04-27 19:54:29 +0000798/* Copy values from the "locals" dict into the fast locals.
799
800 dict is an input argument containing string keys representing
801 variables names and arbitrary PyObject* as values.
802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000804 values is an array of PyObject*. At index i, map[i] is the name of
805 the variable with value values[i]. The function copies the first
806 nmap variable from map/values into dict. If values[i] is NULL,
807 the variable is deleted from dict.
808
809 If deref is true, then the values being copied are cell variables
810 and the value is extracted from the cell variable before being put
811 in dict. If clear is true, then variables in map but not in dict
812 are set to NULL in map; if clear is false, variables missing in
813 dict are ignored.
814
815 Exceptions raised while modifying the dict are silently ignored,
816 because there is no good way to report them.
817*/
818
Guido van Rossum6b356e72001-04-14 17:55:41 +0000819static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000820dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_ssize_t j;
824 assert(PyTuple_Check(map));
825 assert(PyDict_Check(dict));
826 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800827 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyObject *key = PyTuple_GET_ITEM(map, j);
829 PyObject *value = PyObject_GetItem(dict, key);
830 assert(PyUnicode_Check(key));
831 /* We only care about NULLs if clear is true. */
832 if (value == NULL) {
833 PyErr_Clear();
834 if (!clear)
835 continue;
836 }
837 if (deref) {
838 assert(PyCell_Check(values[j]));
839 if (PyCell_GET(values[j]) != value) {
840 if (PyCell_Set(values[j], value) < 0)
841 PyErr_Clear();
842 }
843 } else if (values[j] != value) {
844 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300845 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 }
847 Py_XDECREF(value);
848 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000849}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000850
Victor Stinner41bb43a2013-10-29 01:19:37 +0100851int
852PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 /* Merge fast locals into f->f_locals */
855 PyObject *locals, *map;
856 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyCodeObject *co;
858 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100859 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100860
861 if (f == NULL) {
862 PyErr_BadInternalCall();
863 return -1;
864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 locals = f->f_locals;
866 if (locals == NULL) {
867 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100868 if (locals == NULL)
869 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 }
871 co = f->f_code;
872 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100873 if (!PyTuple_Check(map)) {
874 PyErr_Format(PyExc_SystemError,
875 "co_varnames must be a tuple, not %s",
876 Py_TYPE(map)->tp_name);
877 return -1;
878 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 fast = f->f_localsplus;
880 j = PyTuple_GET_SIZE(map);
881 if (j > co->co_nlocals)
882 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100883 if (co->co_nlocals) {
884 if (map_to_dict(map, j, locals, fast, 0) < 0)
885 return -1;
886 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 ncells = PyTuple_GET_SIZE(co->co_cellvars);
888 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
889 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100890 if (map_to_dict(co->co_cellvars, ncells,
891 locals, fast + co->co_nlocals, 1))
892 return -1;
893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* If the namespace is unoptimized, then one of the
895 following cases applies:
896 1. It does not contain free variables, because it
897 uses import * or is a top-level namespace.
898 2. It is a class namespace.
899 We don't want to accidentally copy free variables
900 into the locals dict used by the class.
901 */
902 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100903 if (map_to_dict(co->co_freevars, nfreevars,
904 locals, fast + co->co_nlocals + ncells, 1) < 0)
905 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
907 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100908 return 0;
909}
910
911void
912PyFrame_FastToLocals(PyFrameObject *f)
913{
914 int res;
915
916 assert(!PyErr_Occurred());
917
918 res = PyFrame_FastToLocalsWithError(f);
919 if (res < 0)
920 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000921}
922
923void
Fred Drake1b190b42000-07-09 05:40:56 +0000924PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Merge f->f_locals into fast locals */
927 PyObject *locals, *map;
928 PyObject **fast;
929 PyObject *error_type, *error_value, *error_traceback;
930 PyCodeObject *co;
931 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100932 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (f == NULL)
934 return;
935 locals = f->f_locals;
936 co = f->f_code;
937 map = co->co_varnames;
938 if (locals == NULL)
939 return;
940 if (!PyTuple_Check(map))
941 return;
942 PyErr_Fetch(&error_type, &error_value, &error_traceback);
943 fast = f->f_localsplus;
944 j = PyTuple_GET_SIZE(map);
945 if (j > co->co_nlocals)
946 j = co->co_nlocals;
947 if (co->co_nlocals)
948 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
949 ncells = PyTuple_GET_SIZE(co->co_cellvars);
950 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
951 if (ncells || nfreevars) {
952 dict_to_map(co->co_cellvars, ncells,
953 locals, fast + co->co_nlocals, 1, clear);
954 /* Same test as in PyFrame_FastToLocals() above. */
955 if (co->co_flags & CO_OPTIMIZED) {
956 dict_to_map(co->co_freevars, nfreevars,
957 locals, fast + co->co_nlocals + ncells, 1,
958 clear);
959 }
960 }
961 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000962}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000963
964/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000965int
966PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 int freelist_size = numfree;
969
970 while (free_list != NULL) {
971 PyFrameObject *f = free_list;
972 free_list = free_list->f_back;
973 PyObject_GC_Del(f);
974 --numfree;
975 }
976 assert(numfree == 0);
977 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000978}
979
980void
981PyFrame_Fini(void)
982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000984}
David Malcolm49526f42012-06-22 14:55:41 -0400985
986/* Print summary info about the state of the optimized allocator */
987void
988_PyFrame_DebugMallocStats(FILE *out)
989{
990 _PyDebugAllocatorStats(out,
991 "free PyFrameObject",
992 numfree, sizeof(PyFrameObject));
993}
994