blob: 400f99f6c96358dd72c1a5f906a63adf3582f281 [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
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +020090frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000091{
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
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200473static int
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 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200501 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000502}
503
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000504static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530505frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200506{
507 if (f->f_executing) {
508 PyErr_SetString(PyExc_RuntimeError,
509 "cannot clear an executing frame");
510 return NULL;
511 }
512 if (f->f_gen) {
513 _PyGen_Finalize(f->f_gen);
514 assert(f->f_gen == NULL);
515 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200516 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200517 Py_RETURN_NONE;
518}
519
520PyDoc_STRVAR(clear__doc__,
521"F.clear(): clear most references held by the frame");
522
523static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530524frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
529 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
530 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
531 ncells + nfrees;
532 /* subtract one as it is already included in PyFrameObject */
533 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000536}
537
538PyDoc_STRVAR(sizeof__doc__,
539"F.__sizeof__() -> size of F in memory, in bytes");
540
Antoine Pitrou14709142017-12-31 22:35:22 +0100541static PyObject *
542frame_repr(PyFrameObject *f)
543{
544 int lineno = PyFrame_GetLineNumber(f);
545 return PyUnicode_FromFormat(
546 "<frame at %p, file %R, line %d, code %S>",
547 f, f->f_code->co_filename, lineno, f->f_code->co_name);
548}
549
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000550static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200551 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
552 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
554 sizeof__doc__},
555 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000556};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000557
Guido van Rossum18752471997-04-29 14:49:28 +0000558PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 PyVarObject_HEAD_INIT(&PyType_Type, 0)
560 "frame",
561 sizeof(PyFrameObject),
562 sizeof(PyObject *),
563 (destructor)frame_dealloc, /* tp_dealloc */
564 0, /* tp_print */
565 0, /* tp_getattr */
566 0, /* tp_setattr */
567 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100568 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 0, /* tp_as_number */
570 0, /* tp_as_sequence */
571 0, /* tp_as_mapping */
572 0, /* tp_hash */
573 0, /* tp_call */
574 0, /* tp_str */
575 PyObject_GenericGetAttr, /* tp_getattro */
576 PyObject_GenericSetAttr, /* tp_setattro */
577 0, /* tp_as_buffer */
578 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
579 0, /* tp_doc */
580 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200581 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 0, /* tp_richcompare */
583 0, /* tp_weaklistoffset */
584 0, /* tp_iter */
585 0, /* tp_iternext */
586 frame_methods, /* tp_methods */
587 frame_memberlist, /* tp_members */
588 frame_getsetlist, /* tp_getset */
589 0, /* tp_base */
590 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000591};
592
Victor Stinner07e9e382013-11-07 22:22:39 +0100593_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000594
Victor Stinnerc6944e72016-11-11 02:13:35 +0100595PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900596_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
597 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 PyFrameObject *back = tstate->frame;
600 PyFrameObject *f;
601 PyObject *builtins;
602 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000603
Michael W. Hudson69734a52002-08-19 16:54:08 +0000604#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
606 (locals != NULL && !PyMapping_Check(locals))) {
607 PyErr_BadInternalCall();
608 return NULL;
609 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000610#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100612 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (builtins) {
614 if (PyModule_Check(builtins)) {
615 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200616 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 }
619 if (builtins == NULL) {
620 /* No builtins! Make up a minimal one
621 Give them 'None', at least. */
622 builtins = PyDict_New();
623 if (builtins == NULL ||
624 PyDict_SetItemString(
625 builtins, "None", Py_None) < 0)
626 return NULL;
627 }
628 else
629 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 }
632 else {
633 /* If we share the globals, we share the builtins.
634 Save a lookup and a call. */
635 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200636 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 Py_INCREF(builtins);
638 }
639 if (code->co_zombieframe != NULL) {
640 f = code->co_zombieframe;
641 code->co_zombieframe = NULL;
642 _Py_NewReference((PyObject *)f);
643 assert(f->f_code == code);
644 }
645 else {
646 Py_ssize_t extras, ncells, nfrees;
647 ncells = PyTuple_GET_SIZE(code->co_cellvars);
648 nfrees = PyTuple_GET_SIZE(code->co_freevars);
649 extras = code->co_stacksize + code->co_nlocals + ncells +
650 nfrees;
651 if (free_list == NULL) {
652 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
653 extras);
654 if (f == NULL) {
655 Py_DECREF(builtins);
656 return NULL;
657 }
658 }
659 else {
660 assert(numfree > 0);
661 --numfree;
662 f = free_list;
663 free_list = free_list->f_back;
664 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000665 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
666 if (new_f == NULL) {
667 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 Py_DECREF(builtins);
669 return NULL;
670 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000671 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 }
673 _Py_NewReference((PyObject *)f);
674 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 f->f_code = code;
677 extras = code->co_nlocals + ncells + nfrees;
678 f->f_valuestack = f->f_localsplus + extras;
679 for (i=0; i<extras; i++)
680 f->f_localsplus[i] = NULL;
681 f->f_locals = NULL;
682 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
684 f->f_stacktop = f->f_valuestack;
685 f->f_builtins = builtins;
686 Py_XINCREF(back);
687 f->f_back = back;
688 Py_INCREF(code);
689 Py_INCREF(globals);
690 f->f_globals = globals;
691 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
692 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
693 (CO_NEWLOCALS | CO_OPTIMIZED))
694 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
695 else if (code->co_flags & CO_NEWLOCALS) {
696 locals = PyDict_New();
697 if (locals == NULL) {
698 Py_DECREF(f);
699 return NULL;
700 }
701 f->f_locals = locals;
702 }
703 else {
704 if (locals == NULL)
705 locals = globals;
706 Py_INCREF(locals);
707 f->f_locals = locals;
708 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 f->f_lasti = -1;
711 f->f_lineno = code->co_firstlineno;
712 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200713 f->f_executing = 0;
714 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000715 f->f_trace_opcodes = 0;
716 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000719}
720
INADA Naoki5a625d02016-12-24 20:19:08 +0900721PyFrameObject*
722PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
723 PyObject *globals, PyObject *locals)
724{
725 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
726 if (f)
727 _PyObject_GC_TRACK(f);
728 return f;
729}
730
731
Guido van Rossum3f5da241990-12-20 15:06:42 +0000732/* Block management */
733
734void
Fred Drake1b190b42000-07-09 05:40:56 +0000735PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyTryBlock *b;
738 if (f->f_iblock >= CO_MAXBLOCKS)
739 Py_FatalError("XXX block stack overflow");
740 b = &f->f_blockstack[f->f_iblock++];
741 b->b_type = type;
742 b->b_level = level;
743 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000744}
745
Guido van Rossum18752471997-04-29 14:49:28 +0000746PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000747PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 PyTryBlock *b;
750 if (f->f_iblock <= 0)
751 Py_FatalError("XXX block stack underflow");
752 b = &f->f_blockstack[--f->f_iblock];
753 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000754}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000755
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757
758 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000759 values is an array of PyObject*. At index i, map[i] is the name of
760 the variable with value values[i]. The function copies the first
761 nmap variable from map/values into dict. If values[i] is NULL,
762 the variable is deleted from dict.
763
764 If deref is true, then the values being copied are cell variables
765 and the value is extracted from the cell variable before being put
766 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000768
Victor Stinner41bb43a2013-10-29 01:19:37 +0100769static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000770map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 Py_ssize_t j;
774 assert(PyTuple_Check(map));
775 assert(PyDict_Check(dict));
776 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800777 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *key = PyTuple_GET_ITEM(map, j);
779 PyObject *value = values[j];
780 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400781 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 assert(PyCell_Check(value));
783 value = PyCell_GET(value);
784 }
785 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100786 if (PyObject_DelItem(dict, key) != 0) {
787 if (PyErr_ExceptionMatches(PyExc_KeyError))
788 PyErr_Clear();
789 else
790 return -1;
791 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 }
793 else {
794 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100795 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 }
797 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100798 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000799}
800
Guido van Rossumd8faa362007-04-27 19:54:29 +0000801/* Copy values from the "locals" dict into the fast locals.
802
803 dict is an input argument containing string keys representing
804 variables names and arbitrary PyObject* as values.
805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000807 values is an array of PyObject*. At index i, map[i] is the name of
808 the variable with value values[i]. The function copies the first
809 nmap variable from map/values into dict. If values[i] is NULL,
810 the variable is deleted from dict.
811
812 If deref is true, then the values being copied are cell variables
813 and the value is extracted from the cell variable before being put
814 in dict. If clear is true, then variables in map but not in dict
815 are set to NULL in map; if clear is false, variables missing in
816 dict are ignored.
817
818 Exceptions raised while modifying the dict are silently ignored,
819 because there is no good way to report them.
820*/
821
Guido van Rossum6b356e72001-04-14 17:55:41 +0000822static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000823dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 Py_ssize_t j;
827 assert(PyTuple_Check(map));
828 assert(PyDict_Check(dict));
829 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800830 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyObject *key = PyTuple_GET_ITEM(map, j);
832 PyObject *value = PyObject_GetItem(dict, key);
833 assert(PyUnicode_Check(key));
834 /* We only care about NULLs if clear is true. */
835 if (value == NULL) {
836 PyErr_Clear();
837 if (!clear)
838 continue;
839 }
840 if (deref) {
841 assert(PyCell_Check(values[j]));
842 if (PyCell_GET(values[j]) != value) {
843 if (PyCell_Set(values[j], value) < 0)
844 PyErr_Clear();
845 }
846 } else if (values[j] != value) {
847 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300848 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 }
850 Py_XDECREF(value);
851 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000852}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000853
Victor Stinner41bb43a2013-10-29 01:19:37 +0100854int
855PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 /* Merge fast locals into f->f_locals */
858 PyObject *locals, *map;
859 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PyCodeObject *co;
861 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100862 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100863
864 if (f == NULL) {
865 PyErr_BadInternalCall();
866 return -1;
867 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 locals = f->f_locals;
869 if (locals == NULL) {
870 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100871 if (locals == NULL)
872 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 }
874 co = f->f_code;
875 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100876 if (!PyTuple_Check(map)) {
877 PyErr_Format(PyExc_SystemError,
878 "co_varnames must be a tuple, not %s",
879 Py_TYPE(map)->tp_name);
880 return -1;
881 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 fast = f->f_localsplus;
883 j = PyTuple_GET_SIZE(map);
884 if (j > co->co_nlocals)
885 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100886 if (co->co_nlocals) {
887 if (map_to_dict(map, j, locals, fast, 0) < 0)
888 return -1;
889 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 ncells = PyTuple_GET_SIZE(co->co_cellvars);
891 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
892 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100893 if (map_to_dict(co->co_cellvars, ncells,
894 locals, fast + co->co_nlocals, 1))
895 return -1;
896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* If the namespace is unoptimized, then one of the
898 following cases applies:
899 1. It does not contain free variables, because it
900 uses import * or is a top-level namespace.
901 2. It is a class namespace.
902 We don't want to accidentally copy free variables
903 into the locals dict used by the class.
904 */
905 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100906 if (map_to_dict(co->co_freevars, nfreevars,
907 locals, fast + co->co_nlocals + ncells, 1) < 0)
908 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 }
910 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100911 return 0;
912}
913
914void
915PyFrame_FastToLocals(PyFrameObject *f)
916{
917 int res;
918
919 assert(!PyErr_Occurred());
920
921 res = PyFrame_FastToLocalsWithError(f);
922 if (res < 0)
923 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000924}
925
926void
Fred Drake1b190b42000-07-09 05:40:56 +0000927PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Merge f->f_locals into fast locals */
930 PyObject *locals, *map;
931 PyObject **fast;
932 PyObject *error_type, *error_value, *error_traceback;
933 PyCodeObject *co;
934 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100935 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (f == NULL)
937 return;
938 locals = f->f_locals;
939 co = f->f_code;
940 map = co->co_varnames;
941 if (locals == NULL)
942 return;
943 if (!PyTuple_Check(map))
944 return;
945 PyErr_Fetch(&error_type, &error_value, &error_traceback);
946 fast = f->f_localsplus;
947 j = PyTuple_GET_SIZE(map);
948 if (j > co->co_nlocals)
949 j = co->co_nlocals;
950 if (co->co_nlocals)
951 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
952 ncells = PyTuple_GET_SIZE(co->co_cellvars);
953 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
954 if (ncells || nfreevars) {
955 dict_to_map(co->co_cellvars, ncells,
956 locals, fast + co->co_nlocals, 1, clear);
957 /* Same test as in PyFrame_FastToLocals() above. */
958 if (co->co_flags & CO_OPTIMIZED) {
959 dict_to_map(co->co_freevars, nfreevars,
960 locals, fast + co->co_nlocals + ncells, 1,
961 clear);
962 }
963 }
964 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000965}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000966
967/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000968int
969PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 int freelist_size = numfree;
972
973 while (free_list != NULL) {
974 PyFrameObject *f = free_list;
975 free_list = free_list->f_back;
976 PyObject_GC_Del(f);
977 --numfree;
978 }
979 assert(numfree == 0);
980 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000981}
982
983void
984PyFrame_Fini(void)
985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000987}
David Malcolm49526f42012-06-22 14:55:41 -0400988
989/* Print summary info about the state of the optimized allocator */
990void
991_PyFrame_DebugMallocStats(FILE *out)
992{
993 _PyDebugAllocatorStats(out,
994 "free PyFrameObject",
995 numfree, sizeof(PyFrameObject));
996}
997