blob: 64ee386ddf9654ba7741699f3ac42e0377642250 [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) {
Serhiy Storchaka397466d2018-03-23 14:46:45 +0200280 op = code[target_addr];
281 PyErr_Format(PyExc_ValueError,
282 "can't jump %s %s block",
283 second_in ? "into" : "out of",
284 (op == DUP_TOP || op == POP_TOP) ?
285 "an 'except'" : "a 'finally'");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200286 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200288 break;
289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* Verify that the blockstack tracking code didn't get lost. */
294 assert(blockstack_top == 0);
295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* Pop any blocks that we're jumping out of. */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200297 if (delta_iblock > 0) {
298 f->f_iblock -= delta_iblock;
299 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Victor Stinner078c4e32018-04-27 14:30:01 +0200300 delta += (int)(f->f_stacktop - f->f_valuestack) - b->b_level;
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200301 if (b->b_type == SETUP_FINALLY &&
302 code[b->b_handler] == WITH_CLEANUP_START)
303 {
304 /* Pop the exit function. */
305 delta++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 }
307 }
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200308 while (delta > 0) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200309 PyObject *v = (*--f->f_stacktop);
310 Py_DECREF(v);
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200311 delta--;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200312 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 /* Finally set the new f_lineno and f_lasti and return OK. */
315 f->f_lineno = new_lineno;
316 f->f_lasti = new_lasti;
317 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000318}
319
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000320static PyObject *
321frame_gettrace(PyFrameObject *f, void *closure)
322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (trace == NULL)
326 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000331}
332
333static int
334frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* We rely on f_lineno being accurate when f_trace is set. */
337 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000338
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300339 if (v == Py_None)
340 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300342 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000345}
346
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000347
Guido van Rossum32d34c82001-09-20 21:45:26 +0000348static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 {"f_locals", (getter)frame_getlocals, NULL, NULL},
350 {"f_lineno", (getter)frame_getlineno,
351 (setter)frame_setlineno, NULL},
352 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
353 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000354};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000355
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000356/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000357 In an attempt to improve the speed of function calls, we:
358
359 1. Hold a single "zombie" frame on each code object. This retains
360 the allocated and initialised frame object from an invocation of
361 the code object. The zombie is reanimated the next time we need a
362 frame object for that code object. Doing this saves the malloc/
363 realloc required when using a free_list frame that isn't the
364 correct size. It also saves some field initialisation.
365
366 In zombie mode, no field of PyFrameObject holds a reference, but
367 the following fields are still valid:
368
369 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370
Mark Shannonae3087c2017-10-22 22:41:51 +0100371 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000372
373 * f_localsplus does not require re-allocation and
374 the local variables in f_localsplus are NULL.
375
376 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000377 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000378 a stack frame is on the free list, only the following members have
379 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 ob_type == &Frametype
381 f_back next item on free list, or NULL
382 f_stacksize size of value stack
383 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000384 Note that the value and block stacks are preserved -- this can save
385 another malloc() call or two (and two free() calls as well!).
386 Also note that, unlike for integers, each frame object is a
387 malloc'ed object in its own right -- it is only the actual calls to
388 malloc() that we are trying to save here, not the administration.
389 After all, while a typical program may make millions of calls, a
390 call depth of more than 20 or 30 is probably already exceptional
391 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000392
Christian Heimes2202f872008-02-06 14:31:34 +0000393 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000394 free_list. Else programs creating lots of cyclic trash involving
395 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000396*/
397
Guido van Rossum18752471997-04-29 14:49:28 +0000398static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000400/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000402
Victor Stinnerc6944e72016-11-11 02:13:35 +0100403static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000404frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000405{
Antoine Pitrou93963562013-05-14 20:37:52 +0200406 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000408
INADA Naoki5a625d02016-12-24 20:19:08 +0900409 if (_PyObject_GC_IS_TRACKED(f))
410 _PyObject_GC_UNTRACK(f);
411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200413 /* Kill all local variables */
414 valuestack = f->f_valuestack;
415 for (p = f->f_localsplus; p < valuestack; p++)
416 Py_CLEAR(*p);
417
418 /* Free stack */
419 if (f->f_stacktop != NULL) {
420 for (p = valuestack; p < f->f_stacktop; p++)
421 Py_XDECREF(*p);
422 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 Py_XDECREF(f->f_back);
425 Py_DECREF(f->f_builtins);
426 Py_DECREF(f->f_globals);
427 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200428 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 co = f->f_code;
431 if (co->co_zombieframe == NULL)
432 co->co_zombieframe = f;
433 else if (numfree < PyFrame_MAXFREELIST) {
434 ++numfree;
435 f->f_back = free_list;
436 free_list = f;
437 }
438 else
439 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 Py_DECREF(co);
442 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000443}
444
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000445static int
446frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100449 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_VISIT(f->f_back);
452 Py_VISIT(f->f_code);
453 Py_VISIT(f->f_builtins);
454 Py_VISIT(f->f_globals);
455 Py_VISIT(f->f_locals);
456 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 /* locals */
459 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
460 fastlocals = f->f_localsplus;
461 for (i = slots; --i >= 0; ++fastlocals)
462 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* stack */
465 if (f->f_stacktop != NULL) {
466 for (p = f->f_valuestack; p < f->f_stacktop; p++)
467 Py_VISIT(*p);
468 }
469 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000470}
471
472static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200473frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100476 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000477
Antoine Pitrou93963562013-05-14 20:37:52 +0200478 /* Before anything else, make sure that this frame is clearly marked
479 * as being defunct! Else, e.g., a generator reachable from this
480 * frame may also point to this frame, believe itself to still be
481 * active, and try cleaning up this frame again.
482 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 oldtop = f->f_stacktop;
484 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200485 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* locals */
490 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
491 fastlocals = f->f_localsplus;
492 for (i = slots; --i >= 0; ++fastlocals)
493 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* stack */
496 if (oldtop != NULL) {
497 for (p = f->f_valuestack; p < oldtop; p++)
498 Py_CLEAR(*p);
499 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000500}
501
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000502static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530503frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200504{
505 if (f->f_executing) {
506 PyErr_SetString(PyExc_RuntimeError,
507 "cannot clear an executing frame");
508 return NULL;
509 }
510 if (f->f_gen) {
511 _PyGen_Finalize(f->f_gen);
512 assert(f->f_gen == NULL);
513 }
514 frame_tp_clear(f);
515 Py_RETURN_NONE;
516}
517
518PyDoc_STRVAR(clear__doc__,
519"F.clear(): clear most references held by the frame");
520
521static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530522frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
527 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
528 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
529 ncells + nfrees;
530 /* subtract one as it is already included in PyFrameObject */
531 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000534}
535
536PyDoc_STRVAR(sizeof__doc__,
537"F.__sizeof__() -> size of F in memory, in bytes");
538
Antoine Pitrou14709142017-12-31 22:35:22 +0100539static PyObject *
540frame_repr(PyFrameObject *f)
541{
542 int lineno = PyFrame_GetLineNumber(f);
543 return PyUnicode_FromFormat(
544 "<frame at %p, file %R, line %d, code %S>",
545 f, f->f_code->co_filename, lineno, f->f_code->co_name);
546}
547
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000548static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200549 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
550 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
552 sizeof__doc__},
553 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000554};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000555
Guido van Rossum18752471997-04-29 14:49:28 +0000556PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyVarObject_HEAD_INIT(&PyType_Type, 0)
558 "frame",
559 sizeof(PyFrameObject),
560 sizeof(PyObject *),
561 (destructor)frame_dealloc, /* tp_dealloc */
562 0, /* tp_print */
563 0, /* tp_getattr */
564 0, /* tp_setattr */
565 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100566 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 0, /* tp_as_number */
568 0, /* tp_as_sequence */
569 0, /* tp_as_mapping */
570 0, /* tp_hash */
571 0, /* tp_call */
572 0, /* tp_str */
573 PyObject_GenericGetAttr, /* tp_getattro */
574 PyObject_GenericSetAttr, /* tp_setattro */
575 0, /* tp_as_buffer */
576 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
577 0, /* tp_doc */
578 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200579 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 0, /* tp_richcompare */
581 0, /* tp_weaklistoffset */
582 0, /* tp_iter */
583 0, /* tp_iternext */
584 frame_methods, /* tp_methods */
585 frame_memberlist, /* tp_members */
586 frame_getsetlist, /* tp_getset */
587 0, /* tp_base */
588 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000589};
590
Victor Stinner07e9e382013-11-07 22:22:39 +0100591_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000592
Victor Stinnerc6944e72016-11-11 02:13:35 +0100593PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900594_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
595 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 PyFrameObject *back = tstate->frame;
598 PyFrameObject *f;
599 PyObject *builtins;
600 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000601
Michael W. Hudson69734a52002-08-19 16:54:08 +0000602#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
604 (locals != NULL && !PyMapping_Check(locals))) {
605 PyErr_BadInternalCall();
606 return NULL;
607 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000608#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100610 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (builtins) {
612 if (PyModule_Check(builtins)) {
613 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200614 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 }
617 if (builtins == NULL) {
618 /* No builtins! Make up a minimal one
619 Give them 'None', at least. */
620 builtins = PyDict_New();
621 if (builtins == NULL ||
622 PyDict_SetItemString(
623 builtins, "None", Py_None) < 0)
624 return NULL;
625 }
626 else
627 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 }
630 else {
631 /* If we share the globals, we share the builtins.
632 Save a lookup and a call. */
633 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200634 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 Py_INCREF(builtins);
636 }
637 if (code->co_zombieframe != NULL) {
638 f = code->co_zombieframe;
639 code->co_zombieframe = NULL;
640 _Py_NewReference((PyObject *)f);
641 assert(f->f_code == code);
642 }
643 else {
644 Py_ssize_t extras, ncells, nfrees;
645 ncells = PyTuple_GET_SIZE(code->co_cellvars);
646 nfrees = PyTuple_GET_SIZE(code->co_freevars);
647 extras = code->co_stacksize + code->co_nlocals + ncells +
648 nfrees;
649 if (free_list == NULL) {
650 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
651 extras);
652 if (f == NULL) {
653 Py_DECREF(builtins);
654 return NULL;
655 }
656 }
657 else {
658 assert(numfree > 0);
659 --numfree;
660 f = free_list;
661 free_list = free_list->f_back;
662 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000663 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
664 if (new_f == NULL) {
665 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 Py_DECREF(builtins);
667 return NULL;
668 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000669 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
671 _Py_NewReference((PyObject *)f);
672 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 f->f_code = code;
675 extras = code->co_nlocals + ncells + nfrees;
676 f->f_valuestack = f->f_localsplus + extras;
677 for (i=0; i<extras; i++)
678 f->f_localsplus[i] = NULL;
679 f->f_locals = NULL;
680 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 }
682 f->f_stacktop = f->f_valuestack;
683 f->f_builtins = builtins;
684 Py_XINCREF(back);
685 f->f_back = back;
686 Py_INCREF(code);
687 Py_INCREF(globals);
688 f->f_globals = globals;
689 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
690 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
691 (CO_NEWLOCALS | CO_OPTIMIZED))
692 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
693 else if (code->co_flags & CO_NEWLOCALS) {
694 locals = PyDict_New();
695 if (locals == NULL) {
696 Py_DECREF(f);
697 return NULL;
698 }
699 f->f_locals = locals;
700 }
701 else {
702 if (locals == NULL)
703 locals = globals;
704 Py_INCREF(locals);
705 f->f_locals = locals;
706 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 f->f_lasti = -1;
709 f->f_lineno = code->co_firstlineno;
710 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200711 f->f_executing = 0;
712 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000713 f->f_trace_opcodes = 0;
714 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000717}
718
INADA Naoki5a625d02016-12-24 20:19:08 +0900719PyFrameObject*
720PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
721 PyObject *globals, PyObject *locals)
722{
723 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
724 if (f)
725 _PyObject_GC_TRACK(f);
726 return f;
727}
728
729
Guido van Rossum3f5da241990-12-20 15:06:42 +0000730/* Block management */
731
732void
Fred Drake1b190b42000-07-09 05:40:56 +0000733PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyTryBlock *b;
736 if (f->f_iblock >= CO_MAXBLOCKS)
737 Py_FatalError("XXX block stack overflow");
738 b = &f->f_blockstack[f->f_iblock++];
739 b->b_type = type;
740 b->b_level = level;
741 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000742}
743
Guido van Rossum18752471997-04-29 14:49:28 +0000744PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000745PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyTryBlock *b;
748 if (f->f_iblock <= 0)
749 Py_FatalError("XXX block stack underflow");
750 b = &f->f_blockstack[--f->f_iblock];
751 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000752}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000753
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755
756 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000757 values is an array of PyObject*. At index i, map[i] is the name of
758 the variable with value values[i]. The function copies the first
759 nmap variable from map/values into dict. If values[i] is NULL,
760 the variable is deleted from dict.
761
762 If deref is true, then the values being copied are cell variables
763 and the value is extracted from the cell variable before being put
764 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000766
Victor Stinner41bb43a2013-10-29 01:19:37 +0100767static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000768map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 Py_ssize_t j;
772 assert(PyTuple_Check(map));
773 assert(PyDict_Check(dict));
774 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800775 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyObject *key = PyTuple_GET_ITEM(map, j);
777 PyObject *value = values[j];
778 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400779 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 assert(PyCell_Check(value));
781 value = PyCell_GET(value);
782 }
783 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100784 if (PyObject_DelItem(dict, key) != 0) {
785 if (PyErr_ExceptionMatches(PyExc_KeyError))
786 PyErr_Clear();
787 else
788 return -1;
789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 }
791 else {
792 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100793 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 }
795 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100796 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000797}
798
Guido van Rossumd8faa362007-04-27 19:54:29 +0000799/* Copy values from the "locals" dict into the fast locals.
800
801 dict is an input argument containing string keys representing
802 variables names and arbitrary PyObject* as values.
803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000805 values is an array of PyObject*. At index i, map[i] is the name of
806 the variable with value values[i]. The function copies the first
807 nmap variable from map/values into dict. If values[i] is NULL,
808 the variable is deleted from dict.
809
810 If deref is true, then the values being copied are cell variables
811 and the value is extracted from the cell variable before being put
812 in dict. If clear is true, then variables in map but not in dict
813 are set to NULL in map; if clear is false, variables missing in
814 dict are ignored.
815
816 Exceptions raised while modifying the dict are silently ignored,
817 because there is no good way to report them.
818*/
819
Guido van Rossum6b356e72001-04-14 17:55:41 +0000820static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000821dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 Py_ssize_t j;
825 assert(PyTuple_Check(map));
826 assert(PyDict_Check(dict));
827 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800828 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyObject *key = PyTuple_GET_ITEM(map, j);
830 PyObject *value = PyObject_GetItem(dict, key);
831 assert(PyUnicode_Check(key));
832 /* We only care about NULLs if clear is true. */
833 if (value == NULL) {
834 PyErr_Clear();
835 if (!clear)
836 continue;
837 }
838 if (deref) {
839 assert(PyCell_Check(values[j]));
840 if (PyCell_GET(values[j]) != value) {
841 if (PyCell_Set(values[j], value) < 0)
842 PyErr_Clear();
843 }
844 } else if (values[j] != value) {
845 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300846 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 }
848 Py_XDECREF(value);
849 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000850}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000851
Victor Stinner41bb43a2013-10-29 01:19:37 +0100852int
853PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* Merge fast locals into f->f_locals */
856 PyObject *locals, *map;
857 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyCodeObject *co;
859 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100860 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100861
862 if (f == NULL) {
863 PyErr_BadInternalCall();
864 return -1;
865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 locals = f->f_locals;
867 if (locals == NULL) {
868 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100869 if (locals == NULL)
870 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 }
872 co = f->f_code;
873 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100874 if (!PyTuple_Check(map)) {
875 PyErr_Format(PyExc_SystemError,
876 "co_varnames must be a tuple, not %s",
877 Py_TYPE(map)->tp_name);
878 return -1;
879 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 fast = f->f_localsplus;
881 j = PyTuple_GET_SIZE(map);
882 if (j > co->co_nlocals)
883 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100884 if (co->co_nlocals) {
885 if (map_to_dict(map, j, locals, fast, 0) < 0)
886 return -1;
887 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 ncells = PyTuple_GET_SIZE(co->co_cellvars);
889 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
890 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100891 if (map_to_dict(co->co_cellvars, ncells,
892 locals, fast + co->co_nlocals, 1))
893 return -1;
894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* If the namespace is unoptimized, then one of the
896 following cases applies:
897 1. It does not contain free variables, because it
898 uses import * or is a top-level namespace.
899 2. It is a class namespace.
900 We don't want to accidentally copy free variables
901 into the locals dict used by the class.
902 */
903 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100904 if (map_to_dict(co->co_freevars, nfreevars,
905 locals, fast + co->co_nlocals + ncells, 1) < 0)
906 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 }
908 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100909 return 0;
910}
911
912void
913PyFrame_FastToLocals(PyFrameObject *f)
914{
915 int res;
916
917 assert(!PyErr_Occurred());
918
919 res = PyFrame_FastToLocalsWithError(f);
920 if (res < 0)
921 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000922}
923
924void
Fred Drake1b190b42000-07-09 05:40:56 +0000925PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* Merge f->f_locals into fast locals */
928 PyObject *locals, *map;
929 PyObject **fast;
930 PyObject *error_type, *error_value, *error_traceback;
931 PyCodeObject *co;
932 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100933 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (f == NULL)
935 return;
936 locals = f->f_locals;
937 co = f->f_code;
938 map = co->co_varnames;
939 if (locals == NULL)
940 return;
941 if (!PyTuple_Check(map))
942 return;
943 PyErr_Fetch(&error_type, &error_value, &error_traceback);
944 fast = f->f_localsplus;
945 j = PyTuple_GET_SIZE(map);
946 if (j > co->co_nlocals)
947 j = co->co_nlocals;
948 if (co->co_nlocals)
949 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
950 ncells = PyTuple_GET_SIZE(co->co_cellvars);
951 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
952 if (ncells || nfreevars) {
953 dict_to_map(co->co_cellvars, ncells,
954 locals, fast + co->co_nlocals, 1, clear);
955 /* Same test as in PyFrame_FastToLocals() above. */
956 if (co->co_flags & CO_OPTIMIZED) {
957 dict_to_map(co->co_freevars, nfreevars,
958 locals, fast + co->co_nlocals + ncells, 1,
959 clear);
960 }
961 }
962 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000963}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000964
965/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000966int
967PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 int freelist_size = numfree;
970
971 while (free_list != NULL) {
972 PyFrameObject *f = free_list;
973 free_list = free_list->f_back;
974 PyObject_GC_Del(f);
975 --numfree;
976 }
977 assert(numfree == 0);
978 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000979}
980
981void
982PyFrame_Fini(void)
983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000985}
David Malcolm49526f42012-06-22 14:55:41 -0400986
987/* Print summary info about the state of the optimized allocator */
988void
989_PyFrame_DebugMallocStats(FILE *out)
990{
991 _PyDebugAllocatorStats(out,
992 "free PyFrameObject",
993 numfree, sizeof(PyFrameObject));
994}
995