frameobject.c revision 64949cb753f206c0ca1d83f55d07afd3c179b81a
1
2/* Frame object implementation */
3
4#include "Python.h"
5
6#include "compile.h"
7#include "frameobject.h"
8#include "opcode.h"
9#include "structmember.h"
10
11#define OFF(x) offsetof(PyFrameObject, x)
12
13static struct memberlist frame_memberlist[] = {
14	{"f_back",	T_OBJECT,	OFF(f_back),	RO},
15	{"f_code",	T_OBJECT,	OFF(f_code),	RO},
16	{"f_builtins",	T_OBJECT,	OFF(f_builtins),RO},
17	{"f_globals",	T_OBJECT,	OFF(f_globals),	RO},
18	{"f_locals",	T_OBJECT,	OFF(f_locals),	RO},
19	{"f_lasti",	T_INT,		OFF(f_lasti),	RO},
20	{"f_lineno",	T_INT,		OFF(f_lineno),	RO},
21	{"f_restricted",T_INT,		OFF(f_restricted),RO},
22	{"f_trace",	T_OBJECT,	OFF(f_trace)},
23	{"f_exc_type",	T_OBJECT,	OFF(f_exc_type)},
24	{"f_exc_value",	T_OBJECT,	OFF(f_exc_value)},
25	{"f_exc_traceback", T_OBJECT,	OFF(f_exc_traceback)},
26	{NULL}	/* Sentinel */
27};
28
29static PyObject *
30frame_getattr(PyFrameObject *f, char *name)
31{
32	if (strcmp(name, "f_locals") == 0)
33		PyFrame_FastToLocals(f);
34	return PyMember_Get((char *)f, frame_memberlist, name);
35}
36
37static int
38frame_setattr(PyFrameObject *f, char *name, PyObject *value)
39{
40	return PyMember_Set((char *)f, frame_memberlist, name, value);
41}
42
43/* Stack frames are allocated and deallocated at a considerable rate.
44   In an attempt to improve the speed of function calls, we maintain a
45   separate free list of stack frames (just like integers are
46   allocated in a special way -- see intobject.c).  When a stack frame
47   is on the free list, only the following members have a meaning:
48	ob_type		== &Frametype
49	f_back		next item on free list, or NULL
50	f_nlocals	number of locals
51	f_stacksize	size of value stack
52   Note that the value and block stacks are preserved -- this can save
53   another malloc() call or two (and two free() calls as well!).
54   Also note that, unlike for integers, each frame object is a
55   malloc'ed object in its own right -- it is only the actual calls to
56   malloc() that we are trying to save here, not the administration.
57   After all, while a typical program may make millions of calls, a
58   call depth of more than 20 or 30 is probably already exceptional
59   unless the program contains run-away recursion.  I hope.
60*/
61
62static PyFrameObject *free_list = NULL;
63
64static void
65frame_dealloc(PyFrameObject *f)
66{
67	int i;
68	PyObject **fastlocals;
69
70	Py_TRASHCAN_SAFE_BEGIN(f)
71	/* Kill all local variables */
72	fastlocals = f->f_localsplus;
73	for (i = f->f_nlocals; --i >= 0; ++fastlocals) {
74		Py_XDECREF(*fastlocals);
75	}
76
77	Py_XDECREF(f->f_back);
78	Py_XDECREF(f->f_code);
79	Py_XDECREF(f->f_builtins);
80	Py_XDECREF(f->f_globals);
81	Py_XDECREF(f->f_locals);
82	Py_XDECREF(f->f_closure);
83	Py_XDECREF(f->f_trace);
84	Py_XDECREF(f->f_exc_type);
85	Py_XDECREF(f->f_exc_value);
86	Py_XDECREF(f->f_exc_traceback);
87	f->f_back = free_list;
88	free_list = f;
89	Py_TRASHCAN_SAFE_END(f)
90}
91
92PyTypeObject PyFrame_Type = {
93	PyObject_HEAD_INIT(&PyType_Type)
94	0,
95	"frame",
96	sizeof(PyFrameObject),
97	0,
98	(destructor)frame_dealloc, /*tp_dealloc*/
99	0,		/*tp_print*/
100	(getattrfunc)frame_getattr, /*tp_getattr*/
101	(setattrfunc)frame_setattr, /*tp_setattr*/
102	0,		/*tp_compare*/
103	0,		/*tp_repr*/
104	0,		/*tp_as_number*/
105	0,		/*tp_as_sequence*/
106	0,		/*tp_as_mapping*/
107};
108
109PyFrameObject *
110PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
111	    PyObject *locals, PyObject *closure)
112{
113	PyFrameObject *back = tstate->frame;
114	static PyObject *builtin_object;
115	PyFrameObject *f;
116	PyObject *builtins;
117	int extras, ncells;
118
119	if (builtin_object == NULL) {
120		builtin_object = PyString_InternFromString("__builtins__");
121		if (builtin_object == NULL)
122			return NULL;
123	}
124	if ((back != NULL && !PyFrame_Check(back)) ||
125	    code == NULL || !PyCode_Check(code) ||
126	    globals == NULL || !PyDict_Check(globals) ||
127	    (locals != NULL && !PyDict_Check(locals))) {
128		PyErr_BadInternalCall();
129		return NULL;
130	}
131	extras = code->co_stacksize + code->co_nlocals;
132	ncells = PyTuple_GET_SIZE(code->co_cellvars);
133	if (back == NULL || back->f_globals != globals) {
134		builtins = PyDict_GetItem(globals, builtin_object);
135		if (builtins != NULL && PyModule_Check(builtins))
136			builtins = PyModule_GetDict(builtins);
137	}
138	else {
139		/* If we share the globals, we share the builtins.
140		   Save a lookup and a call. */
141		builtins = back->f_builtins;
142	}
143	if (builtins != NULL && !PyDict_Check(builtins))
144		builtins = NULL;
145	if (free_list == NULL) {
146		/* PyObject_New is inlined */
147		f = (PyFrameObject *)
148			PyObject_MALLOC(sizeof(PyFrameObject) +
149					extras*sizeof(PyObject *));
150		if (f == NULL)
151			return (PyFrameObject *)PyErr_NoMemory();
152		PyObject_INIT(f, &PyFrame_Type);
153	}
154	else {
155		f = free_list;
156		free_list = free_list->f_back;
157		if (f->f_nlocals + f->f_stacksize < extras) {
158			f = (PyFrameObject *)
159				PyObject_REALLOC(f, sizeof(PyFrameObject) +
160						 extras*sizeof(PyObject *));
161			if (f == NULL)
162				return (PyFrameObject *)PyErr_NoMemory();
163		}
164		else
165			extras = f->f_nlocals + f->f_stacksize;
166		PyObject_INIT(f, &PyFrame_Type);
167	}
168	if (builtins == NULL) {
169		/* No builtins!  Make up a minimal one. */
170		builtins = PyDict_New();
171		if (builtins == NULL || /* Give them 'None', at least. */
172		    PyDict_SetItemString(builtins, "None", Py_None) < 0) {
173			Py_DECREF(f);
174			return NULL;
175		}
176	}
177	else
178		Py_XINCREF(builtins);
179	f->f_builtins = builtins;
180	Py_XINCREF(back);
181	f->f_back = back;
182	Py_INCREF(code);
183	f->f_code = code;
184	Py_INCREF(globals);
185	f->f_globals = globals;
186	if (code->co_flags & CO_NEWLOCALS) {
187		if (code->co_flags & CO_OPTIMIZED)
188			locals = NULL; /* Let fast_2_locals handle it */
189		else {
190			locals = PyDict_New();
191			if (locals == NULL) {
192				Py_DECREF(f);
193				return NULL;
194			}
195		}
196	}
197	else {
198		if (locals == NULL)
199			locals = globals;
200		Py_INCREF(locals);
201	}
202	if (closure || ncells) {
203		int i, size;
204		size = ncells;
205		if (closure)
206			size += PyTuple_GET_SIZE(closure);
207		f->f_closure = PyTuple_New(size);
208		for (i = 0; i < ncells; ++i)
209			PyTuple_SET_ITEM(f->f_closure, i, PyCell_New(NULL));
210		for (i = ncells; i < size; ++i) {
211			PyObject *o = PyTuple_GET_ITEM(closure, i - ncells);
212			Py_INCREF(o);
213			PyTuple_SET_ITEM(f->f_closure, i, o);
214		}
215	}
216	else
217		f->f_closure = NULL;
218	f->f_locals = locals;
219	f->f_trace = NULL;
220	f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
221	f->f_tstate = tstate;
222
223	f->f_lasti = 0;
224	f->f_lineno = code->co_firstlineno;
225	f->f_restricted = (builtins != tstate->interp->builtins);
226	f->f_iblock = 0;
227	f->f_nlocals = code->co_nlocals;
228	f->f_stacksize = extras - code->co_nlocals;
229
230	while (--extras >= 0)
231		f->f_localsplus[extras] = NULL;
232
233	f->f_valuestack = f->f_localsplus + f->f_nlocals;
234
235	return f;
236}
237
238/* Block management */
239
240void
241PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
242{
243	PyTryBlock *b;
244	if (f->f_iblock >= CO_MAXBLOCKS)
245		Py_FatalError("XXX block stack overflow");
246	b = &f->f_blockstack[f->f_iblock++];
247	b->b_type = type;
248	b->b_level = level;
249	b->b_handler = handler;
250}
251
252PyTryBlock *
253PyFrame_BlockPop(PyFrameObject *f)
254{
255	PyTryBlock *b;
256	if (f->f_iblock <= 0)
257		Py_FatalError("XXX block stack underflow");
258	b = &f->f_blockstack[--f->f_iblock];
259	return b;
260}
261
262/* Convert between "fast" version of locals and dictionary version */
263
264void
265PyFrame_FastToLocals(PyFrameObject *f)
266{
267	/* Merge fast locals into f->f_locals */
268	PyObject *locals, *map;
269	PyObject **fast;
270	PyObject *error_type, *error_value, *error_traceback;
271	int j;
272	if (f == NULL)
273		return;
274	locals = f->f_locals;
275	if (locals == NULL) {
276		locals = f->f_locals = PyDict_New();
277		if (locals == NULL) {
278			PyErr_Clear(); /* Can't report it :-( */
279			return;
280		}
281	}
282	if (f->f_nlocals == 0)
283		return;
284	map = f->f_code->co_varnames;
285	if (!PyDict_Check(locals) || !PyTuple_Check(map))
286		return;
287	PyErr_Fetch(&error_type, &error_value, &error_traceback);
288	fast = f->f_localsplus;
289	j = PyTuple_Size(map);
290	if (j > f->f_nlocals)
291		j = f->f_nlocals;
292	for (; --j >= 0; ) {
293		PyObject *key = PyTuple_GetItem(map, j);
294		PyObject *value = fast[j];
295		if (value == NULL) {
296			PyErr_Clear();
297			if (PyDict_DelItem(locals, key) != 0)
298				PyErr_Clear();
299		}
300		else {
301			if (PyDict_SetItem(locals, key, value) != 0)
302				PyErr_Clear();
303		}
304	}
305	PyErr_Restore(error_type, error_value, error_traceback);
306}
307
308void
309PyFrame_LocalsToFast(PyFrameObject *f, int clear)
310{
311	/* Merge f->f_locals into fast locals */
312	PyObject *locals, *map;
313	PyObject **fast;
314	PyObject *error_type, *error_value, *error_traceback;
315	int j;
316	if (f == NULL)
317		return;
318	locals = f->f_locals;
319	map = f->f_code->co_varnames;
320	if (locals == NULL || f->f_code->co_nlocals == 0)
321		return;
322	if (!PyDict_Check(locals) || !PyTuple_Check(map))
323		return;
324	PyErr_Fetch(&error_type, &error_value, &error_traceback);
325	fast = f->f_localsplus;
326	j = PyTuple_Size(map);
327	if (j > f->f_nlocals)
328		j = f->f_nlocals;
329	for (; --j >= 0; ) {
330		PyObject *key = PyTuple_GetItem(map, j);
331		PyObject *value = PyDict_GetItem(locals, key);
332		Py_XINCREF(value);
333		if (value != NULL || clear) {
334			Py_XDECREF(fast[j]);
335			fast[j] = value;
336		}
337	}
338	PyErr_Restore(error_type, error_value, error_traceback);
339}
340
341/* Clear out the free list */
342
343void
344PyFrame_Fini(void)
345{
346	while (free_list != NULL) {
347		PyFrameObject *f = free_list;
348		free_list = free_list->f_back;
349		PyObject_DEL(f);
350	}
351}
352