]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.10/Objects/frameobject.c
AppPkg/Applications/Python/Python-2.7.10: Initial Checkin part 3/5.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / Objects / frameobject.c
diff --git a/AppPkg/Applications/Python/Python-2.7.10/Objects/frameobject.c b/AppPkg/Applications/Python/Python-2.7.10/Objects/frameobject.c
new file mode 100644 (file)
index 0000000..2261b59
--- /dev/null
@@ -0,0 +1,984 @@
+/* Frame object implementation */\r
+\r
+#include "Python.h"\r
+\r
+#include "code.h"\r
+#include "frameobject.h"\r
+#include "opcode.h"\r
+#include "structmember.h"\r
+\r
+#undef MIN\r
+#undef MAX\r
+#define MIN(a, b) ((a) < (b) ? (a) : (b))\r
+#define MAX(a, b) ((a) > (b) ? (a) : (b))\r
+\r
+#define OFF(x) offsetof(PyFrameObject, x)\r
+\r
+static PyMemberDef frame_memberlist[] = {\r
+    {"f_back",          T_OBJECT,       OFF(f_back),    RO},\r
+    {"f_code",          T_OBJECT,       OFF(f_code),    RO},\r
+    {"f_builtins",      T_OBJECT,       OFF(f_builtins),RO},\r
+    {"f_globals",       T_OBJECT,       OFF(f_globals), RO},\r
+    {"f_lasti",         T_INT,          OFF(f_lasti),   RO},\r
+    {NULL}      /* Sentinel */\r
+};\r
+\r
+#define WARN_GET_SET(NAME) \\r
+static PyObject * frame_get_ ## NAME(PyFrameObject *f) { \\r
+    if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \\r
+        return NULL; \\r
+    if (f->NAME) { \\r
+        Py_INCREF(f->NAME); \\r
+        return f->NAME; \\r
+    } \\r
+    Py_RETURN_NONE;     \\r
+} \\r
+static int frame_set_ ## NAME(PyFrameObject *f, PyObject *new) { \\r
+    if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \\r
+        return -1; \\r
+    if (f->NAME) { \\r
+        Py_CLEAR(f->NAME); \\r
+    } \\r
+    if (new == Py_None) \\r
+        new = NULL; \\r
+    Py_XINCREF(new); \\r
+    f->NAME = new; \\r
+    return 0; \\r
+}\r
+\r
+\r
+WARN_GET_SET(f_exc_traceback)\r
+WARN_GET_SET(f_exc_type)\r
+WARN_GET_SET(f_exc_value)\r
+\r
+\r
+static PyObject *\r
+frame_getlocals(PyFrameObject *f, void *closure)\r
+{\r
+    PyFrame_FastToLocals(f);\r
+    Py_INCREF(f->f_locals);\r
+    return f->f_locals;\r
+}\r
+\r
+int\r
+PyFrame_GetLineNumber(PyFrameObject *f)\r
+{\r
+    if (f->f_trace)\r
+        return f->f_lineno;\r
+    else\r
+        return PyCode_Addr2Line(f->f_code, f->f_lasti);\r
+}\r
+\r
+static PyObject *\r
+frame_getlineno(PyFrameObject *f, void *closure)\r
+{\r
+    return PyInt_FromLong(PyFrame_GetLineNumber(f));\r
+}\r
+\r
+/* Setter for f_lineno - you can set f_lineno from within a trace function in\r
+ * order to jump to a given line of code, subject to some restrictions.  Most\r
+ * lines are OK to jump to because they don't make any assumptions about the\r
+ * state of the stack (obvious because you could remove the line and the code\r
+ * would still work without any stack errors), but there are some constructs\r
+ * that limit jumping:\r
+ *\r
+ *  o Lines with an 'except' statement on them can't be jumped to, because\r
+ *    they expect an exception to be on the top of the stack.\r
+ *  o Lines that live in a 'finally' block can't be jumped from or to, since\r
+ *    the END_FINALLY expects to clean up the stack after the 'try' block.\r
+ *  o 'try'/'for'/'while' blocks can't be jumped into because the blockstack\r
+ *    needs to be set up before their code runs, and for 'for' loops the\r
+ *    iterator needs to be on the stack.\r
+ */\r
+static int\r
+frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)\r
+{\r
+    int new_lineno = 0;                 /* The new value of f_lineno */\r
+    int new_lasti = 0;                  /* The new value of f_lasti */\r
+    int new_iblock = 0;                 /* The new value of f_iblock */\r
+    unsigned char *code = NULL;         /* The bytecode for the frame... */\r
+    Py_ssize_t code_len = 0;            /* ...and its length */\r
+    unsigned char *lnotab = NULL;       /* Iterating over co_lnotab */\r
+    Py_ssize_t lnotab_len = 0;          /* (ditto) */\r
+    int offset = 0;                     /* (ditto) */\r
+    int line = 0;                       /* (ditto) */\r
+    int addr = 0;                       /* (ditto) */\r
+    int min_addr = 0;                   /* Scanning the SETUPs and POPs */\r
+    int max_addr = 0;                   /* (ditto) */\r
+    int delta_iblock = 0;               /* (ditto) */\r
+    int min_delta_iblock = 0;           /* (ditto) */\r
+    int min_iblock = 0;                 /* (ditto) */\r
+    int f_lasti_setup_addr = 0;         /* Policing no-jump-into-finally */\r
+    int new_lasti_setup_addr = 0;       /* (ditto) */\r
+    int blockstack[CO_MAXBLOCKS];       /* Walking the 'finally' blocks */\r
+    int in_finally[CO_MAXBLOCKS];       /* (ditto) */\r
+    int blockstack_top = 0;             /* (ditto) */\r
+    unsigned char setup_op = 0;         /* (ditto) */\r
+\r
+    /* f_lineno must be an integer. */\r
+    if (!PyInt_Check(p_new_lineno)) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "lineno must be an integer");\r
+        return -1;\r
+    }\r
+\r
+    /* You can only do this from within a trace function, not via\r
+     * _getframe or similar hackery. */\r
+    if (!f->f_trace)\r
+    {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "f_lineno can only be set by a"\r
+                     " line trace function");\r
+        return -1;\r
+    }\r
+\r
+    /* Fail if the line comes before the start of the code block. */\r
+    new_lineno = (int) PyInt_AsLong(p_new_lineno);\r
+    if (new_lineno < f->f_code->co_firstlineno) {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "line %d comes before the current code block",\r
+                     new_lineno);\r
+        return -1;\r
+    }\r
+    else if (new_lineno == f->f_code->co_firstlineno) {\r
+        new_lasti = 0;\r
+        new_lineno = f->f_code->co_firstlineno;\r
+    }\r
+    else {\r
+        /* Find the bytecode offset for the start of the given\r
+         * line, or the first code-owning line after it. */\r
+        char *tmp;\r
+        PyString_AsStringAndSize(f->f_code->co_lnotab,\r
+                                 &tmp, &lnotab_len);\r
+        lnotab = (unsigned char *) tmp;\r
+        addr = 0;\r
+        line = f->f_code->co_firstlineno;\r
+        new_lasti = -1;\r
+        for (offset = 0; offset < lnotab_len; offset += 2) {\r
+            addr += lnotab[offset];\r
+            line += lnotab[offset+1];\r
+            if (line >= new_lineno) {\r
+                new_lasti = addr;\r
+                new_lineno = line;\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    /* If we didn't reach the requested line, return an error. */\r
+    if (new_lasti == -1) {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "line %d comes after the current code block",\r
+                     new_lineno);\r
+        return -1;\r
+    }\r
+\r
+    /* We're now ready to look at the bytecode. */\r
+    PyString_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);\r
+    min_addr = MIN(new_lasti, f->f_lasti);\r
+    max_addr = MAX(new_lasti, f->f_lasti);\r
+\r
+    /* You can't jump onto a line with an 'except' statement on it -\r
+     * they expect to have an exception on the top of the stack, which\r
+     * won't be true if you jump to them.  They always start with code\r
+     * that either pops the exception using POP_TOP (plain 'except:'\r
+     * lines do this) or duplicates the exception on the stack using\r
+     * DUP_TOP (if there's an exception type specified).  See compile.c,\r
+     * 'com_try_except' for the full details.  There aren't any other\r
+     * cases (AFAIK) where a line's code can start with DUP_TOP or\r
+     * POP_TOP, but if any ever appear, they'll be subject to the same\r
+     * restriction (but with a different error message). */\r
+    if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+            "can't jump to 'except' line as there's no exception");\r
+        return -1;\r
+    }\r
+\r
+    /* You can't jump into or out of a 'finally' block because the 'try'\r
+     * block leaves something on the stack for the END_FINALLY to clean\r
+     * up.      So we walk the bytecode, maintaining a simulated blockstack.\r
+     * When we reach the old or new address and it's in a 'finally' block\r
+     * we note the address of the corresponding SETUP_FINALLY.  The jump\r
+     * is only legal if neither address is in a 'finally' block or\r
+     * they're both in the same one.  'blockstack' is a stack of the\r
+     * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks\r
+     * whether we're in a 'finally' block at each blockstack level. */\r
+    f_lasti_setup_addr = -1;\r
+    new_lasti_setup_addr = -1;\r
+    memset(blockstack, '\0', sizeof(blockstack));\r
+    memset(in_finally, '\0', sizeof(in_finally));\r
+    blockstack_top = 0;\r
+    for (addr = 0; addr < code_len; addr++) {\r
+        unsigned char op = code[addr];\r
+        switch (op) {\r
+        case SETUP_LOOP:\r
+        case SETUP_EXCEPT:\r
+        case SETUP_FINALLY:\r
+        case SETUP_WITH:\r
+            blockstack[blockstack_top++] = addr;\r
+            in_finally[blockstack_top-1] = 0;\r
+            break;\r
+\r
+        case POP_BLOCK:\r
+            assert(blockstack_top > 0);\r
+            setup_op = code[blockstack[blockstack_top-1]];\r
+            if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {\r
+                in_finally[blockstack_top-1] = 1;\r
+            }\r
+            else {\r
+                blockstack_top--;\r
+            }\r
+            break;\r
+\r
+        case END_FINALLY:\r
+            /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist\r
+             * in the bytecode but don't correspond to an actual\r
+             * 'finally' block.  (If blockstack_top is 0, we must\r
+             * be seeing such an END_FINALLY.) */\r
+            if (blockstack_top > 0) {\r
+                setup_op = code[blockstack[blockstack_top-1]];\r
+                if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH) {\r
+                    blockstack_top--;\r
+                }\r
+            }\r
+            break;\r
+        }\r
+\r
+        /* For the addresses we're interested in, see whether they're\r
+         * within a 'finally' block and if so, remember the address\r
+         * of the SETUP_FINALLY. */\r
+        if (addr == new_lasti || addr == f->f_lasti) {\r
+            int i = 0;\r
+            int setup_addr = -1;\r
+            for (i = blockstack_top-1; i >= 0; i--) {\r
+                if (in_finally[i]) {\r
+                    setup_addr = blockstack[i];\r
+                    break;\r
+                }\r
+            }\r
+\r
+            if (setup_addr != -1) {\r
+                if (addr == new_lasti) {\r
+                    new_lasti_setup_addr = setup_addr;\r
+                }\r
+\r
+                if (addr == f->f_lasti) {\r
+                    f_lasti_setup_addr = setup_addr;\r
+                }\r
+            }\r
+        }\r
+\r
+        if (op >= HAVE_ARGUMENT) {\r
+            addr += 2;\r
+        }\r
+    }\r
+\r
+    /* Verify that the blockstack tracking code didn't get lost. */\r
+    assert(blockstack_top == 0);\r
+\r
+    /* After all that, are we jumping into / out of a 'finally' block? */\r
+    if (new_lasti_setup_addr != f_lasti_setup_addr) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                    "can't jump into or out of a 'finally' block");\r
+        return -1;\r
+    }\r
+\r
+\r
+    /* Police block-jumping (you can't jump into the middle of a block)\r
+     * and ensure that the blockstack finishes up in a sensible state (by\r
+     * popping any blocks we're jumping out of).  We look at all the\r
+     * blockstack operations between the current position and the new\r
+     * one, and keep track of how many blocks we drop out of on the way.\r
+     * By also keeping track of the lowest blockstack position we see, we\r
+     * can tell whether the jump goes into any blocks without coming out\r
+     * again - in that case we raise an exception below. */\r
+    delta_iblock = 0;\r
+    for (addr = min_addr; addr < max_addr; addr++) {\r
+        unsigned char op = code[addr];\r
+        switch (op) {\r
+        case SETUP_LOOP:\r
+        case SETUP_EXCEPT:\r
+        case SETUP_FINALLY:\r
+        case SETUP_WITH:\r
+            delta_iblock++;\r
+            break;\r
+\r
+        case POP_BLOCK:\r
+            delta_iblock--;\r
+            break;\r
+        }\r
+\r
+        min_delta_iblock = MIN(min_delta_iblock, delta_iblock);\r
+\r
+        if (op >= HAVE_ARGUMENT) {\r
+            addr += 2;\r
+        }\r
+    }\r
+\r
+    /* Derive the absolute iblock values from the deltas. */\r
+    min_iblock = f->f_iblock + min_delta_iblock;\r
+    if (new_lasti > f->f_lasti) {\r
+        /* Forwards jump. */\r
+        new_iblock = f->f_iblock + delta_iblock;\r
+    }\r
+    else {\r
+        /* Backwards jump. */\r
+        new_iblock = f->f_iblock - delta_iblock;\r
+    }\r
+\r
+    /* Are we jumping into a block? */\r
+    if (new_iblock > min_iblock) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "can't jump into the middle of a block");\r
+        return -1;\r
+    }\r
+\r
+    /* Pop any blocks that we're jumping out of. */\r
+    while (f->f_iblock > new_iblock) {\r
+        PyTryBlock *b = &f->f_blockstack[--f->f_iblock];\r
+        while ((f->f_stacktop - f->f_valuestack) > b->b_level) {\r
+            PyObject *v = (*--f->f_stacktop);\r
+            Py_DECREF(v);\r
+        }\r
+    }\r
+\r
+    /* Finally set the new f_lineno and f_lasti and return OK. */\r
+    f->f_lineno = new_lineno;\r
+    f->f_lasti = new_lasti;\r
+    return 0;\r
+}\r
+\r
+static PyObject *\r
+frame_gettrace(PyFrameObject *f, void *closure)\r
+{\r
+    PyObject* trace = f->f_trace;\r
+\r
+    if (trace == NULL)\r
+        trace = Py_None;\r
+\r
+    Py_INCREF(trace);\r
+\r
+    return trace;\r
+}\r
+\r
+static int\r
+frame_settrace(PyFrameObject *f, PyObject* v, void *closure)\r
+{\r
+    PyObject* old_value;\r
+\r
+    /* We rely on f_lineno being accurate when f_trace is set. */\r
+    f->f_lineno = PyFrame_GetLineNumber(f);\r
+\r
+    old_value = f->f_trace;\r
+    Py_XINCREF(v);\r
+    f->f_trace = v;\r
+    Py_XDECREF(old_value);\r
+\r
+    return 0;\r
+}\r
+\r
+static PyObject *\r
+frame_getrestricted(PyFrameObject *f, void *closure)\r
+{\r
+    return PyBool_FromLong(PyFrame_IsRestricted(f));\r
+}\r
+\r
+static PyGetSetDef frame_getsetlist[] = {\r
+    {"f_locals",        (getter)frame_getlocals, NULL, NULL},\r
+    {"f_lineno",        (getter)frame_getlineno,\r
+                    (setter)frame_setlineno, NULL},\r
+    {"f_trace",         (getter)frame_gettrace, (setter)frame_settrace, NULL},\r
+    {"f_restricted",(getter)frame_getrestricted,NULL, NULL},\r
+    {"f_exc_traceback", (getter)frame_get_f_exc_traceback,\r
+                    (setter)frame_set_f_exc_traceback, NULL},\r
+    {"f_exc_type",  (getter)frame_get_f_exc_type,\r
+                    (setter)frame_set_f_exc_type, NULL},\r
+    {"f_exc_value", (getter)frame_get_f_exc_value,\r
+                    (setter)frame_set_f_exc_value, NULL},\r
+    {0}\r
+};\r
+\r
+/* Stack frames are allocated and deallocated at a considerable rate.\r
+   In an attempt to improve the speed of function calls, we:\r
+\r
+   1. Hold a single "zombie" frame on each code object. This retains\r
+   the allocated and initialised frame object from an invocation of\r
+   the code object. The zombie is reanimated the next time we need a\r
+   frame object for that code object. Doing this saves the malloc/\r
+   realloc required when using a free_list frame that isn't the\r
+   correct size. It also saves some field initialisation.\r
+\r
+   In zombie mode, no field of PyFrameObject holds a reference, but\r
+   the following fields are still valid:\r
+\r
+     * ob_type, ob_size, f_code, f_valuestack;\r
+\r
+     * f_locals, f_trace,\r
+       f_exc_type, f_exc_value, f_exc_traceback are NULL;\r
+\r
+     * f_localsplus does not require re-allocation and\r
+       the local variables in f_localsplus are NULL.\r
+\r
+   2. We also maintain a separate free list of stack frames (just like\r
+   integers are allocated in a special way -- see intobject.c).  When\r
+   a stack frame is on the free list, only the following members have\r
+   a meaning:\r
+    ob_type             == &Frametype\r
+    f_back              next item on free list, or NULL\r
+    f_stacksize         size of value stack\r
+    ob_size             size of localsplus\r
+   Note that the value and block stacks are preserved -- this can save\r
+   another malloc() call or two (and two free() calls as well!).\r
+   Also note that, unlike for integers, each frame object is a\r
+   malloc'ed object in its own right -- it is only the actual calls to\r
+   malloc() that we are trying to save here, not the administration.\r
+   After all, while a typical program may make millions of calls, a\r
+   call depth of more than 20 or 30 is probably already exceptional\r
+   unless the program contains run-away recursion.  I hope.\r
+\r
+   Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on\r
+   free_list.  Else programs creating lots of cyclic trash involving\r
+   frames could provoke free_list into growing without bound.\r
+*/\r
+\r
+static PyFrameObject *free_list = NULL;\r
+static int numfree = 0;         /* number of frames currently in free_list */\r
+/* max value for numfree */\r
+#define PyFrame_MAXFREELIST 200\r
+\r
+static void\r
+frame_dealloc(PyFrameObject *f)\r
+{\r
+    PyObject **p, **valuestack;\r
+    PyCodeObject *co;\r
+\r
+    PyObject_GC_UnTrack(f);\r
+    Py_TRASHCAN_SAFE_BEGIN(f)\r
+    /* Kill all local variables */\r
+    valuestack = f->f_valuestack;\r
+    for (p = f->f_localsplus; p < valuestack; p++)\r
+        Py_CLEAR(*p);\r
+\r
+    /* Free stack */\r
+    if (f->f_stacktop != NULL) {\r
+        for (p = valuestack; p < f->f_stacktop; p++)\r
+            Py_XDECREF(*p);\r
+    }\r
+\r
+    Py_XDECREF(f->f_back);\r
+    Py_DECREF(f->f_builtins);\r
+    Py_DECREF(f->f_globals);\r
+    Py_CLEAR(f->f_locals);\r
+    Py_CLEAR(f->f_trace);\r
+    Py_CLEAR(f->f_exc_type);\r
+    Py_CLEAR(f->f_exc_value);\r
+    Py_CLEAR(f->f_exc_traceback);\r
+\r
+    co = f->f_code;\r
+    if (co->co_zombieframe == NULL)\r
+        co->co_zombieframe = f;\r
+    else if (numfree < PyFrame_MAXFREELIST) {\r
+        ++numfree;\r
+        f->f_back = free_list;\r
+        free_list = f;\r
+    }\r
+    else\r
+        PyObject_GC_Del(f);\r
+\r
+    Py_DECREF(co);\r
+    Py_TRASHCAN_SAFE_END(f)\r
+}\r
+\r
+static int\r
+frame_traverse(PyFrameObject *f, visitproc visit, void *arg)\r
+{\r
+    PyObject **fastlocals, **p;\r
+    int i, slots;\r
+\r
+    Py_VISIT(f->f_back);\r
+    Py_VISIT(f->f_code);\r
+    Py_VISIT(f->f_builtins);\r
+    Py_VISIT(f->f_globals);\r
+    Py_VISIT(f->f_locals);\r
+    Py_VISIT(f->f_trace);\r
+    Py_VISIT(f->f_exc_type);\r
+    Py_VISIT(f->f_exc_value);\r
+    Py_VISIT(f->f_exc_traceback);\r
+\r
+    /* locals */\r
+    slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);\r
+    fastlocals = f->f_localsplus;\r
+    for (i = slots; --i >= 0; ++fastlocals)\r
+        Py_VISIT(*fastlocals);\r
+\r
+    /* stack */\r
+    if (f->f_stacktop != NULL) {\r
+        for (p = f->f_valuestack; p < f->f_stacktop; p++)\r
+            Py_VISIT(*p);\r
+    }\r
+    return 0;\r
+}\r
+\r
+static void\r
+frame_clear(PyFrameObject *f)\r
+{\r
+    PyObject **fastlocals, **p, **oldtop;\r
+    int i, slots;\r
+\r
+    /* Before anything else, make sure that this frame is clearly marked\r
+     * as being defunct!  Else, e.g., a generator reachable from this\r
+     * frame may also point to this frame, believe itself to still be\r
+     * active, and try cleaning up this frame again.\r
+     */\r
+    oldtop = f->f_stacktop;\r
+    f->f_stacktop = NULL;\r
+\r
+    Py_CLEAR(f->f_exc_type);\r
+    Py_CLEAR(f->f_exc_value);\r
+    Py_CLEAR(f->f_exc_traceback);\r
+    Py_CLEAR(f->f_trace);\r
+\r
+    /* locals */\r
+    slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);\r
+    fastlocals = f->f_localsplus;\r
+    for (i = slots; --i >= 0; ++fastlocals)\r
+        Py_CLEAR(*fastlocals);\r
+\r
+    /* stack */\r
+    if (oldtop != NULL) {\r
+        for (p = f->f_valuestack; p < oldtop; p++)\r
+            Py_CLEAR(*p);\r
+    }\r
+}\r
+\r
+static PyObject *\r
+frame_sizeof(PyFrameObject *f)\r
+{\r
+    Py_ssize_t res, extras, ncells, nfrees;\r
+\r
+    ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);\r
+    nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);\r
+    extras = f->f_code->co_stacksize + f->f_code->co_nlocals +\r
+             ncells + nfrees;\r
+    /* subtract one as it is already included in PyFrameObject */\r
+    res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);\r
+\r
+    return PyInt_FromSsize_t(res);\r
+}\r
+\r
+PyDoc_STRVAR(sizeof__doc__,\r
+"F.__sizeof__() -> size of F in memory, in bytes");\r
+\r
+static PyMethodDef frame_methods[] = {\r
+    {"__sizeof__",      (PyCFunction)frame_sizeof,      METH_NOARGS,\r
+     sizeof__doc__},\r
+    {NULL,              NULL}   /* sentinel */\r
+};\r
+\r
+PyTypeObject PyFrame_Type = {\r
+    PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
+    "frame",\r
+    sizeof(PyFrameObject),\r
+    sizeof(PyObject *),\r
+    (destructor)frame_dealloc,                  /* tp_dealloc */\r
+    0,                                          /* tp_print */\r
+    0,                                          /* tp_getattr */\r
+    0,                                          /* tp_setattr */\r
+    0,                                          /* tp_compare */\r
+    0,                                          /* tp_repr */\r
+    0,                                          /* tp_as_number */\r
+    0,                                          /* tp_as_sequence */\r
+    0,                                          /* tp_as_mapping */\r
+    0,                                          /* tp_hash */\r
+    0,                                          /* tp_call */\r
+    0,                                          /* tp_str */\r
+    PyObject_GenericGetAttr,                    /* tp_getattro */\r
+    PyObject_GenericSetAttr,                    /* tp_setattro */\r
+    0,                                          /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */\r
+    0,                                          /* tp_doc */\r
+    (traverseproc)frame_traverse,               /* tp_traverse */\r
+    (inquiry)frame_clear,                       /* tp_clear */\r
+    0,                                          /* tp_richcompare */\r
+    0,                                          /* tp_weaklistoffset */\r
+    0,                                          /* tp_iter */\r
+    0,                                          /* tp_iternext */\r
+    frame_methods,                              /* tp_methods */\r
+    frame_memberlist,                           /* tp_members */\r
+    frame_getsetlist,                           /* tp_getset */\r
+    0,                                          /* tp_base */\r
+    0,                                          /* tp_dict */\r
+};\r
+\r
+static PyObject *builtin_object;\r
+\r
+int _PyFrame_Init()\r
+{\r
+    builtin_object = PyString_InternFromString("__builtins__");\r
+    if (builtin_object == NULL)\r
+        return 0;\r
+    return 1;\r
+}\r
+\r
+PyFrameObject *\r
+PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,\r
+            PyObject *locals)\r
+{\r
+    PyFrameObject *back = tstate->frame;\r
+    PyFrameObject *f;\r
+    PyObject *builtins;\r
+    Py_ssize_t i;\r
+\r
+#ifdef Py_DEBUG\r
+    if (code == NULL || globals == NULL || !PyDict_Check(globals) ||\r
+        (locals != NULL && !PyMapping_Check(locals))) {\r
+        PyErr_BadInternalCall();\r
+        return NULL;\r
+    }\r
+#endif\r
+    if (back == NULL || back->f_globals != globals) {\r
+        builtins = PyDict_GetItem(globals, builtin_object);\r
+        if (builtins) {\r
+            if (PyModule_Check(builtins)) {\r
+                builtins = PyModule_GetDict(builtins);\r
+                assert(!builtins || PyDict_Check(builtins));\r
+            }\r
+            else if (!PyDict_Check(builtins))\r
+                builtins = NULL;\r
+        }\r
+        if (builtins == NULL) {\r
+            /* No builtins!              Make up a minimal one\r
+               Give them 'None', at least. */\r
+            builtins = PyDict_New();\r
+            if (builtins == NULL ||\r
+                PyDict_SetItemString(\r
+                    builtins, "None", Py_None) < 0)\r
+                return NULL;\r
+        }\r
+        else\r
+            Py_INCREF(builtins);\r
+\r
+    }\r
+    else {\r
+        /* If we share the globals, we share the builtins.\r
+           Save a lookup and a call. */\r
+        builtins = back->f_builtins;\r
+        assert(builtins != NULL && PyDict_Check(builtins));\r
+        Py_INCREF(builtins);\r
+    }\r
+    if (code->co_zombieframe != NULL) {\r
+        f = code->co_zombieframe;\r
+        code->co_zombieframe = NULL;\r
+        _Py_NewReference((PyObject *)f);\r
+        assert(f->f_code == code);\r
+    }\r
+    else {\r
+        Py_ssize_t extras, ncells, nfrees;\r
+        ncells = PyTuple_GET_SIZE(code->co_cellvars);\r
+        nfrees = PyTuple_GET_SIZE(code->co_freevars);\r
+        extras = code->co_stacksize + code->co_nlocals + ncells +\r
+            nfrees;\r
+        if (free_list == NULL) {\r
+            f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,\r
+            extras);\r
+            if (f == NULL) {\r
+                Py_DECREF(builtins);\r
+                return NULL;\r
+            }\r
+        }\r
+        else {\r
+            assert(numfree > 0);\r
+            --numfree;\r
+            f = free_list;\r
+            free_list = free_list->f_back;\r
+            if (Py_SIZE(f) < extras) {\r
+                f = PyObject_GC_Resize(PyFrameObject, f, extras);\r
+                if (f == NULL) {\r
+                    Py_DECREF(builtins);\r
+                    return NULL;\r
+                }\r
+            }\r
+            _Py_NewReference((PyObject *)f);\r
+        }\r
+\r
+        f->f_code = code;\r
+        extras = code->co_nlocals + ncells + nfrees;\r
+        f->f_valuestack = f->f_localsplus + extras;\r
+        for (i=0; i<extras; i++)\r
+            f->f_localsplus[i] = NULL;\r
+        f->f_locals = NULL;\r
+        f->f_trace = NULL;\r
+        f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;\r
+    }\r
+    f->f_stacktop = f->f_valuestack;\r
+    f->f_builtins = builtins;\r
+    Py_XINCREF(back);\r
+    f->f_back = back;\r
+    Py_INCREF(code);\r
+    Py_INCREF(globals);\r
+    f->f_globals = globals;\r
+    /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */\r
+    if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==\r
+        (CO_NEWLOCALS | CO_OPTIMIZED))\r
+        ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */\r
+    else if (code->co_flags & CO_NEWLOCALS) {\r
+        locals = PyDict_New();\r
+        if (locals == NULL) {\r
+            Py_DECREF(f);\r
+            return NULL;\r
+        }\r
+        f->f_locals = locals;\r
+    }\r
+    else {\r
+        if (locals == NULL)\r
+            locals = globals;\r
+        Py_INCREF(locals);\r
+        f->f_locals = locals;\r
+    }\r
+    f->f_tstate = tstate;\r
+\r
+    f->f_lasti = -1;\r
+    f->f_lineno = code->co_firstlineno;\r
+    f->f_iblock = 0;\r
+\r
+    _PyObject_GC_TRACK(f);\r
+    return f;\r
+}\r
+\r
+/* Block management */\r
+\r
+void\r
+PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)\r
+{\r
+    PyTryBlock *b;\r
+    if (f->f_iblock >= CO_MAXBLOCKS)\r
+        Py_FatalError("XXX block stack overflow");\r
+    b = &f->f_blockstack[f->f_iblock++];\r
+    b->b_type = type;\r
+    b->b_level = level;\r
+    b->b_handler = handler;\r
+}\r
+\r
+PyTryBlock *\r
+PyFrame_BlockPop(PyFrameObject *f)\r
+{\r
+    PyTryBlock *b;\r
+    if (f->f_iblock <= 0)\r
+        Py_FatalError("XXX block stack underflow");\r
+    b = &f->f_blockstack[--f->f_iblock];\r
+    return b;\r
+}\r
+\r
+/* Convert between "fast" version of locals and dictionary version.\r
+\r
+   map and values are input arguments.  map is a tuple of strings.\r
+   values is an array of PyObject*.  At index i, map[i] is the name of\r
+   the variable with value values[i].  The function copies the first\r
+   nmap variable from map/values into dict.  If values[i] is NULL,\r
+   the variable is deleted from dict.\r
+\r
+   If deref is true, then the values being copied are cell variables\r
+   and the value is extracted from the cell variable before being put\r
+   in dict.\r
+\r
+   Exceptions raised while modifying the dict are silently ignored,\r
+   because there is no good way to report them.\r
+ */\r
+\r
+static void\r
+map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,\r
+            int deref)\r
+{\r
+    Py_ssize_t j;\r
+    assert(PyTuple_Check(map));\r
+    assert(PyDict_Check(dict));\r
+    assert(PyTuple_Size(map) >= nmap);\r
+    for (j = nmap; --j >= 0; ) {\r
+        PyObject *key = PyTuple_GET_ITEM(map, j);\r
+        PyObject *value = values[j];\r
+        assert(PyString_Check(key));\r
+        if (deref) {\r
+            assert(PyCell_Check(value));\r
+            value = PyCell_GET(value);\r
+        }\r
+        if (value == NULL) {\r
+            if (PyObject_DelItem(dict, key) != 0)\r
+                PyErr_Clear();\r
+        }\r
+        else {\r
+            if (PyObject_SetItem(dict, key, value) != 0)\r
+                PyErr_Clear();\r
+        }\r
+    }\r
+}\r
+\r
+/* Copy values from the "locals" dict into the fast locals.\r
+\r
+   dict is an input argument containing string keys representing\r
+   variables names and arbitrary PyObject* as values.\r
+\r
+   map and values are input arguments.  map is a tuple of strings.\r
+   values is an array of PyObject*.  At index i, map[i] is the name of\r
+   the variable with value values[i].  The function copies the first\r
+   nmap variable from map/values into dict.  If values[i] is NULL,\r
+   the variable is deleted from dict.\r
+\r
+   If deref is true, then the values being copied are cell variables\r
+   and the value is extracted from the cell variable before being put\r
+   in dict.  If clear is true, then variables in map but not in dict\r
+   are set to NULL in map; if clear is false, variables missing in\r
+   dict are ignored.\r
+\r
+   Exceptions raised while modifying the dict are silently ignored,\r
+   because there is no good way to report them.\r
+*/\r
+\r
+static void\r
+dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,\r
+            int deref, int clear)\r
+{\r
+    Py_ssize_t j;\r
+    assert(PyTuple_Check(map));\r
+    assert(PyDict_Check(dict));\r
+    assert(PyTuple_Size(map) >= nmap);\r
+    for (j = nmap; --j >= 0; ) {\r
+        PyObject *key = PyTuple_GET_ITEM(map, j);\r
+        PyObject *value = PyObject_GetItem(dict, key);\r
+        assert(PyString_Check(key));\r
+        /* We only care about NULLs if clear is true. */\r
+        if (value == NULL) {\r
+            PyErr_Clear();\r
+            if (!clear)\r
+                continue;\r
+        }\r
+        if (deref) {\r
+            assert(PyCell_Check(values[j]));\r
+            if (PyCell_GET(values[j]) != value) {\r
+                if (PyCell_Set(values[j], value) < 0)\r
+                    PyErr_Clear();\r
+            }\r
+        } else if (values[j] != value) {\r
+            Py_XINCREF(value);\r
+            Py_XDECREF(values[j]);\r
+            values[j] = value;\r
+        }\r
+        Py_XDECREF(value);\r
+    }\r
+}\r
+\r
+void\r
+PyFrame_FastToLocals(PyFrameObject *f)\r
+{\r
+    /* Merge fast locals into f->f_locals */\r
+    PyObject *locals, *map;\r
+    PyObject **fast;\r
+    PyObject *error_type, *error_value, *error_traceback;\r
+    PyCodeObject *co;\r
+    Py_ssize_t j;\r
+    int ncells, nfreevars;\r
+    if (f == NULL)\r
+        return;\r
+    locals = f->f_locals;\r
+    if (locals == NULL) {\r
+        locals = f->f_locals = PyDict_New();\r
+        if (locals == NULL) {\r
+            PyErr_Clear(); /* Can't report it :-( */\r
+            return;\r
+        }\r
+    }\r
+    co = f->f_code;\r
+    map = co->co_varnames;\r
+    if (!PyTuple_Check(map))\r
+        return;\r
+    PyErr_Fetch(&error_type, &error_value, &error_traceback);\r
+    fast = f->f_localsplus;\r
+    j = PyTuple_GET_SIZE(map);\r
+    if (j > co->co_nlocals)\r
+        j = co->co_nlocals;\r
+    if (co->co_nlocals)\r
+        map_to_dict(map, j, locals, fast, 0);\r
+    ncells = PyTuple_GET_SIZE(co->co_cellvars);\r
+    nfreevars = PyTuple_GET_SIZE(co->co_freevars);\r
+    if (ncells || nfreevars) {\r
+        map_to_dict(co->co_cellvars, ncells,\r
+                    locals, fast + co->co_nlocals, 1);\r
+        /* If the namespace is unoptimized, then one of the\r
+           following cases applies:\r
+           1. It does not contain free variables, because it\r
+              uses import * or is a top-level namespace.\r
+           2. It is a class namespace.\r
+           We don't want to accidentally copy free variables\r
+           into the locals dict used by the class.\r
+        */\r
+        if (co->co_flags & CO_OPTIMIZED) {\r
+            map_to_dict(co->co_freevars, nfreevars,\r
+                        locals, fast + co->co_nlocals + ncells, 1);\r
+        }\r
+    }\r
+    PyErr_Restore(error_type, error_value, error_traceback);\r
+}\r
+\r
+void\r
+PyFrame_LocalsToFast(PyFrameObject *f, int clear)\r
+{\r
+    /* Merge f->f_locals into fast locals */\r
+    PyObject *locals, *map;\r
+    PyObject **fast;\r
+    PyObject *error_type, *error_value, *error_traceback;\r
+    PyCodeObject *co;\r
+    Py_ssize_t j;\r
+    int ncells, nfreevars;\r
+    if (f == NULL)\r
+        return;\r
+    locals = f->f_locals;\r
+    co = f->f_code;\r
+    map = co->co_varnames;\r
+    if (locals == NULL)\r
+        return;\r
+    if (!PyTuple_Check(map))\r
+        return;\r
+    PyErr_Fetch(&error_type, &error_value, &error_traceback);\r
+    fast = f->f_localsplus;\r
+    j = PyTuple_GET_SIZE(map);\r
+    if (j > co->co_nlocals)\r
+        j = co->co_nlocals;\r
+    if (co->co_nlocals)\r
+        dict_to_map(co->co_varnames, j, locals, fast, 0, clear);\r
+    ncells = PyTuple_GET_SIZE(co->co_cellvars);\r
+    nfreevars = PyTuple_GET_SIZE(co->co_freevars);\r
+    if (ncells || nfreevars) {\r
+        dict_to_map(co->co_cellvars, ncells,\r
+                    locals, fast + co->co_nlocals, 1, clear);\r
+        /* Same test as in PyFrame_FastToLocals() above. */\r
+        if (co->co_flags & CO_OPTIMIZED) {\r
+            dict_to_map(co->co_freevars, nfreevars,\r
+                locals, fast + co->co_nlocals + ncells, 1,\r
+                clear);\r
+        }\r
+    }\r
+    PyErr_Restore(error_type, error_value, error_traceback);\r
+}\r
+\r
+/* Clear out the free list */\r
+int\r
+PyFrame_ClearFreeList(void)\r
+{\r
+    int freelist_size = numfree;\r
+\r
+    while (free_list != NULL) {\r
+        PyFrameObject *f = free_list;\r
+        free_list = free_list->f_back;\r
+        PyObject_GC_Del(f);\r
+        --numfree;\r
+    }\r
+    assert(numfree == 0);\r
+    return freelist_size;\r
+}\r
+\r
+void\r
+PyFrame_Fini(void)\r
+{\r
+    (void)PyFrame_ClearFreeList();\r
+    Py_XDECREF(builtin_object);\r
+    builtin_object = NULL;\r
+}\r