• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Frame object implementation */
2 
3 #include "Python.h"
4 
5 #include "code.h"
6 #include "frameobject.h"
7 #include "opcode.h"
8 #include "structmember.h"
9 
10 #undef MIN
11 #undef MAX
12 #define MIN(a, b) ((a) < (b) ? (a) : (b))
13 #define MAX(a, b) ((a) > (b) ? (a) : (b))
14 
15 #define OFF(x) offsetof(PyFrameObject, x)
16 
17 static PyMemberDef frame_memberlist[] = {
18     {"f_back",          T_OBJECT,       OFF(f_back),    RO},
19     {"f_code",          T_OBJECT,       OFF(f_code),    RO},
20     {"f_builtins",      T_OBJECT,       OFF(f_builtins),RO},
21     {"f_globals",       T_OBJECT,       OFF(f_globals), RO},
22     {"f_lasti",         T_INT,          OFF(f_lasti),   RO},
23     {NULL}      /* Sentinel */
24 };
25 
26 #define WARN_GET_SET(NAME) \
27 static PyObject * frame_get_ ## NAME(PyFrameObject *f) { \
28     if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
29         return NULL; \
30     if (f->NAME) { \
31         Py_INCREF(f->NAME); \
32         return f->NAME; \
33     } \
34     Py_RETURN_NONE;     \
35 } \
36 static int frame_set_ ## NAME(PyFrameObject *f, PyObject *new) { \
37     if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
38         return -1; \
39     if (f->NAME) { \
40         Py_CLEAR(f->NAME); \
41     } \
42     if (new == Py_None) \
43         new = NULL; \
44     Py_XINCREF(new); \
45     f->NAME = new; \
46     return 0; \
47 }
48 
49 
50 WARN_GET_SET(f_exc_traceback)
WARN_GET_SET(f_exc_type)51 WARN_GET_SET(f_exc_type)
52 WARN_GET_SET(f_exc_value)
53 
54 
55 static PyObject *
56 frame_getlocals(PyFrameObject *f, void *closure)
57 {
58     PyFrame_FastToLocals(f);
59     Py_INCREF(f->f_locals);
60     return f->f_locals;
61 }
62 
63 int
PyFrame_GetLineNumber(PyFrameObject * f)64 PyFrame_GetLineNumber(PyFrameObject *f)
65 {
66     if (f->f_trace)
67         return f->f_lineno;
68     else
69         return PyCode_Addr2Line(f->f_code, f->f_lasti);
70 }
71 
72 static PyObject *
frame_getlineno(PyFrameObject * f,void * closure)73 frame_getlineno(PyFrameObject *f, void *closure)
74 {
75     return PyInt_FromLong(PyFrame_GetLineNumber(f));
76 }
77 
78 /* Setter for f_lineno - you can set f_lineno from within a trace function in
79  * order to jump to a given line of code, subject to some restrictions.  Most
80  * lines are OK to jump to because they don't make any assumptions about the
81  * state of the stack (obvious because you could remove the line and the code
82  * would still work without any stack errors), but there are some constructs
83  * that limit jumping:
84  *
85  *  o Lines with an 'except' statement on them can't be jumped to, because
86  *    they expect an exception to be on the top of the stack.
87  *  o Lines that live in a 'finally' block can't be jumped from or to, since
88  *    the END_FINALLY expects to clean up the stack after the 'try' block.
89  *  o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
90  *    needs to be set up before their code runs, and for 'for' loops the
91  *    iterator needs to be on the stack.
92  *  o Jumps cannot be made from within a trace function invoked with a
93  *    'return' or 'exception' event since the eval loop has been exited at
94  *    that time.
95  */
96 static int
frame_setlineno(PyFrameObject * f,PyObject * p_new_lineno)97 frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
98 {
99     int new_lineno = 0;                 /* The new value of f_lineno */
100     int new_lasti = 0;                  /* The new value of f_lasti */
101     int new_iblock = 0;                 /* The new value of f_iblock */
102     unsigned char *code = NULL;         /* The bytecode for the frame... */
103     Py_ssize_t code_len = 0;            /* ...and its length */
104     unsigned char *lnotab = NULL;       /* Iterating over co_lnotab */
105     Py_ssize_t lnotab_len = 0;          /* (ditto) */
106     int offset = 0;                     /* (ditto) */
107     int line = 0;                       /* (ditto) */
108     int addr = 0;                       /* (ditto) */
109     int min_addr = 0;                   /* Scanning the SETUPs and POPs */
110     int max_addr = 0;                   /* (ditto) */
111     int delta_iblock = 0;               /* (ditto) */
112     int min_delta_iblock = 0;           /* (ditto) */
113     int min_iblock = 0;                 /* (ditto) */
114     int f_lasti_setup_addr = 0;         /* Policing no-jump-into-finally */
115     int new_lasti_setup_addr = 0;       /* (ditto) */
116     int blockstack[CO_MAXBLOCKS];       /* Walking the 'finally' blocks */
117     int in_finally[CO_MAXBLOCKS];       /* (ditto) */
118     int blockstack_top = 0;             /* (ditto) */
119     unsigned char setup_op = 0;         /* (ditto) */
120 
121     /* f_lineno must be an integer. */
122     if (!PyInt_Check(p_new_lineno)) {
123         PyErr_SetString(PyExc_ValueError,
124                         "lineno must be an integer");
125         return -1;
126     }
127 
128     /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and
129      * f->f_trace is NULL, check first on the first condition.
130      * Forbidding jumps from the 'call' event of a new frame is a side effect
131      * of allowing to set f_lineno only from trace functions. */
132     if (f->f_lasti == -1) {
133         PyErr_Format(PyExc_ValueError,
134                      "can't jump from the 'call' trace event of a new frame");
135         return -1;
136     }
137 
138     /* You can only do this from within a trace function, not via
139      * _getframe or similar hackery. */
140     if (!f->f_trace) {
141         PyErr_Format(PyExc_ValueError,
142                      "f_lineno can only be set by a trace function");
143         return -1;
144     }
145 
146     /* Forbid jumps upon a 'return' trace event (except after executing a
147      * YIELD_VALUE opcode, f_stacktop is not NULL in that case) and upon an
148      * 'exception' trace event.
149      * Jumps from 'call' trace events have already been forbidden above for new
150      * frames, so this check does not change anything for 'call' events. */
151     if (f->f_stacktop == NULL) {
152         PyErr_SetString(PyExc_ValueError,
153                 "can only jump from a 'line' trace event");
154         return -1;
155     }
156 
157     /* Fail if the line comes before the start of the code block. */
158     new_lineno = (int) PyInt_AsLong(p_new_lineno);
159     if (new_lineno < f->f_code->co_firstlineno) {
160         PyErr_Format(PyExc_ValueError,
161                      "line %d comes before the current code block",
162                      new_lineno);
163         return -1;
164     }
165     else if (new_lineno == f->f_code->co_firstlineno) {
166         new_lasti = 0;
167         new_lineno = f->f_code->co_firstlineno;
168     }
169     else {
170         /* Find the bytecode offset for the start of the given
171          * line, or the first code-owning line after it. */
172         char *tmp;
173         PyString_AsStringAndSize(f->f_code->co_lnotab,
174                                  &tmp, &lnotab_len);
175         lnotab = (unsigned char *) tmp;
176         addr = 0;
177         line = f->f_code->co_firstlineno;
178         new_lasti = -1;
179         for (offset = 0; offset < lnotab_len; offset += 2) {
180             addr += lnotab[offset];
181             line += lnotab[offset+1];
182             if (line >= new_lineno) {
183                 new_lasti = addr;
184                 new_lineno = line;
185                 break;
186             }
187         }
188     }
189 
190     /* If we didn't reach the requested line, return an error. */
191     if (new_lasti == -1) {
192         PyErr_Format(PyExc_ValueError,
193                      "line %d comes after the current code block",
194                      new_lineno);
195         return -1;
196     }
197 
198     /* We're now ready to look at the bytecode. */
199     PyString_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
200     min_addr = MIN(new_lasti, f->f_lasti);
201     max_addr = MAX(new_lasti, f->f_lasti);
202 
203     /* The trace function is called with a 'return' trace event after the
204      * execution of a yield statement. */
205     assert(f->f_lasti != -1);
206     if (code[f->f_lasti] == YIELD_VALUE) {
207         PyErr_SetString(PyExc_ValueError,
208                 "can't jump from a yield statement");
209         return -1;
210     }
211 
212     /* You can't jump onto a line with an 'except' statement on it -
213      * they expect to have an exception on the top of the stack, which
214      * won't be true if you jump to them.  They always start with code
215      * that either pops the exception using POP_TOP (plain 'except:'
216      * lines do this) or duplicates the exception on the stack using
217      * DUP_TOP (if there's an exception type specified).  See compile.c,
218      * 'com_try_except' for the full details.  There aren't any other
219      * cases (AFAIK) where a line's code can start with DUP_TOP or
220      * POP_TOP, but if any ever appear, they'll be subject to the same
221      * restriction (but with a different error message). */
222     if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
223         PyErr_SetString(PyExc_ValueError,
224             "can't jump to 'except' line as there's no exception");
225         return -1;
226     }
227 
228     /* You can't jump into or out of a 'finally' block because the 'try'
229      * block leaves something on the stack for the END_FINALLY to clean
230      * up.      So we walk the bytecode, maintaining a simulated blockstack.
231      * When we reach the old or new address and it's in a 'finally' block
232      * we note the address of the corresponding SETUP_FINALLY.  The jump
233      * is only legal if neither address is in a 'finally' block or
234      * they're both in the same one.  'blockstack' is a stack of the
235      * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
236      * whether we're in a 'finally' block at each blockstack level. */
237     f_lasti_setup_addr = -1;
238     new_lasti_setup_addr = -1;
239     memset(blockstack, '\0', sizeof(blockstack));
240     memset(in_finally, '\0', sizeof(in_finally));
241     blockstack_top = 0;
242     for (addr = 0; addr < code_len; addr++) {
243         unsigned char op = code[addr];
244         switch (op) {
245         case SETUP_LOOP:
246         case SETUP_EXCEPT:
247         case SETUP_FINALLY:
248         case SETUP_WITH:
249             blockstack[blockstack_top++] = addr;
250             in_finally[blockstack_top-1] = 0;
251             break;
252 
253         case POP_BLOCK:
254             assert(blockstack_top > 0);
255             setup_op = code[blockstack[blockstack_top-1]];
256             if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {
257                 in_finally[blockstack_top-1] = 1;
258             }
259             else {
260                 blockstack_top--;
261             }
262             break;
263 
264         case END_FINALLY:
265             /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
266              * in the bytecode but don't correspond to an actual
267              * 'finally' block.  (If blockstack_top is 0, we must
268              * be seeing such an END_FINALLY.) */
269             if (blockstack_top > 0) {
270                 setup_op = code[blockstack[blockstack_top-1]];
271                 if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {
272                     blockstack_top--;
273                 }
274             }
275             break;
276         }
277 
278         /* For the addresses we're interested in, see whether they're
279          * within a 'finally' block and if so, remember the address
280          * of the SETUP_FINALLY. */
281         if (addr == new_lasti || addr == f->f_lasti) {
282             int i = 0;
283             int setup_addr = -1;
284             for (i = blockstack_top-1; i >= 0; i--) {
285                 if (in_finally[i]) {
286                     setup_addr = blockstack[i];
287                     break;
288                 }
289             }
290 
291             if (setup_addr != -1) {
292                 if (addr == new_lasti) {
293                     new_lasti_setup_addr = setup_addr;
294                 }
295 
296                 if (addr == f->f_lasti) {
297                     f_lasti_setup_addr = setup_addr;
298                 }
299             }
300         }
301 
302         if (op >= HAVE_ARGUMENT) {
303             addr += 2;
304         }
305     }
306 
307     /* Verify that the blockstack tracking code didn't get lost. */
308     assert(blockstack_top == 0);
309 
310     /* After all that, are we jumping into / out of a 'finally' block? */
311     if (new_lasti_setup_addr != f_lasti_setup_addr) {
312         PyErr_SetString(PyExc_ValueError,
313                     "can't jump into or out of a 'finally' block");
314         return -1;
315     }
316 
317 
318     /* Police block-jumping (you can't jump into the middle of a block)
319      * and ensure that the blockstack finishes up in a sensible state (by
320      * popping any blocks we're jumping out of).  We look at all the
321      * blockstack operations between the current position and the new
322      * one, and keep track of how many blocks we drop out of on the way.
323      * By also keeping track of the lowest blockstack position we see, we
324      * can tell whether the jump goes into any blocks without coming out
325      * again - in that case we raise an exception below. */
326     delta_iblock = 0;
327     for (addr = min_addr; addr < max_addr; addr++) {
328         unsigned char op = code[addr];
329         switch (op) {
330         case SETUP_LOOP:
331         case SETUP_EXCEPT:
332         case SETUP_FINALLY:
333         case SETUP_WITH:
334             delta_iblock++;
335             break;
336 
337         case POP_BLOCK:
338             delta_iblock--;
339             break;
340         }
341 
342         min_delta_iblock = MIN(min_delta_iblock, delta_iblock);
343 
344         if (op >= HAVE_ARGUMENT) {
345             addr += 2;
346         }
347     }
348 
349     /* Derive the absolute iblock values from the deltas. */
350     min_iblock = f->f_iblock + min_delta_iblock;
351     if (new_lasti > f->f_lasti) {
352         /* Forwards jump. */
353         new_iblock = f->f_iblock + delta_iblock;
354     }
355     else {
356         /* Backwards jump. */
357         new_iblock = f->f_iblock - delta_iblock;
358     }
359 
360     /* Are we jumping into a block? */
361     if (new_iblock > min_iblock) {
362         PyErr_SetString(PyExc_ValueError,
363                         "can't jump into the middle of a block");
364         return -1;
365     }
366 
367     /* Pop any blocks that we're jumping out of. */
368     while (f->f_iblock > new_iblock) {
369         PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
370         while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
371             PyObject *v = (*--f->f_stacktop);
372             Py_DECREF(v);
373         }
374         if (b->b_type == SETUP_WITH) {
375             /* Pop the exit function. */
376             PyObject *v = (*--f->f_stacktop);
377             Py_DECREF(v);
378         }
379     }
380 
381     /* Finally set the new f_lineno and f_lasti and return OK. */
382     f->f_lineno = new_lineno;
383     f->f_lasti = new_lasti;
384     return 0;
385 }
386 
387 static PyObject *
frame_gettrace(PyFrameObject * f,void * closure)388 frame_gettrace(PyFrameObject *f, void *closure)
389 {
390     PyObject* trace = f->f_trace;
391 
392     if (trace == NULL)
393         trace = Py_None;
394 
395     Py_INCREF(trace);
396 
397     return trace;
398 }
399 
400 static int
frame_settrace(PyFrameObject * f,PyObject * v,void * closure)401 frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
402 {
403     /* We rely on f_lineno being accurate when f_trace is set. */
404     f->f_lineno = PyFrame_GetLineNumber(f);
405 
406     if (v == Py_None)
407         v = NULL;
408     Py_XINCREF(v);
409     Py_XSETREF(f->f_trace, v);
410 
411     return 0;
412 }
413 
414 static PyObject *
frame_getrestricted(PyFrameObject * f,void * closure)415 frame_getrestricted(PyFrameObject *f, void *closure)
416 {
417     return PyBool_FromLong(PyFrame_IsRestricted(f));
418 }
419 
420 static PyGetSetDef frame_getsetlist[] = {
421     {"f_locals",        (getter)frame_getlocals, NULL, NULL},
422     {"f_lineno",        (getter)frame_getlineno,
423                     (setter)frame_setlineno, NULL},
424     {"f_trace",         (getter)frame_gettrace, (setter)frame_settrace, NULL},
425     {"f_restricted",(getter)frame_getrestricted,NULL, NULL},
426     {"f_exc_traceback", (getter)frame_get_f_exc_traceback,
427                     (setter)frame_set_f_exc_traceback, NULL},
428     {"f_exc_type",  (getter)frame_get_f_exc_type,
429                     (setter)frame_set_f_exc_type, NULL},
430     {"f_exc_value", (getter)frame_get_f_exc_value,
431                     (setter)frame_set_f_exc_value, NULL},
432     {0}
433 };
434 
435 /* Stack frames are allocated and deallocated at a considerable rate.
436    In an attempt to improve the speed of function calls, we:
437 
438    1. Hold a single "zombie" frame on each code object. This retains
439    the allocated and initialised frame object from an invocation of
440    the code object. The zombie is reanimated the next time we need a
441    frame object for that code object. Doing this saves the malloc/
442    realloc required when using a free_list frame that isn't the
443    correct size. It also saves some field initialisation.
444 
445    In zombie mode, no field of PyFrameObject holds a reference, but
446    the following fields are still valid:
447 
448      * ob_type, ob_size, f_code, f_valuestack;
449 
450      * f_locals, f_trace,
451        f_exc_type, f_exc_value, f_exc_traceback are NULL;
452 
453      * f_localsplus does not require re-allocation and
454        the local variables in f_localsplus are NULL.
455 
456    2. We also maintain a separate free list of stack frames (just like
457    integers are allocated in a special way -- see intobject.c).  When
458    a stack frame is on the free list, only the following members have
459    a meaning:
460     ob_type             == &Frametype
461     f_back              next item on free list, or NULL
462     f_stacksize         size of value stack
463     ob_size             size of localsplus
464    Note that the value and block stacks are preserved -- this can save
465    another malloc() call or two (and two free() calls as well!).
466    Also note that, unlike for integers, each frame object is a
467    malloc'ed object in its own right -- it is only the actual calls to
468    malloc() that we are trying to save here, not the administration.
469    After all, while a typical program may make millions of calls, a
470    call depth of more than 20 or 30 is probably already exceptional
471    unless the program contains run-away recursion.  I hope.
472 
473    Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
474    free_list.  Else programs creating lots of cyclic trash involving
475    frames could provoke free_list into growing without bound.
476 */
477 
478 static PyFrameObject *free_list = NULL;
479 static int numfree = 0;         /* number of frames currently in free_list */
480 /* max value for numfree */
481 #define PyFrame_MAXFREELIST 200
482 
483 static void
frame_dealloc(PyFrameObject * f)484 frame_dealloc(PyFrameObject *f)
485 {
486     PyObject **p, **valuestack;
487     PyCodeObject *co;
488 
489     PyObject_GC_UnTrack(f);
490     Py_TRASHCAN_SAFE_BEGIN(f)
491     /* Kill all local variables */
492     valuestack = f->f_valuestack;
493     for (p = f->f_localsplus; p < valuestack; p++)
494         Py_CLEAR(*p);
495 
496     /* Free stack */
497     if (f->f_stacktop != NULL) {
498         for (p = valuestack; p < f->f_stacktop; p++)
499             Py_XDECREF(*p);
500     }
501 
502     Py_XDECREF(f->f_back);
503     Py_DECREF(f->f_builtins);
504     Py_DECREF(f->f_globals);
505     Py_CLEAR(f->f_locals);
506     Py_CLEAR(f->f_trace);
507     Py_CLEAR(f->f_exc_type);
508     Py_CLEAR(f->f_exc_value);
509     Py_CLEAR(f->f_exc_traceback);
510 
511     co = f->f_code;
512     if (co->co_zombieframe == NULL)
513         co->co_zombieframe = f;
514     else if (numfree < PyFrame_MAXFREELIST) {
515         ++numfree;
516         f->f_back = free_list;
517         free_list = f;
518     }
519     else
520         PyObject_GC_Del(f);
521 
522     Py_DECREF(co);
523     Py_TRASHCAN_SAFE_END(f)
524 }
525 
526 static int
frame_traverse(PyFrameObject * f,visitproc visit,void * arg)527 frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
528 {
529     PyObject **fastlocals, **p;
530     int i, slots;
531 
532     Py_VISIT(f->f_back);
533     Py_VISIT(f->f_code);
534     Py_VISIT(f->f_builtins);
535     Py_VISIT(f->f_globals);
536     Py_VISIT(f->f_locals);
537     Py_VISIT(f->f_trace);
538     Py_VISIT(f->f_exc_type);
539     Py_VISIT(f->f_exc_value);
540     Py_VISIT(f->f_exc_traceback);
541 
542     /* locals */
543     slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
544     fastlocals = f->f_localsplus;
545     for (i = slots; --i >= 0; ++fastlocals)
546         Py_VISIT(*fastlocals);
547 
548     /* stack */
549     if (f->f_stacktop != NULL) {
550         for (p = f->f_valuestack; p < f->f_stacktop; p++)
551             Py_VISIT(*p);
552     }
553     return 0;
554 }
555 
556 static void
frame_clear(PyFrameObject * f)557 frame_clear(PyFrameObject *f)
558 {
559     PyObject **fastlocals, **p, **oldtop;
560     int i, slots;
561 
562     /* Before anything else, make sure that this frame is clearly marked
563      * as being defunct!  Else, e.g., a generator reachable from this
564      * frame may also point to this frame, believe itself to still be
565      * active, and try cleaning up this frame again.
566      */
567     oldtop = f->f_stacktop;
568     f->f_stacktop = NULL;
569 
570     Py_CLEAR(f->f_exc_type);
571     Py_CLEAR(f->f_exc_value);
572     Py_CLEAR(f->f_exc_traceback);
573     Py_CLEAR(f->f_trace);
574 
575     /* locals */
576     slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
577     fastlocals = f->f_localsplus;
578     for (i = slots; --i >= 0; ++fastlocals)
579         Py_CLEAR(*fastlocals);
580 
581     /* stack */
582     if (oldtop != NULL) {
583         for (p = f->f_valuestack; p < oldtop; p++)
584             Py_CLEAR(*p);
585     }
586 }
587 
588 static PyObject *
frame_sizeof(PyFrameObject * f)589 frame_sizeof(PyFrameObject *f)
590 {
591     Py_ssize_t res, extras, ncells, nfrees;
592 
593     ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
594     nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
595     extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
596              ncells + nfrees;
597     /* subtract one as it is already included in PyFrameObject */
598     res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
599 
600     return PyInt_FromSsize_t(res);
601 }
602 
603 PyDoc_STRVAR(sizeof__doc__,
604 "F.__sizeof__() -> size of F in memory, in bytes");
605 
606 static PyMethodDef frame_methods[] = {
607     {"__sizeof__",      (PyCFunction)frame_sizeof,      METH_NOARGS,
608      sizeof__doc__},
609     {NULL,              NULL}   /* sentinel */
610 };
611 
612 PyTypeObject PyFrame_Type = {
613     PyVarObject_HEAD_INIT(&PyType_Type, 0)
614     "frame",
615     sizeof(PyFrameObject),
616     sizeof(PyObject *),
617     (destructor)frame_dealloc,                  /* tp_dealloc */
618     0,                                          /* tp_print */
619     0,                                          /* tp_getattr */
620     0,                                          /* tp_setattr */
621     0,                                          /* tp_compare */
622     0,                                          /* tp_repr */
623     0,                                          /* tp_as_number */
624     0,                                          /* tp_as_sequence */
625     0,                                          /* tp_as_mapping */
626     0,                                          /* tp_hash */
627     0,                                          /* tp_call */
628     0,                                          /* tp_str */
629     PyObject_GenericGetAttr,                    /* tp_getattro */
630     PyObject_GenericSetAttr,                    /* tp_setattro */
631     0,                                          /* tp_as_buffer */
632     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
633     0,                                          /* tp_doc */
634     (traverseproc)frame_traverse,               /* tp_traverse */
635     (inquiry)frame_clear,                       /* tp_clear */
636     0,                                          /* tp_richcompare */
637     0,                                          /* tp_weaklistoffset */
638     0,                                          /* tp_iter */
639     0,                                          /* tp_iternext */
640     frame_methods,                              /* tp_methods */
641     frame_memberlist,                           /* tp_members */
642     frame_getsetlist,                           /* tp_getset */
643     0,                                          /* tp_base */
644     0,                                          /* tp_dict */
645 };
646 
647 static PyObject *builtin_object;
648 
_PyFrame_Init()649 int _PyFrame_Init()
650 {
651     builtin_object = PyString_InternFromString("__builtins__");
652     if (builtin_object == NULL)
653         return 0;
654     return 1;
655 }
656 
657 PyFrameObject *
PyFrame_New(PyThreadState * tstate,PyCodeObject * code,PyObject * globals,PyObject * locals)658 PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
659             PyObject *locals)
660 {
661     PyFrameObject *back = tstate->frame;
662     PyFrameObject *f;
663     PyObject *builtins;
664     Py_ssize_t i;
665 
666 #ifdef Py_DEBUG
667     if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
668         (locals != NULL && !PyMapping_Check(locals))) {
669         PyErr_BadInternalCall();
670         return NULL;
671     }
672 #endif
673     if (back == NULL || back->f_globals != globals) {
674         builtins = PyDict_GetItem(globals, builtin_object);
675         if (builtins) {
676             if (PyModule_Check(builtins)) {
677                 builtins = PyModule_GetDict(builtins);
678                 assert(!builtins || PyDict_Check(builtins));
679             }
680             else if (!PyDict_Check(builtins))
681                 builtins = NULL;
682         }
683         if (builtins == NULL) {
684             /* No builtins!              Make up a minimal one
685                Give them 'None', at least. */
686             builtins = PyDict_New();
687             if (builtins == NULL ||
688                 PyDict_SetItemString(
689                     builtins, "None", Py_None) < 0)
690                 return NULL;
691         }
692         else
693             Py_INCREF(builtins);
694 
695     }
696     else {
697         /* If we share the globals, we share the builtins.
698            Save a lookup and a call. */
699         builtins = back->f_builtins;
700         assert(builtins != NULL && PyDict_Check(builtins));
701         Py_INCREF(builtins);
702     }
703     if (code->co_zombieframe != NULL) {
704         f = code->co_zombieframe;
705         code->co_zombieframe = NULL;
706         _Py_NewReference((PyObject *)f);
707         assert(f->f_code == code);
708     }
709     else {
710         Py_ssize_t extras, ncells, nfrees;
711         ncells = PyTuple_GET_SIZE(code->co_cellvars);
712         nfrees = PyTuple_GET_SIZE(code->co_freevars);
713         extras = code->co_stacksize + code->co_nlocals + ncells +
714             nfrees;
715         if (free_list == NULL) {
716             f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
717             extras);
718             if (f == NULL) {
719                 Py_DECREF(builtins);
720                 return NULL;
721             }
722         }
723         else {
724             assert(numfree > 0);
725             --numfree;
726             f = free_list;
727             free_list = free_list->f_back;
728             if (Py_SIZE(f) < extras) {
729                 f = PyObject_GC_Resize(PyFrameObject, f, extras);
730                 if (f == NULL) {
731                     Py_DECREF(builtins);
732                     return NULL;
733                 }
734             }
735             _Py_NewReference((PyObject *)f);
736         }
737 
738         f->f_code = code;
739         extras = code->co_nlocals + ncells + nfrees;
740         f->f_valuestack = f->f_localsplus + extras;
741         for (i=0; i<extras; i++)
742             f->f_localsplus[i] = NULL;
743         f->f_locals = NULL;
744         f->f_trace = NULL;
745         f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
746     }
747     f->f_stacktop = f->f_valuestack;
748     f->f_builtins = builtins;
749     Py_XINCREF(back);
750     f->f_back = back;
751     Py_INCREF(code);
752     Py_INCREF(globals);
753     f->f_globals = globals;
754     /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
755     if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
756         (CO_NEWLOCALS | CO_OPTIMIZED))
757         ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
758     else if (code->co_flags & CO_NEWLOCALS) {
759         locals = PyDict_New();
760         if (locals == NULL) {
761             Py_DECREF(f);
762             return NULL;
763         }
764         f->f_locals = locals;
765     }
766     else {
767         if (locals == NULL)
768             locals = globals;
769         Py_INCREF(locals);
770         f->f_locals = locals;
771     }
772     f->f_tstate = tstate;
773 
774     f->f_lasti = -1;
775     f->f_lineno = code->co_firstlineno;
776     f->f_iblock = 0;
777 
778     _PyObject_GC_TRACK(f);
779     return f;
780 }
781 
782 /* Block management */
783 
784 void
PyFrame_BlockSetup(PyFrameObject * f,int type,int handler,int level)785 PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
786 {
787     PyTryBlock *b;
788     if (f->f_iblock >= CO_MAXBLOCKS)
789         Py_FatalError("XXX block stack overflow");
790     b = &f->f_blockstack[f->f_iblock++];
791     b->b_type = type;
792     b->b_level = level;
793     b->b_handler = handler;
794 }
795 
796 PyTryBlock *
PyFrame_BlockPop(PyFrameObject * f)797 PyFrame_BlockPop(PyFrameObject *f)
798 {
799     PyTryBlock *b;
800     if (f->f_iblock <= 0)
801         Py_FatalError("XXX block stack underflow");
802     b = &f->f_blockstack[--f->f_iblock];
803     return b;
804 }
805 
806 /* Convert between "fast" version of locals and dictionary version.
807 
808    map and values are input arguments.  map is a tuple of strings.
809    values is an array of PyObject*.  At index i, map[i] is the name of
810    the variable with value values[i].  The function copies the first
811    nmap variable from map/values into dict.  If values[i] is NULL,
812    the variable is deleted from dict.
813 
814    If deref is true, then the values being copied are cell variables
815    and the value is extracted from the cell variable before being put
816    in dict.
817 
818    Exceptions raised while modifying the dict are silently ignored,
819    because there is no good way to report them.
820  */
821 
822 static void
map_to_dict(PyObject * map,Py_ssize_t nmap,PyObject * dict,PyObject ** values,int deref)823 map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
824             int deref)
825 {
826     Py_ssize_t j;
827     assert(PyTuple_Check(map));
828     assert(PyDict_Check(dict));
829     assert(PyTuple_Size(map) >= nmap);
830     for (j = nmap; --j >= 0; ) {
831         PyObject *key = PyTuple_GET_ITEM(map, j);
832         PyObject *value = values[j];
833         assert(PyString_Check(key));
834         if (deref) {
835             assert(PyCell_Check(value));
836             value = PyCell_GET(value);
837         }
838         if (value == NULL) {
839             if (PyObject_DelItem(dict, key) != 0)
840                 PyErr_Clear();
841         }
842         else {
843             if (PyObject_SetItem(dict, key, value) != 0)
844                 PyErr_Clear();
845         }
846     }
847 }
848 
849 /* Copy values from the "locals" dict into the fast locals.
850 
851    dict is an input argument containing string keys representing
852    variables names and arbitrary PyObject* as values.
853 
854    map and values are input arguments.  map is a tuple of strings.
855    values is an array of PyObject*.  At index i, map[i] is the name of
856    the variable with value values[i].  The function copies the first
857    nmap variable from map/values into dict.  If values[i] is NULL,
858    the variable is deleted from dict.
859 
860    If deref is true, then the values being copied are cell variables
861    and the value is extracted from the cell variable before being put
862    in dict.  If clear is true, then variables in map but not in dict
863    are set to NULL in map; if clear is false, variables missing in
864    dict are ignored.
865 
866    Exceptions raised while modifying the dict are silently ignored,
867    because there is no good way to report them.
868 */
869 
870 static void
dict_to_map(PyObject * map,Py_ssize_t nmap,PyObject * dict,PyObject ** values,int deref,int clear)871 dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
872             int deref, int clear)
873 {
874     Py_ssize_t j;
875     assert(PyTuple_Check(map));
876     assert(PyDict_Check(dict));
877     assert(PyTuple_Size(map) >= nmap);
878     for (j = nmap; --j >= 0; ) {
879         PyObject *key = PyTuple_GET_ITEM(map, j);
880         PyObject *value = PyObject_GetItem(dict, key);
881         assert(PyString_Check(key));
882         /* We only care about NULLs if clear is true. */
883         if (value == NULL) {
884             PyErr_Clear();
885             if (!clear)
886                 continue;
887         }
888         if (deref) {
889             assert(PyCell_Check(values[j]));
890             if (PyCell_GET(values[j]) != value) {
891                 if (PyCell_Set(values[j], value) < 0)
892                     PyErr_Clear();
893             }
894         } else if (values[j] != value) {
895             Py_XINCREF(value);
896             Py_XSETREF(values[j], value);
897         }
898         Py_XDECREF(value);
899     }
900 }
901 
902 void
PyFrame_FastToLocals(PyFrameObject * f)903 PyFrame_FastToLocals(PyFrameObject *f)
904 {
905     /* Merge fast locals into f->f_locals */
906     PyObject *locals, *map;
907     PyObject **fast;
908     PyObject *error_type, *error_value, *error_traceback;
909     PyCodeObject *co;
910     Py_ssize_t j;
911     int ncells, nfreevars;
912     if (f == NULL)
913         return;
914     locals = f->f_locals;
915     if (locals == NULL) {
916         locals = f->f_locals = PyDict_New();
917         if (locals == NULL) {
918             PyErr_Clear(); /* Can't report it :-( */
919             return;
920         }
921     }
922     co = f->f_code;
923     map = co->co_varnames;
924     if (!PyTuple_Check(map))
925         return;
926     PyErr_Fetch(&error_type, &error_value, &error_traceback);
927     fast = f->f_localsplus;
928     j = PyTuple_GET_SIZE(map);
929     if (j > co->co_nlocals)
930         j = co->co_nlocals;
931     if (co->co_nlocals)
932         map_to_dict(map, j, locals, fast, 0);
933     ncells = PyTuple_GET_SIZE(co->co_cellvars);
934     nfreevars = PyTuple_GET_SIZE(co->co_freevars);
935     if (ncells || nfreevars) {
936         map_to_dict(co->co_cellvars, ncells,
937                     locals, fast + co->co_nlocals, 1);
938         /* If the namespace is unoptimized, then one of the
939            following cases applies:
940            1. It does not contain free variables, because it
941               uses import * or is a top-level namespace.
942            2. It is a class namespace.
943            We don't want to accidentally copy free variables
944            into the locals dict used by the class.
945         */
946         if (co->co_flags & CO_OPTIMIZED) {
947             map_to_dict(co->co_freevars, nfreevars,
948                         locals, fast + co->co_nlocals + ncells, 1);
949         }
950     }
951     PyErr_Restore(error_type, error_value, error_traceback);
952 }
953 
954 void
PyFrame_LocalsToFast(PyFrameObject * f,int clear)955 PyFrame_LocalsToFast(PyFrameObject *f, int clear)
956 {
957     /* Merge f->f_locals into fast locals */
958     PyObject *locals, *map;
959     PyObject **fast;
960     PyObject *error_type, *error_value, *error_traceback;
961     PyCodeObject *co;
962     Py_ssize_t j;
963     int ncells, nfreevars;
964     if (f == NULL)
965         return;
966     locals = f->f_locals;
967     co = f->f_code;
968     map = co->co_varnames;
969     if (locals == NULL)
970         return;
971     if (!PyTuple_Check(map))
972         return;
973     PyErr_Fetch(&error_type, &error_value, &error_traceback);
974     fast = f->f_localsplus;
975     j = PyTuple_GET_SIZE(map);
976     if (j > co->co_nlocals)
977         j = co->co_nlocals;
978     if (co->co_nlocals)
979         dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
980     ncells = PyTuple_GET_SIZE(co->co_cellvars);
981     nfreevars = PyTuple_GET_SIZE(co->co_freevars);
982     if (ncells || nfreevars) {
983         dict_to_map(co->co_cellvars, ncells,
984                     locals, fast + co->co_nlocals, 1, clear);
985         /* Same test as in PyFrame_FastToLocals() above. */
986         if (co->co_flags & CO_OPTIMIZED) {
987             dict_to_map(co->co_freevars, nfreevars,
988                 locals, fast + co->co_nlocals + ncells, 1,
989                 clear);
990         }
991     }
992     PyErr_Restore(error_type, error_value, error_traceback);
993 }
994 
995 /* Clear out the free list */
996 int
PyFrame_ClearFreeList(void)997 PyFrame_ClearFreeList(void)
998 {
999     int freelist_size = numfree;
1000 
1001     while (free_list != NULL) {
1002         PyFrameObject *f = free_list;
1003         free_list = free_list->f_back;
1004         PyObject_GC_Del(f);
1005         --numfree;
1006     }
1007     assert(numfree == 0);
1008     return freelist_size;
1009 }
1010 
1011 void
PyFrame_Fini(void)1012 PyFrame_Fini(void)
1013 {
1014     (void)PyFrame_ClearFreeList();
1015     Py_XDECREF(builtin_object);
1016     builtin_object = NULL;
1017 }
1018