blob: b668465df3da19ed48dbaf199c4335269eb74fc7 [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) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200616 builtins = _PyDict_GetItemIdWithError(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) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200624 if (PyErr_Occurred()) {
625 return NULL;
626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* No builtins! Make up a minimal one
628 Give them 'None', at least. */
629 builtins = PyDict_New();
630 if (builtins == NULL ||
631 PyDict_SetItemString(
632 builtins, "None", Py_None) < 0)
633 return NULL;
634 }
635 else
636 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
639 else {
640 /* If we share the globals, we share the builtins.
641 Save a lookup and a call. */
642 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200643 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 Py_INCREF(builtins);
645 }
646 if (code->co_zombieframe != NULL) {
647 f = code->co_zombieframe;
648 code->co_zombieframe = NULL;
649 _Py_NewReference((PyObject *)f);
650 assert(f->f_code == code);
651 }
652 else {
653 Py_ssize_t extras, ncells, nfrees;
654 ncells = PyTuple_GET_SIZE(code->co_cellvars);
655 nfrees = PyTuple_GET_SIZE(code->co_freevars);
656 extras = code->co_stacksize + code->co_nlocals + ncells +
657 nfrees;
658 if (free_list == NULL) {
659 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
660 extras);
661 if (f == NULL) {
662 Py_DECREF(builtins);
663 return NULL;
664 }
665 }
666 else {
667 assert(numfree > 0);
668 --numfree;
669 f = free_list;
670 free_list = free_list->f_back;
671 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000672 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
673 if (new_f == NULL) {
674 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 Py_DECREF(builtins);
676 return NULL;
677 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000678 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
680 _Py_NewReference((PyObject *)f);
681 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 f->f_code = code;
684 extras = code->co_nlocals + ncells + nfrees;
685 f->f_valuestack = f->f_localsplus + extras;
686 for (i=0; i<extras; i++)
687 f->f_localsplus[i] = NULL;
688 f->f_locals = NULL;
689 f->f_trace = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 }
691 f->f_stacktop = f->f_valuestack;
692 f->f_builtins = builtins;
693 Py_XINCREF(back);
694 f->f_back = back;
695 Py_INCREF(code);
696 Py_INCREF(globals);
697 f->f_globals = globals;
698 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
699 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
700 (CO_NEWLOCALS | CO_OPTIMIZED))
701 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
702 else if (code->co_flags & CO_NEWLOCALS) {
703 locals = PyDict_New();
704 if (locals == NULL) {
705 Py_DECREF(f);
706 return NULL;
707 }
708 f->f_locals = locals;
709 }
710 else {
711 if (locals == NULL)
712 locals = globals;
713 Py_INCREF(locals);
714 f->f_locals = locals;
715 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 f->f_lasti = -1;
718 f->f_lineno = code->co_firstlineno;
719 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200720 f->f_executing = 0;
721 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000722 f->f_trace_opcodes = 0;
723 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000726}
727
INADA Naoki5a625d02016-12-24 20:19:08 +0900728PyFrameObject*
729PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
730 PyObject *globals, PyObject *locals)
731{
732 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
733 if (f)
734 _PyObject_GC_TRACK(f);
735 return f;
736}
737
738
Guido van Rossum3f5da241990-12-20 15:06:42 +0000739/* Block management */
740
741void
Fred Drake1b190b42000-07-09 05:40:56 +0000742PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyTryBlock *b;
745 if (f->f_iblock >= CO_MAXBLOCKS)
746 Py_FatalError("XXX block stack overflow");
747 b = &f->f_blockstack[f->f_iblock++];
748 b->b_type = type;
749 b->b_level = level;
750 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000751}
752
Guido van Rossum18752471997-04-29 14:49:28 +0000753PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000754PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyTryBlock *b;
757 if (f->f_iblock <= 0)
758 Py_FatalError("XXX block stack underflow");
759 b = &f->f_blockstack[--f->f_iblock];
760 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000761}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000762
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764
765 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 values is an array of PyObject*. At index i, map[i] is the name of
767 the variable with value values[i]. The function copies the first
768 nmap variable from map/values into dict. If values[i] is NULL,
769 the variable is deleted from dict.
770
771 If deref is true, then the values being copied are cell variables
772 and the value is extracted from the cell variable before being put
773 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000775
Victor Stinner41bb43a2013-10-29 01:19:37 +0100776static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000777map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 Py_ssize_t j;
781 assert(PyTuple_Check(map));
782 assert(PyDict_Check(dict));
783 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800784 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyObject *key = PyTuple_GET_ITEM(map, j);
786 PyObject *value = values[j];
787 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400788 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(PyCell_Check(value));
790 value = PyCell_GET(value);
791 }
792 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100793 if (PyObject_DelItem(dict, key) != 0) {
794 if (PyErr_ExceptionMatches(PyExc_KeyError))
795 PyErr_Clear();
796 else
797 return -1;
798 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 }
800 else {
801 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100802 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
804 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100805 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000806}
807
Guido van Rossumd8faa362007-04-27 19:54:29 +0000808/* Copy values from the "locals" dict into the fast locals.
809
810 dict is an input argument containing string keys representing
811 variables names and arbitrary PyObject* as values.
812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000814 values is an array of PyObject*. At index i, map[i] is the name of
815 the variable with value values[i]. The function copies the first
816 nmap variable from map/values into dict. If values[i] is NULL,
817 the variable is deleted from dict.
818
819 If deref is true, then the values being copied are cell variables
820 and the value is extracted from the cell variable before being put
821 in dict. If clear is true, then variables in map but not in dict
822 are set to NULL in map; if clear is false, variables missing in
823 dict are ignored.
824
825 Exceptions raised while modifying the dict are silently ignored,
826 because there is no good way to report them.
827*/
828
Guido van Rossum6b356e72001-04-14 17:55:41 +0000829static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000830dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 Py_ssize_t j;
834 assert(PyTuple_Check(map));
835 assert(PyDict_Check(dict));
836 assert(PyTuple_Size(map) >= nmap);
Raymond Hettingera4d00012018-01-28 09:40:24 -0800837 for (j=0; j < nmap; j++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyObject *key = PyTuple_GET_ITEM(map, j);
839 PyObject *value = PyObject_GetItem(dict, key);
840 assert(PyUnicode_Check(key));
841 /* We only care about NULLs if clear is true. */
842 if (value == NULL) {
843 PyErr_Clear();
844 if (!clear)
845 continue;
846 }
847 if (deref) {
848 assert(PyCell_Check(values[j]));
849 if (PyCell_GET(values[j]) != value) {
850 if (PyCell_Set(values[j], value) < 0)
851 PyErr_Clear();
852 }
853 } else if (values[j] != value) {
854 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300855 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 }
857 Py_XDECREF(value);
858 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000859}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000860
Victor Stinner41bb43a2013-10-29 01:19:37 +0100861int
862PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 /* Merge fast locals into f->f_locals */
865 PyObject *locals, *map;
866 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 PyCodeObject *co;
868 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100869 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100870
871 if (f == NULL) {
872 PyErr_BadInternalCall();
873 return -1;
874 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 locals = f->f_locals;
876 if (locals == NULL) {
877 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100878 if (locals == NULL)
879 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 }
881 co = f->f_code;
882 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100883 if (!PyTuple_Check(map)) {
884 PyErr_Format(PyExc_SystemError,
885 "co_varnames must be a tuple, not %s",
886 Py_TYPE(map)->tp_name);
887 return -1;
888 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 fast = f->f_localsplus;
890 j = PyTuple_GET_SIZE(map);
891 if (j > co->co_nlocals)
892 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100893 if (co->co_nlocals) {
894 if (map_to_dict(map, j, locals, fast, 0) < 0)
895 return -1;
896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 ncells = PyTuple_GET_SIZE(co->co_cellvars);
898 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
899 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100900 if (map_to_dict(co->co_cellvars, ncells,
901 locals, fast + co->co_nlocals, 1))
902 return -1;
903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* If the namespace is unoptimized, then one of the
905 following cases applies:
906 1. It does not contain free variables, because it
907 uses import * or is a top-level namespace.
908 2. It is a class namespace.
909 We don't want to accidentally copy free variables
910 into the locals dict used by the class.
911 */
912 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100913 if (map_to_dict(co->co_freevars, nfreevars,
914 locals, fast + co->co_nlocals + ncells, 1) < 0)
915 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 }
917 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100918 return 0;
919}
920
921void
922PyFrame_FastToLocals(PyFrameObject *f)
923{
924 int res;
925
926 assert(!PyErr_Occurred());
927
928 res = PyFrame_FastToLocalsWithError(f);
929 if (res < 0)
930 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000931}
932
933void
Fred Drake1b190b42000-07-09 05:40:56 +0000934PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Merge f->f_locals into fast locals */
937 PyObject *locals, *map;
938 PyObject **fast;
939 PyObject *error_type, *error_value, *error_traceback;
940 PyCodeObject *co;
941 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100942 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 if (f == NULL)
944 return;
945 locals = f->f_locals;
946 co = f->f_code;
947 map = co->co_varnames;
948 if (locals == NULL)
949 return;
950 if (!PyTuple_Check(map))
951 return;
952 PyErr_Fetch(&error_type, &error_value, &error_traceback);
953 fast = f->f_localsplus;
954 j = PyTuple_GET_SIZE(map);
955 if (j > co->co_nlocals)
956 j = co->co_nlocals;
957 if (co->co_nlocals)
958 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
959 ncells = PyTuple_GET_SIZE(co->co_cellvars);
960 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
961 if (ncells || nfreevars) {
962 dict_to_map(co->co_cellvars, ncells,
963 locals, fast + co->co_nlocals, 1, clear);
964 /* Same test as in PyFrame_FastToLocals() above. */
965 if (co->co_flags & CO_OPTIMIZED) {
966 dict_to_map(co->co_freevars, nfreevars,
967 locals, fast + co->co_nlocals + ncells, 1,
968 clear);
969 }
970 }
971 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000972}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000973
974/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000975int
976PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 int freelist_size = numfree;
979
980 while (free_list != NULL) {
981 PyFrameObject *f = free_list;
982 free_list = free_list->f_back;
983 PyObject_GC_Del(f);
984 --numfree;
985 }
986 assert(numfree == 0);
987 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000988}
989
990void
991PyFrame_Fini(void)
992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +0000994}
David Malcolm49526f42012-06-22 14:55:41 -0400995
996/* Print summary info about the state of the optimized allocator */
997void
998_PyFrame_DebugMallocStats(FILE *out)
999{
1000 _PyDebugAllocatorStats(out,
1001 "free PyFrameObject",
1002 numfree, sizeof(PyFrameObject));
1003}
1004