pythonrun.c revision c2632a5c34de3448fedc581a978a9a1924089fcd
1
2/* Python interpreter top-level routines, including init/exit */
3
4#include "Python.h"
5
6#include "grammar.h"
7#include "node.h"
8#include "token.h"
9#include "parsetok.h"
10#include "errcode.h"
11#include "compile.h"
12#include "symtable.h"
13#include "eval.h"
14#include "marshal.h"
15
16#include <signal.h>
17
18#ifdef HAVE_LANGINFO_H
19#include <locale.h>
20#include <langinfo.h>
21#endif
22
23#ifdef MS_WINDOWS
24#undef BYTE
25#include "windows.h"
26#endif
27
28extern char *Py_GetPath(void);
29
30extern grammar _PyParser_Grammar; /* From graminit.c */
31
32/* Forward */
33static void initmain(void);
34static void initsite(void);
35static PyObject *run_err_node(node *, const char *, PyObject *, PyObject *,
36			      PyCompilerFlags *);
37static PyObject *run_node(node *, const char *, PyObject *, PyObject *,
38			  PyCompilerFlags *);
39static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
40			      PyCompilerFlags *);
41static void err_input(perrdetail *);
42static void initsigs(void);
43static void call_sys_exitfunc(void);
44static void call_ll_exitfuncs(void);
45extern void _PyUnicode_Init(void);
46extern void _PyUnicode_Fini(void);
47
48#ifdef WITH_THREAD
49extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
50extern void _PyGILState_Fini(void);
51#endif /* WITH_THREAD */
52
53int Py_DebugFlag; /* Needed by parser.c */
54int Py_VerboseFlag; /* Needed by import.c */
55int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
56int Py_NoSiteFlag; /* Suppress 'import site' */
57int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
58int Py_FrozenFlag; /* Needed by getpath.c */
59int Py_UnicodeFlag = 0; /* Needed by compile.c */
60int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
61/* _XXX Py_QnewFlag should go away in 2.3.  It's true iff -Qnew is passed,
62  on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
63  true divisions (which they will be in 2.3). */
64int _Py_QnewFlag = 0;
65
66/* Reference to 'warnings' module, to avoid importing it
67   on the fly when the import lock may be held.  See 683658/771097
68*/
69static PyObject *warnings_module = NULL;
70
71/* Returns a borrowed reference to the 'warnings' module, or NULL.
72   If the module is returned, it is guaranteed to have been obtained
73   without acquiring the import lock
74*/
75PyObject *PyModule_GetWarningsModule(void)
76{
77	PyObject *typ, *val, *tb;
78	PyObject *all_modules;
79	/* If we managed to get the module at init time, just use it */
80	if (warnings_module)
81		return warnings_module;
82	/* If it wasn't available at init time, it may be available
83	   now in sys.modules (common scenario is frozen apps: import
84	   at init time fails, but the frozen init code sets up sys.path
85	   correctly, then does an implicit import of warnings for us
86	*/
87	/* Save and restore any exceptions */
88	PyErr_Fetch(&typ, &val, &tb);
89
90	all_modules = PySys_GetObject("modules");
91	if (all_modules) {
92		warnings_module = PyDict_GetItemString(all_modules, "warnings");
93		/* We keep a ref in the global */
94		Py_XINCREF(warnings_module);
95	}
96	PyErr_Restore(typ, val, tb);
97	return warnings_module;
98}
99
100static int initialized = 0;
101
102/* API to access the initialized flag -- useful for esoteric use */
103
104int
105Py_IsInitialized(void)
106{
107	return initialized;
108}
109
110/* Global initializations.  Can be undone by Py_Finalize().  Don't
111   call this twice without an intervening Py_Finalize() call.  When
112   initializations fail, a fatal error is issued and the function does
113   not return.  On return, the first thread and interpreter state have
114   been created.
115
116   Locking: you must hold the interpreter lock while calling this.
117   (If the lock has not yet been initialized, that's equivalent to
118   having the lock, but you cannot use multiple threads.)
119
120*/
121
122static int
123add_flag(int flag, const char *envs)
124{
125	int env = atoi(envs);
126	if (flag < env)
127		flag = env;
128	if (flag < 1)
129		flag = 1;
130	return flag;
131}
132
133void
134Py_Initialize(void)
135{
136	PyInterpreterState *interp;
137	PyThreadState *tstate;
138	PyObject *bimod, *sysmod;
139	char *p;
140#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
141	char *codeset;
142	char *saved_locale;
143	PyObject *sys_stream, *sys_isatty;
144#endif
145	extern void _Py_ReadyTypes(void);
146
147	if (initialized)
148		return;
149	initialized = 1;
150
151	if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
152		Py_DebugFlag = add_flag(Py_DebugFlag, p);
153	if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
154		Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
155	if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
156		Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
157
158	interp = PyInterpreterState_New();
159	if (interp == NULL)
160		Py_FatalError("Py_Initialize: can't make first interpreter");
161
162	tstate = PyThreadState_New(interp);
163	if (tstate == NULL)
164		Py_FatalError("Py_Initialize: can't make first thread");
165	(void) PyThreadState_Swap(tstate);
166
167	_Py_ReadyTypes();
168
169	if (!_PyFrame_Init())
170		Py_FatalError("Py_Initialize: can't init frames");
171
172	if (!_PyInt_Init())
173		Py_FatalError("Py_Initialize: can't init ints");
174
175	interp->modules = PyDict_New();
176	if (interp->modules == NULL)
177		Py_FatalError("Py_Initialize: can't make modules dictionary");
178
179#ifdef Py_USING_UNICODE
180	/* Init Unicode implementation; relies on the codec registry */
181	_PyUnicode_Init();
182#endif
183
184	bimod = _PyBuiltin_Init();
185	if (bimod == NULL)
186		Py_FatalError("Py_Initialize: can't initialize __builtin__");
187	interp->builtins = PyModule_GetDict(bimod);
188	Py_INCREF(interp->builtins);
189
190	sysmod = _PySys_Init();
191	if (sysmod == NULL)
192		Py_FatalError("Py_Initialize: can't initialize sys");
193	interp->sysdict = PyModule_GetDict(sysmod);
194	Py_INCREF(interp->sysdict);
195	_PyImport_FixupExtension("sys", "sys");
196	PySys_SetPath(Py_GetPath());
197	PyDict_SetItemString(interp->sysdict, "modules",
198			     interp->modules);
199
200	_PyImport_Init();
201
202	/* initialize builtin exceptions */
203	_PyExc_Init();
204	_PyImport_FixupExtension("exceptions", "exceptions");
205
206	/* phase 2 of builtins */
207	_PyImport_FixupExtension("__builtin__", "__builtin__");
208
209	_PyImportHooks_Init();
210
211	initsigs(); /* Signal handling stuff, including initintr() */
212
213	initmain(); /* Module __main__ */
214	if (!Py_NoSiteFlag)
215		initsite(); /* Module site */
216
217	/* auto-thread-state API, if available */
218#ifdef WITH_THREAD
219	_PyGILState_Init(interp, tstate);
220#endif /* WITH_THREAD */
221
222	warnings_module = PyImport_ImportModule("warnings");
223	if (!warnings_module)
224		PyErr_Clear();
225
226#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
227	/* On Unix, set the file system encoding according to the
228	   user's preference, if the CODESET names a well-known
229	   Python codec, and Py_FileSystemDefaultEncoding isn't
230	   initialized by other means. Also set the encoding of
231	   stdin and stdout if these are terminals.  */
232
233	saved_locale = strdup(setlocale(LC_CTYPE, NULL));
234	setlocale(LC_CTYPE, "");
235	codeset = nl_langinfo(CODESET);
236	if (codeset && *codeset) {
237		PyObject *enc = PyCodec_Encoder(codeset);
238		if (enc) {
239			codeset = strdup(codeset);
240			Py_DECREF(enc);
241		} else {
242			codeset = NULL;
243			PyErr_Clear();
244		}
245	} else
246		codeset = NULL;
247	setlocale(LC_CTYPE, saved_locale);
248	free(saved_locale);
249
250	if (codeset) {
251		sys_stream = PySys_GetObject("stdin");
252		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
253		if (!sys_isatty)
254			PyErr_Clear();
255		if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
256			if (!PyFile_SetEncoding(sys_stream, codeset))
257				Py_FatalError("Cannot set codeset of stdin");
258		}
259		Py_XDECREF(sys_isatty);
260
261		sys_stream = PySys_GetObject("stdout");
262		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
263		if (!sys_isatty)
264			PyErr_Clear();
265		if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
266			if (!PyFile_SetEncoding(sys_stream, codeset))
267				Py_FatalError("Cannot set codeset of stdout");
268		}
269		Py_XDECREF(sys_isatty);
270
271		if (!Py_FileSystemDefaultEncoding)
272			Py_FileSystemDefaultEncoding = codeset;
273		else
274			free(codeset);
275	}
276#endif
277}
278
279#ifdef COUNT_ALLOCS
280extern void dump_counts(void);
281#endif
282
283/* Undo the effect of Py_Initialize().
284
285   Beware: if multiple interpreter and/or thread states exist, these
286   are not wiped out; only the current thread and interpreter state
287   are deleted.  But since everything else is deleted, those other
288   interpreter and thread states should no longer be used.
289
290   (XXX We should do better, e.g. wipe out all interpreters and
291   threads.)
292
293   Locking: as above.
294
295*/
296
297void
298Py_Finalize(void)
299{
300	PyInterpreterState *interp;
301	PyThreadState *tstate;
302
303	if (!initialized)
304		return;
305
306	/* The interpreter is still entirely intact at this point, and the
307	 * exit funcs may be relying on that.  In particular, if some thread
308	 * or exit func is still waiting to do an import, the import machinery
309	 * expects Py_IsInitialized() to return true.  So don't say the
310	 * interpreter is uninitialized until after the exit funcs have run.
311	 * Note that Threading.py uses an exit func to do a join on all the
312	 * threads created thru it, so this also protects pending imports in
313	 * the threads created via Threading.
314	 */
315	call_sys_exitfunc();
316	initialized = 0;
317
318	/* Get current thread state and interpreter pointer */
319	tstate = PyThreadState_GET();
320	interp = tstate->interp;
321
322	/* Disable signal handling */
323	PyOS_FiniInterrupts();
324
325	/* drop module references we saved */
326	Py_XDECREF(warnings_module);
327	warnings_module = NULL;
328
329	/* Collect garbage.  This may call finalizers; it's nice to call these
330	 * before all modules are destroyed.
331	 * XXX If a __del__ or weakref callback is triggered here, and tries to
332	 * XXX import a module, bad things can happen, because Python no
333	 * XXX longer believes it's initialized.
334	 * XXX     Fatal Python error: Interpreter not initialized (version mismatch?)
335	 * XXX is easy to provoke that way.  I've also seen, e.g.,
336	 * XXX     Exception exceptions.ImportError: 'No module named sha'
337	 * XXX         in <function callback at 0x008F5718> ignored
338	 * XXX but I'm unclear on exactly how that one happens.  In any case,
339	 * XXX I haven't seen a real-life report of either of these.
340         */
341	PyGC_Collect();
342
343	/* Destroy all modules */
344	PyImport_Cleanup();
345
346	/* Collect final garbage.  This disposes of cycles created by
347	 * new-style class definitions, for example.
348	 * XXX This is disabled because it caused too many problems.  If
349	 * XXX a __del__ or weakref callback triggers here, Python code has
350	 * XXX a hard time running, because even the sys module has been
351	 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
352	 * XXX One symptom is a sequence of information-free messages
353	 * XXX coming from threads (if a __del__ or callback is invoked,
354	 * XXX other threads can execute too, and any exception they encounter
355	 * XXX triggers a comedy of errors as subsystem after subsystem
356	 * XXX fails to find what it *expects* to find in sys to help report
357	 * XXX the exception and consequent unexpected failures).  I've also
358	 * XXX seen segfaults then, after adding print statements to the
359	 * XXX Python code getting called.
360	 */
361#if 0
362	PyGC_Collect();
363#endif
364
365	/* Destroy the database used by _PyImport_{Fixup,Find}Extension */
366	_PyImport_Fini();
367
368	/* Debugging stuff */
369#ifdef COUNT_ALLOCS
370	dump_counts();
371#endif
372
373#ifdef Py_REF_DEBUG
374	fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
375#endif
376
377#ifdef Py_TRACE_REFS
378	/* Display all objects still alive -- this can invoke arbitrary
379	 * __repr__ overrides, so requires a mostly-intact interpreter.
380	 * Alas, a lot of stuff may still be alive now that will be cleaned
381	 * up later.
382	 */
383	if (Py_GETENV("PYTHONDUMPREFS"))
384		_Py_PrintReferences(stderr);
385#endif /* Py_TRACE_REFS */
386
387	/* Now we decref the exception classes.  After this point nothing
388	   can raise an exception.  That's okay, because each Fini() method
389	   below has been checked to make sure no exceptions are ever
390	   raised.
391	*/
392	_PyExc_Fini();
393
394	/* Cleanup auto-thread-state */
395#ifdef WITH_THREAD
396	_PyGILState_Fini();
397#endif /* WITH_THREAD */
398
399	/* Clear interpreter state */
400	PyInterpreterState_Clear(interp);
401
402	/* Delete current thread */
403	PyThreadState_Swap(NULL);
404	PyInterpreterState_Delete(interp);
405
406	/* Sundry finalizers */
407	PyMethod_Fini();
408	PyFrame_Fini();
409	PyCFunction_Fini();
410	PyTuple_Fini();
411	PyString_Fini();
412	PyInt_Fini();
413	PyFloat_Fini();
414
415#ifdef Py_USING_UNICODE
416	/* Cleanup Unicode implementation */
417	_PyUnicode_Fini();
418#endif
419
420	/* XXX Still allocated:
421	   - various static ad-hoc pointers to interned strings
422	   - int and float free list blocks
423	   - whatever various modules and libraries allocate
424	*/
425
426	PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
427
428#ifdef Py_TRACE_REFS
429	/* Display addresses (& refcnts) of all objects still alive.
430	 * An address can be used to find the repr of the object, printed
431	 * above by _Py_PrintReferences.
432	 */
433	if (Py_GETENV("PYTHONDUMPREFS"))
434		_Py_PrintReferenceAddresses(stderr);
435#endif /* Py_TRACE_REFS */
436#ifdef PYMALLOC_DEBUG
437	if (Py_GETENV("PYTHONMALLOCSTATS"))
438		_PyObject_DebugMallocStats();
439#endif
440
441	call_ll_exitfuncs();
442}
443
444/* Create and initialize a new interpreter and thread, and return the
445   new thread.  This requires that Py_Initialize() has been called
446   first.
447
448   Unsuccessful initialization yields a NULL pointer.  Note that *no*
449   exception information is available even in this case -- the
450   exception information is held in the thread, and there is no
451   thread.
452
453   Locking: as above.
454
455*/
456
457PyThreadState *
458Py_NewInterpreter(void)
459{
460	PyInterpreterState *interp;
461	PyThreadState *tstate, *save_tstate;
462	PyObject *bimod, *sysmod;
463
464	if (!initialized)
465		Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
466
467	interp = PyInterpreterState_New();
468	if (interp == NULL)
469		return NULL;
470
471	tstate = PyThreadState_New(interp);
472	if (tstate == NULL) {
473		PyInterpreterState_Delete(interp);
474		return NULL;
475	}
476
477	save_tstate = PyThreadState_Swap(tstate);
478
479	/* XXX The following is lax in error checking */
480
481	interp->modules = PyDict_New();
482
483	bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
484	if (bimod != NULL) {
485		interp->builtins = PyModule_GetDict(bimod);
486		Py_INCREF(interp->builtins);
487	}
488	sysmod = _PyImport_FindExtension("sys", "sys");
489	if (bimod != NULL && sysmod != NULL) {
490		interp->sysdict = PyModule_GetDict(sysmod);
491		Py_INCREF(interp->sysdict);
492		PySys_SetPath(Py_GetPath());
493		PyDict_SetItemString(interp->sysdict, "modules",
494				     interp->modules);
495		_PyImportHooks_Init();
496		initmain();
497		if (!Py_NoSiteFlag)
498			initsite();
499	}
500
501	if (!PyErr_Occurred())
502		return tstate;
503
504	/* Oops, it didn't work.  Undo it all. */
505
506	PyErr_Print();
507	PyThreadState_Clear(tstate);
508	PyThreadState_Swap(save_tstate);
509	PyThreadState_Delete(tstate);
510	PyInterpreterState_Delete(interp);
511
512	return NULL;
513}
514
515/* Delete an interpreter and its last thread.  This requires that the
516   given thread state is current, that the thread has no remaining
517   frames, and that it is its interpreter's only remaining thread.
518   It is a fatal error to violate these constraints.
519
520   (Py_Finalize() doesn't have these constraints -- it zaps
521   everything, regardless.)
522
523   Locking: as above.
524
525*/
526
527void
528Py_EndInterpreter(PyThreadState *tstate)
529{
530	PyInterpreterState *interp = tstate->interp;
531
532	if (tstate != PyThreadState_GET())
533		Py_FatalError("Py_EndInterpreter: thread is not current");
534	if (tstate->frame != NULL)
535		Py_FatalError("Py_EndInterpreter: thread still has a frame");
536	if (tstate != interp->tstate_head || tstate->next != NULL)
537		Py_FatalError("Py_EndInterpreter: not the last thread");
538
539	PyImport_Cleanup();
540	PyInterpreterState_Clear(interp);
541	PyThreadState_Swap(NULL);
542	PyInterpreterState_Delete(interp);
543}
544
545static char *progname = "python";
546
547void
548Py_SetProgramName(char *pn)
549{
550	if (pn && *pn)
551		progname = pn;
552}
553
554char *
555Py_GetProgramName(void)
556{
557	return progname;
558}
559
560static char *default_home = NULL;
561
562void
563Py_SetPythonHome(char *home)
564{
565	default_home = home;
566}
567
568char *
569Py_GetPythonHome(void)
570{
571	char *home = default_home;
572	if (home == NULL && !Py_IgnoreEnvironmentFlag)
573		home = Py_GETENV("PYTHONHOME");
574	return home;
575}
576
577/* Create __main__ module */
578
579static void
580initmain(void)
581{
582	PyObject *m, *d;
583	m = PyImport_AddModule("__main__");
584	if (m == NULL)
585		Py_FatalError("can't create __main__ module");
586	d = PyModule_GetDict(m);
587	if (PyDict_GetItemString(d, "__builtins__") == NULL) {
588		PyObject *bimod = PyImport_ImportModule("__builtin__");
589		if (bimod == NULL ||
590		    PyDict_SetItemString(d, "__builtins__", bimod) != 0)
591			Py_FatalError("can't add __builtins__ to __main__");
592		Py_DECREF(bimod);
593	}
594}
595
596/* Import the site module (not into __main__ though) */
597
598static void
599initsite(void)
600{
601	PyObject *m, *f;
602	m = PyImport_ImportModule("site");
603	if (m == NULL) {
604		f = PySys_GetObject("stderr");
605		if (Py_VerboseFlag) {
606			PyFile_WriteString(
607				"'import site' failed; traceback:\n", f);
608			PyErr_Print();
609		}
610		else {
611			PyFile_WriteString(
612			  "'import site' failed; use -v for traceback\n", f);
613			PyErr_Clear();
614		}
615	}
616	else {
617		Py_DECREF(m);
618	}
619}
620
621/* Parse input from a file and execute it */
622
623int
624PyRun_AnyFile(FILE *fp, const char *filename)
625{
626	return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
627}
628
629int
630PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
631{
632	return PyRun_AnyFileExFlags(fp, filename, 0, flags);
633}
634
635int
636PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
637{
638	return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
639}
640
641int
642PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
643		     PyCompilerFlags *flags)
644{
645	if (filename == NULL)
646		filename = "???";
647	if (Py_FdIsInteractive(fp, filename)) {
648		int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
649		if (closeit)
650			fclose(fp);
651		return err;
652	}
653	else
654		return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
655}
656
657int
658PyRun_InteractiveLoop(FILE *fp, const char *filename)
659{
660	return PyRun_InteractiveLoopFlags(fp, filename, NULL);
661}
662
663int
664PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
665{
666	PyObject *v;
667	int ret;
668	PyCompilerFlags local_flags;
669
670	if (flags == NULL) {
671		flags = &local_flags;
672		local_flags.cf_flags = 0;
673	}
674	v = PySys_GetObject("ps1");
675	if (v == NULL) {
676		PySys_SetObject("ps1", v = PyString_FromString(">>> "));
677		Py_XDECREF(v);
678	}
679	v = PySys_GetObject("ps2");
680	if (v == NULL) {
681		PySys_SetObject("ps2", v = PyString_FromString("... "));
682		Py_XDECREF(v);
683	}
684	for (;;) {
685		ret = PyRun_InteractiveOneFlags(fp, filename, flags);
686#ifdef Py_REF_DEBUG
687		fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
688#endif
689		if (ret == E_EOF)
690			return 0;
691		/*
692		if (ret == E_NOMEM)
693			return -1;
694		*/
695	}
696}
697
698int
699PyRun_InteractiveOne(FILE *fp, const char *filename)
700{
701	return PyRun_InteractiveOneFlags(fp, filename, NULL);
702}
703
704/* compute parser flags based on compiler flags */
705#define PARSER_FLAGS(flags) \
706	(((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
707		PyPARSE_DONT_IMPLY_DEDENT : 0)
708
709int
710PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
711{
712	PyObject *m, *d, *v, *w;
713	node *n;
714	perrdetail err;
715	char *ps1 = "", *ps2 = "";
716
717	v = PySys_GetObject("ps1");
718	if (v != NULL) {
719		v = PyObject_Str(v);
720		if (v == NULL)
721			PyErr_Clear();
722		else if (PyString_Check(v))
723			ps1 = PyString_AsString(v);
724	}
725	w = PySys_GetObject("ps2");
726	if (w != NULL) {
727		w = PyObject_Str(w);
728		if (w == NULL)
729			PyErr_Clear();
730		else if (PyString_Check(w))
731			ps2 = PyString_AsString(w);
732	}
733	n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
734			    	    Py_single_input, ps1, ps2, &err,
735			    	    PARSER_FLAGS(flags));
736	Py_XDECREF(v);
737	Py_XDECREF(w);
738	if (n == NULL) {
739		if (err.error == E_EOF) {
740			if (err.text)
741				PyMem_DEL(err.text);
742			return E_EOF;
743		}
744		err_input(&err);
745		PyErr_Print();
746		return err.error;
747	}
748	m = PyImport_AddModule("__main__");
749	if (m == NULL)
750		return -1;
751	d = PyModule_GetDict(m);
752	v = run_node(n, filename, d, d, flags);
753	if (v == NULL) {
754		PyErr_Print();
755		return -1;
756	}
757	Py_DECREF(v);
758	if (Py_FlushLine())
759		PyErr_Clear();
760	return 0;
761}
762
763int
764PyRun_SimpleFile(FILE *fp, const char *filename)
765{
766	return PyRun_SimpleFileEx(fp, filename, 0);
767}
768
769/* Check whether a file maybe a pyc file: Look at the extension,
770   the file type, and, if we may close it, at the first few bytes. */
771
772static int
773maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
774{
775	if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
776		return 1;
777
778	/* Only look into the file if we are allowed to close it, since
779	   it then should also be seekable. */
780	if (closeit) {
781		/* Read only two bytes of the magic. If the file was opened in
782		   text mode, the bytes 3 and 4 of the magic (\r\n) might not
783		   be read as they are on disk. */
784		unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
785		unsigned char buf[2];
786		/* Mess:  In case of -x, the stream is NOT at its start now,
787		   and ungetc() was used to push back the first newline,
788		   which makes the current stream position formally undefined,
789		   and a x-platform nightmare.
790		   Unfortunately, we have no direct way to know whether -x
791		   was specified.  So we use a terrible hack:  if the current
792		   stream position is not 0, we assume -x was specified, and
793		   give up.  Bug 132850 on SourceForge spells out the
794		   hopelessness of trying anything else (fseek and ftell
795		   don't work predictably x-platform for text-mode files).
796		*/
797		int ispyc = 0;
798		if (ftell(fp) == 0) {
799			if (fread(buf, 1, 2, fp) == 2 &&
800			    ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
801				ispyc = 1;
802			rewind(fp);
803		}
804		return ispyc;
805	}
806	return 0;
807}
808
809int
810PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
811{
812	return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
813}
814
815int
816PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
817			PyCompilerFlags *flags)
818{
819	PyObject *m, *d, *v;
820	const char *ext;
821
822	m = PyImport_AddModule("__main__");
823	if (m == NULL)
824		return -1;
825	d = PyModule_GetDict(m);
826	if (PyDict_GetItemString(d, "__file__") == NULL) {
827		PyObject *f = PyString_FromString(filename);
828		if (f == NULL)
829			return -1;
830		if (PyDict_SetItemString(d, "__file__", f) < 0) {
831			Py_DECREF(f);
832			return -1;
833		}
834		Py_DECREF(f);
835	}
836	ext = filename + strlen(filename) - 4;
837	if (maybe_pyc_file(fp, filename, ext, closeit)) {
838		/* Try to run a pyc file. First, re-open in binary */
839		if (closeit)
840			fclose(fp);
841		if ((fp = fopen(filename, "rb")) == NULL) {
842			fprintf(stderr, "python: Can't reopen .pyc file\n");
843			return -1;
844		}
845		/* Turn on optimization if a .pyo file is given */
846		if (strcmp(ext, ".pyo") == 0)
847			Py_OptimizeFlag = 1;
848		v = run_pyc_file(fp, filename, d, d, flags);
849	} else {
850		v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
851				      closeit, flags);
852	}
853	if (v == NULL) {
854		PyErr_Print();
855		return -1;
856	}
857	Py_DECREF(v);
858	if (Py_FlushLine())
859		PyErr_Clear();
860	return 0;
861}
862
863int
864PyRun_SimpleString(const char *command)
865{
866	return PyRun_SimpleStringFlags(command, NULL);
867}
868
869int
870PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
871{
872	PyObject *m, *d, *v;
873	m = PyImport_AddModule("__main__");
874	if (m == NULL)
875		return -1;
876	d = PyModule_GetDict(m);
877	v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
878	if (v == NULL) {
879		PyErr_Print();
880		return -1;
881	}
882	Py_DECREF(v);
883	if (Py_FlushLine())
884		PyErr_Clear();
885	return 0;
886}
887
888static int
889parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
890		   int *lineno, int *offset, const char **text)
891{
892	long hold;
893	PyObject *v;
894
895	/* old style errors */
896	if (PyTuple_Check(err))
897		return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
898				        lineno, offset, text);
899
900	/* new style errors.  `err' is an instance */
901
902	if (! (v = PyObject_GetAttrString(err, "msg")))
903		goto finally;
904	*message = v;
905
906	if (!(v = PyObject_GetAttrString(err, "filename")))
907		goto finally;
908	if (v == Py_None)
909		*filename = NULL;
910	else if (! (*filename = PyString_AsString(v)))
911		goto finally;
912
913	Py_DECREF(v);
914	if (!(v = PyObject_GetAttrString(err, "lineno")))
915		goto finally;
916	hold = PyInt_AsLong(v);
917	Py_DECREF(v);
918	v = NULL;
919	if (hold < 0 && PyErr_Occurred())
920		goto finally;
921	*lineno = (int)hold;
922
923	if (!(v = PyObject_GetAttrString(err, "offset")))
924		goto finally;
925	if (v == Py_None) {
926		*offset = -1;
927		Py_DECREF(v);
928		v = NULL;
929	} else {
930		hold = PyInt_AsLong(v);
931		Py_DECREF(v);
932		v = NULL;
933		if (hold < 0 && PyErr_Occurred())
934			goto finally;
935		*offset = (int)hold;
936	}
937
938	if (!(v = PyObject_GetAttrString(err, "text")))
939		goto finally;
940	if (v == Py_None)
941		*text = NULL;
942	else if (! (*text = PyString_AsString(v)))
943		goto finally;
944	Py_DECREF(v);
945	return 1;
946
947finally:
948	Py_XDECREF(v);
949	return 0;
950}
951
952void
953PyErr_Print(void)
954{
955	PyErr_PrintEx(1);
956}
957
958static void
959print_error_text(PyObject *f, int offset, const char *text)
960{
961	char *nl;
962	if (offset >= 0) {
963		if (offset > 0 && offset == (int)strlen(text))
964			offset--;
965		for (;;) {
966			nl = strchr(text, '\n');
967			if (nl == NULL || nl-text >= offset)
968				break;
969			offset -= (nl+1-text);
970			text = nl+1;
971		}
972		while (*text == ' ' || *text == '\t') {
973			text++;
974			offset--;
975		}
976	}
977	PyFile_WriteString("    ", f);
978	PyFile_WriteString(text, f);
979	if (*text == '\0' || text[strlen(text)-1] != '\n')
980		PyFile_WriteString("\n", f);
981	if (offset == -1)
982		return;
983	PyFile_WriteString("    ", f);
984	offset--;
985	while (offset > 0) {
986		PyFile_WriteString(" ", f);
987		offset--;
988	}
989	PyFile_WriteString("^\n", f);
990}
991
992static void
993handle_system_exit(void)
994{
995        PyObject *exception, *value, *tb;
996        int exitcode = 0;
997
998	PyErr_Fetch(&exception, &value, &tb);
999	if (Py_FlushLine())
1000		PyErr_Clear();
1001	fflush(stdout);
1002	if (value == NULL || value == Py_None)
1003		goto done;
1004	if (PyInstance_Check(value)) {
1005		/* The error code should be in the `code' attribute. */
1006		PyObject *code = PyObject_GetAttrString(value, "code");
1007		if (code) {
1008			Py_DECREF(value);
1009			value = code;
1010			if (value == Py_None)
1011				goto done;
1012		}
1013		/* If we failed to dig out the 'code' attribute,
1014		   just let the else clause below print the error. */
1015	}
1016	if (PyInt_Check(value))
1017		exitcode = (int)PyInt_AsLong(value);
1018	else {
1019		PyObject_Print(value, stderr, Py_PRINT_RAW);
1020		PySys_WriteStderr("\n");
1021		exitcode = 1;
1022	}
1023 done:
1024 	/* Restore and clear the exception info, in order to properly decref
1025 	 * the exception, value, and traceback.  If we just exit instead,
1026 	 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1027 	 * some finalizers from running.
1028 	 */
1029	PyErr_Restore(exception, value, tb);
1030	PyErr_Clear();
1031	Py_Exit(exitcode);
1032	/* NOTREACHED */
1033}
1034
1035void
1036PyErr_PrintEx(int set_sys_last_vars)
1037{
1038	PyObject *exception, *v, *tb, *hook;
1039
1040	if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1041		handle_system_exit();
1042	}
1043	PyErr_Fetch(&exception, &v, &tb);
1044	PyErr_NormalizeException(&exception, &v, &tb);
1045	if (exception == NULL)
1046		return;
1047	if (set_sys_last_vars) {
1048		PySys_SetObject("last_type", exception);
1049		PySys_SetObject("last_value", v);
1050		PySys_SetObject("last_traceback", tb);
1051	}
1052	hook = PySys_GetObject("excepthook");
1053	if (hook) {
1054		PyObject *args = PyTuple_Pack(3,
1055                    exception, v ? v : Py_None, tb ? tb : Py_None);
1056		PyObject *result = PyEval_CallObject(hook, args);
1057		if (result == NULL) {
1058			PyObject *exception2, *v2, *tb2;
1059			if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1060				handle_system_exit();
1061			}
1062			PyErr_Fetch(&exception2, &v2, &tb2);
1063			PyErr_NormalizeException(&exception2, &v2, &tb2);
1064			if (Py_FlushLine())
1065				PyErr_Clear();
1066			fflush(stdout);
1067			PySys_WriteStderr("Error in sys.excepthook:\n");
1068			PyErr_Display(exception2, v2, tb2);
1069			PySys_WriteStderr("\nOriginal exception was:\n");
1070			PyErr_Display(exception, v, tb);
1071			Py_XDECREF(exception2);
1072			Py_XDECREF(v2);
1073			Py_XDECREF(tb2);
1074		}
1075		Py_XDECREF(result);
1076		Py_XDECREF(args);
1077	} else {
1078		PySys_WriteStderr("sys.excepthook is missing\n");
1079		PyErr_Display(exception, v, tb);
1080	}
1081	Py_XDECREF(exception);
1082	Py_XDECREF(v);
1083	Py_XDECREF(tb);
1084}
1085
1086void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1087{
1088	int err = 0;
1089	PyObject *f = PySys_GetObject("stderr");
1090	Py_INCREF(value);
1091	if (f == NULL)
1092		fprintf(stderr, "lost sys.stderr\n");
1093	else {
1094		if (Py_FlushLine())
1095			PyErr_Clear();
1096		fflush(stdout);
1097		if (tb && tb != Py_None)
1098			err = PyTraceBack_Print(tb, f);
1099		if (err == 0 &&
1100		    PyObject_HasAttrString(value, "print_file_and_line"))
1101		{
1102			PyObject *message;
1103			const char *filename, *text;
1104			int lineno, offset;
1105			if (!parse_syntax_error(value, &message, &filename,
1106						&lineno, &offset, &text))
1107				PyErr_Clear();
1108			else {
1109				char buf[10];
1110				PyFile_WriteString("  File \"", f);
1111				if (filename == NULL)
1112					PyFile_WriteString("<string>", f);
1113				else
1114					PyFile_WriteString(filename, f);
1115				PyFile_WriteString("\", line ", f);
1116				PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1117				PyFile_WriteString(buf, f);
1118				PyFile_WriteString("\n", f);
1119				if (text != NULL)
1120					print_error_text(f, offset, text);
1121				Py_DECREF(value);
1122				value = message;
1123				/* Can't be bothered to check all those
1124				   PyFile_WriteString() calls */
1125				if (PyErr_Occurred())
1126					err = -1;
1127			}
1128		}
1129		if (err) {
1130			/* Don't do anything else */
1131		}
1132		else if (PyClass_Check(exception)) {
1133			PyClassObject* exc = (PyClassObject*)exception;
1134			PyObject* className = exc->cl_name;
1135			PyObject* moduleName =
1136			      PyDict_GetItemString(exc->cl_dict, "__module__");
1137
1138			if (moduleName == NULL)
1139				err = PyFile_WriteString("<unknown>", f);
1140			else {
1141				char* modstr = PyString_AsString(moduleName);
1142				if (modstr && strcmp(modstr, "exceptions"))
1143				{
1144					err = PyFile_WriteString(modstr, f);
1145					err += PyFile_WriteString(".", f);
1146				}
1147			}
1148			if (err == 0) {
1149				if (className == NULL)
1150				      err = PyFile_WriteString("<unknown>", f);
1151				else
1152				      err = PyFile_WriteObject(className, f,
1153							       Py_PRINT_RAW);
1154			}
1155		}
1156		else
1157			err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1158		if (err == 0) {
1159			if (value != Py_None) {
1160				PyObject *s = PyObject_Str(value);
1161				/* only print colon if the str() of the
1162				   object is not the empty string
1163				*/
1164				if (s == NULL)
1165					err = -1;
1166				else if (!PyString_Check(s) ||
1167					 PyString_GET_SIZE(s) != 0)
1168					err = PyFile_WriteString(": ", f);
1169				if (err == 0)
1170				  err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1171				Py_XDECREF(s);
1172			}
1173		}
1174		if (err == 0)
1175			err = PyFile_WriteString("\n", f);
1176	}
1177	Py_DECREF(value);
1178	/* If an error happened here, don't show it.
1179	   XXX This is wrong, but too many callers rely on this behavior. */
1180	if (err != 0)
1181		PyErr_Clear();
1182}
1183
1184PyObject *
1185PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
1186{
1187	return run_err_node(PyParser_SimpleParseString(str, start),
1188			    "<string>", globals, locals, NULL);
1189}
1190
1191PyObject *
1192PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
1193	   PyObject *locals)
1194{
1195	return PyRun_FileEx(fp, filename, start, globals, locals, 0);
1196}
1197
1198PyObject *
1199PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
1200	     PyObject *locals, int closeit)
1201{
1202	node *n = PyParser_SimpleParseFile(fp, filename, start);
1203	if (closeit)
1204		fclose(fp);
1205	return run_err_node(n, filename, globals, locals, NULL);
1206}
1207
1208PyObject *
1209PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
1210		  PyCompilerFlags *flags)
1211{
1212	return run_err_node(PyParser_SimpleParseStringFlags(
1213				    str, start, PARSER_FLAGS(flags)),
1214			    "<string>", globals, locals, flags);
1215}
1216
1217PyObject *
1218PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1219		PyObject *locals, PyCompilerFlags *flags)
1220{
1221	return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1222				 flags);
1223}
1224
1225PyObject *
1226PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1227		  PyObject *locals, int closeit, PyCompilerFlags *flags)
1228{
1229	node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
1230						PARSER_FLAGS(flags));
1231	if (closeit)
1232		fclose(fp);
1233	return run_err_node(n, filename, globals, locals, flags);
1234}
1235
1236static PyObject *
1237run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
1238	     PyCompilerFlags *flags)
1239{
1240	if (n == NULL)
1241		return  NULL;
1242	return run_node(n, filename, globals, locals, flags);
1243}
1244
1245static PyObject *
1246run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
1247	 PyCompilerFlags *flags)
1248{
1249	PyCodeObject *co;
1250	PyObject *v;
1251	co = PyNode_CompileFlags(n, filename, flags);
1252	PyNode_Free(n);
1253	if (co == NULL)
1254		return NULL;
1255	v = PyEval_EvalCode(co, globals, locals);
1256	Py_DECREF(co);
1257	return v;
1258}
1259
1260static PyObject *
1261run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
1262	     PyCompilerFlags *flags)
1263{
1264	PyCodeObject *co;
1265	PyObject *v;
1266	long magic;
1267	long PyImport_GetMagicNumber(void);
1268
1269	magic = PyMarshal_ReadLongFromFile(fp);
1270	if (magic != PyImport_GetMagicNumber()) {
1271		PyErr_SetString(PyExc_RuntimeError,
1272			   "Bad magic number in .pyc file");
1273		return NULL;
1274	}
1275	(void) PyMarshal_ReadLongFromFile(fp);
1276	v = PyMarshal_ReadLastObjectFromFile(fp);
1277	fclose(fp);
1278	if (v == NULL || !PyCode_Check(v)) {
1279		Py_XDECREF(v);
1280		PyErr_SetString(PyExc_RuntimeError,
1281			   "Bad code object in .pyc file");
1282		return NULL;
1283	}
1284	co = (PyCodeObject *)v;
1285	v = PyEval_EvalCode(co, globals, locals);
1286	if (v && flags)
1287		flags->cf_flags |= (co->co_flags & PyCF_MASK);
1288	Py_DECREF(co);
1289	return v;
1290}
1291
1292PyObject *
1293Py_CompileString(const char *str, const char *filename, int start)
1294{
1295	return Py_CompileStringFlags(str, filename, start, NULL);
1296}
1297
1298PyObject *
1299Py_CompileStringFlags(const char *str, const char *filename, int start,
1300		      PyCompilerFlags *flags)
1301{
1302	node *n;
1303	PyCodeObject *co;
1304
1305	n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1306						    PARSER_FLAGS(flags));
1307	if (n == NULL)
1308		return NULL;
1309	co = PyNode_CompileFlags(n, filename, flags);
1310	PyNode_Free(n);
1311	return (PyObject *)co;
1312}
1313
1314struct symtable *
1315Py_SymtableString(const char *str, const char *filename, int start)
1316{
1317	node *n;
1318	struct symtable *st;
1319	n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1320						    start, 0);
1321	if (n == NULL)
1322		return NULL;
1323	st = PyNode_CompileSymtable(n, filename);
1324	PyNode_Free(n);
1325	return st;
1326}
1327
1328/* Simplified interface to parsefile -- return node or set exception */
1329
1330node *
1331PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
1332{
1333	node *n;
1334	perrdetail err;
1335	n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1336					(char *)0, (char *)0, &err, flags);
1337	if (n == NULL)
1338		err_input(&err);
1339	return n;
1340}
1341
1342node *
1343PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1344{
1345	return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1346}
1347
1348/* Simplified interface to parsestring -- return node or set exception */
1349
1350node *
1351PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
1352{
1353	node *n;
1354	perrdetail err;
1355	n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1356				      flags);
1357	if (n == NULL)
1358		err_input(&err);
1359	return n;
1360}
1361
1362node *
1363PyParser_SimpleParseString(const char *str, int start)
1364{
1365	return PyParser_SimpleParseStringFlags(str, start, 0);
1366}
1367
1368node *
1369PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
1370					int start, int flags)
1371{
1372	node *n;
1373	perrdetail err;
1374
1375	n = PyParser_ParseStringFlagsFilename(str, filename,
1376					      &_PyParser_Grammar,
1377					      start, &err, flags);
1378	if (n == NULL)
1379		err_input(&err);
1380	return n;
1381}
1382
1383node *
1384PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
1385{
1386	return PyParser_SimpleParseStringFlagsFilename(str, filename,
1387						       start, 0);
1388}
1389
1390/* May want to move a more generalized form of this to parsetok.c or
1391   even parser modules. */
1392
1393void
1394PyParser_SetError(perrdetail *err)
1395{
1396	err_input(err);
1397}
1398
1399/* Set the error appropriate to the given input error code (see errcode.h) */
1400
1401static void
1402err_input(perrdetail *err)
1403{
1404	PyObject *v, *w, *errtype;
1405	PyObject* u = NULL;
1406	char *msg = NULL;
1407	errtype = PyExc_SyntaxError;
1408	v = Py_BuildValue("(ziiz)", err->filename,
1409			    err->lineno, err->offset, err->text);
1410	if (err->text != NULL) {
1411		PyMem_DEL(err->text);
1412		err->text = NULL;
1413	}
1414	switch (err->error) {
1415	case E_SYNTAX:
1416		errtype = PyExc_IndentationError;
1417		if (err->expected == INDENT)
1418			msg = "expected an indented block";
1419		else if (err->token == INDENT)
1420			msg = "unexpected indent";
1421		else if (err->token == DEDENT)
1422			msg = "unexpected unindent";
1423		else {
1424			errtype = PyExc_SyntaxError;
1425			msg = "invalid syntax";
1426		}
1427		break;
1428	case E_TOKEN:
1429		msg = "invalid token";
1430		break;
1431	case E_EOFS:
1432		msg = "EOF while scanning triple-quoted string";
1433		break;
1434	case E_EOLS:
1435		msg = "EOL while scanning single-quoted string";
1436		break;
1437	case E_INTR:
1438		if (!PyErr_Occurred())
1439			PyErr_SetNone(PyExc_KeyboardInterrupt);
1440		Py_XDECREF(v);
1441		return;
1442	case E_NOMEM:
1443		PyErr_NoMemory();
1444		Py_XDECREF(v);
1445		return;
1446	case E_EOF:
1447		msg = "unexpected EOF while parsing";
1448		break;
1449	case E_TABSPACE:
1450		errtype = PyExc_TabError;
1451		msg = "inconsistent use of tabs and spaces in indentation";
1452		break;
1453	case E_OVERFLOW:
1454		msg = "expression too long";
1455		break;
1456	case E_DEDENT:
1457		errtype = PyExc_IndentationError;
1458		msg = "unindent does not match any outer indentation level";
1459		break;
1460	case E_TOODEEP:
1461		errtype = PyExc_IndentationError;
1462		msg = "too many levels of indentation";
1463		break;
1464	case E_DECODE: {	/* XXX */
1465		PyThreadState* tstate = PyThreadState_GET();
1466		PyObject* value = tstate->curexc_value;
1467		if (value != NULL) {
1468			u = PyObject_Repr(value);
1469			if (u != NULL) {
1470				msg = PyString_AsString(u);
1471				break;
1472			}
1473		}
1474		if (msg == NULL)
1475			msg = "unknown decode error";
1476		break;
1477	}
1478	default:
1479		fprintf(stderr, "error=%d\n", err->error);
1480		msg = "unknown parsing error";
1481		break;
1482	}
1483	w = Py_BuildValue("(sO)", msg, v);
1484	Py_XDECREF(u);
1485	Py_XDECREF(v);
1486	PyErr_SetObject(errtype, w);
1487	Py_XDECREF(w);
1488}
1489
1490/* Print fatal error message and abort */
1491
1492void
1493Py_FatalError(const char *msg)
1494{
1495	fprintf(stderr, "Fatal Python error: %s\n", msg);
1496#ifdef MS_WINDOWS
1497	OutputDebugString("Fatal Python error: ");
1498	OutputDebugString(msg);
1499	OutputDebugString("\n");
1500#ifdef _DEBUG
1501	DebugBreak();
1502#endif
1503#endif /* MS_WINDOWS */
1504	abort();
1505}
1506
1507/* Clean up and exit */
1508
1509#ifdef WITH_THREAD
1510#include "pythread.h"
1511int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
1512#endif
1513
1514#define NEXITFUNCS 32
1515static void (*exitfuncs[NEXITFUNCS])(void);
1516static int nexitfuncs = 0;
1517
1518int Py_AtExit(void (*func)(void))
1519{
1520	if (nexitfuncs >= NEXITFUNCS)
1521		return -1;
1522	exitfuncs[nexitfuncs++] = func;
1523	return 0;
1524}
1525
1526static void
1527call_sys_exitfunc(void)
1528{
1529	PyObject *exitfunc = PySys_GetObject("exitfunc");
1530
1531	if (exitfunc) {
1532		PyObject *res;
1533		Py_INCREF(exitfunc);
1534		PySys_SetObject("exitfunc", (PyObject *)NULL);
1535		res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1536		if (res == NULL) {
1537			if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1538				PySys_WriteStderr("Error in sys.exitfunc:\n");
1539			}
1540			PyErr_Print();
1541		}
1542		Py_DECREF(exitfunc);
1543	}
1544
1545	if (Py_FlushLine())
1546		PyErr_Clear();
1547}
1548
1549static void
1550call_ll_exitfuncs(void)
1551{
1552	while (nexitfuncs > 0)
1553		(*exitfuncs[--nexitfuncs])();
1554
1555	fflush(stdout);
1556	fflush(stderr);
1557}
1558
1559void
1560Py_Exit(int sts)
1561{
1562	Py_Finalize();
1563
1564	exit(sts);
1565}
1566
1567static void
1568initsigs(void)
1569{
1570#ifdef SIGPIPE
1571	signal(SIGPIPE, SIG_IGN);
1572#endif
1573#ifdef SIGXFZ
1574	signal(SIGXFZ, SIG_IGN);
1575#endif
1576#ifdef SIGXFSZ
1577	signal(SIGXFSZ, SIG_IGN);
1578#endif
1579	PyOS_InitInterrupts(); /* May imply initsignal() */
1580}
1581
1582
1583/*
1584 * The file descriptor fd is considered ``interactive'' if either
1585 *   a) isatty(fd) is TRUE, or
1586 *   b) the -i flag was given, and the filename associated with
1587 *      the descriptor is NULL or "<stdin>" or "???".
1588 */
1589int
1590Py_FdIsInteractive(FILE *fp, const char *filename)
1591{
1592	if (isatty((int)fileno(fp)))
1593		return 1;
1594	if (!Py_InteractiveFlag)
1595		return 0;
1596	return (filename == NULL) ||
1597	       (strcmp(filename, "<stdin>") == 0) ||
1598	       (strcmp(filename, "???") == 0);
1599}
1600
1601
1602#if defined(USE_STACKCHECK)
1603#if defined(WIN32) && defined(_MSC_VER)
1604
1605/* Stack checking for Microsoft C */
1606
1607#include <malloc.h>
1608#include <excpt.h>
1609
1610/*
1611 * Return non-zero when we run out of memory on the stack; zero otherwise.
1612 */
1613int
1614PyOS_CheckStack(void)
1615{
1616	__try {
1617		/* alloca throws a stack overflow exception if there's
1618		   not enough space left on the stack */
1619		alloca(PYOS_STACK_MARGIN * sizeof(void*));
1620		return 0;
1621	} __except (EXCEPTION_EXECUTE_HANDLER) {
1622		/* just ignore all errors */
1623	}
1624	return 1;
1625}
1626
1627#endif /* WIN32 && _MSC_VER */
1628
1629/* Alternate implementations can be added here... */
1630
1631#endif /* USE_STACKCHECK */
1632
1633
1634/* Wrappers around sigaction() or signal(). */
1635
1636PyOS_sighandler_t
1637PyOS_getsig(int sig)
1638{
1639#ifdef HAVE_SIGACTION
1640	struct sigaction context;
1641	/* Initialize context.sa_handler to SIG_ERR which makes about as
1642	 * much sense as anything else.  It should get overwritten if
1643	 * sigaction actually succeeds and otherwise we avoid an
1644	 * uninitialized memory read.
1645	 */
1646	context.sa_handler = SIG_ERR;
1647	sigaction(sig, NULL, &context);
1648	return context.sa_handler;
1649#else
1650	PyOS_sighandler_t handler;
1651	handler = signal(sig, SIG_IGN);
1652	signal(sig, handler);
1653	return handler;
1654#endif
1655}
1656
1657PyOS_sighandler_t
1658PyOS_setsig(int sig, PyOS_sighandler_t handler)
1659{
1660#ifdef HAVE_SIGACTION
1661	struct sigaction context;
1662	PyOS_sighandler_t oldhandler;
1663	/* Initialize context.sa_handler to SIG_ERR which makes about as
1664	 * much sense as anything else.  It should get overwritten if
1665	 * sigaction actually succeeds and otherwise we avoid an
1666	 * uninitialized memory read.
1667	 */
1668	context.sa_handler = SIG_ERR;
1669	sigaction(sig, NULL, &context);
1670	oldhandler = context.sa_handler;
1671	context.sa_handler = handler;
1672	sigaction(sig, &context, NULL);
1673	return oldhandler;
1674#else
1675	return signal(sig, handler);
1676#endif
1677}
1678