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