frameobject.c revision c91ed400e053dc9f11dd30c84e2bb611999dce50
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#undef MIN
12#undef MAX
13#define MIN(a, b) ((a) < (b) ? (a) : (b))
14#define MAX(a, b) ((a) > (b) ? (a) : (b))
15
16#define OFF(x) offsetof(PyFrameObject, x)
17
18static PyMemberDef frame_memberlist[] = {
19	{"f_back",	T_OBJECT,	OFF(f_back),	RO},
20	{"f_code",	T_OBJECT,	OFF(f_code),	RO},
21	{"f_builtins",	T_OBJECT,	OFF(f_builtins),RO},
22	{"f_globals",	T_OBJECT,	OFF(f_globals),	RO},
23	{"f_lasti",	T_INT,		OFF(f_lasti),	RO},
24	{"f_restricted",T_INT,		OFF(f_restricted),RO},
25	{"f_exc_type",	T_OBJECT,	OFF(f_exc_type)},
26	{"f_exc_value",	T_OBJECT,	OFF(f_exc_value)},
27	{"f_exc_traceback", T_OBJECT,	OFF(f_exc_traceback)},
28	{NULL}	/* Sentinel */
29};
30
31static PyObject *
32frame_getlocals(PyFrameObject *f, void *closure)
33{
34	PyFrame_FastToLocals(f);
35	Py_INCREF(f->f_locals);
36	return f->f_locals;
37}
38
39static PyObject *
40frame_getlineno(PyFrameObject *f, void *closure)
41{
42	int lineno;
43
44	if (f->f_trace)
45		lineno = f->f_lineno;
46	else
47		lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
48
49	return PyInt_FromLong(lineno);
50}
51
52/* Setter for f_lineno - you can set f_lineno from within a trace function in
53 * order to jump to a given line of code, subject to some restrictions.  Most
54 * lines are OK to jump to because they don't make any assumptions about the
55 * state of the stack (obvious because you could remove the line and the code
56 * would still work without any stack errors), but there are some constructs
57 * that limit jumping:
58 *
59 *  o Lines with an 'except' statement on them can't be jumped to, because
60 *    they expect an exception to be on the top of the stack.
61 *  o Lines that live in a 'finally' block can't be jumped from or to, since
62 *    the END_FINALLY expects to clean up the stack after the 'try' block.
63 *  o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
64 *    needs to be set up before their code runs, and for 'for' loops the
65 *    iterator needs to be on the stack.
66 */
67static int
68frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
69{
70	int new_lineno = 0;		/* The new value of f_lineno */
71	int new_lasti = 0;		/* The new value of f_lasti */
72	int new_iblock = 0;		/* The new value of f_iblock */
73	char *code = NULL;		/* The bytecode for the frame... */
74	int code_len = 0;		/* ...and its length */
75	char *lnotab = NULL;		/* Iterating over co_lnotab */
76	int lnotab_len = 0;		/* (ditto) */
77	int offset = 0;			/* (ditto) */
78	int line = 0;			/* (ditto) */
79	int addr = 0;			/* (ditto) */
80	int min_addr = 0;		/* Scanning the SETUPs and POPs */
81	int max_addr = 0;		/* (ditto) */
82	int delta_iblock = 0;		/* (ditto) */
83	int min_delta_iblock = 0;	/* (ditto) */
84	int min_iblock = 0;		/* (ditto) */
85	int f_lasti_setup_addr = 0;	/* Policing no-jump-into-finally */
86	int new_lasti_setup_addr = 0;	/* (ditto) */
87	int blockstack[CO_MAXBLOCKS];	/* Walking the 'finally' blocks */
88	int in_finally[CO_MAXBLOCKS];	/* (ditto) */
89	int blockstack_top = 0;		/* (ditto) */
90	int setup_op = 0;               /* (ditto) */
91
92	/* f_lineno must be an integer. */
93	if (!PyInt_Check(p_new_lineno)) {
94		PyErr_SetString(PyExc_ValueError,
95				"lineno must be an integer");
96		return -1;
97	}
98
99	/* You can only do this from within a trace function, not via
100	 * _getframe or similar hackery. */
101	if (!f->f_trace)
102	{
103		PyErr_Format(PyExc_ValueError,
104			     "f_lineno can only be set by a trace function");
105		return -1;
106	}
107
108	/* Fail if the line comes before the start of the code block. */
109	new_lineno = (int) PyInt_AsLong(p_new_lineno);
110	if (new_lineno < f->f_code->co_firstlineno) {
111		PyErr_Format(PyExc_ValueError,
112			     "line %d comes before the current code block",
113			     new_lineno);
114		return -1;
115	}
116
117	/* Find the bytecode offset for the start of the given line, or the
118	 * first code-owning line after it. */
119	PyString_AsStringAndSize(f->f_code->co_lnotab, &lnotab, &lnotab_len);
120	addr = 0;
121	line = f->f_code->co_firstlineno;
122	new_lasti = -1;
123	for (offset = 0; offset < lnotab_len; offset += 2) {
124		addr += lnotab[offset];
125		line += lnotab[offset+1];
126		if (line >= new_lineno) {
127			new_lasti = addr;
128			new_lineno = line;
129			break;
130		}
131	}
132
133	/* If we didn't reach the requested line, return an error. */
134	if (new_lasti == -1) {
135		PyErr_Format(PyExc_ValueError,
136			     "line %d comes after the current code block",
137			     new_lineno);
138		return -1;
139	}
140
141	/* We're now ready to look at the bytecode. */
142	PyString_AsStringAndSize(f->f_code->co_code, &code, &code_len);
143	min_addr = MIN(new_lasti, f->f_lasti);
144	max_addr = MAX(new_lasti, f->f_lasti);
145
146	/* You can't jump onto a line with an 'except' statement on it -
147	 * they expect to have an exception on the top of the stack, which
148	 * won't be true if you jump to them.  They always start with code
149	 * that either pops the exception using POP_TOP (plain 'except:'
150	 * lines do this) or duplicates the exception on the stack using
151	 * DUP_TOP (if there's an exception type specified).  See compile.c,
152	 * 'com_try_except' for the full details.  There aren't any other
153	 * cases (AFAIK) where a line's code can start with DUP_TOP or
154	 * POP_TOP, but if any ever appear, they'll be subject to the same
155	 * restriction (but with a different error message). */
156	if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
157		PyErr_SetString(PyExc_ValueError,
158		    "can't jump to 'except' line as there's no exception");
159		return -1;
160	}
161
162	/* You can't jump into or out of a 'finally' block because the 'try'
163	 * block leaves something on the stack for the END_FINALLY to clean
164	 * up.  So we walk the bytecode, maintaining a simulated blockstack.
165	 * When we reach the old or new address and it's in a 'finally' block
166	 * we note the address of the corresponding SETUP_FINALLY.  The jump
167	 * is only legal if neither address is in a 'finally' block or
168	 * they're both in the same one.  'blockstack' is a stack of the
169	 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
170	 * whether we're in a 'finally' block at each blockstack level. */
171	f_lasti_setup_addr = -1;
172	new_lasti_setup_addr = -1;
173	memset(blockstack, '\0', sizeof(blockstack));
174	memset(in_finally, '\0', sizeof(in_finally));
175	blockstack_top = 0;
176	for (addr = 0; addr < code_len; addr++) {
177		unsigned char op = code[addr];
178		switch (op) {
179		case SETUP_LOOP:
180		case SETUP_EXCEPT:
181		case SETUP_FINALLY:
182			blockstack[blockstack_top++] = addr;
183			in_finally[blockstack_top-1] = 0;
184			break;
185
186		case POP_BLOCK:
187			assert(blockstack_top > 0);
188			setup_op = code[blockstack[blockstack_top-1]];
189			if (setup_op == SETUP_FINALLY) {
190				in_finally[blockstack_top-1] = 1;
191			}
192			else {
193				blockstack_top--;
194			}
195			break;
196
197		case END_FINALLY:
198			/* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
199			 * in the bytecode but don't correspond to an actual
200			 * 'finally' block.  (If blockstack_top is 0, we must
201			 * be seeing such an END_FINALLY.) */
202			if (blockstack_top > 0) {
203				setup_op = code[blockstack[blockstack_top-1]];
204				if (setup_op == SETUP_FINALLY) {
205					blockstack_top--;
206				}
207			}
208			break;
209		}
210
211		/* For the addresses we're interested in, see whether they're
212		 * within a 'finally' block and if so, remember the address
213		 * of the SETUP_FINALLY. */
214		if (addr == new_lasti || addr == f->f_lasti) {
215			int i = 0;
216			int setup_addr = -1;
217			for (i = blockstack_top-1; i >= 0; i--) {
218				if (in_finally[i]) {
219					setup_addr = blockstack[i];
220					break;
221				}
222			}
223
224			if (setup_addr != -1) {
225				if (addr == new_lasti) {
226					new_lasti_setup_addr = setup_addr;
227				}
228
229				if (addr == f->f_lasti) {
230					f_lasti_setup_addr = setup_addr;
231				}
232			}
233		}
234
235		if (op >= HAVE_ARGUMENT) {
236			addr += 2;
237		}
238	}
239
240	/* Verify that the blockstack tracking code didn't get lost. */
241	assert(blockstack_top == 0);
242
243	/* After all that, are we jumping into / out of a 'finally' block? */
244	if (new_lasti_setup_addr != f_lasti_setup_addr) {
245		PyErr_SetString(PyExc_ValueError,
246			    "can't jump into or out of a 'finally' block");
247		return -1;
248	}
249
250
251	/* Police block-jumping (you can't jump into the middle of a block)
252	 * and ensure that the blockstack finishes up in a sensible state (by
253	 * popping any blocks we're jumping out of).  We look at all the
254	 * blockstack operations between the current position and the new
255	 * one, and keep track of how many blocks we drop out of on the way.
256	 * By also keeping track of the lowest blockstack position we see, we
257	 * can tell whether the jump goes into any blocks without coming out
258	 * again - in that case we raise an exception below. */
259	delta_iblock = 0;
260	for (addr = min_addr; addr < max_addr; addr++) {
261		unsigned char op = code[addr];
262		switch (op) {
263		case SETUP_LOOP:
264		case SETUP_EXCEPT:
265		case SETUP_FINALLY:
266			delta_iblock++;
267			break;
268
269		case POP_BLOCK:
270			delta_iblock--;
271			break;
272		}
273
274		min_delta_iblock = MIN(min_delta_iblock, delta_iblock);
275
276		if (op >= HAVE_ARGUMENT) {
277			addr += 2;
278		}
279	}
280
281	/* Derive the absolute iblock values from the deltas. */
282	min_iblock = f->f_iblock + min_delta_iblock;
283	if (new_lasti > f->f_lasti) {
284		/* Forwards jump. */
285		new_iblock = f->f_iblock + delta_iblock;
286	}
287	else {
288		/* Backwards jump. */
289		new_iblock = f->f_iblock - delta_iblock;
290	}
291
292	/* Are we jumping into a block? */
293	if (new_iblock > min_iblock) {
294		PyErr_SetString(PyExc_ValueError,
295				"can't jump into the middle of a block");
296		return -1;
297	}
298
299	/* Pop any blocks that we're jumping out of. */
300	while (f->f_iblock > new_iblock) {
301		PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
302		while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
303			PyObject *v = (*--f->f_stacktop);
304			Py_DECREF(v);
305		}
306	}
307
308	/* Finally set the new f_lineno and f_lasti and return OK. */
309	f->f_lineno = new_lineno;
310	f->f_lasti = new_lasti;
311	return 0;
312}
313
314static PyObject *
315frame_gettrace(PyFrameObject *f, void *closure)
316{
317	PyObject* trace = f->f_trace;
318
319	if (trace == NULL)
320		trace = Py_None;
321
322	Py_INCREF(trace);
323
324	return trace;
325}
326
327static int
328frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
329{
330	/* We rely on f_lineno being accurate when f_trace is set. */
331
332	PyObject* old_value = f->f_trace;
333
334	Py_XINCREF(v);
335	f->f_trace = v;
336
337	if (v != NULL)
338		f->f_lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
339
340	Py_XDECREF(old_value);
341
342	return 0;
343}
344
345static PyGetSetDef frame_getsetlist[] = {
346	{"f_locals",	(getter)frame_getlocals, NULL, NULL},
347	{"f_lineno",	(getter)frame_getlineno,
348			(setter)frame_setlineno, NULL},
349	{"f_trace",	(getter)frame_gettrace, (setter)frame_settrace, NULL},
350	{0}
351};
352
353/* Stack frames are allocated and deallocated at a considerable rate.
354   In an attempt to improve the speed of function calls, we maintain a
355   separate free list of stack frames (just like integers are
356   allocated in a special way -- see intobject.c).  When a stack frame
357   is on the free list, only the following members have a meaning:
358	ob_type		== &Frametype
359	f_back		next item on free list, or NULL
360	f_nlocals	number of locals
361	f_stacksize	size of value stack
362        ob_size         size of localsplus
363   Note that the value and block stacks are preserved -- this can save
364   another malloc() call or two (and two free() calls as well!).
365   Also note that, unlike for integers, each frame object is a
366   malloc'ed object in its own right -- it is only the actual calls to
367   malloc() that we are trying to save here, not the administration.
368   After all, while a typical program may make millions of calls, a
369   call depth of more than 20 or 30 is probably already exceptional
370   unless the program contains run-away recursion.  I hope.
371
372   Later, MAXFREELIST was added to bound the # of frames saved on
373   free_list.  Else programs creating lots of cyclic trash involving
374   frames could provoke free_list into growing without bound.
375*/
376
377static PyFrameObject *free_list = NULL;
378static int numfree = 0;		/* number of frames currently in free_list */
379#define MAXFREELIST 200		/* max value for numfree */
380
381static void
382frame_dealloc(PyFrameObject *f)
383{
384	int i, slots;
385	PyObject **fastlocals;
386	PyObject **p;
387
388 	PyObject_GC_UnTrack(f);
389	Py_TRASHCAN_SAFE_BEGIN(f)
390	/* Kill all local variables */
391	slots = f->f_nlocals + f->f_ncells + f->f_nfreevars;
392	fastlocals = f->f_localsplus;
393	for (i = slots; --i >= 0; ++fastlocals) {
394		Py_XDECREF(*fastlocals);
395	}
396
397	/* Free stack */
398	if (f->f_stacktop != NULL) {
399		for (p = f->f_valuestack; p < f->f_stacktop; p++)
400			Py_XDECREF(*p);
401	}
402
403	Py_XDECREF(f->f_back);
404	Py_DECREF(f->f_code);
405	Py_DECREF(f->f_builtins);
406	Py_DECREF(f->f_globals);
407	Py_XDECREF(f->f_locals);
408	Py_XDECREF(f->f_trace);
409	Py_XDECREF(f->f_exc_type);
410	Py_XDECREF(f->f_exc_value);
411	Py_XDECREF(f->f_exc_traceback);
412	if (numfree < MAXFREELIST) {
413		++numfree;
414		f->f_back = free_list;
415		free_list = f;
416	}
417	else
418		PyObject_GC_Del(f);
419	Py_TRASHCAN_SAFE_END(f)
420}
421
422static int
423frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
424{
425	PyObject **fastlocals, **p;
426	int i, err, slots;
427#define VISIT(o) if (o) {if ((err = visit((PyObject *)(o), arg))) return err;}
428
429	VISIT(f->f_back);
430	VISIT(f->f_code);
431	VISIT(f->f_builtins);
432	VISIT(f->f_globals);
433	VISIT(f->f_locals);
434	VISIT(f->f_trace);
435	VISIT(f->f_exc_type);
436	VISIT(f->f_exc_value);
437	VISIT(f->f_exc_traceback);
438
439	/* locals */
440	slots = f->f_nlocals + f->f_ncells + f->f_nfreevars;
441	fastlocals = f->f_localsplus;
442	for (i = slots; --i >= 0; ++fastlocals) {
443		VISIT(*fastlocals);
444	}
445
446	/* stack */
447	if (f->f_stacktop != NULL) {
448		for (p = f->f_valuestack; p < f->f_stacktop; p++)
449			VISIT(*p);
450	}
451	return 0;
452}
453
454static void
455frame_clear(PyFrameObject *f)
456{
457	PyObject **fastlocals, **p;
458	int i, slots;
459
460	Py_XDECREF(f->f_exc_type);
461	f->f_exc_type = NULL;
462
463	Py_XDECREF(f->f_exc_value);
464	f->f_exc_value = NULL;
465
466	Py_XDECREF(f->f_exc_traceback);
467	f->f_exc_traceback = NULL;
468
469	Py_XDECREF(f->f_trace);
470	f->f_trace = NULL;
471
472	/* locals */
473	slots = f->f_nlocals + f->f_ncells + f->f_nfreevars;
474	fastlocals = f->f_localsplus;
475	for (i = slots; --i >= 0; ++fastlocals) {
476		if (*fastlocals != NULL) {
477			Py_XDECREF(*fastlocals);
478			*fastlocals = NULL;
479		}
480	}
481
482	/* stack */
483	if (f->f_stacktop != NULL) {
484		for (p = f->f_valuestack; p < f->f_stacktop; p++) {
485			Py_XDECREF(*p);
486			*p = NULL;
487		}
488	}
489}
490
491
492PyTypeObject PyFrame_Type = {
493	PyObject_HEAD_INIT(&PyType_Type)
494	0,
495	"frame",
496	sizeof(PyFrameObject),
497	sizeof(PyObject *),
498	(destructor)frame_dealloc, 		/* tp_dealloc */
499	0,					/* tp_print */
500	0, 					/* tp_getattr */
501	0,			 		/* tp_setattr */
502	0,					/* tp_compare */
503	0,					/* tp_repr */
504	0,					/* tp_as_number */
505	0,					/* tp_as_sequence */
506	0,					/* tp_as_mapping */
507	0,					/* tp_hash */
508	0,					/* tp_call */
509	0,					/* tp_str */
510	PyObject_GenericGetAttr,		/* tp_getattro */
511	PyObject_GenericSetAttr,		/* tp_setattro */
512	0,					/* tp_as_buffer */
513	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
514	0,             				/* tp_doc */
515 	(traverseproc)frame_traverse,		/* tp_traverse */
516	(inquiry)frame_clear,			/* tp_clear */
517	0,					/* tp_richcompare */
518	0,					/* tp_weaklistoffset */
519	0,					/* tp_iter */
520	0,					/* tp_iternext */
521	0,					/* tp_methods */
522	frame_memberlist,			/* tp_members */
523	frame_getsetlist,			/* tp_getset */
524	0,					/* tp_base */
525	0,					/* tp_dict */
526};
527
528static PyObject *builtin_object;
529
530int PyFrame_Init()
531{
532	builtin_object = PyString_InternFromString("__builtins__");
533	return (builtin_object != NULL);
534}
535
536PyFrameObject *
537PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
538	    PyObject *locals)
539{
540	PyFrameObject *back = tstate->frame;
541	PyFrameObject *f;
542	PyObject *builtins;
543	int extras, ncells, nfrees;
544
545#ifdef Py_DEBUG
546	if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
547	    (locals != NULL && !PyDict_Check(locals))) {
548		PyErr_BadInternalCall();
549		return NULL;
550	}
551#endif
552	ncells = PyTuple_GET_SIZE(code->co_cellvars);
553	nfrees = PyTuple_GET_SIZE(code->co_freevars);
554	extras = code->co_stacksize + code->co_nlocals + ncells + nfrees;
555	if (back == NULL || back->f_globals != globals) {
556		builtins = PyDict_GetItem(globals, builtin_object);
557		if (builtins != NULL && PyModule_Check(builtins))
558			builtins = PyModule_GetDict(builtins);
559	}
560	else {
561		/* If we share the globals, we share the builtins.
562		   Save a lookup and a call. */
563		builtins = back->f_builtins;
564	}
565	if (builtins != NULL && !PyDict_Check(builtins))
566		builtins = NULL;
567	if (free_list == NULL) {
568		f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
569		if (f == NULL)
570			return NULL;
571	}
572	else {
573		assert(numfree > 0);
574		--numfree;
575		f = free_list;
576		free_list = free_list->f_back;
577		if (f->ob_size < extras) {
578			f = PyObject_GC_Resize(PyFrameObject, f, extras);
579			if (f == NULL)
580				return NULL;
581		}
582		_Py_NewReference((PyObject *)f);
583	}
584	if (builtins == NULL) {
585		/* No builtins!  Make up a minimal one. */
586		builtins = PyDict_New();
587		if (builtins == NULL || /* Give them 'None', at least. */
588		    PyDict_SetItemString(builtins, "None", Py_None) < 0) {
589			Py_DECREF(f);
590			return NULL;
591		}
592	}
593	else
594		Py_INCREF(builtins);
595	f->f_builtins = builtins;
596	Py_XINCREF(back);
597	f->f_back = back;
598	Py_INCREF(code);
599	f->f_code = code;
600	Py_INCREF(globals);
601	f->f_globals = globals;
602	if (code->co_flags & CO_NEWLOCALS) {
603		if (code->co_flags & CO_OPTIMIZED)
604			locals = NULL; /* Let fast_2_locals handle it */
605		else {
606			locals = PyDict_New();
607			if (locals == NULL) {
608				Py_DECREF(f);
609				return NULL;
610			}
611		}
612	}
613	else {
614		if (locals == NULL)
615			locals = globals;
616		Py_INCREF(locals);
617	}
618	f->f_locals = locals;
619	f->f_trace = NULL;
620	f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
621	f->f_tstate = tstate;
622
623	f->f_lasti = -1;
624	f->f_lineno = code->co_firstlineno;
625	f->f_restricted = (builtins != tstate->interp->builtins);
626	f->f_iblock = 0;
627	f->f_nlocals = code->co_nlocals;
628	f->f_stacksize = code->co_stacksize;
629	f->f_ncells = ncells;
630	f->f_nfreevars = nfrees;
631
632	extras = f->f_nlocals + ncells + nfrees;
633	memset(f->f_localsplus, 0, extras * sizeof(f->f_localsplus[0]));
634
635	f->f_valuestack = f->f_localsplus + extras;
636	f->f_stacktop = f->f_valuestack;
637	_PyObject_GC_TRACK(f);
638	return f;
639}
640
641/* Block management */
642
643void
644PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
645{
646	PyTryBlock *b;
647	if (f->f_iblock >= CO_MAXBLOCKS)
648		Py_FatalError("XXX block stack overflow");
649	b = &f->f_blockstack[f->f_iblock++];
650	b->b_type = type;
651	b->b_level = level;
652	b->b_handler = handler;
653}
654
655PyTryBlock *
656PyFrame_BlockPop(PyFrameObject *f)
657{
658	PyTryBlock *b;
659	if (f->f_iblock <= 0)
660		Py_FatalError("XXX block stack underflow");
661	b = &f->f_blockstack[--f->f_iblock];
662	return b;
663}
664
665/* Convert between "fast" version of locals and dictionary version */
666
667static void
668map_to_dict(PyObject *map, int nmap, PyObject *dict, PyObject **values,
669	    int deref)
670{
671	int j;
672	for (j = nmap; --j >= 0; ) {
673		PyObject *key = PyTuple_GET_ITEM(map, j);
674		PyObject *value = values[j];
675		if (deref)
676			value = PyCell_GET(value);
677		if (value == NULL) {
678			if (PyDict_DelItem(dict, key) != 0)
679				PyErr_Clear();
680		}
681		else {
682			if (PyDict_SetItem(dict, key, value) != 0)
683				PyErr_Clear();
684		}
685	}
686}
687
688static void
689dict_to_map(PyObject *map, int nmap, PyObject *dict, PyObject **values,
690	    int deref, int clear)
691{
692	int j;
693	for (j = nmap; --j >= 0; ) {
694		PyObject *key = PyTuple_GET_ITEM(map, j);
695		PyObject *value = PyDict_GetItem(dict, key);
696		if (deref) {
697			if (value || clear) {
698				if (PyCell_GET(values[j]) != value) {
699					if (PyCell_Set(values[j], value) < 0)
700						PyErr_Clear();
701				}
702			}
703		} else if (value != NULL || clear) {
704			if (values[j] != value) {
705				Py_XINCREF(value);
706				Py_XDECREF(values[j]);
707				values[j] = value;
708			}
709		}
710	}
711}
712
713void
714PyFrame_FastToLocals(PyFrameObject *f)
715{
716	/* Merge fast locals into f->f_locals */
717	PyObject *locals, *map;
718	PyObject **fast;
719	PyObject *error_type, *error_value, *error_traceback;
720	int j;
721	if (f == NULL)
722		return;
723	locals = f->f_locals;
724	if (locals == NULL) {
725		locals = f->f_locals = PyDict_New();
726		if (locals == NULL) {
727			PyErr_Clear(); /* Can't report it :-( */
728			return;
729		}
730	}
731	map = f->f_code->co_varnames;
732	if (!PyDict_Check(locals) || !PyTuple_Check(map))
733		return;
734	PyErr_Fetch(&error_type, &error_value, &error_traceback);
735	fast = f->f_localsplus;
736	j = PyTuple_Size(map);
737	if (j > f->f_nlocals)
738		j = f->f_nlocals;
739	if (f->f_nlocals)
740	    map_to_dict(map, j, locals, fast, 0);
741	if (f->f_ncells || f->f_nfreevars) {
742		if (!(PyTuple_Check(f->f_code->co_cellvars)
743		      && PyTuple_Check(f->f_code->co_freevars))) {
744			Py_DECREF(locals);
745			return;
746		}
747		map_to_dict(f->f_code->co_cellvars,
748			    PyTuple_GET_SIZE(f->f_code->co_cellvars),
749			    locals, fast + f->f_nlocals, 1);
750		map_to_dict(f->f_code->co_freevars,
751			    PyTuple_GET_SIZE(f->f_code->co_freevars),
752			    locals, fast + f->f_nlocals + f->f_ncells, 1);
753	}
754	PyErr_Restore(error_type, error_value, error_traceback);
755}
756
757void
758PyFrame_LocalsToFast(PyFrameObject *f, int clear)
759{
760	/* Merge f->f_locals into fast locals */
761	PyObject *locals, *map;
762	PyObject **fast;
763	PyObject *error_type, *error_value, *error_traceback;
764	int j;
765	if (f == NULL)
766		return;
767	locals = f->f_locals;
768	map = f->f_code->co_varnames;
769	if (locals == NULL)
770		return;
771	if (!PyDict_Check(locals) || !PyTuple_Check(map))
772		return;
773	PyErr_Fetch(&error_type, &error_value, &error_traceback);
774	fast = f->f_localsplus;
775	j = PyTuple_Size(map);
776	if (j > f->f_nlocals)
777		j = f->f_nlocals;
778	if (f->f_nlocals)
779	    dict_to_map(f->f_code->co_varnames, j, locals, fast, 0, clear);
780	if (f->f_ncells || f->f_nfreevars) {
781		if (!(PyTuple_Check(f->f_code->co_cellvars)
782		      && PyTuple_Check(f->f_code->co_freevars)))
783			return;
784		dict_to_map(f->f_code->co_cellvars,
785			    PyTuple_GET_SIZE(f->f_code->co_cellvars),
786			    locals, fast + f->f_nlocals, 1, clear);
787		dict_to_map(f->f_code->co_freevars,
788			    PyTuple_GET_SIZE(f->f_code->co_freevars),
789			    locals, fast + f->f_nlocals + f->f_ncells, 1,
790			    clear);
791	}
792	PyErr_Restore(error_type, error_value, error_traceback);
793}
794
795/* Clear out the free list */
796
797void
798PyFrame_Fini(void)
799{
800	while (free_list != NULL) {
801		PyFrameObject *f = free_list;
802		free_list = free_list->f_back;
803		PyObject_GC_Del(f);
804		--numfree;
805	}
806	assert(numfree == 0);
807	Py_XDECREF(builtin_object);
808	builtin_object = NULL;
809}
810