blob: 8488b96a9aab9d09b016b71f9ab0f6f5215a17cc [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
Zackery Spytz842acaa2018-12-17 07:52:45 -0700108 if (p_new_lineno == NULL) {
109 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
110 return -1;
111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 /* f_lineno must be an integer. */
113 if (!PyLong_CheckExact(p_new_lineno)) {
114 PyErr_SetString(PyExc_ValueError,
115 "lineno must be an integer");
116 return -1;
117 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000118
xdegayeb8e9d6c2018-03-13 18:31:31 +0100119 /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
120 * f->f_trace is NULL, check first on the first condition.
121 * Forbidding jumps from the 'call' event of a new frame is a side effect
122 * of allowing to set f_lineno only from trace functions. */
123 if (f->f_lasti == -1) {
124 PyErr_Format(PyExc_ValueError,
125 "can't jump from the 'call' trace event of a new frame");
126 return -1;
127 }
128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 /* You can only do this from within a trace function, not via
130 * _getframe or similar hackery. */
xdegayeb8e9d6c2018-03-13 18:31:31 +0100131 if (!f->f_trace) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyErr_Format(PyExc_ValueError,
xdegayeb8e9d6c2018-03-13 18:31:31 +0100133 "f_lineno can only be set by a trace function");
134 return -1;
135 }
136
137 /* Forbid jumps upon a 'return' trace event (except after executing a
138 * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case)
139 * and upon an 'exception' trace event.
140 * Jumps from 'call' trace events have already been forbidden above for new
141 * frames, so this check does not change anything for 'call' events. */
142 if (f->f_stacktop == NULL) {
143 PyErr_SetString(PyExc_ValueError,
144 "can only jump from a 'line' trace event");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 return -1;
146 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 /* Fail if the line comes before the start of the code block. */
149 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
150 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000151#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 || l_new_lineno > INT_MAX
153 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000154#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 ) {
156 PyErr_SetString(PyExc_ValueError,
157 "lineno out of range");
158 return -1;
159 }
160 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 if (new_lineno < f->f_code->co_firstlineno) {
163 PyErr_Format(PyExc_ValueError,
164 "line %d comes before the current code block",
165 new_lineno);
166 return -1;
167 }
168 else if (new_lineno == f->f_code->co_firstlineno) {
169 new_lasti = 0;
170 new_lineno = f->f_code->co_firstlineno;
171 }
172 else {
173 /* Find the bytecode offset for the start of the given
174 * line, or the first code-owning line after it. */
175 char *tmp;
176 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
177 &tmp, &lnotab_len);
178 lnotab = (unsigned char *) tmp;
179 addr = 0;
180 line = f->f_code->co_firstlineno;
181 new_lasti = -1;
182 for (offset = 0; offset < lnotab_len; offset += 2) {
183 addr += lnotab[offset];
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100184 line += (signed char)lnotab[offset+1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 if (line >= new_lineno) {
186 new_lasti = addr;
187 new_lineno = line;
188 break;
189 }
190 }
191 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 /* If we didn't reach the requested line, return an error. */
194 if (new_lasti == -1) {
195 PyErr_Format(PyExc_ValueError,
196 "line %d comes after the current code block",
197 new_lineno);
198 return -1;
199 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 /* We're now ready to look at the bytecode. */
202 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000203
xdegayeb8e9d6c2018-03-13 18:31:31 +0100204 /* The trace function is called with a 'return' trace event after the
205 * execution of a yield statement. */
206 assert(f->f_lasti != -1);
207 if (code[f->f_lasti] == YIELD_VALUE || code[f->f_lasti] == YIELD_FROM) {
208 PyErr_SetString(PyExc_ValueError,
209 "can't jump from a yield statement");
210 return -1;
211 }
212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* You can't jump onto a line with an 'except' statement on it -
214 * they expect to have an exception on the top of the stack, which
215 * won't be true if you jump to them. They always start with code
216 * that either pops the exception using POP_TOP (plain 'except:'
217 * lines do this) or duplicates the exception on the stack using
218 * DUP_TOP (if there's an exception type specified). See compile.c,
219 * 'com_try_except' for the full details. There aren't any other
220 * cases (AFAIK) where a line's code can start with DUP_TOP or
221 * POP_TOP, but if any ever appear, they'll be subject to the same
222 * restriction (but with a different error message). */
223 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
224 PyErr_SetString(PyExc_ValueError,
225 "can't jump to 'except' line as there's no exception");
226 return -1;
227 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 /* You can't jump into or out of a 'finally' block because the 'try'
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200230 * block leaves something on the stack for the END_FINALLY to clean up.
231 * So we walk the bytecode, maintaining a simulated blockstack.
232 * 'blockstack' is a stack of the bytecode addresses of the starts of
233 * the 'finally' blocks. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 memset(blockstack, '\0', sizeof(blockstack));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 blockstack_top = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300236 for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 unsigned char op = code[addr];
238 switch (op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400240 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400241 case SETUP_ASYNC_WITH:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200242 case FOR_ITER: {
243 unsigned int oparg = get_arg((const _Py_CODEUNIT *)code,
244 addr / sizeof(_Py_CODEUNIT));
245 int target_addr = addr + oparg + sizeof(_Py_CODEUNIT);
246 assert(target_addr < code_len);
247 /* Police block-jumping (you can't jump into the middle of a block)
248 * and ensure that the blockstack finishes up in a sensible state (by
249 * popping any blocks we're jumping out of). We look at all the
250 * blockstack operations between the current position and the new
251 * one, and keep track of how many blocks we drop out of on the way.
252 * By also keeping track of the lowest blockstack position we see, we
253 * can tell whether the jump goes into any blocks without coming out
254 * again - in that case we raise an exception below. */
255 int first_in = addr < f->f_lasti && f->f_lasti < target_addr;
256 int second_in = addr < new_lasti && new_lasti < target_addr;
257 if (!first_in && second_in) {
258 PyErr_SetString(PyExc_ValueError,
259 "can't jump into the middle of a block");
260 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200262 if (first_in && !second_in) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200263 if (op != FOR_ITER && code[target_addr] != END_ASYNC_FOR) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200264 delta_iblock++;
265 }
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200266 else if (!delta_iblock) {
267 /* Pop the iterators of any 'for' and 'async for' loop
268 * we're jumping out of. */
269 delta++;
270 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200271 }
Serhiy Storchaka702f8f32018-03-23 14:34:35 +0200272 if (op != FOR_ITER && code[target_addr] != END_ASYNC_FOR) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200273 blockstack[blockstack_top++] = target_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 }
275 break;
276 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000277
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200278 case END_FINALLY: {
279 assert(blockstack_top > 0);
280 int target_addr = blockstack[--blockstack_top];
281 assert(target_addr <= addr);
282 int first_in = target_addr <= f->f_lasti && f->f_lasti <= addr;
283 int second_in = target_addr <= new_lasti && new_lasti <= addr;
284 if (first_in != second_in) {
Serhiy Storchaka397466d2018-03-23 14:46:45 +0200285 op = code[target_addr];
286 PyErr_Format(PyExc_ValueError,
287 "can't jump %s %s block",
288 second_in ? "into" : "out of",
289 (op == DUP_TOP || op == POP_TOP) ?
290 "an 'except'" : "a 'finally'");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200291 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200293 break;
294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* Verify that the blockstack tracking code didn't get lost. */
299 assert(blockstack_top == 0);
300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 /* Pop any blocks that we're jumping out of. */
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200302 if (delta_iblock > 0) {
303 f->f_iblock -= delta_iblock;
304 PyTryBlock *b = &f->f_blockstack[f->f_iblock];
Victor Stinner078c4e32018-04-27 14:30:01 +0200305 delta += (int)(f->f_stacktop - f->f_valuestack) - b->b_level;
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200306 if (b->b_type == SETUP_FINALLY &&
307 code[b->b_handler] == WITH_CLEANUP_START)
308 {
309 /* Pop the exit function. */
310 delta++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 }
312 }
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200313 while (delta > 0) {
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200314 PyObject *v = (*--f->f_stacktop);
315 Py_DECREF(v);
Serhiy Storchaka26c9f562018-03-11 08:32:47 +0200316 delta--;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200317 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* Finally set the new f_lineno and f_lasti and return OK. */
320 f->f_lineno = new_lineno;
321 f->f_lasti = new_lasti;
322 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000323}
324
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000325static PyObject *
326frame_gettrace(PyFrameObject *f, void *closure)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (trace == NULL)
331 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000336}
337
338static int
339frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 /* We rely on f_lineno being accurate when f_trace is set. */
342 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000343
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300344 if (v == Py_None)
345 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300347 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000350}
351
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000352
Guido van Rossum32d34c82001-09-20 21:45:26 +0000353static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 {"f_locals", (getter)frame_getlocals, NULL, NULL},
355 {"f_lineno", (getter)frame_getlineno,
356 (setter)frame_setlineno, NULL},
357 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
358 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000360
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000361/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362 In an attempt to improve the speed of function calls, we:
363
364 1. Hold a single "zombie" frame on each code object. This retains
365 the allocated and initialised frame object from an invocation of
366 the code object. The zombie is reanimated the next time we need a
367 frame object for that code object. Doing this saves the malloc/
368 realloc required when using a free_list frame that isn't the
369 correct size. It also saves some field initialisation.
370
371 In zombie mode, no field of PyFrameObject holds a reference, but
372 the following fields are still valid:
373
374 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375
Mark Shannonae3087c2017-10-22 22:41:51 +0100376 * f_locals, f_trace are NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377
378 * f_localsplus does not require re-allocation and
379 the local variables in f_localsplus are NULL.
380
381 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000382 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383 a stack frame is on the free list, only the following members have
384 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 ob_type == &Frametype
386 f_back next item on free list, or NULL
387 f_stacksize size of value stack
388 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000389 Note that the value and block stacks are preserved -- this can save
390 another malloc() call or two (and two free() calls as well!).
391 Also note that, unlike for integers, each frame object is a
392 malloc'ed object in its own right -- it is only the actual calls to
393 malloc() that we are trying to save here, not the administration.
394 After all, while a typical program may make millions of calls, a
395 call depth of more than 20 or 30 is probably already exceptional
396 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000397
Christian Heimes2202f872008-02-06 14:31:34 +0000398 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000399 free_list. Else programs creating lots of cyclic trash involving
400 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000401*/
402
Guido van Rossum18752471997-04-29 14:49:28 +0000403static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000405/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000407
Victor Stinnerc6944e72016-11-11 02:13:35 +0100408static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000409frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000410{
Antoine Pitrou93963562013-05-14 20:37:52 +0200411 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000413
INADA Naoki5a625d02016-12-24 20:19:08 +0900414 if (_PyObject_GC_IS_TRACKED(f))
415 _PyObject_GC_UNTRACK(f);
416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200418 /* Kill all local variables */
419 valuestack = f->f_valuestack;
420 for (p = f->f_localsplus; p < valuestack; p++)
421 Py_CLEAR(*p);
422
423 /* Free stack */
424 if (f->f_stacktop != NULL) {
425 for (p = valuestack; p < f->f_stacktop; p++)
426 Py_XDECREF(*p);
427 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_XDECREF(f->f_back);
430 Py_DECREF(f->f_builtins);
431 Py_DECREF(f->f_globals);
432 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200433 Py_CLEAR(f->f_trace);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 co = f->f_code;
436 if (co->co_zombieframe == NULL)
437 co->co_zombieframe = f;
438 else if (numfree < PyFrame_MAXFREELIST) {
439 ++numfree;
440 f->f_back = free_list;
441 free_list = f;
442 }
443 else
444 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 Py_DECREF(co);
447 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000448}
449
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000450static int
451frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100454 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_VISIT(f->f_back);
457 Py_VISIT(f->f_code);
458 Py_VISIT(f->f_builtins);
459 Py_VISIT(f->f_globals);
460 Py_VISIT(f->f_locals);
461 Py_VISIT(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* locals */
464 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
465 fastlocals = f->f_localsplus;
466 for (i = slots; --i >= 0; ++fastlocals)
467 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 /* stack */
470 if (f->f_stacktop != NULL) {
471 for (p = f->f_valuestack; p < f->f_stacktop; p++)
472 Py_VISIT(*p);
473 }
474 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000475}
476
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200477static int
Antoine Pitrou58720d62013-08-05 23:26:40 +0200478frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100481 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000482
Antoine Pitrou93963562013-05-14 20:37:52 +0200483 /* Before anything else, make sure that this frame is clearly marked
484 * as being defunct! Else, e.g., a generator reachable from this
485 * frame may also point to this frame, believe itself to still be
486 * active, and try cleaning up this frame again.
487 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 oldtop = f->f_stacktop;
489 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200490 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* locals */
495 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
496 fastlocals = f->f_localsplus;
497 for (i = slots; --i >= 0; ++fastlocals)
498 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* stack */
501 if (oldtop != NULL) {
502 for (p = f->f_valuestack; p < oldtop; p++)
503 Py_CLEAR(*p);
504 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200505 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000506}
507
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000508static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530509frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Antoine Pitrou58720d62013-08-05 23:26:40 +0200510{
511 if (f->f_executing) {
512 PyErr_SetString(PyExc_RuntimeError,
513 "cannot clear an executing frame");
514 return NULL;
515 }
516 if (f->f_gen) {
517 _PyGen_Finalize(f->f_gen);
518 assert(f->f_gen == NULL);
519 }
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200520 (void)frame_tp_clear(f);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200521 Py_RETURN_NONE;
522}
523
524PyDoc_STRVAR(clear__doc__,
525"F.clear(): clear most references held by the frame");
526
527static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530528frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
533 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
534 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
535 ncells + nfrees;
536 /* subtract one as it is already included in PyFrameObject */
537 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000540}
541
542PyDoc_STRVAR(sizeof__doc__,
543"F.__sizeof__() -> size of F in memory, in bytes");
544
Antoine Pitrou14709142017-12-31 22:35:22 +0100545static PyObject *
546frame_repr(PyFrameObject *f)
547{
548 int lineno = PyFrame_GetLineNumber(f);
549 return PyUnicode_FromFormat(
550 "<frame at %p, file %R, line %d, code %S>",
551 f, f->f_code->co_filename, lineno, f->f_code->co_name);
552}
553
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000554static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200555 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
556 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
558 sizeof__doc__},
559 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000560};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000561
Guido van Rossum18752471997-04-29 14:49:28 +0000562PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyVarObject_HEAD_INIT(&PyType_Type, 0)
564 "frame",
565 sizeof(PyFrameObject),
566 sizeof(PyObject *),
567 (destructor)frame_dealloc, /* tp_dealloc */
568 0, /* tp_print */
569 0, /* tp_getattr */
570 0, /* tp_setattr */
571 0, /* tp_reserved */
Antoine Pitrou14709142017-12-31 22:35:22 +0100572 (reprfunc)frame_repr, /* tp_repr */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 0, /* tp_as_number */
574 0, /* tp_as_sequence */
575 0, /* tp_as_mapping */
576 0, /* tp_hash */
577 0, /* tp_call */
578 0, /* tp_str */
579 PyObject_GenericGetAttr, /* tp_getattro */
580 PyObject_GenericSetAttr, /* tp_setattro */
581 0, /* tp_as_buffer */
582 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
583 0, /* tp_doc */
584 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200585 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 0, /* tp_richcompare */
587 0, /* tp_weaklistoffset */
588 0, /* tp_iter */
589 0, /* tp_iternext */
590 frame_methods, /* tp_methods */
591 frame_memberlist, /* tp_members */
592 frame_getsetlist, /* tp_getset */
593 0, /* tp_base */
594 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000595};
596
Victor Stinner07e9e382013-11-07 22:22:39 +0100597_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000598
Victor Stinnerc6944e72016-11-11 02:13:35 +0100599PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900600_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
601 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyFrameObject *back = tstate->frame;
604 PyFrameObject *f;
605 PyObject *builtins;
606 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000607
Michael W. Hudson69734a52002-08-19 16:54:08 +0000608#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
610 (locals != NULL && !PyMapping_Check(locals))) {
611 PyErr_BadInternalCall();
612 return NULL;
613 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000614#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100616 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (builtins) {
618 if (PyModule_Check(builtins)) {
619 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200620 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 }
623 if (builtins == NULL) {
624 /* No builtins! Make up a minimal one
625 Give them 'None', at least. */
626 builtins = PyDict_New();
627 if (builtins == NULL ||
628 PyDict_SetItemString(
629 builtins, "None", Py_None) < 0)
630 return NULL;
631 }
632 else
633 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 }
636 else {
637 /* If we share the globals, we share the builtins.
638 Save a lookup and a call. */
639 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200640 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 Py_INCREF(builtins);
642 }
643 if (code->co_zombieframe != NULL) {
644 f = code->co_zombieframe;
645 code->co_zombieframe = NULL;
646 _Py_NewReference((PyObject *)f);
647 assert(f->f_code == code);
648 }
649 else {
650 Py_ssize_t extras, ncells, nfrees;
651 ncells = PyTuple_GET_SIZE(code->co_cellvars);
652 nfrees = PyTuple_GET_SIZE(code->co_freevars);
653 extras = code->co_stacksize + code->co_nlocals + ncells +
654 nfrees;
655 if (free_list == NULL) {
656 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
657 extras);
658 if (f == NULL) {
659 Py_DECREF(builtins);
660 return NULL;
661 }
662 }
663 else {
664 assert(numfree > 0);
665 --numfree;
666 f = free_list;
667 free_list = free_list->f_back;
668 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000669 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
670 if (new_f == NULL) {
671 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 Py_DECREF(builtins);
673 return NULL;
674 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000675 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 }
677 _Py_NewReference((PyObject *)f);
678 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 f->f_code = code;
681 extras = code->co_nlocals + ncells + nfrees;
682 f->f_valuestack = f->f_localsplus + extras;
683 for (i=0; i<extras; i++)
684 f->f_localsplus[i] = NULL;
685 f->f_locals = NULL;
686 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 }
688 f->f_stacktop = f->f_valuestack;
689 f->f_builtins = builtins;
690 Py_XINCREF(back);
691 f->f_back = back;
692 Py_INCREF(code);
693 Py_INCREF(globals);
694 f->f_globals = globals;
695 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
696 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
697 (CO_NEWLOCALS | CO_OPTIMIZED))
698 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
699 else if (code->co_flags & CO_NEWLOCALS) {
700 locals = PyDict_New();
701 if (locals == NULL) {
702 Py_DECREF(f);
703 return NULL;
704 }
705 f->f_locals = locals;
706 }
707 else {
708 if (locals == NULL)
709 locals = globals;
710 Py_INCREF(locals);
711 f->f_locals = locals;
712 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 f->f_lasti = -1;
715 f->f_lineno = code->co_firstlineno;
716 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200717 f->f_executing = 0;
718 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000719 f->f_trace_opcodes = 0;
720 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000723}
724
INADA Naoki5a625d02016-12-24 20:19:08 +0900725PyFrameObject*
726PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
727 PyObject *globals, PyObject *locals)
728{
729 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
730 if (f)
731 _PyObject_GC_TRACK(f);
732 return f;
733}
734
735
Guido van Rossum3f5da241990-12-20 15:06:42 +0000736/* Block management */
737
738void
Fred Drake1b190b42000-07-09 05:40:56 +0000739PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyTryBlock *b;
742 if (f->f_iblock >= CO_MAXBLOCKS)
743 Py_FatalError("XXX block stack overflow");
744 b = &f->f_blockstack[f->f_iblock++];
745 b->b_type = type;
746 b->b_level = level;
747 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000748}
749
Guido van Rossum18752471997-04-29 14:49:28 +0000750PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000751PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyTryBlock *b;
754 if (f->f_iblock <= 0)
755 Py_FatalError("XXX block stack underflow");
756 b = &f->f_blockstack[--f->f_iblock];
757 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000758}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000759
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761
762 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 values is an array of PyObject*. At index i, map[i] is the name of
764 the variable with value values[i]. The function copies the first
765 nmap variable from map/values into dict. If values[i] is NULL,
766 the variable is deleted from dict.
767
768 If deref is true, then the values being copied are cell variables
769 and the value is extracted from the cell variable before being put
770 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000771 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000772
Victor Stinner41bb43a2013-10-29 01:19:37 +0100773static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000774map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 Py_ssize_t j;
778 assert(PyTuple_Check(map));
779 assert(PyDict_Check(dict));
780 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800781 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyObject *key = PyTuple_GET_ITEM(map, j);
783 PyObject *value = values[j];
784 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400785 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 assert(PyCell_Check(value));
787 value = PyCell_GET(value);
788 }
789 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100790 if (PyObject_DelItem(dict, key) != 0) {
791 if (PyErr_ExceptionMatches(PyExc_KeyError))
792 PyErr_Clear();
793 else
794 return -1;
795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 }
797 else {
798 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100799 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 }
801 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100802 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000803}
804
Guido van Rossumd8faa362007-04-27 19:54:29 +0000805/* Copy values from the "locals" dict into the fast locals.
806
807 dict is an input argument containing string keys representing
808 variables names and arbitrary PyObject* as values.
809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000811 values is an array of PyObject*. At index i, map[i] is the name of
812 the variable with value values[i]. The function copies the first
813 nmap variable from map/values into dict. If values[i] is NULL,
814 the variable is deleted from dict.
815
816 If deref is true, then the values being copied are cell variables
817 and the value is extracted from the cell variable before being put
818 in dict. If clear is true, then variables in map but not in dict
819 are set to NULL in map; if clear is false, variables missing in
820 dict are ignored.
821
822 Exceptions raised while modifying the dict are silently ignored,
823 because there is no good way to report them.
824*/
825
Guido van Rossum6b356e72001-04-14 17:55:41 +0000826static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000827dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_ssize_t j;
831 assert(PyTuple_Check(map));
832 assert(PyDict_Check(dict));
833 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800834 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *key = PyTuple_GET_ITEM(map, j);
836 PyObject *value = PyObject_GetItem(dict, key);
837 assert(PyUnicode_Check(key));
838 /* We only care about NULLs if clear is true. */
839 if (value == NULL) {
840 PyErr_Clear();
841 if (!clear)
842 continue;
843 }
844 if (deref) {
845 assert(PyCell_Check(values[j]));
846 if (PyCell_GET(values[j]) != value) {
847 if (PyCell_Set(values[j], value) < 0)
848 PyErr_Clear();
849 }
850 } else if (values[j] != value) {
851 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300852 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 }
854 Py_XDECREF(value);
855 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000856}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000857
Victor Stinner41bb43a2013-10-29 01:19:37 +0100858int
859PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 /* Merge fast locals into f->f_locals */
862 PyObject *locals, *map;
863 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyCodeObject *co;
865 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100866 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100867
868 if (f == NULL) {
869 PyErr_BadInternalCall();
870 return -1;
871 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 locals = f->f_locals;
873 if (locals == NULL) {
874 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100875 if (locals == NULL)
876 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 }
878 co = f->f_code;
879 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100880 if (!PyTuple_Check(map)) {
881 PyErr_Format(PyExc_SystemError,
882 "co_varnames must be a tuple, not %s",
883 Py_TYPE(map)->tp_name);
884 return -1;
885 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 fast = f->f_localsplus;
887 j = PyTuple_GET_SIZE(map);
888 if (j > co->co_nlocals)
889 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100890 if (co->co_nlocals) {
891 if (map_to_dict(map, j, locals, fast, 0) < 0)
892 return -1;
893 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 ncells = PyTuple_GET_SIZE(co->co_cellvars);
895 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
896 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100897 if (map_to_dict(co->co_cellvars, ncells,
898 locals, fast + co->co_nlocals, 1))
899 return -1;
900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 /* If the namespace is unoptimized, then one of the
902 following cases applies:
903 1. It does not contain free variables, because it
904 uses import * or is a top-level namespace.
905 2. It is a class namespace.
906 We don't want to accidentally copy free variables
907 into the locals dict used by the class.
908 */
909 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100910 if (map_to_dict(co->co_freevars, nfreevars,
911 locals, fast + co->co_nlocals + ncells, 1) < 0)
912 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 }
914 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100915 return 0;
916}
917
918void
919PyFrame_FastToLocals(PyFrameObject *f)
920{
921 int res;
922
923 assert(!PyErr_Occurred());
924
925 res = PyFrame_FastToLocalsWithError(f);
926 if (res < 0)
927 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000928}
929
930void
Fred Drake1b190b42000-07-09 05:40:56 +0000931PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Merge f->f_locals into fast locals */
934 PyObject *locals, *map;
935 PyObject **fast;
936 PyObject *error_type, *error_value, *error_traceback;
937 PyCodeObject *co;
938 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100939 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (f == NULL)
941 return;
942 locals = f->f_locals;
943 co = f->f_code;
944 map = co->co_varnames;
945 if (locals == NULL)
946 return;
947 if (!PyTuple_Check(map))
948 return;
949 PyErr_Fetch(&error_type, &error_value, &error_traceback);
950 fast = f->f_localsplus;
951 j = PyTuple_GET_SIZE(map);
952 if (j > co->co_nlocals)
953 j = co->co_nlocals;
954 if (co->co_nlocals)
955 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
956 ncells = PyTuple_GET_SIZE(co->co_cellvars);
957 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
958 if (ncells || nfreevars) {
959 dict_to_map(co->co_cellvars, ncells,
960 locals, fast + co->co_nlocals, 1, clear);
961 /* Same test as in PyFrame_FastToLocals() above. */
962 if (co->co_flags & CO_OPTIMIZED) {
963 dict_to_map(co->co_freevars, nfreevars,
964 locals, fast + co->co_nlocals + ncells, 1,
965 clear);
966 }
967 }
968 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000969}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000970
971/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000972int
973PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 int freelist_size = numfree;
976
977 while (free_list != NULL) {
978 PyFrameObject *f = free_list;
979 free_list = free_list->f_back;
980 PyObject_GC_Del(f);
981 --numfree;
982 }
983 assert(numfree == 0);
984 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000985}
986
987void
988PyFrame_Fini(void)
989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000991}
David Malcolm49526f42012-06-22 14:55:41 -0400992
993/* Print summary info about the state of the optimized allocator */
994void
995_PyFrame_DebugMallocStats(FILE *out)
996{
997 _PyDebugAllocatorStats(out,
998 "free PyFrameObject",
999 numfree, sizeof(PyFrameObject));
1000}
1001