blob: b3f0b65e51c7ac03eac37de3d03d066ea88d013a [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"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00006#include "frameobject.h"
7#include "opcode.h"
8#include "structmember.h"
9
Guido van Rossum18752471997-04-29 14:49:28 +000010#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000011
Guido van Rossum6f799372001-09-20 20:46:19 +000012static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100013 {"f_back", T_OBJECT, OFF(f_back), READONLY},
14 {"f_code", T_OBJECT, OFF(f_code), READONLY},
15 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
16 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
17 {"f_lasti", T_INT, OFF(f_lasti), READONLY},
Nick Coghlan5a851672017-09-08 10:14:16 +100018 {"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
19 {"f_trace_opcodes", T_BOOL, OFF(f_trace_opcodes), 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000021};
22
Guido van Rossum18752471997-04-29 14:49:28 +000023static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000024frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000025{
Victor Stinner41bb43a2013-10-29 01:19:37 +010026 if (PyFrame_FastToLocalsWithError(f) < 0)
27 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 Py_INCREF(f->f_locals);
29 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000030}
31
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000032int
33PyFrame_GetLineNumber(PyFrameObject *f)
34{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 if (f->f_trace)
36 return f->f_lineno;
37 else
38 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +000039}
40
Michael W. Hudsondd32a912002-08-15 14:59:02 +000041static PyObject *
42frame_getlineno(PyFrameObject *f, void *closure)
43{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +000045}
46
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000047/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000049 * lines are OK to jump to because they don't make any assumptions about the
50 * state of the stack (obvious because you could remove the line and the code
51 * would still work without any stack errors), but there are some constructs
52 * that limit jumping:
53 *
54 * o Lines with an 'except' statement on them can't be jumped to, because
55 * they expect an exception to be on the top of the stack.
56 * o Lines that live in a 'finally' block can't be jumped from or to, since
57 * the END_FINALLY expects to clean up the stack after the 'try' block.
58 * o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
59 * needs to be set up before their code runs, and for 'for' loops the
60 * iterator needs to be on the stack.
61 */
62static int
63frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
64{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 int new_lineno = 0; /* The new value of f_lineno */
66 long l_new_lineno;
67 int overflow;
68 int new_lasti = 0; /* The new value of f_lasti */
69 int new_iblock = 0; /* The new value of f_iblock */
70 unsigned char *code = NULL; /* The bytecode for the frame... */
71 Py_ssize_t code_len = 0; /* ...and its length */
72 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
73 Py_ssize_t lnotab_len = 0; /* (ditto) */
74 int offset = 0; /* (ditto) */
75 int line = 0; /* (ditto) */
76 int addr = 0; /* (ditto) */
77 int min_addr = 0; /* Scanning the SETUPs and POPs */
78 int max_addr = 0; /* (ditto) */
79 int delta_iblock = 0; /* (ditto) */
80 int min_delta_iblock = 0; /* (ditto) */
81 int min_iblock = 0; /* (ditto) */
82 int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
83 int new_lasti_setup_addr = 0; /* (ditto) */
84 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
85 int in_finally[CO_MAXBLOCKS]; /* (ditto) */
86 int blockstack_top = 0; /* (ditto) */
87 unsigned char setup_op = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 /* f_lineno must be an integer. */
90 if (!PyLong_CheckExact(p_new_lineno)) {
91 PyErr_SetString(PyExc_ValueError,
92 "lineno must be an integer");
93 return -1;
94 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 /* You can only do this from within a trace function, not via
97 * _getframe or similar hackery. */
98 if (!f->f_trace)
99 {
100 PyErr_Format(PyExc_ValueError,
101 "f_lineno can only be set by a"
102 " line trace function");
103 return -1;
104 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 /* Fail if the line comes before the start of the code block. */
107 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
108 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000109#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 || l_new_lineno > INT_MAX
111 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000112#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 ) {
114 PyErr_SetString(PyExc_ValueError,
115 "lineno out of range");
116 return -1;
117 }
118 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 if (new_lineno < f->f_code->co_firstlineno) {
121 PyErr_Format(PyExc_ValueError,
122 "line %d comes before the current code block",
123 new_lineno);
124 return -1;
125 }
126 else if (new_lineno == f->f_code->co_firstlineno) {
127 new_lasti = 0;
128 new_lineno = f->f_code->co_firstlineno;
129 }
130 else {
131 /* Find the bytecode offset for the start of the given
132 * line, or the first code-owning line after it. */
133 char *tmp;
134 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
135 &tmp, &lnotab_len);
136 lnotab = (unsigned char *) tmp;
137 addr = 0;
138 line = f->f_code->co_firstlineno;
139 new_lasti = -1;
140 for (offset = 0; offset < lnotab_len; offset += 2) {
141 addr += lnotab[offset];
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100142 line += (signed char)lnotab[offset+1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (line >= new_lineno) {
144 new_lasti = addr;
145 new_lineno = line;
146 break;
147 }
148 }
149 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 /* If we didn't reach the requested line, return an error. */
152 if (new_lasti == -1) {
153 PyErr_Format(PyExc_ValueError,
154 "line %d comes after the current code block",
155 new_lineno);
156 return -1;
157 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 /* We're now ready to look at the bytecode. */
160 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
Victor Stinner640c35c2013-06-04 23:14:37 +0200161 min_addr = Py_MIN(new_lasti, f->f_lasti);
162 max_addr = Py_MAX(new_lasti, f->f_lasti);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 /* You can't jump onto a line with an 'except' statement on it -
165 * they expect to have an exception on the top of the stack, which
166 * won't be true if you jump to them. They always start with code
167 * that either pops the exception using POP_TOP (plain 'except:'
168 * lines do this) or duplicates the exception on the stack using
169 * DUP_TOP (if there's an exception type specified). See compile.c,
170 * 'com_try_except' for the full details. There aren't any other
171 * cases (AFAIK) where a line's code can start with DUP_TOP or
172 * POP_TOP, but if any ever appear, they'll be subject to the same
173 * restriction (but with a different error message). */
174 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
175 PyErr_SetString(PyExc_ValueError,
176 "can't jump to 'except' line as there's no exception");
177 return -1;
178 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 /* You can't jump into or out of a 'finally' block because the 'try'
181 * block leaves something on the stack for the END_FINALLY to clean
182 * up. So we walk the bytecode, maintaining a simulated blockstack.
183 * When we reach the old or new address and it's in a 'finally' block
184 * we note the address of the corresponding SETUP_FINALLY. The jump
185 * is only legal if neither address is in a 'finally' block or
186 * they're both in the same one. 'blockstack' is a stack of the
187 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
188 * whether we're in a 'finally' block at each blockstack level. */
189 f_lasti_setup_addr = -1;
190 new_lasti_setup_addr = -1;
191 memset(blockstack, '\0', sizeof(blockstack));
192 memset(in_finally, '\0', sizeof(in_finally));
193 blockstack_top = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300194 for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 unsigned char op = code[addr];
196 switch (op) {
197 case SETUP_LOOP:
198 case SETUP_EXCEPT:
199 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400200 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400201 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 blockstack[blockstack_top++] = addr;
203 in_finally[blockstack_top-1] = 0;
204 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 case POP_BLOCK:
207 assert(blockstack_top > 0);
208 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400209 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
210 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 in_finally[blockstack_top-1] = 1;
212 }
213 else {
214 blockstack_top--;
215 }
216 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 case END_FINALLY:
219 /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
220 * in the bytecode but don't correspond to an actual
221 * 'finally' block. (If blockstack_top is 0, we must
222 * be seeing such an END_FINALLY.) */
223 if (blockstack_top > 0) {
224 setup_op = code[blockstack[blockstack_top-1]];
Yury Selivanov75445082015-05-11 22:57:16 -0400225 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH
226 || setup_op == SETUP_ASYNC_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 blockstack_top--;
228 }
229 }
230 break;
231 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 /* For the addresses we're interested in, see whether they're
234 * within a 'finally' block and if so, remember the address
235 * of the SETUP_FINALLY. */
236 if (addr == new_lasti || addr == f->f_lasti) {
237 int i = 0;
238 int setup_addr = -1;
239 for (i = blockstack_top-1; i >= 0; i--) {
240 if (in_finally[i]) {
241 setup_addr = blockstack[i];
242 break;
243 }
244 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (setup_addr != -1) {
247 if (addr == new_lasti) {
248 new_lasti_setup_addr = setup_addr;
249 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (addr == f->f_lasti) {
252 f_lasti_setup_addr = setup_addr;
253 }
254 }
255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 /* Verify that the blockstack tracking code didn't get lost. */
259 assert(blockstack_top == 0);
260
261 /* After all that, are we jumping into / out of a 'finally' block? */
262 if (new_lasti_setup_addr != f_lasti_setup_addr) {
263 PyErr_SetString(PyExc_ValueError,
264 "can't jump into or out of a 'finally' block");
265 return -1;
266 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000267
268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 /* Police block-jumping (you can't jump into the middle of a block)
270 * and ensure that the blockstack finishes up in a sensible state (by
271 * popping any blocks we're jumping out of). We look at all the
272 * blockstack operations between the current position and the new
273 * one, and keep track of how many blocks we drop out of on the way.
274 * By also keeping track of the lowest blockstack position we see, we
275 * can tell whether the jump goes into any blocks without coming out
276 * again - in that case we raise an exception below. */
277 delta_iblock = 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +0300278 for (addr = min_addr; addr < max_addr; addr += sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 unsigned char op = code[addr];
280 switch (op) {
281 case SETUP_LOOP:
282 case SETUP_EXCEPT:
283 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400284 case SETUP_WITH:
Yury Selivanov75445082015-05-11 22:57:16 -0400285 case SETUP_ASYNC_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 delta_iblock++;
287 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 case POP_BLOCK:
290 delta_iblock--;
291 break;
292 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000293
Victor Stinner640c35c2013-06-04 23:14:37 +0200294 min_delta_iblock = Py_MIN(min_delta_iblock, delta_iblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 /* Derive the absolute iblock values from the deltas. */
298 min_iblock = f->f_iblock + min_delta_iblock;
299 if (new_lasti > f->f_lasti) {
300 /* Forwards jump. */
301 new_iblock = f->f_iblock + delta_iblock;
302 }
303 else {
304 /* Backwards jump. */
305 new_iblock = f->f_iblock - delta_iblock;
306 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* Are we jumping into a block? */
309 if (new_iblock > min_iblock) {
310 PyErr_SetString(PyExc_ValueError,
311 "can't jump into the middle of a block");
312 return -1;
313 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 /* Pop any blocks that we're jumping out of. */
316 while (f->f_iblock > new_iblock) {
317 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
318 while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
319 PyObject *v = (*--f->f_stacktop);
320 Py_DECREF(v);
321 }
322 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 /* Finally set the new f_lineno and f_lasti and return OK. */
325 f->f_lineno = new_lineno;
326 f->f_lasti = new_lasti;
327 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000328}
329
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000330static PyObject *
331frame_gettrace(PyFrameObject *f, void *closure)
332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (trace == NULL)
336 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000341}
342
343static int
344frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* We rely on f_lineno being accurate when f_trace is set. */
347 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000348
Serhiy Storchaka64a263a2016-06-04 20:32:36 +0300349 if (v == Py_None)
350 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 Py_XINCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300352 Py_XSETREF(f->f_trace, v);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000355}
356
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000357
Guido van Rossum32d34c82001-09-20 21:45:26 +0000358static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 {"f_locals", (getter)frame_getlocals, NULL, NULL},
360 {"f_lineno", (getter)frame_getlineno,
361 (setter)frame_setlineno, NULL},
362 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
363 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000365
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000366/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000367 In an attempt to improve the speed of function calls, we:
368
369 1. Hold a single "zombie" frame on each code object. This retains
370 the allocated and initialised frame object from an invocation of
371 the code object. The zombie is reanimated the next time we need a
372 frame object for that code object. Doing this saves the malloc/
373 realloc required when using a free_list frame that isn't the
374 correct size. It also saves some field initialisation.
375
376 In zombie mode, no field of PyFrameObject holds a reference, but
377 the following fields are still valid:
378
379 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380
Thomas Wouters477c8d52006-05-27 19:21:47 +0000381 * f_locals, f_trace,
382 f_exc_type, f_exc_value, f_exc_traceback are NULL;
383
384 * f_localsplus does not require re-allocation and
385 the local variables in f_localsplus are NULL.
386
387 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000388 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000389 a stack frame is on the free list, only the following members have
390 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 ob_type == &Frametype
392 f_back next item on free list, or NULL
393 f_stacksize size of value stack
394 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000395 Note that the value and block stacks are preserved -- this can save
396 another malloc() call or two (and two free() calls as well!).
397 Also note that, unlike for integers, each frame object is a
398 malloc'ed object in its own right -- it is only the actual calls to
399 malloc() that we are trying to save here, not the administration.
400 After all, while a typical program may make millions of calls, a
401 call depth of more than 20 or 30 is probably already exceptional
402 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000403
Christian Heimes2202f872008-02-06 14:31:34 +0000404 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000405 free_list. Else programs creating lots of cyclic trash involving
406 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000407*/
408
Guido van Rossum18752471997-04-29 14:49:28 +0000409static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000411/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000413
Victor Stinnerc6944e72016-11-11 02:13:35 +0100414static void _Py_HOT_FUNCTION
Fred Drake1b190b42000-07-09 05:40:56 +0000415frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000416{
Antoine Pitrou93963562013-05-14 20:37:52 +0200417 PyObject **p, **valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000419
INADA Naoki5a625d02016-12-24 20:19:08 +0900420 if (_PyObject_GC_IS_TRACKED(f))
421 _PyObject_GC_UNTRACK(f);
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_TRASHCAN_SAFE_BEGIN(f)
Antoine Pitrou93963562013-05-14 20:37:52 +0200424 /* Kill all local variables */
425 valuestack = f->f_valuestack;
426 for (p = f->f_localsplus; p < valuestack; p++)
427 Py_CLEAR(*p);
428
429 /* Free stack */
430 if (f->f_stacktop != NULL) {
431 for (p = valuestack; p < f->f_stacktop; p++)
432 Py_XDECREF(*p);
433 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_XDECREF(f->f_back);
436 Py_DECREF(f->f_builtins);
437 Py_DECREF(f->f_globals);
438 Py_CLEAR(f->f_locals);
Antoine Pitrou93963562013-05-14 20:37:52 +0200439 Py_CLEAR(f->f_trace);
440 Py_CLEAR(f->f_exc_type);
441 Py_CLEAR(f->f_exc_value);
442 Py_CLEAR(f->f_exc_traceback);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 co = f->f_code;
445 if (co->co_zombieframe == NULL)
446 co->co_zombieframe = f;
447 else if (numfree < PyFrame_MAXFREELIST) {
448 ++numfree;
449 f->f_back = free_list;
450 free_list = f;
451 }
452 else
453 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(co);
456 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000457}
458
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000459static int
460frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100463 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_VISIT(f->f_back);
466 Py_VISIT(f->f_code);
467 Py_VISIT(f->f_builtins);
468 Py_VISIT(f->f_globals);
469 Py_VISIT(f->f_locals);
470 Py_VISIT(f->f_trace);
471 Py_VISIT(f->f_exc_type);
472 Py_VISIT(f->f_exc_value);
473 Py_VISIT(f->f_exc_traceback);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* locals */
476 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
477 fastlocals = f->f_localsplus;
478 for (i = slots; --i >= 0; ++fastlocals)
479 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 /* stack */
482 if (f->f_stacktop != NULL) {
483 for (p = f->f_valuestack; p < f->f_stacktop; p++)
484 Py_VISIT(*p);
485 }
486 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000487}
488
489static void
Antoine Pitrou58720d62013-08-05 23:26:40 +0200490frame_tp_clear(PyFrameObject *f)
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100493 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000494
Antoine Pitrou93963562013-05-14 20:37:52 +0200495 /* Before anything else, make sure that this frame is clearly marked
496 * as being defunct! Else, e.g., a generator reachable from this
497 * frame may also point to this frame, believe itself to still be
498 * active, and try cleaning up this frame again.
499 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 oldtop = f->f_stacktop;
501 f->f_stacktop = NULL;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200502 f->f_executing = 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 Py_CLEAR(f->f_exc_type);
505 Py_CLEAR(f->f_exc_value);
506 Py_CLEAR(f->f_exc_traceback);
507 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* locals */
510 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
511 fastlocals = f->f_localsplus;
512 for (i = slots; --i >= 0; ++fastlocals)
513 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* stack */
516 if (oldtop != NULL) {
517 for (p = f->f_valuestack; p < oldtop; p++)
518 Py_CLEAR(*p);
519 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000520}
521
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000522static PyObject *
Antoine Pitrou58720d62013-08-05 23:26:40 +0200523frame_clear(PyFrameObject *f)
524{
525 if (f->f_executing) {
526 PyErr_SetString(PyExc_RuntimeError,
527 "cannot clear an executing frame");
528 return NULL;
529 }
530 if (f->f_gen) {
531 _PyGen_Finalize(f->f_gen);
532 assert(f->f_gen == NULL);
533 }
534 frame_tp_clear(f);
535 Py_RETURN_NONE;
536}
537
538PyDoc_STRVAR(clear__doc__,
539"F.clear(): clear most references held by the frame");
540
541static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000542frame_sizeof(PyFrameObject *f)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
547 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
548 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
549 ncells + nfrees;
550 /* subtract one as it is already included in PyFrameObject */
551 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000554}
555
556PyDoc_STRVAR(sizeof__doc__,
557"F.__sizeof__() -> size of F in memory, in bytes");
558
559static PyMethodDef frame_methods[] = {
Antoine Pitrou58720d62013-08-05 23:26:40 +0200560 {"clear", (PyCFunction)frame_clear, METH_NOARGS,
561 clear__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
563 sizeof__doc__},
564 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000565};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000566
Guido van Rossum18752471997-04-29 14:49:28 +0000567PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 PyVarObject_HEAD_INIT(&PyType_Type, 0)
569 "frame",
570 sizeof(PyFrameObject),
571 sizeof(PyObject *),
572 (destructor)frame_dealloc, /* tp_dealloc */
573 0, /* tp_print */
574 0, /* tp_getattr */
575 0, /* tp_setattr */
576 0, /* tp_reserved */
577 0, /* tp_repr */
578 0, /* tp_as_number */
579 0, /* tp_as_sequence */
580 0, /* tp_as_mapping */
581 0, /* tp_hash */
582 0, /* tp_call */
583 0, /* tp_str */
584 PyObject_GenericGetAttr, /* tp_getattro */
585 PyObject_GenericSetAttr, /* tp_setattro */
586 0, /* tp_as_buffer */
587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
588 0, /* tp_doc */
589 (traverseproc)frame_traverse, /* tp_traverse */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200590 (inquiry)frame_tp_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 0, /* tp_richcompare */
592 0, /* tp_weaklistoffset */
593 0, /* tp_iter */
594 0, /* tp_iternext */
595 frame_methods, /* tp_methods */
596 frame_memberlist, /* tp_members */
597 frame_getsetlist, /* tp_getset */
598 0, /* tp_base */
599 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000600};
601
Victor Stinner07e9e382013-11-07 22:22:39 +0100602_Py_IDENTIFIER(__builtins__);
Neal Norwitzc91ed402002-12-30 22:29:22 +0000603
Neal Norwitzb2501f42002-12-31 03:42:13 +0000604int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000605{
Victor Stinner07e9e382013-11-07 22:22:39 +0100606 /* Before, PyId___builtins__ was a string created explicitly in
607 this function. Now there is nothing to initialize anymore, but
608 the function is kept for backward compatibility. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000610}
611
Victor Stinnerc6944e72016-11-11 02:13:35 +0100612PyFrameObject* _Py_HOT_FUNCTION
INADA Naoki5a625d02016-12-24 20:19:08 +0900613_PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code,
614 PyObject *globals, PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyFrameObject *back = tstate->frame;
617 PyFrameObject *f;
618 PyObject *builtins;
619 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000620
Michael W. Hudson69734a52002-08-19 16:54:08 +0000621#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
623 (locals != NULL && !PyMapping_Check(locals))) {
624 PyErr_BadInternalCall();
625 return NULL;
626 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000627#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (back == NULL || back->f_globals != globals) {
Victor Stinner07e9e382013-11-07 22:22:39 +0100629 builtins = _PyDict_GetItemId(globals, &PyId___builtins__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (builtins) {
631 if (PyModule_Check(builtins)) {
632 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200633 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 }
636 if (builtins == NULL) {
637 /* No builtins! Make up a minimal one
638 Give them 'None', at least. */
639 builtins = PyDict_New();
640 if (builtins == NULL ||
641 PyDict_SetItemString(
642 builtins, "None", Py_None) < 0)
643 return NULL;
644 }
645 else
646 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
649 else {
650 /* If we share the globals, we share the builtins.
651 Save a lookup and a call. */
652 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200653 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 Py_INCREF(builtins);
655 }
656 if (code->co_zombieframe != NULL) {
657 f = code->co_zombieframe;
658 code->co_zombieframe = NULL;
659 _Py_NewReference((PyObject *)f);
660 assert(f->f_code == code);
661 }
662 else {
663 Py_ssize_t extras, ncells, nfrees;
664 ncells = PyTuple_GET_SIZE(code->co_cellvars);
665 nfrees = PyTuple_GET_SIZE(code->co_freevars);
666 extras = code->co_stacksize + code->co_nlocals + ncells +
667 nfrees;
668 if (free_list == NULL) {
669 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
670 extras);
671 if (f == NULL) {
672 Py_DECREF(builtins);
673 return NULL;
674 }
675 }
676 else {
677 assert(numfree > 0);
678 --numfree;
679 f = free_list;
680 free_list = free_list->f_back;
681 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000682 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
683 if (new_f == NULL) {
684 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 Py_DECREF(builtins);
686 return NULL;
687 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000688 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 }
690 _Py_NewReference((PyObject *)f);
691 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 f->f_code = code;
694 extras = code->co_nlocals + ncells + nfrees;
695 f->f_valuestack = f->f_localsplus + extras;
696 for (i=0; i<extras; i++)
697 f->f_localsplus[i] = NULL;
698 f->f_locals = NULL;
699 f->f_trace = NULL;
700 f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
701 }
702 f->f_stacktop = f->f_valuestack;
703 f->f_builtins = builtins;
704 Py_XINCREF(back);
705 f->f_back = back;
706 Py_INCREF(code);
707 Py_INCREF(globals);
708 f->f_globals = globals;
709 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
710 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
711 (CO_NEWLOCALS | CO_OPTIMIZED))
712 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
713 else if (code->co_flags & CO_NEWLOCALS) {
714 locals = PyDict_New();
715 if (locals == NULL) {
716 Py_DECREF(f);
717 return NULL;
718 }
719 f->f_locals = locals;
720 }
721 else {
722 if (locals == NULL)
723 locals = globals;
724 Py_INCREF(locals);
725 f->f_locals = locals;
726 }
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 f->f_lasti = -1;
729 f->f_lineno = code->co_firstlineno;
730 f->f_iblock = 0;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200731 f->f_executing = 0;
732 f->f_gen = NULL;
Nick Coghlan5a851672017-09-08 10:14:16 +1000733 f->f_trace_opcodes = 0;
734 f->f_trace_lines = 1;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000737}
738
INADA Naoki5a625d02016-12-24 20:19:08 +0900739PyFrameObject*
740PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
741 PyObject *globals, PyObject *locals)
742{
743 PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals);
744 if (f)
745 _PyObject_GC_TRACK(f);
746 return f;
747}
748
749
Guido van Rossum3f5da241990-12-20 15:06:42 +0000750/* Block management */
751
752void
Fred Drake1b190b42000-07-09 05:40:56 +0000753PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 PyTryBlock *b;
756 if (f->f_iblock >= CO_MAXBLOCKS)
757 Py_FatalError("XXX block stack overflow");
758 b = &f->f_blockstack[f->f_iblock++];
759 b->b_type = type;
760 b->b_level = level;
761 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000762}
763
Guido van Rossum18752471997-04-29 14:49:28 +0000764PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000765PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyTryBlock *b;
768 if (f->f_iblock <= 0)
769 Py_FatalError("XXX block stack underflow");
770 b = &f->f_blockstack[--f->f_iblock];
771 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000772}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000773
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775
776 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 values is an array of PyObject*. At index i, map[i] is the name of
778 the variable with value values[i]. The function copies the first
779 nmap variable from map/values into dict. If values[i] is NULL,
780 the variable is deleted from dict.
781
782 If deref is true, then the values being copied are cell variables
783 and the value is extracted from the cell variable before being put
784 in dict.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000785 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000786
Victor Stinner41bb43a2013-10-29 01:19:37 +0100787static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000788map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 Py_ssize_t j;
792 assert(PyTuple_Check(map));
793 assert(PyDict_Check(dict));
794 assert(PyTuple_Size(map) >= nmap);
795 for (j = nmap; --j >= 0; ) {
796 PyObject *key = PyTuple_GET_ITEM(map, j);
797 PyObject *value = values[j];
798 assert(PyUnicode_Check(key));
Antoine Pitrouacc8cf22014-07-04 20:24:13 -0400799 if (deref && value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 assert(PyCell_Check(value));
801 value = PyCell_GET(value);
802 }
803 if (value == NULL) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100804 if (PyObject_DelItem(dict, key) != 0) {
805 if (PyErr_ExceptionMatches(PyExc_KeyError))
806 PyErr_Clear();
807 else
808 return -1;
809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 }
811 else {
812 if (PyObject_SetItem(dict, key, value) != 0)
Victor Stinner41bb43a2013-10-29 01:19:37 +0100813 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 }
815 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100816 return 0;
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000817}
818
Guido van Rossumd8faa362007-04-27 19:54:29 +0000819/* Copy values from the "locals" dict into the fast locals.
820
821 dict is an input argument containing string keys representing
822 variables names and arbitrary PyObject* as values.
823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825 values is an array of PyObject*. At index i, map[i] is the name of
826 the variable with value values[i]. The function copies the first
827 nmap variable from map/values into dict. If values[i] is NULL,
828 the variable is deleted from dict.
829
830 If deref is true, then the values being copied are cell variables
831 and the value is extracted from the cell variable before being put
832 in dict. If clear is true, then variables in map but not in dict
833 are set to NULL in map; if clear is false, variables missing in
834 dict are ignored.
835
836 Exceptions raised while modifying the dict are silently ignored,
837 because there is no good way to report them.
838*/
839
Guido van Rossum6b356e72001-04-14 17:55:41 +0000840static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000841dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 Py_ssize_t j;
845 assert(PyTuple_Check(map));
846 assert(PyDict_Check(dict));
847 assert(PyTuple_Size(map) >= nmap);
848 for (j = nmap; --j >= 0; ) {
849 PyObject *key = PyTuple_GET_ITEM(map, j);
850 PyObject *value = PyObject_GetItem(dict, key);
851 assert(PyUnicode_Check(key));
852 /* We only care about NULLs if clear is true. */
853 if (value == NULL) {
854 PyErr_Clear();
855 if (!clear)
856 continue;
857 }
858 if (deref) {
859 assert(PyCell_Check(values[j]));
860 if (PyCell_GET(values[j]) != value) {
861 if (PyCell_Set(values[j], value) < 0)
862 PyErr_Clear();
863 }
864 } else if (values[j] != value) {
865 Py_XINCREF(value);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300866 Py_XSETREF(values[j], value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 }
868 Py_XDECREF(value);
869 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000870}
Jeremy Hylton2b724da2001-01-29 22:51:52 +0000871
Victor Stinner41bb43a2013-10-29 01:19:37 +0100872int
873PyFrame_FastToLocalsWithError(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 /* Merge fast locals into f->f_locals */
876 PyObject *locals, *map;
877 PyObject **fast;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyCodeObject *co;
879 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100880 Py_ssize_t ncells, nfreevars;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100881
882 if (f == NULL) {
883 PyErr_BadInternalCall();
884 return -1;
885 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 locals = f->f_locals;
887 if (locals == NULL) {
888 locals = f->f_locals = PyDict_New();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100889 if (locals == NULL)
890 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 }
892 co = f->f_code;
893 map = co->co_varnames;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100894 if (!PyTuple_Check(map)) {
895 PyErr_Format(PyExc_SystemError,
896 "co_varnames must be a tuple, not %s",
897 Py_TYPE(map)->tp_name);
898 return -1;
899 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 fast = f->f_localsplus;
901 j = PyTuple_GET_SIZE(map);
902 if (j > co->co_nlocals)
903 j = co->co_nlocals;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100904 if (co->co_nlocals) {
905 if (map_to_dict(map, j, locals, fast, 0) < 0)
906 return -1;
907 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 ncells = PyTuple_GET_SIZE(co->co_cellvars);
909 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
910 if (ncells || nfreevars) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100911 if (map_to_dict(co->co_cellvars, ncells,
912 locals, fast + co->co_nlocals, 1))
913 return -1;
914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* If the namespace is unoptimized, then one of the
916 following cases applies:
917 1. It does not contain free variables, because it
918 uses import * or is a top-level namespace.
919 2. It is a class namespace.
920 We don't want to accidentally copy free variables
921 into the locals dict used by the class.
922 */
923 if (co->co_flags & CO_OPTIMIZED) {
Victor Stinner41bb43a2013-10-29 01:19:37 +0100924 if (map_to_dict(co->co_freevars, nfreevars,
925 locals, fast + co->co_nlocals + ncells, 1) < 0)
926 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 }
928 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100929 return 0;
930}
931
932void
933PyFrame_FastToLocals(PyFrameObject *f)
934{
935 int res;
936
937 assert(!PyErr_Occurred());
938
939 res = PyFrame_FastToLocalsWithError(f);
940 if (res < 0)
941 PyErr_Clear();
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000942}
943
944void
Fred Drake1b190b42000-07-09 05:40:56 +0000945PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* Merge f->f_locals into fast locals */
948 PyObject *locals, *map;
949 PyObject **fast;
950 PyObject *error_type, *error_value, *error_traceback;
951 PyCodeObject *co;
952 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100953 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (f == NULL)
955 return;
956 locals = f->f_locals;
957 co = f->f_code;
958 map = co->co_varnames;
959 if (locals == NULL)
960 return;
961 if (!PyTuple_Check(map))
962 return;
963 PyErr_Fetch(&error_type, &error_value, &error_traceback);
964 fast = f->f_localsplus;
965 j = PyTuple_GET_SIZE(map);
966 if (j > co->co_nlocals)
967 j = co->co_nlocals;
968 if (co->co_nlocals)
969 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
970 ncells = PyTuple_GET_SIZE(co->co_cellvars);
971 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
972 if (ncells || nfreevars) {
973 dict_to_map(co->co_cellvars, ncells,
974 locals, fast + co->co_nlocals, 1, clear);
975 /* Same test as in PyFrame_FastToLocals() above. */
976 if (co->co_flags & CO_OPTIMIZED) {
977 dict_to_map(co->co_freevars, nfreevars,
978 locals, fast + co->co_nlocals + ncells, 1,
979 clear);
980 }
981 }
982 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000983}
Guido van Rossum404b95d1997-08-05 02:09:46 +0000984
985/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +0000986int
987PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 int freelist_size = numfree;
990
991 while (free_list != NULL) {
992 PyFrameObject *f = free_list;
993 free_list = free_list->f_back;
994 PyObject_GC_Del(f);
995 --numfree;
996 }
997 assert(numfree == 0);
998 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +0000999}
1000
1001void
1002PyFrame_Fini(void)
1003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 (void)PyFrame_ClearFreeList();
Guido van Rossum404b95d1997-08-05 02:09:46 +00001005}
David Malcolm49526f42012-06-22 14:55:41 -04001006
1007/* Print summary info about the state of the optimized allocator */
1008void
1009_PyFrame_DebugMallocStats(FILE *out)
1010{
1011 _PyDebugAllocatorStats(out,
1012 "free PyFrameObject",
1013 numfree, sizeof(PyFrameObject));
1014}
1015