2 /* Python interpreter top-level routines, including init/exit */
6 #include "Python-ast.h"
7 #undef Yield /* undefine macro conflicting with winbase.h */
28 #include "malloc.h" /* for alloca */
31 #ifdef HAVE_LANGINFO_H
39 #define PATH_MAX MAXPATHLEN
43 #define PRINT_TOTAL_REFS()
44 #else /* Py_REF_DEBUG */
45 #define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
54 extern wchar_t *Py_GetPath(void);
56 extern grammar _PyParser_Grammar
; /* From graminit.c */
59 static void initmain(void);
60 static void initsite(void);
61 static int initstdio(void);
62 static void flush_io(void);
63 static PyObject
*run_mod(mod_ty
, const char *, PyObject
*, PyObject
*,
64 PyCompilerFlags
*, PyArena
*);
65 static PyObject
*run_pyc_file(FILE *, const char *, PyObject
*, PyObject
*,
67 static void err_input(perrdetail
*);
68 static void initsigs(void);
69 static void call_py_exitfuncs(void);
70 static void wait_for_thread_shutdown(void);
71 static void call_ll_exitfuncs(void);
72 extern void _PyUnicode_Init(void);
73 extern void _PyUnicode_Fini(void);
74 extern int _PyLong_Init(void);
75 extern void PyLong_Fini(void);
78 extern void _PyGILState_Init(PyInterpreterState
*, PyThreadState
*);
79 extern void _PyGILState_Fini(void);
80 #endif /* WITH_THREAD */
82 int Py_DebugFlag
; /* Needed by parser.c */
83 int Py_VerboseFlag
; /* Needed by import.c */
84 int Py_InteractiveFlag
; /* Needed by Py_FdIsInteractive() below */
85 int Py_InspectFlag
; /* Needed to determine whether to exit at SystemError */
86 int Py_NoSiteFlag
; /* Suppress 'import site' */
87 int Py_BytesWarningFlag
; /* Warn on str(bytes) and str(buffer) */
88 int Py_DontWriteBytecodeFlag
; /* Suppress writing bytecode files (*.py[co]) */
89 int Py_UseClassExceptionsFlag
= 1; /* Needed by bltinmodule.c: deprecated */
90 int Py_FrozenFlag
; /* Needed by getpath.c */
91 int Py_IgnoreEnvironmentFlag
; /* e.g. PYTHONPATH, PYTHONHOME */
92 int Py_NoUserSiteDirectory
= 0; /* for -s and site.py */
93 int Py_UnbufferedStdioFlag
= 0; /* Unbuffered binary std{in,out,err} */
95 /* PyModule_GetWarningsModule is no longer necessary as of 2.6
96 since _warnings is builtin. This API should not be used. */
98 PyModule_GetWarningsModule(void)
100 return PyImport_ImportModule("warnings");
103 static int initialized
= 0;
105 /* API to access the initialized flag -- useful for esoteric use */
108 Py_IsInitialized(void)
113 /* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
126 add_flag(int flag
, const char *envs
)
128 int env
= atoi(envs
);
136 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
141 PyObject
*codec
, *name
;
143 codeset
= nl_langinfo(CODESET
);
144 if (!codeset
|| codeset
[0] == '\0')
147 codec
= _PyCodec_Lookup(codeset
);
151 name
= PyObject_GetAttrString(codec
, "name");
156 codeset
= strdup(_PyUnicode_AsString(name
));
168 Py_InitializeEx(int install_sigs
)
170 PyInterpreterState
*interp
;
171 PyThreadState
*tstate
;
172 PyObject
*bimod
, *sysmod
, *pstderr
;
174 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
177 extern void _Py_ReadyTypes(void);
183 #ifdef HAVE_SETLOCALE
184 /* Set up the LC_CTYPE locale, so we can obtain
185 the locale's charset without having to switch
187 setlocale(LC_CTYPE
, "");
190 if ((p
= Py_GETENV("PYTHONDEBUG")) && *p
!= '\0')
191 Py_DebugFlag
= add_flag(Py_DebugFlag
, p
);
192 if ((p
= Py_GETENV("PYTHONVERBOSE")) && *p
!= '\0')
193 Py_VerboseFlag
= add_flag(Py_VerboseFlag
, p
);
194 if ((p
= Py_GETENV("PYTHONOPTIMIZE")) && *p
!= '\0')
195 Py_OptimizeFlag
= add_flag(Py_OptimizeFlag
, p
);
196 if ((p
= Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p
!= '\0')
197 Py_DontWriteBytecodeFlag
= add_flag(Py_DontWriteBytecodeFlag
, p
);
199 interp
= PyInterpreterState_New();
201 Py_FatalError("Py_Initialize: can't make first interpreter");
203 tstate
= PyThreadState_New(interp
);
205 Py_FatalError("Py_Initialize: can't make first thread");
206 (void) PyThreadState_Swap(tstate
);
210 if (!_PyFrame_Init())
211 Py_FatalError("Py_Initialize: can't init frames");
214 Py_FatalError("Py_Initialize: can't init longs");
216 if (!PyByteArray_Init())
217 Py_FatalError("Py_Initialize: can't init bytearray");
221 interp
->modules
= PyDict_New();
222 if (interp
->modules
== NULL
)
223 Py_FatalError("Py_Initialize: can't make modules dictionary");
224 interp
->modules_reloading
= PyDict_New();
225 if (interp
->modules_reloading
== NULL
)
226 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
228 /* Init Unicode implementation; relies on the codec registry */
231 bimod
= _PyBuiltin_Init();
233 Py_FatalError("Py_Initialize: can't initialize builtins modules");
234 _PyImport_FixupExtension(bimod
, "builtins", "builtins");
235 interp
->builtins
= PyModule_GetDict(bimod
);
236 if (interp
->builtins
== NULL
)
237 Py_FatalError("Py_Initialize: can't initialize builtins dict");
238 Py_INCREF(interp
->builtins
);
240 /* initialize builtin exceptions */
243 sysmod
= _PySys_Init();
245 Py_FatalError("Py_Initialize: can't initialize sys");
246 interp
->sysdict
= PyModule_GetDict(sysmod
);
247 if (interp
->sysdict
== NULL
)
248 Py_FatalError("Py_Initialize: can't initialize sys dict");
249 Py_INCREF(interp
->sysdict
);
250 _PyImport_FixupExtension(sysmod
, "sys", "sys");
251 PySys_SetPath(Py_GetPath());
252 PyDict_SetItemString(interp
->sysdict
, "modules",
255 /* Set up a preliminary stderr printer until we have enough
256 infrastructure for the io module in place. */
257 pstderr
= PyFile_NewStdPrinter(fileno(stderr
));
259 Py_FatalError("Py_Initialize: can't set preliminary stderr");
260 PySys_SetObject("stderr", pstderr
);
261 PySys_SetObject("__stderr__", pstderr
);
266 _PyImportHooks_Init();
268 /* Initialize _warnings. */
271 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
272 /* On Unix, set the file system encoding according to the
273 user's preference, if the CODESET names a well-known
274 Python codec, and Py_FileSystemDefaultEncoding isn't
275 initialized by other means. Also set the encoding of
276 stdin and stdout if these are terminals. */
278 codeset
= get_codeset();
280 if (!Py_FileSystemDefaultEncoding
)
281 Py_FileSystemDefaultEncoding
= codeset
;
288 initsigs(); /* Signal handling stuff, including initintr() */
290 /* Initialize warnings. */
291 if (PySys_HasWarnOptions()) {
292 PyObject
*warnings_module
= PyImport_ImportModule("warnings");
293 if (!warnings_module
)
295 Py_XDECREF(warnings_module
);
298 initmain(); /* Module __main__ */
301 "Py_Initialize: can't initialize sys standard streams");
303 /* auto-thread-state API, if available */
305 _PyGILState_Init(interp
, tstate
);
306 #endif /* WITH_THREAD */
309 initsite(); /* Module site */
320 extern void dump_counts(FILE*);
323 /* Flush stdout and stderr */
326 flush_std_files(void)
328 PyObject
*fout
= PySys_GetObject("stdout");
329 PyObject
*ferr
= PySys_GetObject("stderr");
332 if (fout
!= NULL
&& fout
!= Py_None
) {
333 tmp
= PyObject_CallMethod(fout
, "flush", "");
335 PyErr_WriteUnraisable(fout
);
340 if (ferr
!= NULL
&& ferr
!= Py_None
) {
341 tmp
= PyObject_CallMethod(ferr
, "flush", "");
349 /* Undo the effect of Py_Initialize().
351 Beware: if multiple interpreter and/or thread states exist, these
352 are not wiped out; only the current thread and interpreter state
353 are deleted. But since everything else is deleted, those other
354 interpreter and thread states should no longer be used.
356 (XXX We should do better, e.g. wipe out all interpreters and
366 PyInterpreterState
*interp
;
367 PyThreadState
*tstate
;
372 wait_for_thread_shutdown();
374 /* The interpreter is still entirely intact at this point, and the
375 * exit funcs may be relying on that. In particular, if some thread
376 * or exit func is still waiting to do an import, the import machinery
377 * expects Py_IsInitialized() to return true. So don't say the
378 * interpreter is uninitialized until after the exit funcs have run.
379 * Note that Threading.py uses an exit func to do a join on all the
380 * threads created thru it, so this also protects pending imports in
381 * the threads created via Threading.
386 /* Flush stdout+stderr */
389 /* Get current thread state and interpreter pointer */
390 tstate
= PyThreadState_GET();
391 interp
= tstate
->interp
;
393 /* Disable signal handling */
394 PyOS_FiniInterrupts();
396 /* Clear type lookup cache */
399 /* Collect garbage. This may call finalizers; it's nice to call these
400 * before all modules are destroyed.
401 * XXX If a __del__ or weakref callback is triggered here, and tries to
402 * XXX import a module, bad things can happen, because Python no
403 * XXX longer believes it's initialized.
404 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
405 * XXX is easy to provoke that way. I've also seen, e.g.,
406 * XXX Exception exceptions.ImportError: 'No module named sha'
407 * XXX in <function callback at 0x008F5718> ignored
408 * XXX but I'm unclear on exactly how that one happens. In any case,
409 * XXX I haven't seen a real-life report of either of these.
413 /* With COUNT_ALLOCS, it helps to run GC multiple times:
414 each collection might release some types from the type
415 list, so they become garbage. */
416 while (PyGC_Collect() > 0)
420 /* Destroy all modules */
423 /* Flush stdout+stderr (again, in case more was printed) */
426 /* Collect final garbage. This disposes of cycles created by
427 * new-style class definitions, for example.
428 * XXX This is disabled because it caused too many problems. If
429 * XXX a __del__ or weakref callback triggers here, Python code has
430 * XXX a hard time running, because even the sys module has been
431 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
432 * XXX One symptom is a sequence of information-free messages
433 * XXX coming from threads (if a __del__ or callback is invoked,
434 * XXX other threads can execute too, and any exception they encounter
435 * XXX triggers a comedy of errors as subsystem after subsystem
436 * XXX fails to find what it *expects* to find in sys to help report
437 * XXX the exception and consequent unexpected failures). I've also
438 * XXX seen segfaults then, after adding print statements to the
439 * XXX Python code getting called.
445 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
448 /* Debugging stuff */
456 /* Display all objects still alive -- this can invoke arbitrary
457 * __repr__ overrides, so requires a mostly-intact interpreter.
458 * Alas, a lot of stuff may still be alive now that will be cleaned
461 if (Py_GETENV("PYTHONDUMPREFS"))
462 _Py_PrintReferences(stderr
);
463 #endif /* Py_TRACE_REFS */
465 /* Clear interpreter state */
466 PyInterpreterState_Clear(interp
);
468 /* Now we decref the exception classes. After this point nothing
469 can raise an exception. That's okay, because each Fini() method
470 below has been checked to make sure no exceptions are ever
476 /* Cleanup auto-thread-state */
479 #endif /* WITH_THREAD */
481 /* Delete current thread */
482 PyThreadState_Swap(NULL
);
483 PyInterpreterState_Delete(interp
);
485 /* Sundry finalizers */
498 /* Cleanup Unicode implementation */
501 /* reset file system default encoding */
502 if (!Py_HasFileSystemDefaultEncoding
) {
503 free((char*)Py_FileSystemDefaultEncoding
);
504 Py_FileSystemDefaultEncoding
= NULL
;
507 /* XXX Still allocated:
508 - various static ad-hoc pointers to interned strings
509 - int and float free list blocks
510 - whatever various modules and libraries allocate
513 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
516 /* Display addresses (& refcnts) of all objects still alive.
517 * An address can be used to find the repr of the object, printed
518 * above by _Py_PrintReferences.
520 if (Py_GETENV("PYTHONDUMPREFS"))
521 _Py_PrintReferenceAddresses(stderr
);
522 #endif /* Py_TRACE_REFS */
523 #ifdef PYMALLOC_DEBUG
524 if (Py_GETENV("PYTHONMALLOCSTATS"))
525 _PyObject_DebugMallocStats();
531 /* Create and initialize a new interpreter and thread, and return the
532 new thread. This requires that Py_Initialize() has been called
535 Unsuccessful initialization yields a NULL pointer. Note that *no*
536 exception information is available even in this case -- the
537 exception information is held in the thread, and there is no
545 Py_NewInterpreter(void)
547 PyInterpreterState
*interp
;
548 PyThreadState
*tstate
, *save_tstate
;
549 PyObject
*bimod
, *sysmod
;
552 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
554 interp
= PyInterpreterState_New();
558 tstate
= PyThreadState_New(interp
);
559 if (tstate
== NULL
) {
560 PyInterpreterState_Delete(interp
);
564 save_tstate
= PyThreadState_Swap(tstate
);
566 /* XXX The following is lax in error checking */
568 interp
->modules
= PyDict_New();
569 interp
->modules_reloading
= PyDict_New();
571 bimod
= _PyImport_FindExtension("builtins", "builtins");
573 interp
->builtins
= PyModule_GetDict(bimod
);
574 if (interp
->builtins
== NULL
)
576 Py_INCREF(interp
->builtins
);
579 /* initialize builtin exceptions */
582 sysmod
= _PyImport_FindExtension("sys", "sys");
583 if (bimod
!= NULL
&& sysmod
!= NULL
) {
585 interp
->sysdict
= PyModule_GetDict(sysmod
);
586 if (interp
->sysdict
== NULL
)
588 Py_INCREF(interp
->sysdict
);
589 PySys_SetPath(Py_GetPath());
590 PyDict_SetItemString(interp
->sysdict
, "modules",
592 /* Set up a preliminary stderr printer until we have enough
593 infrastructure for the io module in place. */
594 pstderr
= PyFile_NewStdPrinter(fileno(stderr
));
596 Py_FatalError("Py_Initialize: can't set preliminary stderr");
597 PySys_SetObject("stderr", pstderr
);
598 PySys_SetObject("__stderr__", pstderr
);
601 _PyImportHooks_Init();
604 "Py_Initialize: can't initialize sys standard streams");
610 if (!PyErr_Occurred())
614 /* Oops, it didn't work. Undo it all. */
617 PyThreadState_Clear(tstate
);
618 PyThreadState_Swap(save_tstate
);
619 PyThreadState_Delete(tstate
);
620 PyInterpreterState_Delete(interp
);
625 /* Delete an interpreter and its last thread. This requires that the
626 given thread state is current, that the thread has no remaining
627 frames, and that it is its interpreter's only remaining thread.
628 It is a fatal error to violate these constraints.
630 (Py_Finalize() doesn't have these constraints -- it zaps
631 everything, regardless.)
638 Py_EndInterpreter(PyThreadState
*tstate
)
640 PyInterpreterState
*interp
= tstate
->interp
;
642 if (tstate
!= PyThreadState_GET())
643 Py_FatalError("Py_EndInterpreter: thread is not current");
644 if (tstate
->frame
!= NULL
)
645 Py_FatalError("Py_EndInterpreter: thread still has a frame");
646 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
647 Py_FatalError("Py_EndInterpreter: not the last thread");
650 PyInterpreterState_Clear(interp
);
651 PyThreadState_Swap(NULL
);
652 PyInterpreterState_Delete(interp
);
655 static wchar_t *progname
= L
"python";
658 Py_SetProgramName(wchar_t *pn
)
665 Py_GetProgramName(void)
670 static wchar_t *default_home
= NULL
;
671 static wchar_t env_home
[PATH_MAX
+1];
674 Py_SetPythonHome(wchar_t *home
)
680 Py_GetPythonHome(void)
682 wchar_t *home
= default_home
;
683 if (home
== NULL
&& !Py_IgnoreEnvironmentFlag
) {
684 char* chome
= Py_GETENV("PYTHONHOME");
686 size_t r
= mbstowcs(env_home
, chome
, PATH_MAX
+1);
687 if (r
!= (size_t)-1 && r
<= PATH_MAX
)
695 /* Create __main__ module */
701 m
= PyImport_AddModule("__main__");
703 Py_FatalError("can't create __main__ module");
704 d
= PyModule_GetDict(m
);
705 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
706 PyObject
*bimod
= PyImport_ImportModule("builtins");
708 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
709 Py_FatalError("can't add __builtins__ to __main__");
714 /* Import the site module (not into __main__ though) */
720 m
= PyImport_ImportModule("site");
722 f
= PySys_GetObject("stderr");
723 if (f
== NULL
|| f
== Py_None
)
725 if (Py_VerboseFlag
) {
726 PyObject
*type
, *value
, *traceback
;
727 PyErr_Fetch(&type
, &value
, &traceback
);
729 "'import site' failed; traceback:\n", f
);
730 PyErr_Restore(type
, value
, traceback
);
736 "'import site' failed; use -v for traceback\n", f
);
745 create_stdio(PyObject
* io
,
746 int fd
, int write_mode
, char* name
,
747 char* encoding
, char* errors
)
749 PyObject
*buf
= NULL
, *stream
= NULL
, *text
= NULL
, *raw
= NULL
, *res
;
751 PyObject
*line_buffering
;
752 int buffering
, isatty
;
754 /* stdin is always opened in buffered mode, first because it shouldn't
755 make a difference in common use cases, second because TextIOWrapper
756 depends on the presence of a read1() method which only exists on
759 if (Py_UnbufferedStdioFlag
&& write_mode
)
767 buf
= PyObject_CallMethod(io
, "open", "isiOOOi",
769 Py_None
, Py_None
, Py_None
, 0);
774 raw
= PyObject_GetAttrString(buf
, "raw");
783 text
= PyUnicode_FromString(name
);
784 if (text
== NULL
|| PyObject_SetAttrString(raw
, "name", text
) < 0)
786 res
= PyObject_CallMethod(raw
, "isatty", "");
789 isatty
= PyObject_IsTrue(res
);
793 if (isatty
|| Py_UnbufferedStdioFlag
)
794 line_buffering
= Py_True
;
796 line_buffering
= Py_False
;
801 stream
= PyObject_CallMethod(io
, "TextIOWrapper", "OsssO",
802 buf
, encoding
, errors
,
803 "\n", line_buffering
);
812 text
= PyUnicode_FromString(mode
);
813 if (!text
|| PyObject_SetAttrString(stream
, "mode", text
) < 0)
826 /* Initialize sys.stdin, stdout, stderr and builtins.open */
830 PyObject
*iomod
= NULL
, *wrapper
;
831 PyObject
*bimod
= NULL
;
833 PyObject
*std
= NULL
;
835 PyObject
* encoding_attr
;
836 char *encoding
= NULL
, *errors
;
838 /* Hack to avoid a nasty recursion issue when Python is invoked
839 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
840 if ((m
= PyImport_ImportModule("encodings.utf_8")) == NULL
) {
845 if (!(m
= PyImport_ImportModule("encodings.latin_1"))) {
850 if (!(bimod
= PyImport_ImportModule("builtins"))) {
854 if (!(iomod
= PyImport_ImportModule("io"))) {
857 if (!(wrapper
= PyObject_GetAttrString(iomod
, "OpenWrapper"))) {
861 /* Set builtins.open */
862 if (PyObject_SetAttrString(bimod
, "open", wrapper
) == -1) {
866 encoding
= Py_GETENV("PYTHONIOENCODING");
869 encoding
= strdup(encoding
);
870 errors
= strchr(encoding
, ':');
879 /* Under some conditions stdin, stdout and stderr may not be connected
880 * and fileno() may point to an invalid file descriptor. For example
881 * GUI apps don't have valid standard streams by default.
892 std
= create_stdio(iomod
, fd
, 0, "<stdin>", encoding
, errors
);
896 PySys_SetObject("__stdin__", std
);
897 PySys_SetObject("stdin", std
);
911 std
= create_stdio(iomod
, fd
, 1, "<stdout>", encoding
, errors
);
915 PySys_SetObject("__stdout__", std
);
916 PySys_SetObject("stdout", std
);
919 #if 1 /* Disable this if you have trouble debugging bootstrap stuff */
920 /* Set sys.stderr, replaces the preliminary stderr */
931 std
= create_stdio(iomod
, fd
, 1, "<stderr>", encoding
, "backslashreplace");
936 /* Same as hack above, pre-import stderr's codec to avoid recursion
937 when import.c tries to write to stderr in verbose mode. */
938 encoding_attr
= PyObject_GetAttrString(std
, "encoding");
939 if (encoding_attr
!= NULL
) {
940 const char * encoding
;
941 encoding
= _PyUnicode_AsString(encoding_attr
);
942 if (encoding
!= NULL
) {
943 _PyCodec_Lookup(encoding
);
945 Py_DECREF(encoding_attr
);
947 PyErr_Clear(); /* Not a fatal error if codec isn't available */
949 PySys_SetObject("__stderr__", std
);
950 PySys_SetObject("stderr", std
);
966 /* Parse input from a file and execute it */
969 PyRun_AnyFileExFlags(FILE *fp
, const char *filename
, int closeit
,
970 PyCompilerFlags
*flags
)
972 if (filename
== NULL
)
974 if (Py_FdIsInteractive(fp
, filename
)) {
975 int err
= PyRun_InteractiveLoopFlags(fp
, filename
, flags
);
981 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, flags
);
985 PyRun_InteractiveLoopFlags(FILE *fp
, const char *filename
, PyCompilerFlags
*flags
)
989 PyCompilerFlags local_flags
;
992 flags
= &local_flags
;
993 local_flags
.cf_flags
= 0;
995 v
= PySys_GetObject("ps1");
997 PySys_SetObject("ps1", v
= PyUnicode_FromString(">>> "));
1000 v
= PySys_GetObject("ps2");
1002 PySys_SetObject("ps2", v
= PyUnicode_FromString("... "));
1006 ret
= PyRun_InteractiveOneFlags(fp
, filename
, flags
);
1017 /* compute parser flags based on compiler flags */
1018 static int PARSER_FLAGS(PyCompilerFlags
*flags
)
1020 int parser_flags
= 0;
1023 if (flags
->cf_flags
& PyCF_DONT_IMPLY_DEDENT
)
1024 parser_flags
|= PyPARSE_DONT_IMPLY_DEDENT
;
1025 if (flags
->cf_flags
& PyCF_IGNORE_COOKIE
)
1026 parser_flags
|= PyPARSE_IGNORE_COOKIE
;
1027 if (flags
->cf_flags
& CO_FUTURE_BARRY_AS_BDFL
)
1028 parser_flags
|= PyPARSE_BARRY_AS_BDFL
;
1029 return parser_flags
;
1033 /* Keep an example of flags with future keyword support. */
1034 #define PARSER_FLAGS(flags) \
1035 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1036 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1037 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1038 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1042 PyRun_InteractiveOneFlags(FILE *fp
, const char *filename
, PyCompilerFlags
*flags
)
1044 PyObject
*m
, *d
, *v
, *w
, *oenc
= NULL
;
1047 char *ps1
= "", *ps2
= "", *enc
= NULL
;
1051 /* Fetch encoding from sys.stdin */
1052 v
= PySys_GetObject("stdin");
1053 if (v
== NULL
|| v
== Py_None
)
1055 oenc
= PyObject_GetAttrString(v
, "encoding");
1058 enc
= _PyUnicode_AsString(oenc
);
1060 v
= PySys_GetObject("ps1");
1062 v
= PyObject_Str(v
);
1065 else if (PyUnicode_Check(v
))
1066 ps1
= _PyUnicode_AsString(v
);
1068 w
= PySys_GetObject("ps2");
1070 w
= PyObject_Str(w
);
1073 else if (PyUnicode_Check(w
))
1074 ps2
= _PyUnicode_AsString(w
);
1076 arena
= PyArena_New();
1077 if (arena
== NULL
) {
1083 mod
= PyParser_ASTFromFile(fp
, filename
, enc
,
1084 Py_single_input
, ps1
, ps2
,
1085 flags
, &errcode
, arena
);
1090 PyArena_Free(arena
);
1091 if (errcode
== E_EOF
) {
1098 m
= PyImport_AddModule("__main__");
1100 PyArena_Free(arena
);
1103 d
= PyModule_GetDict(m
);
1104 v
= run_mod(mod
, filename
, d
, d
, flags
, arena
);
1105 PyArena_Free(arena
);
1115 /* Check whether a file maybe a pyc file: Look at the extension,
1116 the file type, and, if we may close it, at the first few bytes. */
1119 maybe_pyc_file(FILE *fp
, const char* filename
, const char* ext
, int closeit
)
1121 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0)
1124 /* Only look into the file if we are allowed to close it, since
1125 it then should also be seekable. */
1127 /* Read only two bytes of the magic. If the file was opened in
1128 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1129 be read as they are on disk. */
1130 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
1131 unsigned char buf
[2];
1132 /* Mess: In case of -x, the stream is NOT at its start now,
1133 and ungetc() was used to push back the first newline,
1134 which makes the current stream position formally undefined,
1135 and a x-platform nightmare.
1136 Unfortunately, we have no direct way to know whether -x
1137 was specified. So we use a terrible hack: if the current
1138 stream position is not 0, we assume -x was specified, and
1139 give up. Bug 132850 on SourceForge spells out the
1140 hopelessness of trying anything else (fseek and ftell
1141 don't work predictably x-platform for text-mode files).
1144 if (ftell(fp
) == 0) {
1145 if (fread(buf
, 1, 2, fp
) == 2 &&
1146 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
1156 PyRun_SimpleFileExFlags(FILE *fp
, const char *filename
, int closeit
,
1157 PyCompilerFlags
*flags
)
1159 PyObject
*m
, *d
, *v
;
1161 int set_file_name
= 0, ret
, len
;
1163 m
= PyImport_AddModule("__main__");
1166 d
= PyModule_GetDict(m
);
1167 if (PyDict_GetItemString(d
, "__file__") == NULL
) {
1169 f
= PyUnicode_DecodeFSDefault(filename
);
1172 if (PyDict_SetItemString(d
, "__file__", f
) < 0) {
1179 len
= strlen(filename
);
1180 ext
= filename
+ len
- (len
> 4 ? 4 : 0);
1181 if (maybe_pyc_file(fp
, filename
, ext
, closeit
)) {
1182 /* Try to run a pyc file. First, re-open in binary */
1185 if ((fp
= fopen(filename
, "rb")) == NULL
) {
1186 fprintf(stderr
, "python: Can't reopen .pyc file\n");
1190 /* Turn on optimization if a .pyo file is given */
1191 if (strcmp(ext
, ".pyo") == 0)
1192 Py_OptimizeFlag
= 1;
1193 v
= run_pyc_file(fp
, filename
, d
, d
, flags
);
1195 v
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, d
, d
,
1207 if (set_file_name
&& PyDict_DelItemString(d
, "__file__"))
1213 PyRun_SimpleStringFlags(const char *command
, PyCompilerFlags
*flags
)
1215 PyObject
*m
, *d
, *v
;
1216 m
= PyImport_AddModule("__main__");
1219 d
= PyModule_GetDict(m
);
1220 v
= PyRun_StringFlags(command
, Py_file_input
, d
, d
, flags
);
1230 parse_syntax_error(PyObject
*err
, PyObject
**message
, const char **filename
,
1231 int *lineno
, int *offset
, const char **text
)
1236 /* old style errors */
1237 if (PyTuple_Check(err
))
1238 return PyArg_ParseTuple(err
, "O(ziiz)", message
, filename
,
1239 lineno
, offset
, text
);
1241 /* new style errors. `err' is an instance */
1243 if (! (v
= PyObject_GetAttrString(err
, "msg")))
1247 if (!(v
= PyObject_GetAttrString(err
, "filename")))
1251 else if (! (*filename
= _PyUnicode_AsString(v
)))
1255 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
1257 hold
= PyLong_AsLong(v
);
1260 if (hold
< 0 && PyErr_Occurred())
1262 *lineno
= (int)hold
;
1264 if (!(v
= PyObject_GetAttrString(err
, "offset")))
1271 hold
= PyLong_AsLong(v
);
1274 if (hold
< 0 && PyErr_Occurred())
1276 *offset
= (int)hold
;
1279 if (!(v
= PyObject_GetAttrString(err
, "text")))
1283 else if (!PyUnicode_Check(v
) ||
1284 !(*text
= _PyUnicode_AsString(v
)))
1301 print_error_text(PyObject
*f
, int offset
, const char *text
)
1305 if (offset
> 0 && offset
== strlen(text
) && text
[offset
- 1] == '\n')
1308 nl
= strchr(text
, '\n');
1309 if (nl
== NULL
|| nl
-text
>= offset
)
1311 offset
-= (int)(nl
+1-text
);
1314 while (*text
== ' ' || *text
== '\t') {
1319 PyFile_WriteString(" ", f
);
1320 PyFile_WriteString(text
, f
);
1321 if (*text
== '\0' || text
[strlen(text
)-1] != '\n')
1322 PyFile_WriteString("\n", f
);
1325 PyFile_WriteString(" ", f
);
1326 while (--offset
> 0)
1327 PyFile_WriteString(" ", f
);
1328 PyFile_WriteString("^\n", f
);
1332 handle_system_exit(void)
1334 PyObject
*exception
, *value
, *tb
;
1338 /* Don't exit if -i flag was given. This flag is set to 0
1339 * when entering interactive mode for inspecting. */
1342 PyErr_Fetch(&exception
, &value
, &tb
);
1344 if (value
== NULL
|| value
== Py_None
)
1346 if (PyExceptionInstance_Check(value
)) {
1347 /* The error code should be in the `code' attribute. */
1348 PyObject
*code
= PyObject_GetAttrString(value
, "code");
1352 if (value
== Py_None
)
1355 /* If we failed to dig out the 'code' attribute,
1356 just let the else clause below print the error. */
1358 if (PyLong_Check(value
))
1359 exitcode
= (int)PyLong_AsLong(value
);
1361 PyObject
*sys_stderr
= PySys_GetObject("stderr");
1362 if (sys_stderr
!= NULL
)
1363 PyObject_CallMethod(sys_stderr
, "flush", NULL
);
1364 PyObject_Print(value
, stderr
, Py_PRINT_RAW
);
1366 PySys_WriteStderr("\n");
1370 /* Restore and clear the exception info, in order to properly decref
1371 * the exception, value, and traceback. If we just exit instead,
1372 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1373 * some finalizers from running.
1375 PyErr_Restore(exception
, value
, tb
);
1382 PyErr_PrintEx(int set_sys_last_vars
)
1384 PyObject
*exception
, *v
, *tb
, *hook
;
1386 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1387 handle_system_exit();
1389 PyErr_Fetch(&exception
, &v
, &tb
);
1390 if (exception
== NULL
)
1392 PyErr_NormalizeException(&exception
, &v
, &tb
);
1397 PyException_SetTraceback(v
, tb
);
1398 if (exception
== NULL
)
1400 /* Now we know v != NULL too */
1401 if (set_sys_last_vars
) {
1402 PySys_SetObject("last_type", exception
);
1403 PySys_SetObject("last_value", v
);
1404 PySys_SetObject("last_traceback", tb
);
1406 hook
= PySys_GetObject("excepthook");
1408 PyObject
*args
= PyTuple_Pack(3, exception
, v
, tb
);
1409 PyObject
*result
= PyEval_CallObject(hook
, args
);
1410 if (result
== NULL
) {
1411 PyObject
*exception2
, *v2
, *tb2
;
1412 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1413 handle_system_exit();
1415 PyErr_Fetch(&exception2
, &v2
, &tb2
);
1416 PyErr_NormalizeException(&exception2
, &v2
, &tb2
);
1417 /* It should not be possible for exception2 or v2
1418 to be NULL. However PyErr_Display() can't
1419 tolerate NULLs, so just be safe. */
1420 if (exception2
== NULL
) {
1421 exception2
= Py_None
;
1422 Py_INCREF(exception2
);
1429 PySys_WriteStderr("Error in sys.excepthook:\n");
1430 PyErr_Display(exception2
, v2
, tb2
);
1431 PySys_WriteStderr("\nOriginal exception was:\n");
1432 PyErr_Display(exception
, v
, tb
);
1433 Py_DECREF(exception2
);
1440 PySys_WriteStderr("sys.excepthook is missing\n");
1441 PyErr_Display(exception
, v
, tb
);
1443 Py_XDECREF(exception
);
1449 print_exception(PyObject
*f
, PyObject
*value
)
1452 PyObject
*type
, *tb
;
1454 if (!PyExceptionInstance_Check(value
)) {
1455 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f
);
1456 PyFile_WriteString(Py_TYPE(value
)->tp_name
, f
);
1457 PyFile_WriteString(" found\n", f
);
1463 type
= (PyObject
*) Py_TYPE(value
);
1464 tb
= PyException_GetTraceback(value
);
1465 if (tb
&& tb
!= Py_None
)
1466 err
= PyTraceBack_Print(tb
, f
);
1468 PyObject_HasAttrString(value
, "print_file_and_line"))
1471 const char *filename
, *text
;
1473 if (!parse_syntax_error(value
, &message
, &filename
,
1474 &lineno
, &offset
, &text
))
1478 PyFile_WriteString(" File \"", f
);
1479 if (filename
== NULL
)
1480 PyFile_WriteString("<string>", f
);
1482 PyFile_WriteString(filename
, f
);
1483 PyFile_WriteString("\", line ", f
);
1484 PyOS_snprintf(buf
, sizeof(buf
), "%d", lineno
);
1485 PyFile_WriteString(buf
, f
);
1486 PyFile_WriteString("\n", f
);
1488 print_error_text(f
, offset
, text
);
1491 /* Can't be bothered to check all those
1492 PyFile_WriteString() calls */
1493 if (PyErr_Occurred())
1498 /* Don't do anything else */
1501 PyObject
* moduleName
;
1503 assert(PyExceptionClass_Check(type
));
1504 className
= PyExceptionClass_Name(type
);
1505 if (className
!= NULL
) {
1506 char *dot
= strrchr(className
, '.');
1511 moduleName
= PyObject_GetAttrString(type
, "__module__");
1512 if (moduleName
== NULL
|| !PyUnicode_Check(moduleName
))
1514 Py_DECREF(moduleName
);
1515 err
= PyFile_WriteString("<unknown>", f
);
1518 char* modstr
= _PyUnicode_AsString(moduleName
);
1519 if (modstr
&& strcmp(modstr
, "builtins"))
1521 err
= PyFile_WriteString(modstr
, f
);
1522 err
+= PyFile_WriteString(".", f
);
1524 Py_DECREF(moduleName
);
1527 if (className
== NULL
)
1528 err
= PyFile_WriteString("<unknown>", f
);
1530 err
= PyFile_WriteString(className
, f
);
1533 if (err
== 0 && (value
!= Py_None
)) {
1534 PyObject
*s
= PyObject_Str(value
);
1535 /* only print colon if the str() of the
1536 object is not the empty string
1540 else if (!PyUnicode_Check(s
) ||
1541 PyUnicode_GetSize(s
) != 0)
1542 err
= PyFile_WriteString(": ", f
);
1544 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
1547 /* try to write a newline in any case */
1548 err
+= PyFile_WriteString("\n", f
);
1551 /* If an error happened here, don't show it.
1552 XXX This is wrong, but too many callers rely on this behavior. */
1557 static const char *cause_message
=
1558 "\nThe above exception was the direct cause "
1559 "of the following exception:\n\n";
1561 static const char *context_message
=
1562 "\nDuring handling of the above exception, "
1563 "another exception occurred:\n\n";
1566 print_exception_recursive(PyObject
*f
, PyObject
*value
, PyObject
*seen
)
1569 PyObject
*cause
, *context
;
1572 /* Exception chaining */
1573 if (PySet_Add(seen
, value
) == -1)
1575 else if (PyExceptionInstance_Check(value
)) {
1576 cause
= PyException_GetCause(value
);
1577 context
= PyException_GetContext(value
);
1579 res
= PySet_Contains(seen
, cause
);
1583 print_exception_recursive(
1585 err
|= PyFile_WriteString(
1590 res
= PySet_Contains(seen
, context
);
1594 print_exception_recursive(
1596 err
|= PyFile_WriteString(
1597 context_message
, f
);
1600 Py_XDECREF(context
);
1604 print_exception(f
, value
);
1610 PyErr_Display(PyObject
*exception
, PyObject
*value
, PyObject
*tb
)
1613 PyObject
*f
= PySys_GetObject("stderr");
1617 else if (f
== NULL
) {
1618 _PyObject_Dump(value
);
1619 fprintf(stderr
, "lost sys.stderr\n");
1622 /* We choose to ignore seen being possibly NULL, and report
1623 at least the main exception (it could be a MemoryError).
1625 seen
= PySet_New(NULL
);
1628 print_exception_recursive(f
, value
, seen
);
1634 PyRun_StringFlags(const char *str
, int start
, PyObject
*globals
,
1635 PyObject
*locals
, PyCompilerFlags
*flags
)
1637 PyObject
*ret
= NULL
;
1639 PyArena
*arena
= PyArena_New();
1643 mod
= PyParser_ASTFromString(str
, "<string>", start
, flags
, arena
);
1645 ret
= run_mod(mod
, "<string>", globals
, locals
, flags
, arena
);
1646 PyArena_Free(arena
);
1651 PyRun_FileExFlags(FILE *fp
, const char *filename
, int start
, PyObject
*globals
,
1652 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1656 PyArena
*arena
= PyArena_New();
1660 mod
= PyParser_ASTFromFile(fp
, filename
, NULL
, start
, 0, 0,
1661 flags
, NULL
, arena
);
1665 PyArena_Free(arena
);
1668 ret
= run_mod(mod
, filename
, globals
, locals
, flags
, arena
);
1669 PyArena_Free(arena
);
1677 PyObject
*type
, *value
, *traceback
;
1679 /* Save the current exception */
1680 PyErr_Fetch(&type
, &value
, &traceback
);
1682 f
= PySys_GetObject("stderr");
1684 r
= PyObject_CallMethod(f
, "flush", "");
1690 f
= PySys_GetObject("stdout");
1692 r
= PyObject_CallMethod(f
, "flush", "");
1699 PyErr_Restore(type
, value
, traceback
);
1703 run_mod(mod_ty mod
, const char *filename
, PyObject
*globals
, PyObject
*locals
,
1704 PyCompilerFlags
*flags
, PyArena
*arena
)
1708 co
= PyAST_Compile(mod
, filename
, flags
, arena
);
1711 v
= PyEval_EvalCode(co
, globals
, locals
);
1717 run_pyc_file(FILE *fp
, const char *filename
, PyObject
*globals
,
1718 PyObject
*locals
, PyCompilerFlags
*flags
)
1723 long PyImport_GetMagicNumber(void);
1725 magic
= PyMarshal_ReadLongFromFile(fp
);
1726 if (magic
!= PyImport_GetMagicNumber()) {
1727 PyErr_SetString(PyExc_RuntimeError
,
1728 "Bad magic number in .pyc file");
1731 (void) PyMarshal_ReadLongFromFile(fp
);
1732 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1734 if (v
== NULL
|| !PyCode_Check(v
)) {
1736 PyErr_SetString(PyExc_RuntimeError
,
1737 "Bad code object in .pyc file");
1740 co
= (PyCodeObject
*)v
;
1741 v
= PyEval_EvalCode(co
, globals
, locals
);
1743 flags
->cf_flags
|= (co
->co_flags
& PyCF_MASK
);
1749 Py_CompileStringFlags(const char *str
, const char *filename
, int start
,
1750 PyCompilerFlags
*flags
)
1754 PyArena
*arena
= PyArena_New();
1758 mod
= PyParser_ASTFromString(str
, filename
, start
, flags
, arena
);
1760 PyArena_Free(arena
);
1763 if (flags
&& (flags
->cf_flags
& PyCF_ONLY_AST
)) {
1764 PyObject
*result
= PyAST_mod2obj(mod
);
1765 PyArena_Free(arena
);
1768 co
= PyAST_Compile(mod
, filename
, flags
, arena
);
1769 PyArena_Free(arena
);
1770 return (PyObject
*)co
;
1774 Py_SymtableString(const char *str
, const char *filename
, int start
)
1776 struct symtable
*st
;
1778 PyCompilerFlags flags
;
1779 PyArena
*arena
= PyArena_New();
1784 mod
= PyParser_ASTFromString(str
, filename
, start
, &flags
, arena
);
1786 PyArena_Free(arena
);
1789 st
= PySymtable_Build(mod
, filename
, 0);
1790 PyArena_Free(arena
);
1794 /* Preferred access to parser is through AST. */
1796 PyParser_ASTFromString(const char *s
, const char *filename
, int start
,
1797 PyCompilerFlags
*flags
, PyArena
*arena
)
1800 PyCompilerFlags localflags
;
1802 int iflags
= PARSER_FLAGS(flags
);
1804 node
*n
= PyParser_ParseStringFlagsFilenameEx(s
, filename
,
1805 &_PyParser_Grammar
, start
, &err
,
1807 if (flags
== NULL
) {
1808 localflags
.cf_flags
= 0;
1809 flags
= &localflags
;
1812 flags
->cf_flags
|= iflags
& PyCF_MASK
;
1813 mod
= PyAST_FromNode(n
, flags
, filename
, arena
);
1824 PyParser_ASTFromFile(FILE *fp
, const char *filename
, const char* enc
,
1825 int start
, char *ps1
,
1826 char *ps2
, PyCompilerFlags
*flags
, int *errcode
,
1830 PyCompilerFlags localflags
;
1832 int iflags
= PARSER_FLAGS(flags
);
1834 node
*n
= PyParser_ParseFileFlagsEx(fp
, filename
, enc
,
1836 start
, ps1
, ps2
, &err
, &iflags
);
1837 if (flags
== NULL
) {
1838 localflags
.cf_flags
= 0;
1839 flags
= &localflags
;
1842 flags
->cf_flags
|= iflags
& PyCF_MASK
;
1843 mod
= PyAST_FromNode(n
, flags
, filename
, arena
);
1850 *errcode
= err
.error
;
1855 /* Simplified interface to parsefile -- return node or set exception */
1858 PyParser_SimpleParseFileFlags(FILE *fp
, const char *filename
, int start
, int flags
)
1861 node
*n
= PyParser_ParseFileFlags(fp
, filename
, NULL
,
1863 start
, NULL
, NULL
, &err
, flags
);
1870 /* Simplified interface to parsestring -- return node or set exception */
1873 PyParser_SimpleParseStringFlags(const char *str
, int start
, int flags
)
1876 node
*n
= PyParser_ParseStringFlags(str
, &_PyParser_Grammar
,
1877 start
, &err
, flags
);
1884 PyParser_SimpleParseStringFlagsFilename(const char *str
, const char *filename
,
1885 int start
, int flags
)
1888 node
*n
= PyParser_ParseStringFlagsFilename(str
, filename
,
1889 &_PyParser_Grammar
, start
, &err
, flags
);
1896 PyParser_SimpleParseStringFilename(const char *str
, const char *filename
, int start
)
1898 return PyParser_SimpleParseStringFlagsFilename(str
, filename
, start
, 0);
1901 /* May want to move a more generalized form of this to parsetok.c or
1902 even parser modules. */
1905 PyParser_SetError(perrdetail
*err
)
1910 /* Set the error appropriate to the given input error code (see errcode.h) */
1913 err_input(perrdetail
*err
)
1915 PyObject
*v
, *w
, *errtype
, *errtext
;
1920 errtype
= PyExc_SyntaxError
;
1921 switch (err
->error
) {
1925 errtype
= PyExc_IndentationError
;
1926 if (err
->expected
== INDENT
)
1927 msg
= "expected an indented block";
1928 else if (err
->token
== INDENT
)
1929 msg
= "unexpected indent";
1930 else if (err
->token
== DEDENT
)
1931 msg
= "unexpected unindent";
1933 errtype
= PyExc_SyntaxError
;
1934 msg
= "invalid syntax";
1938 msg
= "invalid token";
1941 msg
= "EOF while scanning triple-quoted string literal";
1944 msg
= "EOL while scanning string literal";
1947 if (!PyErr_Occurred())
1948 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1954 msg
= "unexpected EOF while parsing";
1957 errtype
= PyExc_TabError
;
1958 msg
= "inconsistent use of tabs and spaces in indentation";
1961 msg
= "expression too long";
1964 errtype
= PyExc_IndentationError
;
1965 msg
= "unindent does not match any outer indentation level";
1968 errtype
= PyExc_IndentationError
;
1969 msg
= "too many levels of indentation";
1972 PyObject
*type
, *value
, *tb
;
1973 PyErr_Fetch(&type
, &value
, &tb
);
1974 if (value
!= NULL
) {
1975 u
= PyObject_Str(value
);
1977 msg
= _PyUnicode_AsString(u
);
1981 msg
= "unknown decode error";
1988 msg
= "unexpected character after line continuation character";
1992 msg
= "invalid character in identifier";
1995 fprintf(stderr
, "error=%d\n", err
->error
);
1996 msg
= "unknown parsing error";
1999 /* err->text may not be UTF-8 in case of decoding errors.
2000 Explicitly convert to an object. */
2005 errtext
= PyUnicode_DecodeUTF8(err
->text
, strlen(err
->text
),
2008 if (err
->filename
!= NULL
)
2009 filename
= PyUnicode_DecodeFSDefault(err
->filename
);
2014 if (filename
!= NULL
)
2015 v
= Py_BuildValue("(NiiN)", filename
,
2016 err
->lineno
, err
->offset
, errtext
);
2021 w
= Py_BuildValue("(sO)", msg
, v
);
2024 PyErr_SetObject(errtype
, w
);
2027 if (err
->text
!= NULL
) {
2028 PyObject_FREE(err
->text
);
2033 /* Print fatal error message and abort */
2036 Py_FatalError(const char *msg
)
2038 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
2039 fflush(stderr
); /* it helps in Windows debug build */
2040 if (PyErr_Occurred()) {
2045 size_t len
= strlen(msg
);
2049 /* Convert the message to wchar_t. This uses a simple one-to-one
2050 conversion, assuming that the this error message actually uses ASCII
2051 only. If this ceases to be true, we will have to convert. */
2052 buffer
= alloca( (len
+1) * (sizeof *buffer
));
2053 for( i
=0; i
<=len
; ++i
)
2055 OutputDebugStringW(L
"Fatal Python error: ");
2056 OutputDebugStringW(buffer
);
2057 OutputDebugStringW(L
"\n");
2062 #endif /* MS_WINDOWS */
2066 /* Clean up and exit */
2069 #include "pythread.h"
2072 static void (*pyexitfunc
)(void) = NULL
;
2073 /* For the atexit module. */
2074 void _Py_PyAtExit(void (*func
)(void))
2080 call_py_exitfuncs(void)
2082 if (pyexitfunc
== NULL
)
2089 /* Wait until threading._shutdown completes, provided
2090 the threading module was imported in the first place.
2091 The shutdown routine will wait until all non-daemon
2092 "threading" threads have completed. */
2094 wait_for_thread_shutdown(void)
2098 PyThreadState
*tstate
= PyThreadState_GET();
2099 PyObject
*threading
= PyMapping_GetItemString(tstate
->interp
->modules
,
2101 if (threading
== NULL
) {
2102 /* threading not imported */
2106 result
= PyObject_CallMethod(threading
, "_shutdown", "");
2107 if (result
== NULL
) {
2108 PyErr_WriteUnraisable(threading
);
2113 Py_DECREF(threading
);
2117 #define NEXITFUNCS 32
2118 static void (*exitfuncs
[NEXITFUNCS
])(void);
2119 static int nexitfuncs
= 0;
2121 int Py_AtExit(void (*func
)(void))
2123 if (nexitfuncs
>= NEXITFUNCS
)
2125 exitfuncs
[nexitfuncs
++] = func
;
2130 call_ll_exitfuncs(void)
2132 while (nexitfuncs
> 0)
2133 (*exitfuncs
[--nexitfuncs
])();
2151 PyOS_setsig(SIGPIPE
, SIG_IGN
);
2154 PyOS_setsig(SIGXFZ
, SIG_IGN
);
2157 PyOS_setsig(SIGXFSZ
, SIG_IGN
);
2159 PyOS_InitInterrupts(); /* May imply initsignal() */
2164 * The file descriptor fd is considered ``interactive'' if either
2165 * a) isatty(fd) is TRUE, or
2166 * b) the -i flag was given, and the filename associated with
2167 * the descriptor is NULL or "<stdin>" or "???".
2170 Py_FdIsInteractive(FILE *fp
, const char *filename
)
2172 if (isatty((int)fileno(fp
)))
2174 if (!Py_InteractiveFlag
)
2176 return (filename
== NULL
) ||
2177 (strcmp(filename
, "<stdin>") == 0) ||
2178 (strcmp(filename
, "???") == 0);
2182 #if defined(USE_STACKCHECK)
2183 #if defined(WIN32) && defined(_MSC_VER)
2185 /* Stack checking for Microsoft C */
2191 * Return non-zero when we run out of memory on the stack; zero otherwise.
2194 PyOS_CheckStack(void)
2197 /* alloca throws a stack overflow exception if there's
2198 not enough space left on the stack */
2199 alloca(PYOS_STACK_MARGIN
* sizeof(void*));
2201 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW
?
2202 EXCEPTION_EXECUTE_HANDLER
:
2203 EXCEPTION_CONTINUE_SEARCH
) {
2204 int errcode
= _resetstkoflw();
2207 Py_FatalError("Could not reset the stack!");
2213 #endif /* WIN32 && _MSC_VER */
2215 /* Alternate implementations can be added here... */
2217 #endif /* USE_STACKCHECK */
2220 /* Wrappers around sigaction() or signal(). */
2223 PyOS_getsig(int sig
)
2225 #ifdef HAVE_SIGACTION
2226 struct sigaction context
;
2227 if (sigaction(sig
, NULL
, &context
) == -1)
2229 return context
.sa_handler
;
2231 PyOS_sighandler_t handler
;
2232 /* Special signal handling for the secure CRT in Visual Studio 2005 */
2233 #if defined(_MSC_VER) && _MSC_VER >= 1400
2235 /* Only these signals are valid */
2244 /* Don't call signal() with other values or it will assert */
2248 #endif /* _MSC_VER && _MSC_VER >= 1400 */
2249 handler
= signal(sig
, SIG_IGN
);
2250 if (handler
!= SIG_ERR
)
2251 signal(sig
, handler
);
2257 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
2259 #ifdef HAVE_SIGACTION
2260 /* Some code in Modules/signalmodule.c depends on sigaction() being
2261 * used here if HAVE_SIGACTION is defined. Fix that if this code
2262 * changes to invalidate that assumption.
2264 struct sigaction context
, ocontext
;
2265 context
.sa_handler
= handler
;
2266 sigemptyset(&context
.sa_mask
);
2267 context
.sa_flags
= 0;
2268 if (sigaction(sig
, &context
, &ocontext
) == -1)
2270 return ocontext
.sa_handler
;
2272 PyOS_sighandler_t oldhandler
;
2273 oldhandler
= signal(sig
, handler
);
2274 #ifdef HAVE_SIGINTERRUPT
2275 siginterrupt(sig
, 1);
2281 /* Deprecated C API functions still provided for binary compatiblity */
2283 #undef PyParser_SimpleParseFile
2285 PyParser_SimpleParseFile(FILE *fp
, const char *filename
, int start
)
2287 return PyParser_SimpleParseFileFlags(fp
, filename
, start
, 0);
2290 #undef PyParser_SimpleParseString
2292 PyParser_SimpleParseString(const char *str
, int start
)
2294 return PyParser_SimpleParseStringFlags(str
, start
, 0);
2297 #undef PyRun_AnyFile
2299 PyRun_AnyFile(FILE *fp
, const char *name
)
2301 return PyRun_AnyFileExFlags(fp
, name
, 0, NULL
);
2304 #undef PyRun_AnyFileEx
2306 PyRun_AnyFileEx(FILE *fp
, const char *name
, int closeit
)
2308 return PyRun_AnyFileExFlags(fp
, name
, closeit
, NULL
);
2311 #undef PyRun_AnyFileFlags
2313 PyRun_AnyFileFlags(FILE *fp
, const char *name
, PyCompilerFlags
*flags
)
2315 return PyRun_AnyFileExFlags(fp
, name
, 0, flags
);
2319 PyAPI_FUNC(PyObject
*)
2320 PyRun_File(FILE *fp
, const char *p
, int s
, PyObject
*g
, PyObject
*l
)
2322 return PyRun_FileExFlags(fp
, p
, s
, g
, l
, 0, NULL
);
2326 PyAPI_FUNC(PyObject
*)
2327 PyRun_FileEx(FILE *fp
, const char *p
, int s
, PyObject
*g
, PyObject
*l
, int c
)
2329 return PyRun_FileExFlags(fp
, p
, s
, g
, l
, c
, NULL
);
2332 #undef PyRun_FileFlags
2333 PyAPI_FUNC(PyObject
*)
2334 PyRun_FileFlags(FILE *fp
, const char *p
, int s
, PyObject
*g
, PyObject
*l
,
2335 PyCompilerFlags
*flags
)
2337 return PyRun_FileExFlags(fp
, p
, s
, g
, l
, 0, flags
);
2340 #undef PyRun_SimpleFile
2342 PyRun_SimpleFile(FILE *f
, const char *p
)
2344 return PyRun_SimpleFileExFlags(f
, p
, 0, NULL
);
2347 #undef PyRun_SimpleFileEx
2349 PyRun_SimpleFileEx(FILE *f
, const char *p
, int c
)
2351 return PyRun_SimpleFileExFlags(f
, p
, c
, NULL
);
2356 PyAPI_FUNC(PyObject
*)
2357 PyRun_String(const char *str
, int s
, PyObject
*g
, PyObject
*l
)
2359 return PyRun_StringFlags(str
, s
, g
, l
, NULL
);
2362 #undef PyRun_SimpleString
2364 PyRun_SimpleString(const char *s
)
2366 return PyRun_SimpleStringFlags(s
, NULL
);
2369 #undef Py_CompileString
2370 PyAPI_FUNC(PyObject
*)
2371 Py_CompileString(const char *str
, const char *p
, int s
)
2373 return Py_CompileStringFlags(str
, p
, s
, NULL
);
2376 #undef PyRun_InteractiveOne
2378 PyRun_InteractiveOne(FILE *f
, const char *p
)
2380 return PyRun_InteractiveOneFlags(f
, p
, NULL
);
2383 #undef PyRun_InteractiveLoop
2385 PyRun_InteractiveLoop(FILE *f
, const char *p
)
2387 return PyRun_InteractiveLoopFlags(f
, p
, NULL
);