blob: 4f5efc963c7722b2be204c328a06bc9d47adb11b [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
7#include "grammar.h"
8#include "node.h"
9#include "token.h"
10#include "parsetok.h"
11#include "errcode.h"
12#include "code.h"
13#include "symtable.h"
14#include "ast.h"
15#include "marshal.h"
16#include "osdefs.h"
17#include <locale.h>
18
19#ifdef HAVE_SIGNAL_H
20#include <signal.h>
21#endif
22
23#ifdef MS_WINDOWS
24#include "malloc.h" /* for alloca */
25#endif
26
27#ifdef HAVE_LANGINFO_H
28#include <langinfo.h>
29#endif
30
31#ifdef MS_WINDOWS
32#undef BYTE
33#include "windows.h"
34#endif
35
36_Py_IDENTIFIER(flush);
37_Py_IDENTIFIER(name);
38_Py_IDENTIFIER(stdin);
39_Py_IDENTIFIER(stdout);
40_Py_IDENTIFIER(stderr);
41
42#ifdef __cplusplus
43extern "C" {
44#endif
45
46extern wchar_t *Py_GetPath(void);
47
48extern grammar _PyParser_Grammar; /* From graminit.c */
49
50/* Forward */
51static void initmain(PyInterpreterState *interp);
52static int initfsencoding(PyInterpreterState *interp);
53static void initsite(void);
54static int initstdio(void);
55static void initsigs(void);
56static void call_py_exitfuncs(void);
57static void wait_for_thread_shutdown(void);
58static void call_ll_exitfuncs(void);
59extern int _PyUnicode_Init(void);
60extern int _PyStructSequence_Init(void);
61extern void _PyUnicode_Fini(void);
62extern int _PyLong_Init(void);
63extern void PyLong_Fini(void);
64extern int _PyFaulthandler_Init(void);
65extern void _PyFaulthandler_Fini(void);
66extern void _PyHash_Fini(void);
67extern int _PyTraceMalloc_Init(void);
68extern int _PyTraceMalloc_Fini(void);
69
70#ifdef WITH_THREAD
71extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
72extern void _PyGILState_Fini(void);
73#endif /* WITH_THREAD */
74
75/* Global configuration variable declarations are in pydebug.h */
76/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
77int Py_DebugFlag; /* Needed by parser.c */
78int Py_VerboseFlag; /* Needed by import.c */
79int Py_QuietFlag; /* Needed by sysmodule.c */
80int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
81int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
82int Py_OptimizeFlag = 0; /* Needed by compile.c */
83int Py_NoSiteFlag; /* Suppress 'import site' */
84int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
85int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
86int Py_FrozenFlag; /* Needed by getpath.c */
87int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
88int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
89int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
90int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
91int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
92int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
93
94PyThreadState *_Py_Finalizing = NULL;
95
96/* Hack to force loading of object files */
97int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
98 PyOS_mystrnicmp; /* Python/pystrcmp.o */
99
100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
104{
105 return PyImport_ImportModule("warnings");
106}
107
108static int initialized = 0;
109
110/* API to access the initialized flag -- useful for esoteric use */
111
112int
113Py_IsInitialized(void)
114{
115 return initialized;
116}
117
118/* Helper to allow an embedding application to override the normal
119 * mechanism that attempts to figure out an appropriate IO encoding
120 */
121
122static char *_Py_StandardStreamEncoding = NULL;
123static char *_Py_StandardStreamErrors = NULL;
124
125int
126Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
127{
128 if (Py_IsInitialized()) {
129 /* This is too late to have any effect */
130 return -1;
131 }
132 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
133 * initialised yet.
134 *
135 * However, the raw memory allocators are initialised appropriately
136 * as C static variables, so _PyMem_RawStrdup is OK even though
137 * Py_Initialize hasn't been called yet.
138 */
139 if (encoding) {
140 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
141 if (!_Py_StandardStreamEncoding) {
142 return -2;
143 }
144 }
145 if (errors) {
146 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
147 if (!_Py_StandardStreamErrors) {
148 if (_Py_StandardStreamEncoding) {
149 PyMem_RawFree(_Py_StandardStreamEncoding);
150 }
151 return -3;
152 }
153 }
154 return 0;
155}
156
157/* Global initializations. Can be undone by Py_Finalize(). Don't
158 call this twice without an intervening Py_Finalize() call. When
159 initializations fail, a fatal error is issued and the function does
160 not return. On return, the first thread and interpreter state have
161 been created.
162
163 Locking: you must hold the interpreter lock while calling this.
164 (If the lock has not yet been initialized, that's equivalent to
165 having the lock, but you cannot use multiple threads.)
166
167*/
168
169static int
170add_flag(int flag, const char *envs)
171{
172 int env = atoi(envs);
173 if (flag < env)
174 flag = env;
175 if (flag < 1)
176 flag = 1;
177 return flag;
178}
179
180static char*
181get_codec_name(const char *encoding)
182{
183 char *name_utf8, *name_str;
184 PyObject *codec, *name = NULL;
185
186 codec = _PyCodec_Lookup(encoding);
187 if (!codec)
188 goto error;
189
190 name = _PyObject_GetAttrId(codec, &PyId_name);
191 Py_CLEAR(codec);
192 if (!name)
193 goto error;
194
195 name_utf8 = _PyUnicode_AsString(name);
196 if (name_utf8 == NULL)
197 goto error;
198 name_str = _PyMem_RawStrdup(name_utf8);
199 Py_DECREF(name);
200 if (name_str == NULL) {
201 PyErr_NoMemory();
202 return NULL;
203 }
204 return name_str;
205
206error:
207 Py_XDECREF(codec);
208 Py_XDECREF(name);
209 return NULL;
210}
211
212static char*
213get_locale_encoding(void)
214{
215#ifdef MS_WINDOWS
216 char codepage[100];
217 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
218 return get_codec_name(codepage);
219#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
220 char* codeset = nl_langinfo(CODESET);
221 if (!codeset || codeset[0] == '\0') {
222 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
223 return NULL;
224 }
225 return get_codec_name(codeset);
226#else
227 PyErr_SetNone(PyExc_NotImplementedError);
228 return NULL;
229#endif
230}
231
232static void
233import_init(PyInterpreterState *interp, PyObject *sysmod)
234{
235 PyObject *importlib;
236 PyObject *impmod;
237 PyObject *sys_modules;
238 PyObject *value;
239
240 /* Import _importlib through its frozen version, _frozen_importlib. */
241 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
242 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
243 }
244 else if (Py_VerboseFlag) {
245 PySys_FormatStderr("import _frozen_importlib # frozen\n");
246 }
247 importlib = PyImport_AddModule("_frozen_importlib");
248 if (importlib == NULL) {
249 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
250 "sys.modules");
251 }
252 interp->importlib = importlib;
253 Py_INCREF(interp->importlib);
254
Victor Stinnercd6e6942015-09-18 09:11:57 +0200255 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000256 impmod = PyInit_imp();
257 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200258 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000259 }
260 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200261 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000262 }
263 sys_modules = PyImport_GetModuleDict();
264 if (Py_VerboseFlag) {
265 PySys_FormatStderr("import sys # builtin\n");
266 }
267 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
268 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
269 }
270
Victor Stinnercd6e6942015-09-18 09:11:57 +0200271 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000272 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
273 if (value == NULL) {
274 PyErr_Print();
275 Py_FatalError("Py_Initialize: importlib install failed");
276 }
277 Py_DECREF(value);
278 Py_DECREF(impmod);
279
280 _PyImportZip_Init();
281}
282
283
284void
285_Py_InitializeEx_Private(int install_sigs, int install_importlib)
286{
287 PyInterpreterState *interp;
288 PyThreadState *tstate;
289 PyObject *bimod, *sysmod, *pstderr;
290 char *p;
291 extern void _Py_ReadyTypes(void);
292
293 if (initialized)
294 return;
295 initialized = 1;
296 _Py_Finalizing = NULL;
297
298#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
299 /* Set up the LC_CTYPE locale, so we can obtain
300 the locale's charset without having to switch
301 locales. */
302 setlocale(LC_CTYPE, "");
303#endif
304
305 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
306 Py_DebugFlag = add_flag(Py_DebugFlag, p);
307 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
308 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
309 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
310 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
311 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
312 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
313 /* The variable is only tested for existence here; _PyRandom_Init will
314 check its value further. */
315 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
316 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
317
318 _PyRandom_Init();
319
320 interp = PyInterpreterState_New();
321 if (interp == NULL)
322 Py_FatalError("Py_Initialize: can't make first interpreter");
323
324 tstate = PyThreadState_New(interp);
325 if (tstate == NULL)
326 Py_FatalError("Py_Initialize: can't make first thread");
327 (void) PyThreadState_Swap(tstate);
328
329#ifdef WITH_THREAD
330 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
331 destroying the GIL might fail when it is being referenced from
332 another running thread (see issue #9901).
333 Instead we destroy the previously created GIL here, which ensures
334 that we can call Py_Initialize / Py_Finalize multiple times. */
335 _PyEval_FiniThreads();
336
337 /* Auto-thread-state API */
338 _PyGILState_Init(interp, tstate);
339#endif /* WITH_THREAD */
340
341 _Py_ReadyTypes();
342
343 if (!_PyFrame_Init())
344 Py_FatalError("Py_Initialize: can't init frames");
345
346 if (!_PyLong_Init())
347 Py_FatalError("Py_Initialize: can't init longs");
348
349 if (!PyByteArray_Init())
350 Py_FatalError("Py_Initialize: can't init bytearray");
351
352 if (!_PyFloat_Init())
353 Py_FatalError("Py_Initialize: can't init float");
354
355 interp->modules = PyDict_New();
356 if (interp->modules == NULL)
357 Py_FatalError("Py_Initialize: can't make modules dictionary");
358
359 /* Init Unicode implementation; relies on the codec registry */
360 if (_PyUnicode_Init() < 0)
361 Py_FatalError("Py_Initialize: can't initialize unicode");
362 if (_PyStructSequence_Init() < 0)
363 Py_FatalError("Py_Initialize: can't initialize structseq");
364
365 bimod = _PyBuiltin_Init();
366 if (bimod == NULL)
367 Py_FatalError("Py_Initialize: can't initialize builtins modules");
368 _PyImport_FixupBuiltin(bimod, "builtins");
369 interp->builtins = PyModule_GetDict(bimod);
370 if (interp->builtins == NULL)
371 Py_FatalError("Py_Initialize: can't initialize builtins dict");
372 Py_INCREF(interp->builtins);
373
374 /* initialize builtin exceptions */
375 _PyExc_Init(bimod);
376
377 sysmod = _PySys_Init();
378 if (sysmod == NULL)
379 Py_FatalError("Py_Initialize: can't initialize sys");
380 interp->sysdict = PyModule_GetDict(sysmod);
381 if (interp->sysdict == NULL)
382 Py_FatalError("Py_Initialize: can't initialize sys dict");
383 Py_INCREF(interp->sysdict);
384 _PyImport_FixupBuiltin(sysmod, "sys");
385 PySys_SetPath(Py_GetPath());
386 PyDict_SetItemString(interp->sysdict, "modules",
387 interp->modules);
388
389 /* Set up a preliminary stderr printer until we have enough
390 infrastructure for the io module in place. */
391 pstderr = PyFile_NewStdPrinter(fileno(stderr));
392 if (pstderr == NULL)
393 Py_FatalError("Py_Initialize: can't set preliminary stderr");
394 _PySys_SetObjectId(&PyId_stderr, pstderr);
395 PySys_SetObject("__stderr__", pstderr);
396 Py_DECREF(pstderr);
397
398 _PyImport_Init();
399
400 _PyImportHooks_Init();
401
402 /* Initialize _warnings. */
403 _PyWarnings_Init();
404
405 if (!install_importlib)
406 return;
407
Victor Stinner13019fd2015-04-03 13:10:54 +0200408 if (_PyTime_Init() < 0)
409 Py_FatalError("Py_Initialize: can't initialize time");
410
Nick Coghland6009512014-11-20 21:39:37 +1000411 import_init(interp, sysmod);
412
413 /* initialize the faulthandler module */
414 if (_PyFaulthandler_Init())
415 Py_FatalError("Py_Initialize: can't initialize faulthandler");
416
Nick Coghland6009512014-11-20 21:39:37 +1000417 if (initfsencoding(interp) < 0)
418 Py_FatalError("Py_Initialize: unable to load the file system codec");
419
420 if (install_sigs)
421 initsigs(); /* Signal handling stuff, including initintr() */
422
423 if (_PyTraceMalloc_Init() < 0)
424 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
425
426 initmain(interp); /* Module __main__ */
427 if (initstdio() < 0)
428 Py_FatalError(
429 "Py_Initialize: can't initialize sys standard streams");
430
431 /* Initialize warnings. */
432 if (PySys_HasWarnOptions()) {
433 PyObject *warnings_module = PyImport_ImportModule("warnings");
434 if (warnings_module == NULL) {
435 fprintf(stderr, "'import warnings' failed; traceback:\n");
436 PyErr_Print();
437 }
438 Py_XDECREF(warnings_module);
439 }
440
441 if (!Py_NoSiteFlag)
442 initsite(); /* Module site */
443}
444
445void
446Py_InitializeEx(int install_sigs)
447{
448 _Py_InitializeEx_Private(install_sigs, 1);
449}
450
451void
452Py_Initialize(void)
453{
454 Py_InitializeEx(1);
455}
456
457
458#ifdef COUNT_ALLOCS
459extern void dump_counts(FILE*);
460#endif
461
462/* Flush stdout and stderr */
463
464static int
465file_is_closed(PyObject *fobj)
466{
467 int r;
468 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
469 if (tmp == NULL) {
470 PyErr_Clear();
471 return 0;
472 }
473 r = PyObject_IsTrue(tmp);
474 Py_DECREF(tmp);
475 if (r < 0)
476 PyErr_Clear();
477 return r > 0;
478}
479
480static void
481flush_std_files(void)
482{
483 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
484 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
485 PyObject *tmp;
486
487 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
488 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
489 if (tmp == NULL)
490 PyErr_WriteUnraisable(fout);
491 else
492 Py_DECREF(tmp);
493 }
494
495 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
496 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
497 if (tmp == NULL)
498 PyErr_Clear();
499 else
500 Py_DECREF(tmp);
501 }
502}
503
504/* Undo the effect of Py_Initialize().
505
506 Beware: if multiple interpreter and/or thread states exist, these
507 are not wiped out; only the current thread and interpreter state
508 are deleted. But since everything else is deleted, those other
509 interpreter and thread states should no longer be used.
510
511 (XXX We should do better, e.g. wipe out all interpreters and
512 threads.)
513
514 Locking: as above.
515
516*/
517
518void
519Py_Finalize(void)
520{
521 PyInterpreterState *interp;
522 PyThreadState *tstate;
523
524 if (!initialized)
525 return;
526
527 wait_for_thread_shutdown();
528
529 /* The interpreter is still entirely intact at this point, and the
530 * exit funcs may be relying on that. In particular, if some thread
531 * or exit func is still waiting to do an import, the import machinery
532 * expects Py_IsInitialized() to return true. So don't say the
533 * interpreter is uninitialized until after the exit funcs have run.
534 * Note that Threading.py uses an exit func to do a join on all the
535 * threads created thru it, so this also protects pending imports in
536 * the threads created via Threading.
537 */
538 call_py_exitfuncs();
539
540 /* Get current thread state and interpreter pointer */
541 tstate = PyThreadState_GET();
542 interp = tstate->interp;
543
544 /* Remaining threads (e.g. daemon threads) will automatically exit
545 after taking the GIL (in PyEval_RestoreThread()). */
546 _Py_Finalizing = tstate;
547 initialized = 0;
548
Victor Stinnere0deff32015-03-24 13:46:18 +0100549 /* Flush sys.stdout and sys.stderr */
Nick Coghland6009512014-11-20 21:39:37 +1000550 flush_std_files();
551
552 /* Disable signal handling */
553 PyOS_FiniInterrupts();
554
555 /* Collect garbage. This may call finalizers; it's nice to call these
556 * before all modules are destroyed.
557 * XXX If a __del__ or weakref callback is triggered here, and tries to
558 * XXX import a module, bad things can happen, because Python no
559 * XXX longer believes it's initialized.
560 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
561 * XXX is easy to provoke that way. I've also seen, e.g.,
562 * XXX Exception exceptions.ImportError: 'No module named sha'
563 * XXX in <function callback at 0x008F5718> ignored
564 * XXX but I'm unclear on exactly how that one happens. In any case,
565 * XXX I haven't seen a real-life report of either of these.
566 */
567 PyGC_Collect();
568#ifdef COUNT_ALLOCS
569 /* With COUNT_ALLOCS, it helps to run GC multiple times:
570 each collection might release some types from the type
571 list, so they become garbage. */
572 while (PyGC_Collect() > 0)
573 /* nothing */;
574#endif
575 /* Destroy all modules */
576 PyImport_Cleanup();
577
Victor Stinnere0deff32015-03-24 13:46:18 +0100578 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Nick Coghland6009512014-11-20 21:39:37 +1000579 flush_std_files();
580
581 /* Collect final garbage. This disposes of cycles created by
582 * class definitions, for example.
583 * XXX This is disabled because it caused too many problems. If
584 * XXX a __del__ or weakref callback triggers here, Python code has
585 * XXX a hard time running, because even the sys module has been
586 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
587 * XXX One symptom is a sequence of information-free messages
588 * XXX coming from threads (if a __del__ or callback is invoked,
589 * XXX other threads can execute too, and any exception they encounter
590 * XXX triggers a comedy of errors as subsystem after subsystem
591 * XXX fails to find what it *expects* to find in sys to help report
592 * XXX the exception and consequent unexpected failures). I've also
593 * XXX seen segfaults then, after adding print statements to the
594 * XXX Python code getting called.
595 */
596#if 0
597 PyGC_Collect();
598#endif
599
600 /* Disable tracemalloc after all Python objects have been destroyed,
601 so it is possible to use tracemalloc in objects destructor. */
602 _PyTraceMalloc_Fini();
603
604 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
605 _PyImport_Fini();
606
607 /* Cleanup typeobject.c's internal caches. */
608 _PyType_Fini();
609
610 /* unload faulthandler module */
611 _PyFaulthandler_Fini();
612
613 /* Debugging stuff */
614#ifdef COUNT_ALLOCS
615 dump_counts(stdout);
616#endif
617 /* dump hash stats */
618 _PyHash_Fini();
619
620 _PY_DEBUG_PRINT_TOTAL_REFS();
621
622#ifdef Py_TRACE_REFS
623 /* Display all objects still alive -- this can invoke arbitrary
624 * __repr__ overrides, so requires a mostly-intact interpreter.
625 * Alas, a lot of stuff may still be alive now that will be cleaned
626 * up later.
627 */
628 if (Py_GETENV("PYTHONDUMPREFS"))
629 _Py_PrintReferences(stderr);
630#endif /* Py_TRACE_REFS */
631
632 /* Clear interpreter state and all thread states. */
633 PyInterpreterState_Clear(interp);
634
635 /* Now we decref the exception classes. After this point nothing
636 can raise an exception. That's okay, because each Fini() method
637 below has been checked to make sure no exceptions are ever
638 raised.
639 */
640
641 _PyExc_Fini();
642
643 /* Sundry finalizers */
644 PyMethod_Fini();
645 PyFrame_Fini();
646 PyCFunction_Fini();
647 PyTuple_Fini();
648 PyList_Fini();
649 PySet_Fini();
650 PyBytes_Fini();
651 PyByteArray_Fini();
652 PyLong_Fini();
653 PyFloat_Fini();
654 PyDict_Fini();
655 PySlice_Fini();
656 _PyGC_Fini();
657 _PyRandom_Fini();
658
659 /* Cleanup Unicode implementation */
660 _PyUnicode_Fini();
661
662 /* reset file system default encoding */
663 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
664 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
665 Py_FileSystemDefaultEncoding = NULL;
666 }
667
668 /* XXX Still allocated:
669 - various static ad-hoc pointers to interned strings
670 - int and float free list blocks
671 - whatever various modules and libraries allocate
672 */
673
674 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
675
676 /* Cleanup auto-thread-state */
677#ifdef WITH_THREAD
678 _PyGILState_Fini();
679#endif /* WITH_THREAD */
680
681 /* Delete current thread. After this, many C API calls become crashy. */
682 PyThreadState_Swap(NULL);
683 PyInterpreterState_Delete(interp);
684
685#ifdef Py_TRACE_REFS
686 /* Display addresses (& refcnts) of all objects still alive.
687 * An address can be used to find the repr of the object, printed
688 * above by _Py_PrintReferences.
689 */
690 if (Py_GETENV("PYTHONDUMPREFS"))
691 _Py_PrintReferenceAddresses(stderr);
692#endif /* Py_TRACE_REFS */
693#ifdef PYMALLOC_DEBUG
694 if (Py_GETENV("PYTHONMALLOCSTATS"))
695 _PyObject_DebugMallocStats(stderr);
696#endif
697
698 call_ll_exitfuncs();
699}
700
701/* Create and initialize a new interpreter and thread, and return the
702 new thread. This requires that Py_Initialize() has been called
703 first.
704
705 Unsuccessful initialization yields a NULL pointer. Note that *no*
706 exception information is available even in this case -- the
707 exception information is held in the thread, and there is no
708 thread.
709
710 Locking: as above.
711
712*/
713
714PyThreadState *
715Py_NewInterpreter(void)
716{
717 PyInterpreterState *interp;
718 PyThreadState *tstate, *save_tstate;
719 PyObject *bimod, *sysmod;
720
721 if (!initialized)
722 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
723
724 interp = PyInterpreterState_New();
725 if (interp == NULL)
726 return NULL;
727
728 tstate = PyThreadState_New(interp);
729 if (tstate == NULL) {
730 PyInterpreterState_Delete(interp);
731 return NULL;
732 }
733
734 save_tstate = PyThreadState_Swap(tstate);
735
736 /* XXX The following is lax in error checking */
737
738 interp->modules = PyDict_New();
739
740 bimod = _PyImport_FindBuiltin("builtins");
741 if (bimod != NULL) {
742 interp->builtins = PyModule_GetDict(bimod);
743 if (interp->builtins == NULL)
744 goto handle_error;
745 Py_INCREF(interp->builtins);
746 }
747
748 /* initialize builtin exceptions */
749 _PyExc_Init(bimod);
750
751 sysmod = _PyImport_FindBuiltin("sys");
752 if (bimod != NULL && sysmod != NULL) {
753 PyObject *pstderr;
754
755 interp->sysdict = PyModule_GetDict(sysmod);
756 if (interp->sysdict == NULL)
757 goto handle_error;
758 Py_INCREF(interp->sysdict);
759 PySys_SetPath(Py_GetPath());
760 PyDict_SetItemString(interp->sysdict, "modules",
761 interp->modules);
762 /* Set up a preliminary stderr printer until we have enough
763 infrastructure for the io module in place. */
764 pstderr = PyFile_NewStdPrinter(fileno(stderr));
765 if (pstderr == NULL)
766 Py_FatalError("Py_Initialize: can't set preliminary stderr");
767 _PySys_SetObjectId(&PyId_stderr, pstderr);
768 PySys_SetObject("__stderr__", pstderr);
769 Py_DECREF(pstderr);
770
771 _PyImportHooks_Init();
772
773 import_init(interp, sysmod);
774
775 if (initfsencoding(interp) < 0)
776 goto handle_error;
777
778 if (initstdio() < 0)
779 Py_FatalError(
780 "Py_Initialize: can't initialize sys standard streams");
781 initmain(interp);
782 if (!Py_NoSiteFlag)
783 initsite();
784 }
785
786 if (!PyErr_Occurred())
787 return tstate;
788
789handle_error:
790 /* Oops, it didn't work. Undo it all. */
791
792 PyErr_PrintEx(0);
793 PyThreadState_Clear(tstate);
794 PyThreadState_Swap(save_tstate);
795 PyThreadState_Delete(tstate);
796 PyInterpreterState_Delete(interp);
797
798 return NULL;
799}
800
801/* Delete an interpreter and its last thread. This requires that the
802 given thread state is current, that the thread has no remaining
803 frames, and that it is its interpreter's only remaining thread.
804 It is a fatal error to violate these constraints.
805
806 (Py_Finalize() doesn't have these constraints -- it zaps
807 everything, regardless.)
808
809 Locking: as above.
810
811*/
812
813void
814Py_EndInterpreter(PyThreadState *tstate)
815{
816 PyInterpreterState *interp = tstate->interp;
817
818 if (tstate != PyThreadState_GET())
819 Py_FatalError("Py_EndInterpreter: thread is not current");
820 if (tstate->frame != NULL)
821 Py_FatalError("Py_EndInterpreter: thread still has a frame");
822
823 wait_for_thread_shutdown();
824
825 if (tstate != interp->tstate_head || tstate->next != NULL)
826 Py_FatalError("Py_EndInterpreter: not the last thread");
827
828 PyImport_Cleanup();
829 PyInterpreterState_Clear(interp);
830 PyThreadState_Swap(NULL);
831 PyInterpreterState_Delete(interp);
832}
833
834#ifdef MS_WINDOWS
835static wchar_t *progname = L"python";
836#else
837static wchar_t *progname = L"python3";
838#endif
839
840void
841Py_SetProgramName(wchar_t *pn)
842{
843 if (pn && *pn)
844 progname = pn;
845}
846
847wchar_t *
848Py_GetProgramName(void)
849{
850 return progname;
851}
852
853static wchar_t *default_home = NULL;
854static wchar_t env_home[MAXPATHLEN+1];
855
856void
857Py_SetPythonHome(wchar_t *home)
858{
859 default_home = home;
860}
861
862wchar_t *
863Py_GetPythonHome(void)
864{
865 wchar_t *home = default_home;
866 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
867 char* chome = Py_GETENV("PYTHONHOME");
868 if (chome) {
869 size_t size = Py_ARRAY_LENGTH(env_home);
870 size_t r = mbstowcs(env_home, chome, size);
871 if (r != (size_t)-1 && r < size)
872 home = env_home;
873 }
874
875 }
876 return home;
877}
878
879/* Create __main__ module */
880
881static void
882initmain(PyInterpreterState *interp)
883{
884 PyObject *m, *d, *loader;
885 m = PyImport_AddModule("__main__");
886 if (m == NULL)
887 Py_FatalError("can't create __main__ module");
888 d = PyModule_GetDict(m);
889 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
890 PyObject *bimod = PyImport_ImportModule("builtins");
891 if (bimod == NULL) {
892 Py_FatalError("Failed to retrieve builtins module");
893 }
894 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
895 Py_FatalError("Failed to initialize __main__.__builtins__");
896 }
897 Py_DECREF(bimod);
898 }
899 /* Main is a little special - imp.is_builtin("__main__") will return
900 * False, but BuiltinImporter is still the most appropriate initial
901 * setting for its __loader__ attribute. A more suitable value will
902 * be set if __main__ gets further initialized later in the startup
903 * process.
904 */
905 loader = PyDict_GetItemString(d, "__loader__");
906 if (loader == NULL || loader == Py_None) {
907 PyObject *loader = PyObject_GetAttrString(interp->importlib,
908 "BuiltinImporter");
909 if (loader == NULL) {
910 Py_FatalError("Failed to retrieve BuiltinImporter");
911 }
912 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
913 Py_FatalError("Failed to initialize __main__.__loader__");
914 }
915 Py_DECREF(loader);
916 }
917}
918
919static int
920initfsencoding(PyInterpreterState *interp)
921{
922 PyObject *codec;
923
924 if (Py_FileSystemDefaultEncoding == NULL)
925 {
926 Py_FileSystemDefaultEncoding = get_locale_encoding();
927 if (Py_FileSystemDefaultEncoding == NULL)
928 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
929
930 Py_HasFileSystemDefaultEncoding = 0;
931 interp->fscodec_initialized = 1;
932 return 0;
933 }
934
935 /* the encoding is mbcs, utf-8 or ascii */
936 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
937 if (!codec) {
938 /* Such error can only occurs in critical situations: no more
939 * memory, import a module of the standard library failed,
940 * etc. */
941 return -1;
942 }
943 Py_DECREF(codec);
944 interp->fscodec_initialized = 1;
945 return 0;
946}
947
948/* Import the site module (not into __main__ though) */
949
950static void
951initsite(void)
952{
953 PyObject *m;
954 m = PyImport_ImportModule("site");
955 if (m == NULL) {
956 fprintf(stderr, "Failed to import the site module\n");
957 PyErr_Print();
958 Py_Finalize();
959 exit(1);
960 }
961 else {
962 Py_DECREF(m);
963 }
964}
965
Victor Stinner874dbe82015-09-04 17:29:57 +0200966/* Check if a file descriptor is valid or not.
967 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
968static int
969is_valid_fd(int fd)
970{
971 int fd2;
972 if (fd < 0 || !_PyVerify_fd(fd))
973 return 0;
974 _Py_BEGIN_SUPPRESS_IPH
975 fd2 = dup(fd);
976 if (fd2 >= 0)
977 close(fd2);
978 _Py_END_SUPPRESS_IPH
979 return fd2 >= 0;
980}
981
982/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +1000983static PyObject*
984create_stdio(PyObject* io,
985 int fd, int write_mode, char* name,
986 char* encoding, char* errors)
987{
988 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
989 const char* mode;
990 const char* newline;
991 PyObject *line_buffering;
992 int buffering, isatty;
993 _Py_IDENTIFIER(open);
994 _Py_IDENTIFIER(isatty);
995 _Py_IDENTIFIER(TextIOWrapper);
996 _Py_IDENTIFIER(mode);
997
Victor Stinner874dbe82015-09-04 17:29:57 +0200998 if (!is_valid_fd(fd))
999 Py_RETURN_NONE;
1000
Nick Coghland6009512014-11-20 21:39:37 +10001001 /* stdin is always opened in buffered mode, first because it shouldn't
1002 make a difference in common use cases, second because TextIOWrapper
1003 depends on the presence of a read1() method which only exists on
1004 buffered streams.
1005 */
1006 if (Py_UnbufferedStdioFlag && write_mode)
1007 buffering = 0;
1008 else
1009 buffering = -1;
1010 if (write_mode)
1011 mode = "wb";
1012 else
1013 mode = "rb";
1014 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1015 fd, mode, buffering,
1016 Py_None, Py_None, Py_None, 0);
1017 if (buf == NULL)
1018 goto error;
1019
1020 if (buffering) {
1021 _Py_IDENTIFIER(raw);
1022 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1023 if (raw == NULL)
1024 goto error;
1025 }
1026 else {
1027 raw = buf;
1028 Py_INCREF(raw);
1029 }
1030
1031 text = PyUnicode_FromString(name);
1032 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1033 goto error;
1034 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1035 if (res == NULL)
1036 goto error;
1037 isatty = PyObject_IsTrue(res);
1038 Py_DECREF(res);
1039 if (isatty == -1)
1040 goto error;
1041 if (isatty || Py_UnbufferedStdioFlag)
1042 line_buffering = Py_True;
1043 else
1044 line_buffering = Py_False;
1045
1046 Py_CLEAR(raw);
1047 Py_CLEAR(text);
1048
1049#ifdef MS_WINDOWS
1050 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1051 newlines to "\n".
1052 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1053 newline = NULL;
1054#else
1055 /* sys.stdin: split lines at "\n".
1056 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1057 newline = "\n";
1058#endif
1059
1060 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1061 buf, encoding, errors,
1062 newline, line_buffering);
1063 Py_CLEAR(buf);
1064 if (stream == NULL)
1065 goto error;
1066
1067 if (write_mode)
1068 mode = "w";
1069 else
1070 mode = "r";
1071 text = PyUnicode_FromString(mode);
1072 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1073 goto error;
1074 Py_CLEAR(text);
1075 return stream;
1076
1077error:
1078 Py_XDECREF(buf);
1079 Py_XDECREF(stream);
1080 Py_XDECREF(text);
1081 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001082
Victor Stinner874dbe82015-09-04 17:29:57 +02001083 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1084 /* Issue #24891: the file descriptor was closed after the first
1085 is_valid_fd() check was called. Ignore the OSError and set the
1086 stream to None. */
1087 PyErr_Clear();
1088 Py_RETURN_NONE;
1089 }
1090 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001091}
1092
1093/* Initialize sys.stdin, stdout, stderr and builtins.open */
1094static int
1095initstdio(void)
1096{
1097 PyObject *iomod = NULL, *wrapper;
1098 PyObject *bimod = NULL;
1099 PyObject *m;
1100 PyObject *std = NULL;
1101 int status = 0, fd;
1102 PyObject * encoding_attr;
1103 char *pythonioencoding = NULL, *encoding, *errors;
1104
1105 /* Hack to avoid a nasty recursion issue when Python is invoked
1106 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1107 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1108 goto error;
1109 }
1110 Py_DECREF(m);
1111
1112 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1113 goto error;
1114 }
1115 Py_DECREF(m);
1116
1117 if (!(bimod = PyImport_ImportModule("builtins"))) {
1118 goto error;
1119 }
1120
1121 if (!(iomod = PyImport_ImportModule("io"))) {
1122 goto error;
1123 }
1124 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1125 goto error;
1126 }
1127
1128 /* Set builtins.open */
1129 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1130 Py_DECREF(wrapper);
1131 goto error;
1132 }
1133 Py_DECREF(wrapper);
1134
1135 encoding = _Py_StandardStreamEncoding;
1136 errors = _Py_StandardStreamErrors;
1137 if (!encoding || !errors) {
1138 if (!errors) {
1139 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1140 stdin and stdout use the surrogateescape error handler by
1141 default, instead of the strict error handler. */
1142 char *loc = setlocale(LC_CTYPE, NULL);
1143 if (loc != NULL && strcmp(loc, "C") == 0)
1144 errors = "surrogateescape";
1145 }
1146
1147 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1148 if (pythonioencoding) {
1149 char *err;
1150 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1151 if (pythonioencoding == NULL) {
1152 PyErr_NoMemory();
1153 goto error;
1154 }
1155 err = strchr(pythonioencoding, ':');
1156 if (err) {
1157 *err = '\0';
1158 err++;
1159 if (*err && !_Py_StandardStreamErrors) {
1160 errors = err;
1161 }
1162 }
1163 if (*pythonioencoding && !encoding) {
1164 encoding = pythonioencoding;
1165 }
1166 }
1167 }
1168
1169 /* Set sys.stdin */
1170 fd = fileno(stdin);
1171 /* Under some conditions stdin, stdout and stderr may not be connected
1172 * and fileno() may point to an invalid file descriptor. For example
1173 * GUI apps don't have valid standard streams by default.
1174 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001175 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1176 if (std == NULL)
1177 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001178 PySys_SetObject("__stdin__", std);
1179 _PySys_SetObjectId(&PyId_stdin, std);
1180 Py_DECREF(std);
1181
1182 /* Set sys.stdout */
1183 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001184 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1185 if (std == NULL)
1186 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001187 PySys_SetObject("__stdout__", std);
1188 _PySys_SetObjectId(&PyId_stdout, std);
1189 Py_DECREF(std);
1190
1191#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1192 /* Set sys.stderr, replaces the preliminary stderr */
1193 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001194 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1195 if (std == NULL)
1196 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001197
1198 /* Same as hack above, pre-import stderr's codec to avoid recursion
1199 when import.c tries to write to stderr in verbose mode. */
1200 encoding_attr = PyObject_GetAttrString(std, "encoding");
1201 if (encoding_attr != NULL) {
1202 const char * std_encoding;
1203 std_encoding = _PyUnicode_AsString(encoding_attr);
1204 if (std_encoding != NULL) {
1205 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1206 Py_XDECREF(codec_info);
1207 }
1208 Py_DECREF(encoding_attr);
1209 }
1210 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1211
1212 if (PySys_SetObject("__stderr__", std) < 0) {
1213 Py_DECREF(std);
1214 goto error;
1215 }
1216 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1217 Py_DECREF(std);
1218 goto error;
1219 }
1220 Py_DECREF(std);
1221#endif
1222
1223 if (0) {
1224 error:
1225 status = -1;
1226 }
1227
1228 /* We won't need them anymore. */
1229 if (_Py_StandardStreamEncoding) {
1230 PyMem_RawFree(_Py_StandardStreamEncoding);
1231 _Py_StandardStreamEncoding = NULL;
1232 }
1233 if (_Py_StandardStreamErrors) {
1234 PyMem_RawFree(_Py_StandardStreamErrors);
1235 _Py_StandardStreamErrors = NULL;
1236 }
1237 PyMem_Free(pythonioencoding);
1238 Py_XDECREF(bimod);
1239 Py_XDECREF(iomod);
1240 return status;
1241}
1242
1243
Victor Stinner10dc4842015-03-24 12:01:30 +01001244/* Print the current exception (if an exception is set) with its traceback,
1245 * or display the current Python stack.
1246 *
1247 * Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1248 * called on catastrophic cases. */
1249
1250static void
1251_Py_PrintFatalError(int fd)
1252{
Victor Stinnere0deff32015-03-24 13:46:18 +01001253 PyObject *ferr, *res;
Victor Stinner10dc4842015-03-24 12:01:30 +01001254 PyObject *exception, *v, *tb;
1255 int has_tb;
1256 PyThreadState *tstate;
1257
1258 PyErr_Fetch(&exception, &v, &tb);
1259 if (exception == NULL) {
1260 /* No current exception */
1261 goto display_stack;
1262 }
1263
Victor Stinnere0deff32015-03-24 13:46:18 +01001264 ferr = _PySys_GetObjectId(&PyId_stderr);
1265 if (ferr == NULL || ferr == Py_None) {
1266 /* sys.stderr is not set yet or set to None,
1267 no need to try to display the exception */
1268 goto display_stack;
1269 }
1270
Victor Stinner10dc4842015-03-24 12:01:30 +01001271 PyErr_NormalizeException(&exception, &v, &tb);
1272 if (tb == NULL) {
1273 tb = Py_None;
1274 Py_INCREF(tb);
1275 }
1276 PyException_SetTraceback(v, tb);
1277 if (exception == NULL) {
Victor Stinnere0deff32015-03-24 13:46:18 +01001278 /* PyErr_NormalizeException() failed */
Victor Stinner10dc4842015-03-24 12:01:30 +01001279 goto display_stack;
1280 }
1281
Christian Heimese8e42832015-04-16 17:25:45 +02001282 has_tb = (tb != Py_None);
Victor Stinner10dc4842015-03-24 12:01:30 +01001283 PyErr_Display(exception, v, tb);
1284 Py_XDECREF(exception);
1285 Py_XDECREF(v);
1286 Py_XDECREF(tb);
Victor Stinnere0deff32015-03-24 13:46:18 +01001287
1288 /* sys.stderr may be buffered: call sys.stderr.flush() */
1289 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1290 if (res == NULL)
1291 PyErr_Clear();
1292 else
1293 Py_DECREF(res);
1294
Victor Stinner10dc4842015-03-24 12:01:30 +01001295 if (has_tb)
1296 return;
1297
1298display_stack:
Benjamin Peterson55c14352015-04-06 09:59:23 -04001299#ifdef WITH_THREAD
Victor Stinner10dc4842015-03-24 12:01:30 +01001300 /* PyGILState_GetThisThreadState() works even if the GIL was released */
1301 tstate = PyGILState_GetThisThreadState();
Benjamin Peterson55c14352015-04-06 09:59:23 -04001302#else
1303 tstate = PyThreadState_GET();
1304#endif
Victor Stinner10dc4842015-03-24 12:01:30 +01001305 if (tstate == NULL) {
1306 /* _Py_DumpTracebackThreads() requires the thread state to display
1307 * frames */
1308 return;
1309 }
1310
1311 fputc('\n', stderr);
1312 fflush(stderr);
1313
1314 /* display the current Python stack */
1315 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
1316}
Nick Coghland6009512014-11-20 21:39:37 +10001317/* Print fatal error message and abort */
1318
1319void
1320Py_FatalError(const char *msg)
1321{
1322 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001323 static int reentrant = 0;
1324#ifdef MS_WINDOWS
1325 size_t len;
1326 WCHAR* buffer;
1327 size_t i;
1328#endif
1329
1330 if (reentrant) {
1331 /* Py_FatalError() caused a second fatal error.
1332 Example: flush_std_files() raises a recursion error. */
1333 goto exit;
1334 }
1335 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001336
1337 fprintf(stderr, "Fatal Python error: %s\n", msg);
1338 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001339
Victor Stinnere0deff32015-03-24 13:46:18 +01001340 /* Print the exception (if an exception is set) with its traceback,
1341 * or display the current Python stack. */
Victor Stinner10dc4842015-03-24 12:01:30 +01001342 _Py_PrintFatalError(fd);
1343
Victor Stinnere0deff32015-03-24 13:46:18 +01001344 /* Flush sys.stdout and sys.stderr */
1345 flush_std_files();
1346
Victor Stinner10dc4842015-03-24 12:01:30 +01001347 /* The main purpose of faulthandler is to display the traceback. We already
Victor Stinnere0deff32015-03-24 13:46:18 +01001348 * did our best to display it. So faulthandler can now be disabled.
1349 * (Don't trigger it on abort().) */
Victor Stinner10dc4842015-03-24 12:01:30 +01001350 _PyFaulthandler_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001351
1352#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001353 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001354
Victor Stinner53345a42015-03-25 01:55:14 +01001355 /* Convert the message to wchar_t. This uses a simple one-to-one
1356 conversion, assuming that the this error message actually uses ASCII
1357 only. If this ceases to be true, we will have to convert. */
1358 buffer = alloca( (len+1) * (sizeof *buffer));
1359 for( i=0; i<=len; ++i)
1360 buffer[i] = msg[i];
1361 OutputDebugStringW(L"Fatal Python error: ");
1362 OutputDebugStringW(buffer);
1363 OutputDebugStringW(L"\n");
1364#endif /* MS_WINDOWS */
1365
1366exit:
1367#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001368 DebugBreak();
1369#endif
Nick Coghland6009512014-11-20 21:39:37 +10001370 abort();
1371}
1372
1373/* Clean up and exit */
1374
1375#ifdef WITH_THREAD
1376#include "pythread.h"
1377#endif
1378
1379static void (*pyexitfunc)(void) = NULL;
1380/* For the atexit module. */
1381void _Py_PyAtExit(void (*func)(void))
1382{
1383 pyexitfunc = func;
1384}
1385
1386static void
1387call_py_exitfuncs(void)
1388{
1389 if (pyexitfunc == NULL)
1390 return;
1391
1392 (*pyexitfunc)();
1393 PyErr_Clear();
1394}
1395
1396/* Wait until threading._shutdown completes, provided
1397 the threading module was imported in the first place.
1398 The shutdown routine will wait until all non-daemon
1399 "threading" threads have completed. */
1400static void
1401wait_for_thread_shutdown(void)
1402{
1403#ifdef WITH_THREAD
1404 _Py_IDENTIFIER(_shutdown);
1405 PyObject *result;
1406 PyThreadState *tstate = PyThreadState_GET();
1407 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1408 "threading");
1409 if (threading == NULL) {
1410 /* threading not imported */
1411 PyErr_Clear();
1412 return;
1413 }
1414 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1415 if (result == NULL) {
1416 PyErr_WriteUnraisable(threading);
1417 }
1418 else {
1419 Py_DECREF(result);
1420 }
1421 Py_DECREF(threading);
1422#endif
1423}
1424
1425#define NEXITFUNCS 32
1426static void (*exitfuncs[NEXITFUNCS])(void);
1427static int nexitfuncs = 0;
1428
1429int Py_AtExit(void (*func)(void))
1430{
1431 if (nexitfuncs >= NEXITFUNCS)
1432 return -1;
1433 exitfuncs[nexitfuncs++] = func;
1434 return 0;
1435}
1436
1437static void
1438call_ll_exitfuncs(void)
1439{
1440 while (nexitfuncs > 0)
1441 (*exitfuncs[--nexitfuncs])();
1442
1443 fflush(stdout);
1444 fflush(stderr);
1445}
1446
1447void
1448Py_Exit(int sts)
1449{
1450 Py_Finalize();
1451
1452 exit(sts);
1453}
1454
1455static void
1456initsigs(void)
1457{
1458#ifdef SIGPIPE
1459 PyOS_setsig(SIGPIPE, SIG_IGN);
1460#endif
1461#ifdef SIGXFZ
1462 PyOS_setsig(SIGXFZ, SIG_IGN);
1463#endif
1464#ifdef SIGXFSZ
1465 PyOS_setsig(SIGXFSZ, SIG_IGN);
1466#endif
1467 PyOS_InitInterrupts(); /* May imply initsignal() */
1468 if (PyErr_Occurred()) {
1469 Py_FatalError("Py_Initialize: can't import signal");
1470 }
1471}
1472
1473
1474/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1475 *
1476 * All of the code in this function must only use async-signal-safe functions,
1477 * listed at `man 7 signal` or
1478 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1479 */
1480void
1481_Py_RestoreSignals(void)
1482{
1483#ifdef SIGPIPE
1484 PyOS_setsig(SIGPIPE, SIG_DFL);
1485#endif
1486#ifdef SIGXFZ
1487 PyOS_setsig(SIGXFZ, SIG_DFL);
1488#endif
1489#ifdef SIGXFSZ
1490 PyOS_setsig(SIGXFSZ, SIG_DFL);
1491#endif
1492}
1493
1494
1495/*
1496 * The file descriptor fd is considered ``interactive'' if either
1497 * a) isatty(fd) is TRUE, or
1498 * b) the -i flag was given, and the filename associated with
1499 * the descriptor is NULL or "<stdin>" or "???".
1500 */
1501int
1502Py_FdIsInteractive(FILE *fp, const char *filename)
1503{
1504 if (isatty((int)fileno(fp)))
1505 return 1;
1506 if (!Py_InteractiveFlag)
1507 return 0;
1508 return (filename == NULL) ||
1509 (strcmp(filename, "<stdin>") == 0) ||
1510 (strcmp(filename, "???") == 0);
1511}
1512
1513
Nick Coghland6009512014-11-20 21:39:37 +10001514/* Wrappers around sigaction() or signal(). */
1515
1516PyOS_sighandler_t
1517PyOS_getsig(int sig)
1518{
1519#ifdef HAVE_SIGACTION
1520 struct sigaction context;
1521 if (sigaction(sig, NULL, &context) == -1)
1522 return SIG_ERR;
1523 return context.sa_handler;
1524#else
1525 PyOS_sighandler_t handler;
1526/* Special signal handling for the secure CRT in Visual Studio 2005 */
1527#if defined(_MSC_VER) && _MSC_VER >= 1400
1528 switch (sig) {
1529 /* Only these signals are valid */
1530 case SIGINT:
1531 case SIGILL:
1532 case SIGFPE:
1533 case SIGSEGV:
1534 case SIGTERM:
1535 case SIGBREAK:
1536 case SIGABRT:
1537 break;
1538 /* Don't call signal() with other values or it will assert */
1539 default:
1540 return SIG_ERR;
1541 }
1542#endif /* _MSC_VER && _MSC_VER >= 1400 */
1543 handler = signal(sig, SIG_IGN);
1544 if (handler != SIG_ERR)
1545 signal(sig, handler);
1546 return handler;
1547#endif
1548}
1549
1550/*
1551 * All of the code in this function must only use async-signal-safe functions,
1552 * listed at `man 7 signal` or
1553 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1554 */
1555PyOS_sighandler_t
1556PyOS_setsig(int sig, PyOS_sighandler_t handler)
1557{
1558#ifdef HAVE_SIGACTION
1559 /* Some code in Modules/signalmodule.c depends on sigaction() being
1560 * used here if HAVE_SIGACTION is defined. Fix that if this code
1561 * changes to invalidate that assumption.
1562 */
1563 struct sigaction context, ocontext;
1564 context.sa_handler = handler;
1565 sigemptyset(&context.sa_mask);
1566 context.sa_flags = 0;
1567 if (sigaction(sig, &context, &ocontext) == -1)
1568 return SIG_ERR;
1569 return ocontext.sa_handler;
1570#else
1571 PyOS_sighandler_t oldhandler;
1572 oldhandler = signal(sig, handler);
1573#ifdef HAVE_SIGINTERRUPT
1574 siginterrupt(sig, 1);
1575#endif
1576 return oldhandler;
1577#endif
1578}
1579
1580#ifdef __cplusplus
1581}
1582#endif