blob: ce52990496931ca13937dbfd3e7f8c1defec070e [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) {
Nick Coghland6009512014-11-20 21:39:37 +10001138 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1139 if (pythonioencoding) {
1140 char *err;
1141 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1142 if (pythonioencoding == NULL) {
1143 PyErr_NoMemory();
1144 goto error;
1145 }
1146 err = strchr(pythonioencoding, ':');
1147 if (err) {
1148 *err = '\0';
1149 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001150 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001151 errors = err;
1152 }
1153 }
1154 if (*pythonioencoding && !encoding) {
1155 encoding = pythonioencoding;
1156 }
1157 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001158 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1159 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1160 stdin and stdout use the surrogateescape error handler by
1161 default, instead of the strict error handler. */
1162 char *loc = setlocale(LC_CTYPE, NULL);
1163 if (loc != NULL && strcmp(loc, "C") == 0)
1164 errors = "surrogateescape";
1165 }
Nick Coghland6009512014-11-20 21:39:37 +10001166 }
1167
1168 /* Set sys.stdin */
1169 fd = fileno(stdin);
1170 /* Under some conditions stdin, stdout and stderr may not be connected
1171 * and fileno() may point to an invalid file descriptor. For example
1172 * GUI apps don't have valid standard streams by default.
1173 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001174 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1175 if (std == NULL)
1176 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001177 PySys_SetObject("__stdin__", std);
1178 _PySys_SetObjectId(&PyId_stdin, std);
1179 Py_DECREF(std);
1180
1181 /* Set sys.stdout */
1182 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001183 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1184 if (std == NULL)
1185 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001186 PySys_SetObject("__stdout__", std);
1187 _PySys_SetObjectId(&PyId_stdout, std);
1188 Py_DECREF(std);
1189
1190#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1191 /* Set sys.stderr, replaces the preliminary stderr */
1192 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001193 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1194 if (std == NULL)
1195 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001196
1197 /* Same as hack above, pre-import stderr's codec to avoid recursion
1198 when import.c tries to write to stderr in verbose mode. */
1199 encoding_attr = PyObject_GetAttrString(std, "encoding");
1200 if (encoding_attr != NULL) {
1201 const char * std_encoding;
1202 std_encoding = _PyUnicode_AsString(encoding_attr);
1203 if (std_encoding != NULL) {
1204 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1205 Py_XDECREF(codec_info);
1206 }
1207 Py_DECREF(encoding_attr);
1208 }
1209 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1210
1211 if (PySys_SetObject("__stderr__", std) < 0) {
1212 Py_DECREF(std);
1213 goto error;
1214 }
1215 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1216 Py_DECREF(std);
1217 goto error;
1218 }
1219 Py_DECREF(std);
1220#endif
1221
1222 if (0) {
1223 error:
1224 status = -1;
1225 }
1226
1227 /* We won't need them anymore. */
1228 if (_Py_StandardStreamEncoding) {
1229 PyMem_RawFree(_Py_StandardStreamEncoding);
1230 _Py_StandardStreamEncoding = NULL;
1231 }
1232 if (_Py_StandardStreamErrors) {
1233 PyMem_RawFree(_Py_StandardStreamErrors);
1234 _Py_StandardStreamErrors = NULL;
1235 }
1236 PyMem_Free(pythonioencoding);
1237 Py_XDECREF(bimod);
1238 Py_XDECREF(iomod);
1239 return status;
1240}
1241
1242
Victor Stinner10dc4842015-03-24 12:01:30 +01001243static void
Victor Stinner4ddee7f2016-03-14 16:53:12 +01001244_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001245{
Victor Stinner10dc4842015-03-24 12:01:30 +01001246 PyThreadState *tstate;
1247
Benjamin Peterson55c14352015-04-06 09:59:23 -04001248#ifdef WITH_THREAD
Victor Stinner10dc4842015-03-24 12:01:30 +01001249 /* PyGILState_GetThisThreadState() works even if the GIL was released */
1250 tstate = PyGILState_GetThisThreadState();
Benjamin Peterson55c14352015-04-06 09:59:23 -04001251#else
1252 tstate = PyThreadState_GET();
1253#endif
Victor Stinner10dc4842015-03-24 12:01:30 +01001254 if (tstate == NULL) {
1255 /* _Py_DumpTracebackThreads() requires the thread state to display
1256 * frames */
1257 return;
1258 }
1259
1260 fputc('\n', stderr);
1261 fflush(stderr);
1262
1263 /* display the current Python stack */
1264 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
1265}
Victor Stinner4ddee7f2016-03-14 16:53:12 +01001266
1267/* Print the current exception (if an exception is set) with its traceback,
1268 or display the current Python stack.
1269
1270 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1271 called on catastrophic cases.
1272
1273 Return 1 if the traceback was displayed, 0 otherwise. */
1274
1275static int
1276_Py_FatalError_PrintExc(int fd)
1277{
1278 PyObject *ferr, *res;
1279 PyObject *exception, *v, *tb;
1280 int has_tb;
1281
1282 if (PyThreadState_GET() == NULL) {
1283 /* The GIL is released: trying to acquire it is likely to deadlock,
1284 just give up. */
1285 return 0;
1286 }
1287
1288 PyErr_Fetch(&exception, &v, &tb);
1289 if (exception == NULL) {
1290 /* No current exception */
1291 return 0;
1292 }
1293
1294 ferr = _PySys_GetObjectId(&PyId_stderr);
1295 if (ferr == NULL || ferr == Py_None) {
1296 /* sys.stderr is not set yet or set to None,
1297 no need to try to display the exception */
1298 return 0;
1299 }
1300
1301 PyErr_NormalizeException(&exception, &v, &tb);
1302 if (tb == NULL) {
1303 tb = Py_None;
1304 Py_INCREF(tb);
1305 }
1306 PyException_SetTraceback(v, tb);
1307 if (exception == NULL) {
1308 /* PyErr_NormalizeException() failed */
1309 return 0;
1310 }
1311
1312 has_tb = (tb != Py_None);
1313 PyErr_Display(exception, v, tb);
1314 Py_XDECREF(exception);
1315 Py_XDECREF(v);
1316 Py_XDECREF(tb);
1317
1318 /* sys.stderr may be buffered: call sys.stderr.flush() */
1319 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1320 if (res == NULL)
1321 PyErr_Clear();
1322 else
1323 Py_DECREF(res);
1324
1325 return has_tb;
1326}
1327
Nick Coghland6009512014-11-20 21:39:37 +10001328/* Print fatal error message and abort */
1329
1330void
1331Py_FatalError(const char *msg)
1332{
1333 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001334 static int reentrant = 0;
1335#ifdef MS_WINDOWS
1336 size_t len;
1337 WCHAR* buffer;
1338 size_t i;
1339#endif
1340
1341 if (reentrant) {
1342 /* Py_FatalError() caused a second fatal error.
1343 Example: flush_std_files() raises a recursion error. */
1344 goto exit;
1345 }
1346 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001347
1348 fprintf(stderr, "Fatal Python error: %s\n", msg);
1349 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001350
Victor Stinnere0deff32015-03-24 13:46:18 +01001351 /* Print the exception (if an exception is set) with its traceback,
1352 * or display the current Python stack. */
Victor Stinner4ddee7f2016-03-14 16:53:12 +01001353 if (!_Py_FatalError_PrintExc(fd))
1354 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001355
Victor Stinnera2e5e042016-03-16 23:19:15 +01001356 /* The main purpose of faulthandler is to display the traceback. We already
1357 * did our best to display it. So faulthandler can now be disabled.
1358 * (Don't trigger it on abort().) */
1359 _PyFaulthandler_Fini();
1360
Victor Stinner4ddee7f2016-03-14 16:53:12 +01001361 /* Check if the current Python thread hold the GIL */
1362 if (PyThreadState_GET() != NULL) {
1363 /* Flush sys.stdout and sys.stderr */
1364 flush_std_files();
1365 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001366
Nick Coghland6009512014-11-20 21:39:37 +10001367#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001368 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001369
Victor Stinner53345a42015-03-25 01:55:14 +01001370 /* Convert the message to wchar_t. This uses a simple one-to-one
1371 conversion, assuming that the this error message actually uses ASCII
1372 only. If this ceases to be true, we will have to convert. */
1373 buffer = alloca( (len+1) * (sizeof *buffer));
1374 for( i=0; i<=len; ++i)
1375 buffer[i] = msg[i];
1376 OutputDebugStringW(L"Fatal Python error: ");
1377 OutputDebugStringW(buffer);
1378 OutputDebugStringW(L"\n");
1379#endif /* MS_WINDOWS */
1380
1381exit:
1382#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001383 DebugBreak();
1384#endif
Nick Coghland6009512014-11-20 21:39:37 +10001385 abort();
1386}
1387
1388/* Clean up and exit */
1389
1390#ifdef WITH_THREAD
1391#include "pythread.h"
1392#endif
1393
1394static void (*pyexitfunc)(void) = NULL;
1395/* For the atexit module. */
1396void _Py_PyAtExit(void (*func)(void))
1397{
1398 pyexitfunc = func;
1399}
1400
1401static void
1402call_py_exitfuncs(void)
1403{
1404 if (pyexitfunc == NULL)
1405 return;
1406
1407 (*pyexitfunc)();
1408 PyErr_Clear();
1409}
1410
1411/* Wait until threading._shutdown completes, provided
1412 the threading module was imported in the first place.
1413 The shutdown routine will wait until all non-daemon
1414 "threading" threads have completed. */
1415static void
1416wait_for_thread_shutdown(void)
1417{
1418#ifdef WITH_THREAD
1419 _Py_IDENTIFIER(_shutdown);
1420 PyObject *result;
1421 PyThreadState *tstate = PyThreadState_GET();
1422 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1423 "threading");
1424 if (threading == NULL) {
1425 /* threading not imported */
1426 PyErr_Clear();
1427 return;
1428 }
1429 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1430 if (result == NULL) {
1431 PyErr_WriteUnraisable(threading);
1432 }
1433 else {
1434 Py_DECREF(result);
1435 }
1436 Py_DECREF(threading);
1437#endif
1438}
1439
1440#define NEXITFUNCS 32
1441static void (*exitfuncs[NEXITFUNCS])(void);
1442static int nexitfuncs = 0;
1443
1444int Py_AtExit(void (*func)(void))
1445{
1446 if (nexitfuncs >= NEXITFUNCS)
1447 return -1;
1448 exitfuncs[nexitfuncs++] = func;
1449 return 0;
1450}
1451
1452static void
1453call_ll_exitfuncs(void)
1454{
1455 while (nexitfuncs > 0)
1456 (*exitfuncs[--nexitfuncs])();
1457
1458 fflush(stdout);
1459 fflush(stderr);
1460}
1461
1462void
1463Py_Exit(int sts)
1464{
1465 Py_Finalize();
1466
1467 exit(sts);
1468}
1469
1470static void
1471initsigs(void)
1472{
1473#ifdef SIGPIPE
1474 PyOS_setsig(SIGPIPE, SIG_IGN);
1475#endif
1476#ifdef SIGXFZ
1477 PyOS_setsig(SIGXFZ, SIG_IGN);
1478#endif
1479#ifdef SIGXFSZ
1480 PyOS_setsig(SIGXFSZ, SIG_IGN);
1481#endif
1482 PyOS_InitInterrupts(); /* May imply initsignal() */
1483 if (PyErr_Occurred()) {
1484 Py_FatalError("Py_Initialize: can't import signal");
1485 }
1486}
1487
1488
1489/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1490 *
1491 * All of the code in this function must only use async-signal-safe functions,
1492 * listed at `man 7 signal` or
1493 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1494 */
1495void
1496_Py_RestoreSignals(void)
1497{
1498#ifdef SIGPIPE
1499 PyOS_setsig(SIGPIPE, SIG_DFL);
1500#endif
1501#ifdef SIGXFZ
1502 PyOS_setsig(SIGXFZ, SIG_DFL);
1503#endif
1504#ifdef SIGXFSZ
1505 PyOS_setsig(SIGXFSZ, SIG_DFL);
1506#endif
1507}
1508
1509
1510/*
1511 * The file descriptor fd is considered ``interactive'' if either
1512 * a) isatty(fd) is TRUE, or
1513 * b) the -i flag was given, and the filename associated with
1514 * the descriptor is NULL or "<stdin>" or "???".
1515 */
1516int
1517Py_FdIsInteractive(FILE *fp, const char *filename)
1518{
1519 if (isatty((int)fileno(fp)))
1520 return 1;
1521 if (!Py_InteractiveFlag)
1522 return 0;
1523 return (filename == NULL) ||
1524 (strcmp(filename, "<stdin>") == 0) ||
1525 (strcmp(filename, "???") == 0);
1526}
1527
1528
Nick Coghland6009512014-11-20 21:39:37 +10001529/* Wrappers around sigaction() or signal(). */
1530
1531PyOS_sighandler_t
1532PyOS_getsig(int sig)
1533{
1534#ifdef HAVE_SIGACTION
1535 struct sigaction context;
1536 if (sigaction(sig, NULL, &context) == -1)
1537 return SIG_ERR;
1538 return context.sa_handler;
1539#else
1540 PyOS_sighandler_t handler;
1541/* Special signal handling for the secure CRT in Visual Studio 2005 */
1542#if defined(_MSC_VER) && _MSC_VER >= 1400
1543 switch (sig) {
1544 /* Only these signals are valid */
1545 case SIGINT:
1546 case SIGILL:
1547 case SIGFPE:
1548 case SIGSEGV:
1549 case SIGTERM:
1550 case SIGBREAK:
1551 case SIGABRT:
1552 break;
1553 /* Don't call signal() with other values or it will assert */
1554 default:
1555 return SIG_ERR;
1556 }
1557#endif /* _MSC_VER && _MSC_VER >= 1400 */
1558 handler = signal(sig, SIG_IGN);
1559 if (handler != SIG_ERR)
1560 signal(sig, handler);
1561 return handler;
1562#endif
1563}
1564
1565/*
1566 * All of the code in this function must only use async-signal-safe functions,
1567 * listed at `man 7 signal` or
1568 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1569 */
1570PyOS_sighandler_t
1571PyOS_setsig(int sig, PyOS_sighandler_t handler)
1572{
1573#ifdef HAVE_SIGACTION
1574 /* Some code in Modules/signalmodule.c depends on sigaction() being
1575 * used here if HAVE_SIGACTION is defined. Fix that if this code
1576 * changes to invalidate that assumption.
1577 */
1578 struct sigaction context, ocontext;
1579 context.sa_handler = handler;
1580 sigemptyset(&context.sa_mask);
1581 context.sa_flags = 0;
1582 if (sigaction(sig, &context, &ocontext) == -1)
1583 return SIG_ERR;
1584 return ocontext.sa_handler;
1585#else
1586 PyOS_sighandler_t oldhandler;
1587 oldhandler = signal(sig, handler);
1588#ifdef HAVE_SIGINTERRUPT
1589 siginterrupt(sig, 1);
1590#endif
1591 return oldhandler;
1592#endif
1593}
1594
1595#ifdef __cplusplus
1596}
1597#endif