blob: b1a83d82a398a83c4c06706103bb392bd73f79c6 [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"
Victor Stinnerbcda8f12018-11-21 22:27:47 +01004#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pystate.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#include "frameobject.h"
9#include "opcode.h"
10#include "structmember.h"
11
Guido van Rossum18752471997-04-29 14:49:28 +000012#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000013
Guido van Rossum6f799372001-09-20 20:46:19 +000014static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100015 {"f_back", T_OBJECT, OFF(f_back), READONLY},
16 {"f_code", T_OBJECT, OFF(f_code), READONLY},
17 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
18 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
19 {"f_lasti", T_INT, OFF(f_lasti), READONLY},
Nick Coghlan5a851672017-09-08 10:14:16 +100020 {"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
21 {"f_trace_opcodes", T_BOOL, OFF(f_trace_opcodes), 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000023};
24
Guido van Rossum18752471997-04-29 14:49:28 +000025static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000026frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000027{
Victor Stinner41bb43a2013-10-29 01:19:37 +010028 if (PyFrame_FastToLocalsWithError(f) < 0)
29 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 Py_INCREF(f->f_locals);
31 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000032}
33
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000034int
35PyFrame_GetLineNumber(PyFrameObject *f)
36{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 if (f->f_trace)
38 return f->f_lineno;
39 else
40 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000041}
42
Michael W. Hudsondd32a912002-08-15 14:59:02 +000043static PyObject *
44frame_getlineno(PyFrameObject *f, void *closure)
45{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000047}
48
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020049
50/* Given the index of the effective opcode,
51 scan back to construct the oparg with EXTENDED_ARG */
52static unsigned int
53get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
54{
55 _Py_CODEUNIT word;
56 unsigned int oparg = _Py_OPARG(codestr[i]);
57 if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
58 oparg |= _Py_OPARG(word) << 8;
59 if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
60 oparg |= _Py_OPARG(word) << 16;
61 if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
62 oparg |= _Py_OPARG(word) << 24;
63 }
64 }
65 }
66 return oparg;
67}
68
69
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000070/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000072 * lines are OK to jump to because they don't make any assumptions about the
73 * state of the stack (obvious because you could remove the line and the code
74 * would still work without any stack errors), but there are some constructs
75 * that limit jumping:
76 *
77 * o Lines with an 'except' statement on them can't be jumped to, because
78 * they expect an exception to be on the top of the stack.
79 * o Lines that live in a 'finally' block can't be jumped from or to, since
80 * the END_FINALLY expects to clean up the stack after the 'try' block.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020081 * o 'try', 'with' and 'async with' blocks can't be jumped into because
82 * the blockstack needs to be set up before their code runs.
83 * o 'for' and 'async for' loops can't be jumped into because the
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000084 * iterator needs to be on the stack.
xdegayeb8e9d6c2018-03-13 18:31:31 +010085 * o Jumps cannot be made from within a trace function invoked with a
86 * 'return' or 'exception' event since the eval loop has been exited at
87 * that time.
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000088 */
89static int
90frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
91{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 int new_lineno = 0; /* The new value of f_lineno */
93 long l_new_lineno;
94 int overflow;
95 int new_lasti = 0; /* The new value of f_lasti */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 unsigned char *code = NULL; /* The bytecode for the frame... */
97 Py_ssize_t code_len = 0; /* ...and its length */
98 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
99 Py_ssize_t lnotab_len = 0; /* (ditto) */
100 int offset = 0; /* (ditto) */
101 int line = 0; /* (ditto) */
102 int addr = 0; /* (ditto) */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200103 int delta_iblock = 0; /* Scanning the SETUPs and POPs */
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200104 int delta = 0;
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) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200259 if (op != FOR_ITER && code[target_addr] != END_ASYNC_FOR) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200260 delta_iblock++;
261 }
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200262 else if (!delta_iblock) {
263 /* Pop the iterators of any 'for' and 'async for' loop
264 * we're jumping out of. */
265 delta++;
266 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200267 }
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200268 if (op != FOR_ITER && code[target_addr] != END_ASYNC_FOR) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200269 blockstack[blockstack_top++] = target_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 }
271 break;
272 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000273
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200274 case END_FINALLY: {
275 assert(blockstack_top > 0);
276 int target_addr = blockstack[--blockstack_top];
277 assert(target_addr <= addr);
278 int first_in = target_addr <= f->f_lasti && f->f_lasti <= addr;
279 int second_in = target_addr <= new_lasti && new_lasti <= addr;
280 if (first_in != second_in) {
Serhiy Storchaka397466d2018-03-23 14:46:45 +0200281 op = code[target_addr];
282 PyErr_Format(PyExc_ValueError,
283 "can't jump %s %s block",
284 second_in ? "into" : "out of",
285 (op == DUP_TOP || op == POP_TOP) ?
286 "an 'except'" : "a 'finally'");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200287 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200289 break;
290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* Verify that the blockstack tracking code didn't get lost. */
295 assert(blockstack_top == 0);
296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 /* Pop any blocks that we're jumping out of. */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200298 if (delta_iblock > 0) {
299 f->f_iblock -= delta_iblock;
300 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Victor Stinner078c4e32018-04-27 14:30:01 +0200301 delta += (int)(f->f_stacktop - f->f_valuestack) - b->b_level;
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200302 if (b->b_type == SETUP_FINALLY &&
303 code[b->b_handler] == WITH_CLEANUP_START)
304 {
305 /* Pop the exit function. */
306 delta++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 }
308 }
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200309 while (delta > 0) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200310 PyObject *v = (*--f->f_stacktop);
311 Py_DECREF(v);
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200312 delta--;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200313 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 /* Finally set the new f_lineno and f_lasti and return OK. */
316 f->f_lineno = new_lineno;
317 f->f_lasti = new_lasti;
318 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000319}
320
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000321static PyObject *
322frame_gettrace(PyFrameObject *f, void *closure)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (trace == NULL)
327 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000332}
333
334static int
335frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 /* We rely on f_lineno being accurate when f_trace is set. */
338 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000339
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300340 if (v == Py_None)
341 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300343 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000346}
347
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000348
Guido van Rossum32d34c82001-09-20 21:45:26 +0000349static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 {"f_locals", (getter)frame_getlocals, NULL, NULL},
351 {"f_lineno", (getter)frame_getlineno,
352 (setter)frame_setlineno, NULL},
353 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
354 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000355};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000356
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000357/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000358 In an attempt to improve the speed of function calls, we:
359
360 1. Hold a single "zombie" frame on each code object. This retains
361 the allocated and initialised frame object from an invocation of
362 the code object. The zombie is reanimated the next time we need a
363 frame object for that code object. Doing this saves the malloc/
364 realloc required when using a free_list frame that isn't the
365 correct size. It also saves some field initialisation.
366
367 In zombie mode, no field of PyFrameObject holds a reference, but
368 the following fields are still valid:
369
370 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371
Mark Shannonae3087c2017-10-22 22:41:51 +0100372 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373
374 * f_localsplus does not require re-allocation and
375 the local variables in f_localsplus are NULL.
376
377 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000378 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000379 a stack frame is on the free list, only the following members have
380 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 ob_type == &Frametype
382 f_back next item on free list, or NULL
383 f_stacksize size of value stack
384 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000385 Note that the value and block stacks are preserved -- this can save
386 another malloc() call or two (and two free() calls as well!).
387 Also note that, unlike for integers, each frame object is a
388 malloc'ed object in its own right -- it is only the actual calls to
389 malloc() that we are trying to save here, not the administration.
390 After all, while a typical program may make millions of calls, a
391 call depth of more than 20 or 30 is probably already exceptional
392 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000393
Christian Heimes2202f872008-02-06 14:31:34 +0000394 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000395 free_list. Else programs creating lots of cyclic trash involving
396 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000397*/
398
Guido van Rossum18752471997-04-29 14:49:28 +0000399static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000401/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000403
Victor Stinnerc6944e72016-11-11 02:13:35 +0100404static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000405frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000406{
Antoine Pitrou93963562013-05-14 20:37:52 +0200407 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000409
INADA Naoki5a625d02016-12-24 20:19:08 +0900410 if (_PyObject_GC_IS_TRACKED(f))
411 _PyObject_GC_UNTRACK(f);
412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200414 /* Kill all local variables */
415 valuestack = f->f_valuestack;
416 for (p = f->f_localsplus; p < valuestack; p++)
417 Py_CLEAR(*p);
418
419 /* Free stack */
420 if (f->f_stacktop != NULL) {
421 for (p = valuestack; p < f->f_stacktop; p++)
422 Py_XDECREF(*p);
423 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_XDECREF(f->f_back);
426 Py_DECREF(f->f_builtins);
427 Py_DECREF(f->f_globals);
428 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200429 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 co = f->f_code;
432 if (co->co_zombieframe == NULL)
433 co->co_zombieframe = f;
434 else if (numfree < PyFrame_MAXFREELIST) {
435 ++numfree;
436 f->f_back = free_list;
437 free_list = f;
438 }
439 else
440 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 Py_DECREF(co);
443 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000444}
445
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000446static int
447frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100450 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 Py_VISIT(f->f_back);
453 Py_VISIT(f->f_code);
454 Py_VISIT(f->f_builtins);
455 Py_VISIT(f->f_globals);
456 Py_VISIT(f->f_locals);
457 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 /* locals */
460 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
461 fastlocals = f->f_localsplus;
462 for (i = slots; --i >= 0; ++fastlocals)
463 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* stack */
466 if (f->f_stacktop != NULL) {
467 for (p = f->f_valuestack; p < f->f_stacktop; p++)
468 Py_VISIT(*p);
469 }
470 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000471}
472
473static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200474frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100477 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000478
Antoine Pitrou93963562013-05-14 20:37:52 +0200479 /* Before anything else, make sure that this frame is clearly marked
480 * as being defunct! Else, e.g., a generator reachable from this
481 * frame may also point to this frame, believe itself to still be
482 * active, and try cleaning up this frame again.
483 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 oldtop = f->f_stacktop;
485 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200486 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* locals */
491 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
492 fastlocals = f->f_localsplus;
493 for (i = slots; --i >= 0; ++fastlocals)
494 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* stack */
497 if (oldtop != NULL) {
498 for (p = f->f_valuestack; p < oldtop; p++)
499 Py_CLEAR(*p);
500 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000501}
502
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000503static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530504frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200505{
506 if (f->f_executing) {
507 PyErr_SetString(PyExc_RuntimeError,
508 "cannot clear an executing frame");
509 return NULL;
510 }
511 if (f->f_gen) {
512 _PyGen_Finalize(f->f_gen);
513 assert(f->f_gen == NULL);
514 }
515 frame_tp_clear(f);
516 Py_RETURN_NONE;
517}
518
519PyDoc_STRVAR(clear__doc__,
520"F.clear(): clear most references held by the frame");
521
522static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530523frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
528 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
529 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
530 ncells + nfrees;
531 /* subtract one as it is already included in PyFrameObject */
532 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000535}
536
537PyDoc_STRVAR(sizeof__doc__,
538"F.__sizeof__() -> size of F in memory, in bytes");
539
Antoine Pitrou14709142017-12-31 22:35:22 +0100540static PyObject *
541frame_repr(PyFrameObject *f)
542{
543 int lineno = PyFrame_GetLineNumber(f);
544 return PyUnicode_FromFormat(
545 "<frame at %p, file %R, line %d, code %S>",
546 f, f->f_code->co_filename, lineno, f->f_code->co_name);
547}
548
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000549static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200550 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
551 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
553 sizeof__doc__},
554 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000555};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000556
Guido van Rossum18752471997-04-29 14:49:28 +0000557PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 PyVarObject_HEAD_INIT(&PyType_Type, 0)
559 "frame",
560 sizeof(PyFrameObject),
561 sizeof(PyObject *),
562 (destructor)frame_dealloc, /* tp_dealloc */
563 0, /* tp_print */
564 0, /* tp_getattr */
565 0, /* tp_setattr */
566 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100567 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 0, /* tp_as_number */
569 0, /* tp_as_sequence */
570 0, /* tp_as_mapping */
571 0, /* tp_hash */
572 0, /* tp_call */
573 0, /* tp_str */
574 PyObject_GenericGetAttr, /* tp_getattro */
575 PyObject_GenericSetAttr, /* tp_setattro */
576 0, /* tp_as_buffer */
577 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
578 0, /* tp_doc */
579 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200580 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 0, /* tp_richcompare */
582 0, /* tp_weaklistoffset */
583 0, /* tp_iter */
584 0, /* tp_iternext */
585 frame_methods, /* tp_methods */
586 frame_memberlist, /* tp_members */
587 frame_getsetlist, /* tp_getset */
588 0, /* tp_base */
589 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000590};
591
Victor Stinner07e9e382013-11-07 22:22:39 +0100592_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000593
Victor Stinnerc6944e72016-11-11 02:13:35 +0100594PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900595_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
596 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 PyFrameObject *back = tstate->frame;
599 PyFrameObject *f;
600 PyObject *builtins;
601 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000602
Michael W. Hudson69734a52002-08-19 16:54:08 +0000603#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
605 (locals != NULL && !PyMapping_Check(locals))) {
606 PyErr_BadInternalCall();
607 return NULL;
608 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000609#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100611 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (builtins) {
613 if (PyModule_Check(builtins)) {
614 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200615 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 }
618 if (builtins == NULL) {
619 /* No builtins! Make up a minimal one
620 Give them 'None', at least. */
621 builtins = PyDict_New();
622 if (builtins == NULL ||
623 PyDict_SetItemString(
624 builtins, "None", Py_None) < 0)
625 return NULL;
626 }
627 else
628 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 }
631 else {
632 /* If we share the globals, we share the builtins.
633 Save a lookup and a call. */
634 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200635 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_INCREF(builtins);
637 }
638 if (code->co_zombieframe != NULL) {
639 f = code->co_zombieframe;
640 code->co_zombieframe = NULL;
641 _Py_NewReference((PyObject *)f);
642 assert(f->f_code == code);
643 }
644 else {
645 Py_ssize_t extras, ncells, nfrees;
646 ncells = PyTuple_GET_SIZE(code->co_cellvars);
647 nfrees = PyTuple_GET_SIZE(code->co_freevars);
648 extras = code->co_stacksize + code->co_nlocals + ncells +
649 nfrees;
650 if (free_list == NULL) {
651 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
652 extras);
653 if (f == NULL) {
654 Py_DECREF(builtins);
655 return NULL;
656 }
657 }
658 else {
659 assert(numfree > 0);
660 --numfree;
661 f = free_list;
662 free_list = free_list->f_back;
663 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000664 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
665 if (new_f == NULL) {
666 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 Py_DECREF(builtins);
668 return NULL;
669 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000670 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 }
672 _Py_NewReference((PyObject *)f);
673 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 f->f_code = code;
676 extras = code->co_nlocals + ncells + nfrees;
677 f->f_valuestack = f->f_localsplus + extras;
678 for (i=0; i<extras; i++)
679 f->f_localsplus[i] = NULL;
680 f->f_locals = NULL;
681 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 }
683 f->f_stacktop = f->f_valuestack;
684 f->f_builtins = builtins;
685 Py_XINCREF(back);
686 f->f_back = back;
687 Py_INCREF(code);
688 Py_INCREF(globals);
689 f->f_globals = globals;
690 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
691 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
692 (CO_NEWLOCALS | CO_OPTIMIZED))
693 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
694 else if (code->co_flags & CO_NEWLOCALS) {
695 locals = PyDict_New();
696 if (locals == NULL) {
697 Py_DECREF(f);
698 return NULL;
699 }
700 f->f_locals = locals;
701 }
702 else {
703 if (locals == NULL)
704 locals = globals;
705 Py_INCREF(locals);
706 f->f_locals = locals;
707 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 f->f_lasti = -1;
710 f->f_lineno = code->co_firstlineno;
711 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200712 f->f_executing = 0;
713 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000714 f->f_trace_opcodes = 0;
715 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000718}
719
INADA Naoki5a625d02016-12-24 20:19:08 +0900720PyFrameObject*
721PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
722 PyObject *globals, PyObject *locals)
723{
724 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
725 if (f)
726 _PyObject_GC_TRACK(f);
727 return f;
728}
729
730
Guido van Rossum3f5da241990-12-20 15:06:42 +0000731/* Block management */
732
733void
Fred Drake1b190b42000-07-09 05:40:56 +0000734PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyTryBlock *b;
737 if (f->f_iblock >= CO_MAXBLOCKS)
738 Py_FatalError("XXX block stack overflow");
739 b = &f->f_blockstack[f->f_iblock++];
740 b->b_type = type;
741 b->b_level = level;
742 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000743}
744
Guido van Rossum18752471997-04-29 14:49:28 +0000745PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000746PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 PyTryBlock *b;
749 if (f->f_iblock <= 0)
750 Py_FatalError("XXX block stack underflow");
751 b = &f->f_blockstack[--f->f_iblock];
752 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000753}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000754
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756
757 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 values is an array of PyObject*. At index i, map[i] is the name of
759 the variable with value values[i]. The function copies the first
760 nmap variable from map/values into dict. If values[i] is NULL,
761 the variable is deleted from dict.
762
763 If deref is true, then the values being copied are cell variables
764 and the value is extracted from the cell variable before being put
765 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000767
Victor Stinner41bb43a2013-10-29 01:19:37 +0100768static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000769map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 Py_ssize_t j;
773 assert(PyTuple_Check(map));
774 assert(PyDict_Check(dict));
775 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800776 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyObject *key = PyTuple_GET_ITEM(map, j);
778 PyObject *value = values[j];
779 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400780 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 assert(PyCell_Check(value));
782 value = PyCell_GET(value);
783 }
784 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100785 if (PyObject_DelItem(dict, key) != 0) {
786 if (PyErr_ExceptionMatches(PyExc_KeyError))
787 PyErr_Clear();
788 else
789 return -1;
790 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 }
792 else {
793 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100794 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
796 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100797 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000798}
799
Guido van Rossumd8faa362007-04-27 19:54:29 +0000800/* Copy values from the "locals" dict into the fast locals.
801
802 dict is an input argument containing string keys representing
803 variables names and arbitrary PyObject* as values.
804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000806 values is an array of PyObject*. At index i, map[i] is the name of
807 the variable with value values[i]. The function copies the first
808 nmap variable from map/values into dict. If values[i] is NULL,
809 the variable is deleted from dict.
810
811 If deref is true, then the values being copied are cell variables
812 and the value is extracted from the cell variable before being put
813 in dict. If clear is true, then variables in map but not in dict
814 are set to NULL in map; if clear is false, variables missing in
815 dict are ignored.
816
817 Exceptions raised while modifying the dict are silently ignored,
818 because there is no good way to report them.
819*/
820
Guido van Rossum6b356e72001-04-14 17:55:41 +0000821static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000822dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 Py_ssize_t j;
826 assert(PyTuple_Check(map));
827 assert(PyDict_Check(dict));
828 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800829 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *key = PyTuple_GET_ITEM(map, j);
831 PyObject *value = PyObject_GetItem(dict, key);
832 assert(PyUnicode_Check(key));
833 /* We only care about NULLs if clear is true. */
834 if (value == NULL) {
835 PyErr_Clear();
836 if (!clear)
837 continue;
838 }
839 if (deref) {
840 assert(PyCell_Check(values[j]));
841 if (PyCell_GET(values[j]) != value) {
842 if (PyCell_Set(values[j], value) < 0)
843 PyErr_Clear();
844 }
845 } else if (values[j] != value) {
846 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300847 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
849 Py_XDECREF(value);
850 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000851}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000852
Victor Stinner41bb43a2013-10-29 01:19:37 +0100853int
854PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 /* Merge fast locals into f->f_locals */
857 PyObject *locals, *map;
858 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyCodeObject *co;
860 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100861 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100862
863 if (f == NULL) {
864 PyErr_BadInternalCall();
865 return -1;
866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 locals = f->f_locals;
868 if (locals == NULL) {
869 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100870 if (locals == NULL)
871 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 }
873 co = f->f_code;
874 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100875 if (!PyTuple_Check(map)) {
876 PyErr_Format(PyExc_SystemError,
877 "co_varnames must be a tuple, not %s",
878 Py_TYPE(map)->tp_name);
879 return -1;
880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 fast = f->f_localsplus;
882 j = PyTuple_GET_SIZE(map);
883 if (j > co->co_nlocals)
884 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100885 if (co->co_nlocals) {
886 if (map_to_dict(map, j, locals, fast, 0) < 0)
887 return -1;
888 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 ncells = PyTuple_GET_SIZE(co->co_cellvars);
890 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
891 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100892 if (map_to_dict(co->co_cellvars, ncells,
893 locals, fast + co->co_nlocals, 1))
894 return -1;
895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 /* If the namespace is unoptimized, then one of the
897 following cases applies:
898 1. It does not contain free variables, because it
899 uses import * or is a top-level namespace.
900 2. It is a class namespace.
901 We don't want to accidentally copy free variables
902 into the locals dict used by the class.
903 */
904 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100905 if (map_to_dict(co->co_freevars, nfreevars,
906 locals, fast + co->co_nlocals + ncells, 1) < 0)
907 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
909 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100910 return 0;
911}
912
913void
914PyFrame_FastToLocals(PyFrameObject *f)
915{
916 int res;
917
918 assert(!PyErr_Occurred());
919
920 res = PyFrame_FastToLocalsWithError(f);
921 if (res < 0)
922 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000923}
924
925void
Fred Drake1b190b42000-07-09 05:40:56 +0000926PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* Merge f->f_locals into fast locals */
929 PyObject *locals, *map;
930 PyObject **fast;
931 PyObject *error_type, *error_value, *error_traceback;
932 PyCodeObject *co;
933 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100934 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (f == NULL)
936 return;
937 locals = f->f_locals;
938 co = f->f_code;
939 map = co->co_varnames;
940 if (locals == NULL)
941 return;
942 if (!PyTuple_Check(map))
943 return;
944 PyErr_Fetch(&error_type, &error_value, &error_traceback);
945 fast = f->f_localsplus;
946 j = PyTuple_GET_SIZE(map);
947 if (j > co->co_nlocals)
948 j = co->co_nlocals;
949 if (co->co_nlocals)
950 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
951 ncells = PyTuple_GET_SIZE(co->co_cellvars);
952 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
953 if (ncells || nfreevars) {
954 dict_to_map(co->co_cellvars, ncells,
955 locals, fast + co->co_nlocals, 1, clear);
956 /* Same test as in PyFrame_FastToLocals() above. */
957 if (co->co_flags & CO_OPTIMIZED) {
958 dict_to_map(co->co_freevars, nfreevars,
959 locals, fast + co->co_nlocals + ncells, 1,
960 clear);
961 }
962 }
963 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000964}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000965
966/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000967int
968PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 int freelist_size = numfree;
971
972 while (free_list != NULL) {
973 PyFrameObject *f = free_list;
974 free_list = free_list->f_back;
975 PyObject_GC_Del(f);
976 --numfree;
977 }
978 assert(numfree == 0);
979 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000980}
981
982void
983PyFrame_Fini(void)
984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000986}
David Malcolm49526f42012-06-22 14:55:41 -0400987
988/* Print summary info about the state of the optimized allocator */
989void
990_PyFrame_DebugMallocStats(FILE *out)
991{
992 _PyDebugAllocatorStats(out,
993 "free PyFrameObject",
994 numfree, sizeof(PyFrameObject));
995}
996