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