blob: 857a543cf546bc4c8d1ff29cff7ccc0b7b9b1b50 [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
Victor Stinner449b2712015-09-29 13:59:50 +0200975 /* Prefer dup() over fstat(). fstat() can require input/output whereas
976 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
977 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +0200978 fd2 = dup(fd);
979 if (fd2 >= 0)
980 close(fd2);
981 _Py_END_SUPPRESS_IPH
982 return fd2 >= 0;
983}
984
985/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +1000986static PyObject*
987create_stdio(PyObject* io,
988 int fd, int write_mode, char* name,
989 char* encoding, char* errors)
990{
991 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
992 const char* mode;
993 const char* newline;
994 PyObject *line_buffering;
995 int buffering, isatty;
996 _Py_IDENTIFIER(open);
997 _Py_IDENTIFIER(isatty);
998 _Py_IDENTIFIER(TextIOWrapper);
999 _Py_IDENTIFIER(mode);
1000
Victor Stinner874dbe82015-09-04 17:29:57 +02001001 if (!is_valid_fd(fd))
1002 Py_RETURN_NONE;
1003
Nick Coghland6009512014-11-20 21:39:37 +10001004 /* stdin is always opened in buffered mode, first because it shouldn't
1005 make a difference in common use cases, second because TextIOWrapper
1006 depends on the presence of a read1() method which only exists on
1007 buffered streams.
1008 */
1009 if (Py_UnbufferedStdioFlag && write_mode)
1010 buffering = 0;
1011 else
1012 buffering = -1;
1013 if (write_mode)
1014 mode = "wb";
1015 else
1016 mode = "rb";
1017 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1018 fd, mode, buffering,
1019 Py_None, Py_None, Py_None, 0);
1020 if (buf == NULL)
1021 goto error;
1022
1023 if (buffering) {
1024 _Py_IDENTIFIER(raw);
1025 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1026 if (raw == NULL)
1027 goto error;
1028 }
1029 else {
1030 raw = buf;
1031 Py_INCREF(raw);
1032 }
1033
1034 text = PyUnicode_FromString(name);
1035 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1036 goto error;
1037 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1038 if (res == NULL)
1039 goto error;
1040 isatty = PyObject_IsTrue(res);
1041 Py_DECREF(res);
1042 if (isatty == -1)
1043 goto error;
1044 if (isatty || Py_UnbufferedStdioFlag)
1045 line_buffering = Py_True;
1046 else
1047 line_buffering = Py_False;
1048
1049 Py_CLEAR(raw);
1050 Py_CLEAR(text);
1051
1052#ifdef MS_WINDOWS
1053 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1054 newlines to "\n".
1055 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1056 newline = NULL;
1057#else
1058 /* sys.stdin: split lines at "\n".
1059 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1060 newline = "\n";
1061#endif
1062
1063 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1064 buf, encoding, errors,
1065 newline, line_buffering);
1066 Py_CLEAR(buf);
1067 if (stream == NULL)
1068 goto error;
1069
1070 if (write_mode)
1071 mode = "w";
1072 else
1073 mode = "r";
1074 text = PyUnicode_FromString(mode);
1075 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1076 goto error;
1077 Py_CLEAR(text);
1078 return stream;
1079
1080error:
1081 Py_XDECREF(buf);
1082 Py_XDECREF(stream);
1083 Py_XDECREF(text);
1084 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001085
Victor Stinner874dbe82015-09-04 17:29:57 +02001086 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1087 /* Issue #24891: the file descriptor was closed after the first
1088 is_valid_fd() check was called. Ignore the OSError and set the
1089 stream to None. */
1090 PyErr_Clear();
1091 Py_RETURN_NONE;
1092 }
1093 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001094}
1095
1096/* Initialize sys.stdin, stdout, stderr and builtins.open */
1097static int
1098initstdio(void)
1099{
1100 PyObject *iomod = NULL, *wrapper;
1101 PyObject *bimod = NULL;
1102 PyObject *m;
1103 PyObject *std = NULL;
1104 int status = 0, fd;
1105 PyObject * encoding_attr;
1106 char *pythonioencoding = NULL, *encoding, *errors;
1107
1108 /* Hack to avoid a nasty recursion issue when Python is invoked
1109 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1110 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1111 goto error;
1112 }
1113 Py_DECREF(m);
1114
1115 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1116 goto error;
1117 }
1118 Py_DECREF(m);
1119
1120 if (!(bimod = PyImport_ImportModule("builtins"))) {
1121 goto error;
1122 }
1123
1124 if (!(iomod = PyImport_ImportModule("io"))) {
1125 goto error;
1126 }
1127 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1128 goto error;
1129 }
1130
1131 /* Set builtins.open */
1132 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1133 Py_DECREF(wrapper);
1134 goto error;
1135 }
1136 Py_DECREF(wrapper);
1137
1138 encoding = _Py_StandardStreamEncoding;
1139 errors = _Py_StandardStreamErrors;
1140 if (!encoding || !errors) {
1141 if (!errors) {
1142 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1143 stdin and stdout use the surrogateescape error handler by
1144 default, instead of the strict error handler. */
1145 char *loc = setlocale(LC_CTYPE, NULL);
1146 if (loc != NULL && strcmp(loc, "C") == 0)
1147 errors = "surrogateescape";
1148 }
1149
1150 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1151 if (pythonioencoding) {
1152 char *err;
1153 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1154 if (pythonioencoding == NULL) {
1155 PyErr_NoMemory();
1156 goto error;
1157 }
1158 err = strchr(pythonioencoding, ':');
1159 if (err) {
1160 *err = '\0';
1161 err++;
1162 if (*err && !_Py_StandardStreamErrors) {
1163 errors = err;
1164 }
1165 }
1166 if (*pythonioencoding && !encoding) {
1167 encoding = pythonioencoding;
1168 }
1169 }
1170 }
1171
1172 /* Set sys.stdin */
1173 fd = fileno(stdin);
1174 /* Under some conditions stdin, stdout and stderr may not be connected
1175 * and fileno() may point to an invalid file descriptor. For example
1176 * GUI apps don't have valid standard streams by default.
1177 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001178 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1179 if (std == NULL)
1180 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001181 PySys_SetObject("__stdin__", std);
1182 _PySys_SetObjectId(&PyId_stdin, std);
1183 Py_DECREF(std);
1184
1185 /* Set sys.stdout */
1186 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001187 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1188 if (std == NULL)
1189 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001190 PySys_SetObject("__stdout__", std);
1191 _PySys_SetObjectId(&PyId_stdout, std);
1192 Py_DECREF(std);
1193
1194#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1195 /* Set sys.stderr, replaces the preliminary stderr */
1196 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001197 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1198 if (std == NULL)
1199 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001200
1201 /* Same as hack above, pre-import stderr's codec to avoid recursion
1202 when import.c tries to write to stderr in verbose mode. */
1203 encoding_attr = PyObject_GetAttrString(std, "encoding");
1204 if (encoding_attr != NULL) {
1205 const char * std_encoding;
1206 std_encoding = _PyUnicode_AsString(encoding_attr);
1207 if (std_encoding != NULL) {
1208 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1209 Py_XDECREF(codec_info);
1210 }
1211 Py_DECREF(encoding_attr);
1212 }
1213 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1214
1215 if (PySys_SetObject("__stderr__", std) < 0) {
1216 Py_DECREF(std);
1217 goto error;
1218 }
1219 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1220 Py_DECREF(std);
1221 goto error;
1222 }
1223 Py_DECREF(std);
1224#endif
1225
1226 if (0) {
1227 error:
1228 status = -1;
1229 }
1230
1231 /* We won't need them anymore. */
1232 if (_Py_StandardStreamEncoding) {
1233 PyMem_RawFree(_Py_StandardStreamEncoding);
1234 _Py_StandardStreamEncoding = NULL;
1235 }
1236 if (_Py_StandardStreamErrors) {
1237 PyMem_RawFree(_Py_StandardStreamErrors);
1238 _Py_StandardStreamErrors = NULL;
1239 }
1240 PyMem_Free(pythonioencoding);
1241 Py_XDECREF(bimod);
1242 Py_XDECREF(iomod);
1243 return status;
1244}
1245
1246
Victor Stinner10dc4842015-03-24 12:01:30 +01001247/* Print the current exception (if an exception is set) with its traceback,
1248 * or display the current Python stack.
1249 *
1250 * Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1251 * called on catastrophic cases. */
1252
1253static void
1254_Py_PrintFatalError(int fd)
1255{
Victor Stinnere0deff32015-03-24 13:46:18 +01001256 PyObject *ferr, *res;
Victor Stinner10dc4842015-03-24 12:01:30 +01001257 PyObject *exception, *v, *tb;
1258 int has_tb;
1259 PyThreadState *tstate;
1260
1261 PyErr_Fetch(&exception, &v, &tb);
1262 if (exception == NULL) {
1263 /* No current exception */
1264 goto display_stack;
1265 }
1266
Victor Stinnere0deff32015-03-24 13:46:18 +01001267 ferr = _PySys_GetObjectId(&PyId_stderr);
1268 if (ferr == NULL || ferr == Py_None) {
1269 /* sys.stderr is not set yet or set to None,
1270 no need to try to display the exception */
1271 goto display_stack;
1272 }
1273
Victor Stinner10dc4842015-03-24 12:01:30 +01001274 PyErr_NormalizeException(&exception, &v, &tb);
1275 if (tb == NULL) {
1276 tb = Py_None;
1277 Py_INCREF(tb);
1278 }
1279 PyException_SetTraceback(v, tb);
1280 if (exception == NULL) {
Victor Stinnere0deff32015-03-24 13:46:18 +01001281 /* PyErr_NormalizeException() failed */
Victor Stinner10dc4842015-03-24 12:01:30 +01001282 goto display_stack;
1283 }
1284
Christian Heimese8e42832015-04-16 17:25:45 +02001285 has_tb = (tb != Py_None);
Victor Stinner10dc4842015-03-24 12:01:30 +01001286 PyErr_Display(exception, v, tb);
1287 Py_XDECREF(exception);
1288 Py_XDECREF(v);
1289 Py_XDECREF(tb);
Victor Stinnere0deff32015-03-24 13:46:18 +01001290
1291 /* sys.stderr may be buffered: call sys.stderr.flush() */
1292 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1293 if (res == NULL)
1294 PyErr_Clear();
1295 else
1296 Py_DECREF(res);
1297
Victor Stinner10dc4842015-03-24 12:01:30 +01001298 if (has_tb)
1299 return;
1300
1301display_stack:
Benjamin Peterson55c14352015-04-06 09:59:23 -04001302#ifdef WITH_THREAD
Victor Stinner10dc4842015-03-24 12:01:30 +01001303 /* PyGILState_GetThisThreadState() works even if the GIL was released */
1304 tstate = PyGILState_GetThisThreadState();
Benjamin Peterson55c14352015-04-06 09:59:23 -04001305#else
1306 tstate = PyThreadState_GET();
1307#endif
Victor Stinner10dc4842015-03-24 12:01:30 +01001308 if (tstate == NULL) {
1309 /* _Py_DumpTracebackThreads() requires the thread state to display
1310 * frames */
1311 return;
1312 }
1313
1314 fputc('\n', stderr);
1315 fflush(stderr);
1316
1317 /* display the current Python stack */
1318 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
1319}
Nick Coghland6009512014-11-20 21:39:37 +10001320/* Print fatal error message and abort */
1321
1322void
1323Py_FatalError(const char *msg)
1324{
1325 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001326 static int reentrant = 0;
1327#ifdef MS_WINDOWS
1328 size_t len;
1329 WCHAR* buffer;
1330 size_t i;
1331#endif
1332
1333 if (reentrant) {
1334 /* Py_FatalError() caused a second fatal error.
1335 Example: flush_std_files() raises a recursion error. */
1336 goto exit;
1337 }
1338 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001339
1340 fprintf(stderr, "Fatal Python error: %s\n", msg);
1341 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001342
Victor Stinnere0deff32015-03-24 13:46:18 +01001343 /* Print the exception (if an exception is set) with its traceback,
1344 * or display the current Python stack. */
Victor Stinner10dc4842015-03-24 12:01:30 +01001345 _Py_PrintFatalError(fd);
1346
Victor Stinnere0deff32015-03-24 13:46:18 +01001347 /* Flush sys.stdout and sys.stderr */
1348 flush_std_files();
1349
Victor Stinner10dc4842015-03-24 12:01:30 +01001350 /* The main purpose of faulthandler is to display the traceback. We already
Victor Stinnere0deff32015-03-24 13:46:18 +01001351 * did our best to display it. So faulthandler can now be disabled.
1352 * (Don't trigger it on abort().) */
Victor Stinner10dc4842015-03-24 12:01:30 +01001353 _PyFaulthandler_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001354
1355#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001356 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001357
Victor Stinner53345a42015-03-25 01:55:14 +01001358 /* Convert the message to wchar_t. This uses a simple one-to-one
1359 conversion, assuming that the this error message actually uses ASCII
1360 only. If this ceases to be true, we will have to convert. */
1361 buffer = alloca( (len+1) * (sizeof *buffer));
1362 for( i=0; i<=len; ++i)
1363 buffer[i] = msg[i];
1364 OutputDebugStringW(L"Fatal Python error: ");
1365 OutputDebugStringW(buffer);
1366 OutputDebugStringW(L"\n");
1367#endif /* MS_WINDOWS */
1368
1369exit:
1370#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001371 DebugBreak();
1372#endif
Nick Coghland6009512014-11-20 21:39:37 +10001373 abort();
1374}
1375
1376/* Clean up and exit */
1377
1378#ifdef WITH_THREAD
1379#include "pythread.h"
1380#endif
1381
1382static void (*pyexitfunc)(void) = NULL;
1383/* For the atexit module. */
1384void _Py_PyAtExit(void (*func)(void))
1385{
1386 pyexitfunc = func;
1387}
1388
1389static void
1390call_py_exitfuncs(void)
1391{
1392 if (pyexitfunc == NULL)
1393 return;
1394
1395 (*pyexitfunc)();
1396 PyErr_Clear();
1397}
1398
1399/* Wait until threading._shutdown completes, provided
1400 the threading module was imported in the first place.
1401 The shutdown routine will wait until all non-daemon
1402 "threading" threads have completed. */
1403static void
1404wait_for_thread_shutdown(void)
1405{
1406#ifdef WITH_THREAD
1407 _Py_IDENTIFIER(_shutdown);
1408 PyObject *result;
1409 PyThreadState *tstate = PyThreadState_GET();
1410 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1411 "threading");
1412 if (threading == NULL) {
1413 /* threading not imported */
1414 PyErr_Clear();
1415 return;
1416 }
1417 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1418 if (result == NULL) {
1419 PyErr_WriteUnraisable(threading);
1420 }
1421 else {
1422 Py_DECREF(result);
1423 }
1424 Py_DECREF(threading);
1425#endif
1426}
1427
1428#define NEXITFUNCS 32
1429static void (*exitfuncs[NEXITFUNCS])(void);
1430static int nexitfuncs = 0;
1431
1432int Py_AtExit(void (*func)(void))
1433{
1434 if (nexitfuncs >= NEXITFUNCS)
1435 return -1;
1436 exitfuncs[nexitfuncs++] = func;
1437 return 0;
1438}
1439
1440static void
1441call_ll_exitfuncs(void)
1442{
1443 while (nexitfuncs > 0)
1444 (*exitfuncs[--nexitfuncs])();
1445
1446 fflush(stdout);
1447 fflush(stderr);
1448}
1449
1450void
1451Py_Exit(int sts)
1452{
1453 Py_Finalize();
1454
1455 exit(sts);
1456}
1457
1458static void
1459initsigs(void)
1460{
1461#ifdef SIGPIPE
1462 PyOS_setsig(SIGPIPE, SIG_IGN);
1463#endif
1464#ifdef SIGXFZ
1465 PyOS_setsig(SIGXFZ, SIG_IGN);
1466#endif
1467#ifdef SIGXFSZ
1468 PyOS_setsig(SIGXFSZ, SIG_IGN);
1469#endif
1470 PyOS_InitInterrupts(); /* May imply initsignal() */
1471 if (PyErr_Occurred()) {
1472 Py_FatalError("Py_Initialize: can't import signal");
1473 }
1474}
1475
1476
1477/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1478 *
1479 * All of the code in this function must only use async-signal-safe functions,
1480 * listed at `man 7 signal` or
1481 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1482 */
1483void
1484_Py_RestoreSignals(void)
1485{
1486#ifdef SIGPIPE
1487 PyOS_setsig(SIGPIPE, SIG_DFL);
1488#endif
1489#ifdef SIGXFZ
1490 PyOS_setsig(SIGXFZ, SIG_DFL);
1491#endif
1492#ifdef SIGXFSZ
1493 PyOS_setsig(SIGXFSZ, SIG_DFL);
1494#endif
1495}
1496
1497
1498/*
1499 * The file descriptor fd is considered ``interactive'' if either
1500 * a) isatty(fd) is TRUE, or
1501 * b) the -i flag was given, and the filename associated with
1502 * the descriptor is NULL or "<stdin>" or "???".
1503 */
1504int
1505Py_FdIsInteractive(FILE *fp, const char *filename)
1506{
1507 if (isatty((int)fileno(fp)))
1508 return 1;
1509 if (!Py_InteractiveFlag)
1510 return 0;
1511 return (filename == NULL) ||
1512 (strcmp(filename, "<stdin>") == 0) ||
1513 (strcmp(filename, "???") == 0);
1514}
1515
1516
Nick Coghland6009512014-11-20 21:39:37 +10001517/* Wrappers around sigaction() or signal(). */
1518
1519PyOS_sighandler_t
1520PyOS_getsig(int sig)
1521{
1522#ifdef HAVE_SIGACTION
1523 struct sigaction context;
1524 if (sigaction(sig, NULL, &context) == -1)
1525 return SIG_ERR;
1526 return context.sa_handler;
1527#else
1528 PyOS_sighandler_t handler;
1529/* Special signal handling for the secure CRT in Visual Studio 2005 */
1530#if defined(_MSC_VER) && _MSC_VER >= 1400
1531 switch (sig) {
1532 /* Only these signals are valid */
1533 case SIGINT:
1534 case SIGILL:
1535 case SIGFPE:
1536 case SIGSEGV:
1537 case SIGTERM:
1538 case SIGBREAK:
1539 case SIGABRT:
1540 break;
1541 /* Don't call signal() with other values or it will assert */
1542 default:
1543 return SIG_ERR;
1544 }
1545#endif /* _MSC_VER && _MSC_VER >= 1400 */
1546 handler = signal(sig, SIG_IGN);
1547 if (handler != SIG_ERR)
1548 signal(sig, handler);
1549 return handler;
1550#endif
1551}
1552
1553/*
1554 * All of the code in this function must only use async-signal-safe functions,
1555 * listed at `man 7 signal` or
1556 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1557 */
1558PyOS_sighandler_t
1559PyOS_setsig(int sig, PyOS_sighandler_t handler)
1560{
1561#ifdef HAVE_SIGACTION
1562 /* Some code in Modules/signalmodule.c depends on sigaction() being
1563 * used here if HAVE_SIGACTION is defined. Fix that if this code
1564 * changes to invalidate that assumption.
1565 */
1566 struct sigaction context, ocontext;
1567 context.sa_handler = handler;
1568 sigemptyset(&context.sa_mask);
1569 context.sa_flags = 0;
1570 if (sigaction(sig, &context, &ocontext) == -1)
1571 return SIG_ERR;
1572 return ocontext.sa_handler;
1573#else
1574 PyOS_sighandler_t oldhandler;
1575 oldhandler = signal(sig, handler);
1576#ifdef HAVE_SIGINTERRUPT
1577 siginterrupt(sig, 1);
1578#endif
1579 return oldhandler;
1580#endif
1581}
1582
1583#ifdef __cplusplus
1584}
1585#endif