blob: df7a1de03e1bc1e36bee689de66fd85af5542688 [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
Neal Norwitz91787cb2002-12-18 23:33:35 +000010#undef MIN
11#undef MAX
Michael W. Hudsoncfd38842002-12-17 16:15:34 +000012#define MIN(a, b) ((a) < (b) ? (a) : (b))
13#define MAX(a, b) ((a) > (b) ? (a) : (b))
14
Guido van Rossum18752471997-04-29 14:49:28 +000015#define OFF(x) offsetof(PyFrameObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000016
Guido van Rossum6f799372001-09-20 20:46:19 +000017static PyMemberDef frame_memberlist[] = {
Nick Coghlan1f7ce622012-01-13 21:43:40 +100018 {"f_back", T_OBJECT, OFF(f_back), READONLY},
19 {"f_code", T_OBJECT, OFF(f_code), READONLY},
20 {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
21 {"f_globals", T_OBJECT, OFF(f_globals), READONLY},
22 {"f_lasti", T_INT, OFF(f_lasti), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000024};
25
Guido van Rossum18752471997-04-29 14:49:28 +000026static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000027frame_getlocals(PyFrameObject *f, void *closure)
Guido van Rossum3f5da241990-12-20 15:06:42 +000028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 PyFrame_FastToLocals(f);
30 Py_INCREF(f->f_locals);
31 return f->f_locals;
Guido van Rossum3f5da241990-12-20 15:06:42 +000032}
33
Antoine Pitrou04e70d12013-05-08 18:12:35 +020034/*
35 * Generator support.
36 */
37
38PyObject *
39_PyFrame_YieldingFrom(PyFrameObject *f)
40{
41 PyObject *yf = NULL;
42
43 if (f && f->f_stacktop) {
44 PyObject *bytecode = f->f_code->co_code;
45 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
46
47 if (code[f->f_lasti + 1] != YIELD_FROM)
48 return NULL;
49 yf = f->f_stacktop[-1];
50 Py_INCREF(yf);
51 }
52 return yf;
53}
54
55PyObject *
56_PyFrame_GeneratorSend(PyFrameObject *f, PyObject *arg, int exc)
57{
58 PyThreadState *tstate = PyThreadState_GET();
59 PyObject *result;
60 PyGenObject *gen = (PyGenObject *) f->f_gen;
61
62 assert(gen == NULL || PyGen_CheckExact(gen));
63 if (gen && gen->gi_running) {
64 PyErr_SetString(PyExc_ValueError,
65 "generator already executing");
66 return NULL;
67 }
68 if (f->f_stacktop == NULL) {
69 /* Only set exception if send() called, not throw() or next() */
70 if (arg && !exc)
71 PyErr_SetNone(PyExc_StopIteration);
72 return NULL;
73 }
74
75 if (f->f_lasti == -1) {
76 if (arg && arg != Py_None) {
77 PyErr_SetString(PyExc_TypeError,
78 "can't send non-None value to a "
79 "just-started generator");
80 return NULL;
81 }
82 } else {
83 /* Push arg onto the frame's value stack */
84 result = arg ? arg : Py_None;
85 Py_INCREF(result);
86 *(f->f_stacktop++) = result;
87 }
88
89 /* Generators always return to their most recent caller, not
90 * necessarily their creator. */
91 Py_XINCREF(tstate->frame);
92 assert(f->f_back == NULL);
93 f->f_back = tstate->frame;
94
95 if (gen) {
96 Py_INCREF(gen);
97 gen->gi_running = 1;
98 }
99 result = PyEval_EvalFrameEx(f, exc);
100 if (gen) {
101 gen->gi_running = 0;
102 /* In case running the frame has lost all external references
103 * to gen, we must be careful not to hold on an invalid object. */
104 if (Py_REFCNT(gen) == 1)
105 Py_CLEAR(gen);
106 else
107 Py_DECREF(gen);
108 }
109
110 /* Don't keep the reference to f_back any longer than necessary. It
111 * may keep a chain of frames alive or it could create a reference
112 * cycle. */
113 assert(f->f_back == tstate->frame);
114 Py_CLEAR(f->f_back);
115
116 /* If the generator just returned (as opposed to yielding), signal
117 * that the generator is exhausted. */
118 if (result && f->f_stacktop == NULL) {
119 if (result == Py_None) {
120 /* Delay exception instantiation if we can */
121 PyErr_SetNone(PyExc_StopIteration);
122 } else {
123 PyObject *e = PyObject_CallFunctionObjArgs(
124 PyExc_StopIteration, result, NULL);
125 if (e != NULL) {
126 PyErr_SetObject(PyExc_StopIteration, e);
127 Py_DECREF(e);
128 }
129 }
130 Py_CLEAR(result);
131 }
132
133 if (f->f_stacktop == NULL) {
134 /* generator can't be rerun, so release the frame */
135 /* first clean reference cycle through stored exception traceback */
136 PyObject *t, *v, *tb;
137 t = f->f_exc_type;
138 v = f->f_exc_value;
139 tb = f->f_exc_traceback;
140 f->f_exc_type = NULL;
141 f->f_exc_value = NULL;
142 f->f_exc_traceback = NULL;
143 Py_XDECREF(t);
144 Py_XDECREF(v);
145 Py_XDECREF(tb);
146 if (gen) {
147 f->f_gen = NULL;
148 Py_CLEAR(gen->gi_frame);
149 }
150 }
151
152 return result;
153}
154
155int
156_PyFrame_CloseIterator(PyObject *yf)
157{
158 PyObject *retval = NULL;
159 _Py_IDENTIFIER(close);
160
161 if (PyGen_CheckExact(yf)) {
162 PyFrameObject *f = ((PyGenObject *) yf)->gi_frame;
163 assert(f != NULL);
164 retval = _PyFrame_Finalize(f);
165 if (retval == NULL)
166 return -1;
167 } else {
168 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
169 if (meth == NULL) {
170 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
171 PyErr_WriteUnraisable(yf);
172 PyErr_Clear();
173 } else {
174 retval = PyObject_CallFunction(meth, "");
175 Py_DECREF(meth);
176 if (retval == NULL)
177 return -1;
178 }
179 }
180 Py_XDECREF(retval);
181 return 0;
182}
183
184PyObject *
185_PyFrame_Finalize(PyFrameObject *f)
186{
187 int err = 0;
188 PyObject *retval;
189 PyGenObject *gen = (PyGenObject *) f->f_gen;
190 PyObject *yf = _PyFrame_YieldingFrom(f);
191
192 assert(gen == NULL || PyGen_CheckExact(gen));
193 if (yf) {
194 if (gen)
195 gen->gi_running = 1;
196 err = _PyFrame_CloseIterator(yf);
197 if (gen)
198 gen->gi_running = 0;
199 Py_DECREF(yf);
200 }
201 if (err == 0)
202 PyErr_SetNone(PyExc_GeneratorExit);
203 retval = _PyFrame_GeneratorSend(f, Py_None, 1);
204 if (retval) {
205 Py_DECREF(retval);
206 PyErr_SetString(PyExc_RuntimeError,
207 "generator ignored GeneratorExit");
208 return NULL;
209 }
210 if (PyErr_ExceptionMatches(PyExc_StopIteration)
211 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
212 PyErr_Clear(); /* ignore these errors */
213 Py_INCREF(Py_None);
214 return Py_None;
215 }
216 return NULL;
217}
218
219/*
220 * Line number support.
221 */
222
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000223int
224PyFrame_GetLineNumber(PyFrameObject *f)
225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (f->f_trace)
227 return f->f_lineno;
228 else
229 return PyCode_Addr2Line(f->f_code, f->f_lasti);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000230}
231
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000232static PyObject *
233frame_getlineno(PyFrameObject *f, void *closure)
234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return PyLong_FromLong(PyFrame_GetLineNumber(f));
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000236}
237
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000238/* Setter for f_lineno - you can set f_lineno from within a trace function in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 * order to jump to a given line of code, subject to some restrictions. Most
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000240 * lines are OK to jump to because they don't make any assumptions about the
241 * state of the stack (obvious because you could remove the line and the code
242 * would still work without any stack errors), but there are some constructs
243 * that limit jumping:
244 *
245 * o Lines with an 'except' statement on them can't be jumped to, because
246 * they expect an exception to be on the top of the stack.
247 * o Lines that live in a 'finally' block can't be jumped from or to, since
248 * the END_FINALLY expects to clean up the stack after the 'try' block.
249 * o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
250 * needs to be set up before their code runs, and for 'for' loops the
251 * iterator needs to be on the stack.
252 */
253static int
254frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 int new_lineno = 0; /* The new value of f_lineno */
257 long l_new_lineno;
258 int overflow;
259 int new_lasti = 0; /* The new value of f_lasti */
260 int new_iblock = 0; /* The new value of f_iblock */
261 unsigned char *code = NULL; /* The bytecode for the frame... */
262 Py_ssize_t code_len = 0; /* ...and its length */
263 unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
264 Py_ssize_t lnotab_len = 0; /* (ditto) */
265 int offset = 0; /* (ditto) */
266 int line = 0; /* (ditto) */
267 int addr = 0; /* (ditto) */
268 int min_addr = 0; /* Scanning the SETUPs and POPs */
269 int max_addr = 0; /* (ditto) */
270 int delta_iblock = 0; /* (ditto) */
271 int min_delta_iblock = 0; /* (ditto) */
272 int min_iblock = 0; /* (ditto) */
273 int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
274 int new_lasti_setup_addr = 0; /* (ditto) */
275 int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
276 int in_finally[CO_MAXBLOCKS]; /* (ditto) */
277 int blockstack_top = 0; /* (ditto) */
278 unsigned char setup_op = 0; /* (ditto) */
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 /* f_lineno must be an integer. */
281 if (!PyLong_CheckExact(p_new_lineno)) {
282 PyErr_SetString(PyExc_ValueError,
283 "lineno must be an integer");
284 return -1;
285 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 /* You can only do this from within a trace function, not via
288 * _getframe or similar hackery. */
289 if (!f->f_trace)
290 {
291 PyErr_Format(PyExc_ValueError,
292 "f_lineno can only be set by a"
293 " line trace function");
294 return -1;
295 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 /* Fail if the line comes before the start of the code block. */
298 l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
299 if (overflow
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000300#if SIZEOF_LONG > SIZEOF_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 || l_new_lineno > INT_MAX
302 || l_new_lineno < INT_MIN
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000303#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 ) {
305 PyErr_SetString(PyExc_ValueError,
306 "lineno out of range");
307 return -1;
308 }
309 new_lineno = (int)l_new_lineno;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 if (new_lineno < f->f_code->co_firstlineno) {
312 PyErr_Format(PyExc_ValueError,
313 "line %d comes before the current code block",
314 new_lineno);
315 return -1;
316 }
317 else if (new_lineno == f->f_code->co_firstlineno) {
318 new_lasti = 0;
319 new_lineno = f->f_code->co_firstlineno;
320 }
321 else {
322 /* Find the bytecode offset for the start of the given
323 * line, or the first code-owning line after it. */
324 char *tmp;
325 PyBytes_AsStringAndSize(f->f_code->co_lnotab,
326 &tmp, &lnotab_len);
327 lnotab = (unsigned char *) tmp;
328 addr = 0;
329 line = f->f_code->co_firstlineno;
330 new_lasti = -1;
331 for (offset = 0; offset < lnotab_len; offset += 2) {
332 addr += lnotab[offset];
333 line += lnotab[offset+1];
334 if (line >= new_lineno) {
335 new_lasti = addr;
336 new_lineno = line;
337 break;
338 }
339 }
340 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 /* If we didn't reach the requested line, return an error. */
343 if (new_lasti == -1) {
344 PyErr_Format(PyExc_ValueError,
345 "line %d comes after the current code block",
346 new_lineno);
347 return -1;
348 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 /* We're now ready to look at the bytecode. */
351 PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
352 min_addr = MIN(new_lasti, f->f_lasti);
353 max_addr = MAX(new_lasti, f->f_lasti);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* You can't jump onto a line with an 'except' statement on it -
356 * they expect to have an exception on the top of the stack, which
357 * won't be true if you jump to them. They always start with code
358 * that either pops the exception using POP_TOP (plain 'except:'
359 * lines do this) or duplicates the exception on the stack using
360 * DUP_TOP (if there's an exception type specified). See compile.c,
361 * 'com_try_except' for the full details. There aren't any other
362 * cases (AFAIK) where a line's code can start with DUP_TOP or
363 * POP_TOP, but if any ever appear, they'll be subject to the same
364 * restriction (but with a different error message). */
365 if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
366 PyErr_SetString(PyExc_ValueError,
367 "can't jump to 'except' line as there's no exception");
368 return -1;
369 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 /* You can't jump into or out of a 'finally' block because the 'try'
372 * block leaves something on the stack for the END_FINALLY to clean
373 * up. So we walk the bytecode, maintaining a simulated blockstack.
374 * When we reach the old or new address and it's in a 'finally' block
375 * we note the address of the corresponding SETUP_FINALLY. The jump
376 * is only legal if neither address is in a 'finally' block or
377 * they're both in the same one. 'blockstack' is a stack of the
378 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
379 * whether we're in a 'finally' block at each blockstack level. */
380 f_lasti_setup_addr = -1;
381 new_lasti_setup_addr = -1;
382 memset(blockstack, '\0', sizeof(blockstack));
383 memset(in_finally, '\0', sizeof(in_finally));
384 blockstack_top = 0;
385 for (addr = 0; addr < code_len; addr++) {
386 unsigned char op = code[addr];
387 switch (op) {
388 case SETUP_LOOP:
389 case SETUP_EXCEPT:
390 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400391 case SETUP_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 blockstack[blockstack_top++] = addr;
393 in_finally[blockstack_top-1] = 0;
394 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 case POP_BLOCK:
397 assert(blockstack_top > 0);
398 setup_op = code[blockstack[blockstack_top-1]];
Benjamin Petersone42fb302012-04-18 11:14:31 -0400399 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 in_finally[blockstack_top-1] = 1;
401 }
402 else {
403 blockstack_top--;
404 }
405 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 case END_FINALLY:
408 /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
409 * in the bytecode but don't correspond to an actual
410 * 'finally' block. (If blockstack_top is 0, we must
411 * be seeing such an END_FINALLY.) */
412 if (blockstack_top > 0) {
413 setup_op = code[blockstack[blockstack_top-1]];
Benjamin Petersone42fb302012-04-18 11:14:31 -0400414 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 blockstack_top--;
416 }
417 }
418 break;
419 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 /* For the addresses we're interested in, see whether they're
422 * within a 'finally' block and if so, remember the address
423 * of the SETUP_FINALLY. */
424 if (addr == new_lasti || addr == f->f_lasti) {
425 int i = 0;
426 int setup_addr = -1;
427 for (i = blockstack_top-1; i >= 0; i--) {
428 if (in_finally[i]) {
429 setup_addr = blockstack[i];
430 break;
431 }
432 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (setup_addr != -1) {
435 if (addr == new_lasti) {
436 new_lasti_setup_addr = setup_addr;
437 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (addr == f->f_lasti) {
440 f_lasti_setup_addr = setup_addr;
441 }
442 }
443 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (op >= HAVE_ARGUMENT) {
446 addr += 2;
447 }
448 }
Neal Norwitzee65e222002-12-19 18:16:57 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 /* Verify that the blockstack tracking code didn't get lost. */
451 assert(blockstack_top == 0);
452
453 /* After all that, are we jumping into / out of a 'finally' block? */
454 if (new_lasti_setup_addr != f_lasti_setup_addr) {
455 PyErr_SetString(PyExc_ValueError,
456 "can't jump into or out of a 'finally' block");
457 return -1;
458 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000459
460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* Police block-jumping (you can't jump into the middle of a block)
462 * and ensure that the blockstack finishes up in a sensible state (by
463 * popping any blocks we're jumping out of). We look at all the
464 * blockstack operations between the current position and the new
465 * one, and keep track of how many blocks we drop out of on the way.
466 * By also keeping track of the lowest blockstack position we see, we
467 * can tell whether the jump goes into any blocks without coming out
468 * again - in that case we raise an exception below. */
469 delta_iblock = 0;
470 for (addr = min_addr; addr < max_addr; addr++) {
471 unsigned char op = code[addr];
472 switch (op) {
473 case SETUP_LOOP:
474 case SETUP_EXCEPT:
475 case SETUP_FINALLY:
Benjamin Petersone42fb302012-04-18 11:14:31 -0400476 case SETUP_WITH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 delta_iblock++;
478 break;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 case POP_BLOCK:
481 delta_iblock--;
482 break;
483 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 min_delta_iblock = MIN(min_delta_iblock, delta_iblock);
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (op >= HAVE_ARGUMENT) {
488 addr += 2;
489 }
490 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* Derive the absolute iblock values from the deltas. */
493 min_iblock = f->f_iblock + min_delta_iblock;
494 if (new_lasti > f->f_lasti) {
495 /* Forwards jump. */
496 new_iblock = f->f_iblock + delta_iblock;
497 }
498 else {
499 /* Backwards jump. */
500 new_iblock = f->f_iblock - delta_iblock;
501 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Are we jumping into a block? */
504 if (new_iblock > min_iblock) {
505 PyErr_SetString(PyExc_ValueError,
506 "can't jump into the middle of a block");
507 return -1;
508 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* Pop any blocks that we're jumping out of. */
511 while (f->f_iblock > new_iblock) {
512 PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
513 while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
514 PyObject *v = (*--f->f_stacktop);
515 Py_DECREF(v);
516 }
517 }
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 /* Finally set the new f_lineno and f_lasti and return OK. */
520 f->f_lineno = new_lineno;
521 f->f_lasti = new_lasti;
522 return 0;
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000523}
524
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000525static PyObject *
526frame_gettrace(PyFrameObject *f, void *closure)
527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 PyObject* trace = f->f_trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (trace == NULL)
531 trace = Py_None;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 Py_INCREF(trace);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return trace;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000536}
537
538static int
539frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyObject* old_value;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 /* We rely on f_lineno being accurate when f_trace is set. */
544 f->f_lineno = PyFrame_GetLineNumber(f);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 old_value = f->f_trace;
547 Py_XINCREF(v);
548 f->f_trace = v;
549 Py_XDECREF(old_value);
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return 0;
Michael W. Hudson02ff6a92002-09-11 15:36:32 +0000552}
553
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000554
Guido van Rossum32d34c82001-09-20 21:45:26 +0000555static PyGetSetDef frame_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 {"f_locals", (getter)frame_getlocals, NULL, NULL},
557 {"f_lineno", (getter)frame_getlineno,
558 (setter)frame_setlineno, NULL},
559 {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
560 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000561};
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000562
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000563/* Stack frames are allocated and deallocated at a considerable rate.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000564 In an attempt to improve the speed of function calls, we:
565
566 1. Hold a single "zombie" frame on each code object. This retains
567 the allocated and initialised frame object from an invocation of
568 the code object. The zombie is reanimated the next time we need a
569 frame object for that code object. Doing this saves the malloc/
570 realloc required when using a free_list frame that isn't the
571 correct size. It also saves some field initialisation.
572
573 In zombie mode, no field of PyFrameObject holds a reference, but
574 the following fields are still valid:
575
576 * ob_type, ob_size, f_code, f_valuestack;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577
Thomas Wouters477c8d52006-05-27 19:21:47 +0000578 * f_locals, f_trace,
579 f_exc_type, f_exc_value, f_exc_traceback are NULL;
580
581 * f_localsplus does not require re-allocation and
582 the local variables in f_localsplus are NULL.
583
584 2. We also maintain a separate free list of stack frames (just like
Mark Dickinsond19052c2010-06-27 18:19:09 +0000585 floats are allocated in a special way -- see floatobject.c). When
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586 a stack frame is on the free list, only the following members have
587 a meaning:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 ob_type == &Frametype
589 f_back next item on free list, or NULL
590 f_stacksize size of value stack
591 ob_size size of localsplus
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000592 Note that the value and block stacks are preserved -- this can save
593 another malloc() call or two (and two free() calls as well!).
594 Also note that, unlike for integers, each frame object is a
595 malloc'ed object in its own right -- it is only the actual calls to
596 malloc() that we are trying to save here, not the administration.
597 After all, while a typical program may make millions of calls, a
598 call depth of more than 20 or 30 is probably already exceptional
599 unless the program contains run-away recursion. I hope.
Tim Petersb7ba7432002-04-13 05:21:47 +0000600
Christian Heimes2202f872008-02-06 14:31:34 +0000601 Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
Tim Petersb7ba7432002-04-13 05:21:47 +0000602 free_list. Else programs creating lots of cyclic trash involving
603 frames could provoke free_list into growing without bound.
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000604*/
605
Guido van Rossum18752471997-04-29 14:49:28 +0000606static PyFrameObject *free_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607static int numfree = 0; /* number of frames currently in free_list */
Christian Heimes2202f872008-02-06 14:31:34 +0000608/* max value for numfree */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609#define PyFrame_MAXFREELIST 200
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000610
Guido van Rossum3f5da241990-12-20 15:06:42 +0000611static void
Antoine Pitrou04e70d12013-05-08 18:12:35 +0200612frame_clear(PyFrameObject *f);
613
614static void
Fred Drake1b190b42000-07-09 05:40:56 +0000615frame_dealloc(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyCodeObject *co;
Guido van Rossum7582bfb1997-02-14 16:27:29 +0000618
Antoine Pitrou04e70d12013-05-08 18:12:35 +0200619 Py_REFCNT(f)++;
620 frame_clear(f);
621 Py_REFCNT(f)--;
622 if (Py_REFCNT(f) > 0) {
623 /* Frame resurrected! */
624 Py_ssize_t refcnt = Py_REFCNT(f);
625 _Py_NewReference((PyObject *) f);
626 Py_REFCNT(f) = refcnt;
627 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
628 * we need to undo that. */
629 _Py_DEC_REFTOTAL;
630 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
631 * chain, so no more to do there.
632 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
633 * _Py_NewReference bumped tp_allocs: both of those need to be
634 * undone.
635 */
636#ifdef COUNT_ALLOCS
637 --(Py_TYPE(self)->tp_frees);
638 --(Py_TYPE(self)->tp_allocs);
639#endif
640 }
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject_GC_UnTrack(f);
643 Py_TRASHCAN_SAFE_BEGIN(f)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 Py_XDECREF(f->f_back);
646 Py_DECREF(f->f_builtins);
647 Py_DECREF(f->f_globals);
648 Py_CLEAR(f->f_locals);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 co = f->f_code;
651 if (co->co_zombieframe == NULL)
652 co->co_zombieframe = f;
653 else if (numfree < PyFrame_MAXFREELIST) {
654 ++numfree;
655 f->f_back = free_list;
656 free_list = f;
657 }
658 else
659 PyObject_GC_Del(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_DECREF(co);
662 Py_TRASHCAN_SAFE_END(f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000663}
664
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000665static int
666frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject **fastlocals, **p;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100669 Py_ssize_t i, slots;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 Py_VISIT(f->f_back);
672 Py_VISIT(f->f_code);
673 Py_VISIT(f->f_builtins);
674 Py_VISIT(f->f_globals);
675 Py_VISIT(f->f_locals);
676 Py_VISIT(f->f_trace);
677 Py_VISIT(f->f_exc_type);
678 Py_VISIT(f->f_exc_value);
679 Py_VISIT(f->f_exc_traceback);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 /* locals */
682 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
683 fastlocals = f->f_localsplus;
684 for (i = slots; --i >= 0; ++fastlocals)
685 Py_VISIT(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 /* stack */
688 if (f->f_stacktop != NULL) {
689 for (p = f->f_valuestack; p < f->f_stacktop; p++)
690 Py_VISIT(*p);
691 }
692 return 0;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000693}
694
695static void
696frame_clear(PyFrameObject *f)
697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyObject **fastlocals, **p, **oldtop;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +0100699 Py_ssize_t i, slots;
Antoine Pitrou04e70d12013-05-08 18:12:35 +0200700 PyObject *retval;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000701
Antoine Pitrou04e70d12013-05-08 18:12:35 +0200702 if (f->f_back == NULL) {
703 PyObject *t, *v, *tb;
704 PyErr_Fetch(&t, &v, &tb);
705 /* Note that this can finalize a suspended generator frame even
706 * if the generator object was disposed of (i.e. if f_gen is NULL).
707 */
708 retval = _PyFrame_Finalize(f);
709 if (retval == NULL) {
710 if (PyErr_Occurred())
711 PyErr_WriteUnraisable((PyObject *) f);
712 }
713 else
714 Py_DECREF(retval);
715 PyErr_Restore(t, v, tb);
716 }
717
718 /* Make sure the frame is now clearly marked as being defunct */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 oldtop = f->f_stacktop;
720 f->f_stacktop = NULL;
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 Py_CLEAR(f->f_exc_type);
723 Py_CLEAR(f->f_exc_value);
724 Py_CLEAR(f->f_exc_traceback);
725 Py_CLEAR(f->f_trace);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 /* locals */
728 slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
729 fastlocals = f->f_localsplus;
730 for (i = slots; --i >= 0; ++fastlocals)
731 Py_CLEAR(*fastlocals);
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 /* stack */
734 if (oldtop != NULL) {
735 for (p = f->f_valuestack; p < oldtop; p++)
736 Py_CLEAR(*p);
737 }
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000738}
739
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000740static PyObject *
741frame_sizeof(PyFrameObject *f)
742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 Py_ssize_t res, extras, ncells, nfrees;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
746 nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
747 extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
748 ncells + nfrees;
749 /* subtract one as it is already included in PyFrameObject */
750 res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000753}
754
755PyDoc_STRVAR(sizeof__doc__,
756"F.__sizeof__() -> size of F in memory, in bytes");
757
758static PyMethodDef frame_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
760 sizeof__doc__},
761 {NULL, NULL} /* sentinel */
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000762};
Neil Schemenauer19cd2922001-07-12 13:27:11 +0000763
Guido van Rossum18752471997-04-29 14:49:28 +0000764PyTypeObject PyFrame_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyVarObject_HEAD_INIT(&PyType_Type, 0)
766 "frame",
767 sizeof(PyFrameObject),
768 sizeof(PyObject *),
769 (destructor)frame_dealloc, /* tp_dealloc */
770 0, /* tp_print */
771 0, /* tp_getattr */
772 0, /* tp_setattr */
773 0, /* tp_reserved */
774 0, /* tp_repr */
775 0, /* tp_as_number */
776 0, /* tp_as_sequence */
777 0, /* tp_as_mapping */
778 0, /* tp_hash */
779 0, /* tp_call */
780 0, /* tp_str */
781 PyObject_GenericGetAttr, /* tp_getattro */
782 PyObject_GenericSetAttr, /* tp_setattro */
783 0, /* tp_as_buffer */
784 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
785 0, /* tp_doc */
786 (traverseproc)frame_traverse, /* tp_traverse */
787 (inquiry)frame_clear, /* tp_clear */
788 0, /* tp_richcompare */
789 0, /* tp_weaklistoffset */
790 0, /* tp_iter */
791 0, /* tp_iternext */
792 frame_methods, /* tp_methods */
793 frame_memberlist, /* tp_members */
794 frame_getsetlist, /* tp_getset */
795 0, /* tp_base */
796 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000797};
798
Neal Norwitzc91ed402002-12-30 22:29:22 +0000799static PyObject *builtin_object;
800
Neal Norwitzb2501f42002-12-31 03:42:13 +0000801int _PyFrame_Init()
Neal Norwitzc91ed402002-12-30 22:29:22 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 builtin_object = PyUnicode_InternFromString("__builtins__");
804 if (builtin_object == NULL)
805 return 0;
806 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +0000807}
808
Guido van Rossum18752471997-04-29 14:49:28 +0000809PyFrameObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000810PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 PyObject *locals)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyFrameObject *back = tstate->frame;
814 PyFrameObject *f;
815 PyObject *builtins;
816 Py_ssize_t i;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000817
Michael W. Hudson69734a52002-08-19 16:54:08 +0000818#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
820 (locals != NULL && !PyMapping_Check(locals))) {
821 PyErr_BadInternalCall();
822 return NULL;
823 }
Michael W. Hudson69734a52002-08-19 16:54:08 +0000824#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 if (back == NULL || back->f_globals != globals) {
826 builtins = PyDict_GetItem(globals, builtin_object);
827 if (builtins) {
828 if (PyModule_Check(builtins)) {
829 builtins = PyModule_GetDict(builtins);
Victor Stinnerb0b22422012-04-19 00:57:45 +0200830 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
833 if (builtins == NULL) {
834 /* No builtins! Make up a minimal one
835 Give them 'None', at least. */
836 builtins = PyDict_New();
837 if (builtins == NULL ||
838 PyDict_SetItemString(
839 builtins, "None", Py_None) < 0)
840 return NULL;
841 }
842 else
843 Py_INCREF(builtins);
Jeremy Hyltonbd5cbf82003-02-05 22:39:29 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 }
846 else {
847 /* If we share the globals, we share the builtins.
848 Save a lookup and a call. */
849 builtins = back->f_builtins;
Victor Stinnerb0b22422012-04-19 00:57:45 +0200850 assert(builtins != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 Py_INCREF(builtins);
852 }
853 if (code->co_zombieframe != NULL) {
854 f = code->co_zombieframe;
855 code->co_zombieframe = NULL;
856 _Py_NewReference((PyObject *)f);
857 assert(f->f_code == code);
858 }
859 else {
860 Py_ssize_t extras, ncells, nfrees;
861 ncells = PyTuple_GET_SIZE(code->co_cellvars);
862 nfrees = PyTuple_GET_SIZE(code->co_freevars);
863 extras = code->co_stacksize + code->co_nlocals + ncells +
864 nfrees;
865 if (free_list == NULL) {
866 f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
867 extras);
868 if (f == NULL) {
869 Py_DECREF(builtins);
870 return NULL;
871 }
872 }
873 else {
874 assert(numfree > 0);
875 --numfree;
876 f = free_list;
877 free_list = free_list->f_back;
878 if (Py_SIZE(f) < extras) {
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000879 PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras);
880 if (new_f == NULL) {
881 PyObject_GC_Del(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_DECREF(builtins);
883 return NULL;
884 }
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +0000885 f = new_f;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 }
887 _Py_NewReference((PyObject *)f);
888 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 f->f_code = code;
891 extras = code->co_nlocals + ncells + nfrees;
892 f->f_valuestack = f->f_localsplus + extras;
893 for (i=0; i<extras; i++)
894 f->f_localsplus[i] = NULL;
895 f->f_locals = NULL;
896 f->f_trace = NULL;
897 f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
898 }
899 f->f_stacktop = f->f_valuestack;
900 f->f_builtins = builtins;
901 Py_XINCREF(back);
902 f->f_back = back;
903 Py_INCREF(code);
904 Py_INCREF(globals);
905 f->f_globals = globals;
906 /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
907 if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
908 (CO_NEWLOCALS | CO_OPTIMIZED))
909 ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
910 else if (code->co_flags & CO_NEWLOCALS) {
911 locals = PyDict_New();
912 if (locals == NULL) {
913 Py_DECREF(f);
914 return NULL;
915 }
916 f->f_locals = locals;
917 }
918 else {
919 if (locals == NULL)
920 locals = globals;
921 Py_INCREF(locals);
922 f->f_locals = locals;
923 }
924 f->f_tstate = tstate;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 f->f_lasti = -1;
927 f->f_lineno = code->co_firstlineno;
928 f->f_iblock = 0;
Antoine Pitrou04e70d12013-05-08 18:12:35 +0200929 f->f_gen = NULL;
Guido van Rossumf3e85a01997-01-20 04:20:52 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 _PyObject_GC_TRACK(f);
932 return f;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000933}
934
Guido van Rossum3f5da241990-12-20 15:06:42 +0000935/* Block management */
936
937void
Fred Drake1b190b42000-07-09 05:40:56 +0000938PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyTryBlock *b;
941 if (f->f_iblock >= CO_MAXBLOCKS)
942 Py_FatalError("XXX block stack overflow");
943 b = &f->f_blockstack[f->f_iblock++];
944 b->b_type = type;
945 b->b_level = level;
946 b->b_handler = handler;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000947}
948
Guido van Rossum18752471997-04-29 14:49:28 +0000949PyTryBlock *
Fred Drake1b190b42000-07-09 05:40:56 +0000950PyFrame_BlockPop(PyFrameObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyTryBlock *b;
953 if (f->f_iblock <= 0)
954 Py_FatalError("XXX block stack underflow");
955 b = &f->f_blockstack[--f->f_iblock];
956 return b;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000957}
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000958
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959/* Convert between "fast" version of locals and dictionary version.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960
961 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000962 values is an array of PyObject*. At index i, map[i] is the name of
963 the variable with value values[i]. The function copies the first
964 nmap variable from map/values into dict. If values[i] is NULL,
965 the variable is deleted from dict.
966
967 If deref is true, then the values being copied are cell variables
968 and the value is extracted from the cell variable before being put
969 in dict.
970
971 Exceptions raised while modifying the dict are silently ignored,
972 because there is no good way to report them.
973 */
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000974
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000975static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000976map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 int deref)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +0000978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 Py_ssize_t j;
980 assert(PyTuple_Check(map));
981 assert(PyDict_Check(dict));
982 assert(PyTuple_Size(map) >= nmap);
983 for (j = nmap; --j >= 0; ) {
984 PyObject *key = PyTuple_GET_ITEM(map, j);
985 PyObject *value = values[j];
986 assert(PyUnicode_Check(key));
987 if (deref) {
988 assert(PyCell_Check(value));
989 value = PyCell_GET(value);
990 }
991 if (value == NULL) {
992 if (PyObject_DelItem(dict, key) != 0)
993 PyErr_Clear();
994 }
995 else {
996 if (PyObject_SetItem(dict, key, value) != 0)
997 PyErr_Clear();
998 }
999 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001000}
1001
Guido van Rossumd8faa362007-04-27 19:54:29 +00001002/* Copy values from the "locals" dict into the fast locals.
1003
1004 dict is an input argument containing string keys representing
1005 variables names and arbitrary PyObject* as values.
1006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 map and values are input arguments. map is a tuple of strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008 values is an array of PyObject*. At index i, map[i] is the name of
1009 the variable with value values[i]. The function copies the first
1010 nmap variable from map/values into dict. If values[i] is NULL,
1011 the variable is deleted from dict.
1012
1013 If deref is true, then the values being copied are cell variables
1014 and the value is extracted from the cell variable before being put
1015 in dict. If clear is true, then variables in map but not in dict
1016 are set to NULL in map; if clear is false, variables missing in
1017 dict are ignored.
1018
1019 Exceptions raised while modifying the dict are silently ignored,
1020 because there is no good way to report them.
1021*/
1022
Guido van Rossum6b356e72001-04-14 17:55:41 +00001023static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001024dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 int deref, int clear)
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 Py_ssize_t j;
1028 assert(PyTuple_Check(map));
1029 assert(PyDict_Check(dict));
1030 assert(PyTuple_Size(map) >= nmap);
1031 for (j = nmap; --j >= 0; ) {
1032 PyObject *key = PyTuple_GET_ITEM(map, j);
1033 PyObject *value = PyObject_GetItem(dict, key);
1034 assert(PyUnicode_Check(key));
1035 /* We only care about NULLs if clear is true. */
1036 if (value == NULL) {
1037 PyErr_Clear();
1038 if (!clear)
1039 continue;
1040 }
1041 if (deref) {
1042 assert(PyCell_Check(values[j]));
1043 if (PyCell_GET(values[j]) != value) {
1044 if (PyCell_Set(values[j], value) < 0)
1045 PyErr_Clear();
1046 }
1047 } else if (values[j] != value) {
1048 Py_XINCREF(value);
1049 Py_XDECREF(values[j]);
1050 values[j] = value;
1051 }
1052 Py_XDECREF(value);
1053 }
Jeremy Hylton220ae7c2001-03-21 16:43:47 +00001054}
Jeremy Hylton2b724da2001-01-29 22:51:52 +00001055
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001056void
Fred Drake1b190b42000-07-09 05:40:56 +00001057PyFrame_FastToLocals(PyFrameObject *f)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 /* Merge fast locals into f->f_locals */
1060 PyObject *locals, *map;
1061 PyObject **fast;
1062 PyObject *error_type, *error_value, *error_traceback;
1063 PyCodeObject *co;
1064 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001065 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (f == NULL)
1067 return;
1068 locals = f->f_locals;
1069 if (locals == NULL) {
1070 locals = f->f_locals = PyDict_New();
1071 if (locals == NULL) {
1072 PyErr_Clear(); /* Can't report it :-( */
1073 return;
1074 }
1075 }
1076 co = f->f_code;
1077 map = co->co_varnames;
1078 if (!PyTuple_Check(map))
1079 return;
1080 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1081 fast = f->f_localsplus;
1082 j = PyTuple_GET_SIZE(map);
1083 if (j > co->co_nlocals)
1084 j = co->co_nlocals;
1085 if (co->co_nlocals)
1086 map_to_dict(map, j, locals, fast, 0);
1087 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1088 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1089 if (ncells || nfreevars) {
1090 map_to_dict(co->co_cellvars, ncells,
1091 locals, fast + co->co_nlocals, 1);
1092 /* If the namespace is unoptimized, then one of the
1093 following cases applies:
1094 1. It does not contain free variables, because it
1095 uses import * or is a top-level namespace.
1096 2. It is a class namespace.
1097 We don't want to accidentally copy free variables
1098 into the locals dict used by the class.
1099 */
1100 if (co->co_flags & CO_OPTIMIZED) {
1101 map_to_dict(co->co_freevars, nfreevars,
1102 locals, fast + co->co_nlocals + ncells, 1);
1103 }
1104 }
1105 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001106}
1107
1108void
Fred Drake1b190b42000-07-09 05:40:56 +00001109PyFrame_LocalsToFast(PyFrameObject *f, int clear)
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 /* Merge f->f_locals into fast locals */
1112 PyObject *locals, *map;
1113 PyObject **fast;
1114 PyObject *error_type, *error_value, *error_traceback;
1115 PyCodeObject *co;
1116 Py_ssize_t j;
Victor Stinner7a6d7cf2012-10-31 00:37:41 +01001117 Py_ssize_t ncells, nfreevars;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (f == NULL)
1119 return;
1120 locals = f->f_locals;
1121 co = f->f_code;
1122 map = co->co_varnames;
1123 if (locals == NULL)
1124 return;
1125 if (!PyTuple_Check(map))
1126 return;
1127 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1128 fast = f->f_localsplus;
1129 j = PyTuple_GET_SIZE(map);
1130 if (j > co->co_nlocals)
1131 j = co->co_nlocals;
1132 if (co->co_nlocals)
1133 dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
1134 ncells = PyTuple_GET_SIZE(co->co_cellvars);
1135 nfreevars = PyTuple_GET_SIZE(co->co_freevars);
1136 if (ncells || nfreevars) {
1137 dict_to_map(co->co_cellvars, ncells,
1138 locals, fast + co->co_nlocals, 1, clear);
1139 /* Same test as in PyFrame_FastToLocals() above. */
1140 if (co->co_flags & CO_OPTIMIZED) {
1141 dict_to_map(co->co_freevars, nfreevars,
1142 locals, fast + co->co_nlocals + ncells, 1,
1143 clear);
1144 }
1145 }
1146 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001147}
Guido van Rossum404b95d1997-08-05 02:09:46 +00001148
1149/* Clear out the free list */
Christian Heimesa156e092008-02-16 07:38:31 +00001150int
1151PyFrame_ClearFreeList(void)
Guido van Rossum404b95d1997-08-05 02:09:46 +00001152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 int freelist_size = numfree;
1154
1155 while (free_list != NULL) {
1156 PyFrameObject *f = free_list;
1157 free_list = free_list->f_back;
1158 PyObject_GC_Del(f);
1159 --numfree;
1160 }
1161 assert(numfree == 0);
1162 return freelist_size;
Christian Heimesa156e092008-02-16 07:38:31 +00001163}
1164
1165void
1166PyFrame_Fini(void)
1167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 (void)PyFrame_ClearFreeList();
1169 Py_XDECREF(builtin_object);
1170 builtin_object = NULL;
Guido van Rossum404b95d1997-08-05 02:09:46 +00001171}
David Malcolm49526f42012-06-22 14:55:41 -04001172
1173/* Print summary info about the state of the optimized allocator */
1174void
1175_PyFrame_DebugMallocStats(FILE *out)
1176{
1177 _PyDebugAllocatorStats(out,
1178 "free PyFrameObject",
1179 numfree, sizeof(PyFrameObject));
1180}
1181