blob: aaf58119e501cff3f225d43c9542dd2a08bda62d [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
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000157/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
158 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000159 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
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000330 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000331 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
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000334 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000335 _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
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000480static int
Nick Coghland6009512014-11-20 21:39:37 +1000481flush_std_files(void)
482{
483 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
484 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
485 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000486 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000487
488 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
489 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000490 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000491 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000492 status = -1;
493 }
Nick Coghland6009512014-11-20 21:39:37 +1000494 else
495 Py_DECREF(tmp);
496 }
497
498 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
499 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000500 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000501 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000502 status = -1;
503 }
Nick Coghland6009512014-11-20 21:39:37 +1000504 else
505 Py_DECREF(tmp);
506 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000507
508 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000509}
510
511/* Undo the effect of Py_Initialize().
512
513 Beware: if multiple interpreter and/or thread states exist, these
514 are not wiped out; only the current thread and interpreter state
515 are deleted. But since everything else is deleted, those other
516 interpreter and thread states should no longer be used.
517
518 (XXX We should do better, e.g. wipe out all interpreters and
519 threads.)
520
521 Locking: as above.
522
523*/
524
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000525int
526Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000527{
528 PyInterpreterState *interp;
529 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000530 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000531
532 if (!initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000533 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000534
535 wait_for_thread_shutdown();
536
537 /* The interpreter is still entirely intact at this point, and the
538 * exit funcs may be relying on that. In particular, if some thread
539 * or exit func is still waiting to do an import, the import machinery
540 * expects Py_IsInitialized() to return true. So don't say the
541 * interpreter is uninitialized until after the exit funcs have run.
542 * Note that Threading.py uses an exit func to do a join on all the
543 * threads created thru it, so this also protects pending imports in
544 * the threads created via Threading.
545 */
546 call_py_exitfuncs();
547
548 /* Get current thread state and interpreter pointer */
549 tstate = PyThreadState_GET();
550 interp = tstate->interp;
551
552 /* Remaining threads (e.g. daemon threads) will automatically exit
553 after taking the GIL (in PyEval_RestoreThread()). */
554 _Py_Finalizing = tstate;
555 initialized = 0;
556
Victor Stinnere0deff32015-03-24 13:46:18 +0100557 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000558 if (flush_std_files() < 0) {
559 status = -1;
560 }
Nick Coghland6009512014-11-20 21:39:37 +1000561
562 /* Disable signal handling */
563 PyOS_FiniInterrupts();
564
565 /* Collect garbage. This may call finalizers; it's nice to call these
566 * before all modules are destroyed.
567 * XXX If a __del__ or weakref callback is triggered here, and tries to
568 * XXX import a module, bad things can happen, because Python no
569 * XXX longer believes it's initialized.
570 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
571 * XXX is easy to provoke that way. I've also seen, e.g.,
572 * XXX Exception exceptions.ImportError: 'No module named sha'
573 * XXX in <function callback at 0x008F5718> ignored
574 * XXX but I'm unclear on exactly how that one happens. In any case,
575 * XXX I haven't seen a real-life report of either of these.
576 */
577 PyGC_Collect();
578#ifdef COUNT_ALLOCS
579 /* With COUNT_ALLOCS, it helps to run GC multiple times:
580 each collection might release some types from the type
581 list, so they become garbage. */
582 while (PyGC_Collect() > 0)
583 /* nothing */;
584#endif
585 /* Destroy all modules */
586 PyImport_Cleanup();
587
Victor Stinnere0deff32015-03-24 13:46:18 +0100588 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000589 if (flush_std_files() < 0) {
590 status = -1;
591 }
Nick Coghland6009512014-11-20 21:39:37 +1000592
593 /* Collect final garbage. This disposes of cycles created by
594 * class definitions, for example.
595 * XXX This is disabled because it caused too many problems. If
596 * XXX a __del__ or weakref callback triggers here, Python code has
597 * XXX a hard time running, because even the sys module has been
598 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
599 * XXX One symptom is a sequence of information-free messages
600 * XXX coming from threads (if a __del__ or callback is invoked,
601 * XXX other threads can execute too, and any exception they encounter
602 * XXX triggers a comedy of errors as subsystem after subsystem
603 * XXX fails to find what it *expects* to find in sys to help report
604 * XXX the exception and consequent unexpected failures). I've also
605 * XXX seen segfaults then, after adding print statements to the
606 * XXX Python code getting called.
607 */
608#if 0
609 PyGC_Collect();
610#endif
611
612 /* Disable tracemalloc after all Python objects have been destroyed,
613 so it is possible to use tracemalloc in objects destructor. */
614 _PyTraceMalloc_Fini();
615
616 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
617 _PyImport_Fini();
618
619 /* Cleanup typeobject.c's internal caches. */
620 _PyType_Fini();
621
622 /* unload faulthandler module */
623 _PyFaulthandler_Fini();
624
625 /* Debugging stuff */
626#ifdef COUNT_ALLOCS
627 dump_counts(stdout);
628#endif
629 /* dump hash stats */
630 _PyHash_Fini();
631
632 _PY_DEBUG_PRINT_TOTAL_REFS();
633
634#ifdef Py_TRACE_REFS
635 /* Display all objects still alive -- this can invoke arbitrary
636 * __repr__ overrides, so requires a mostly-intact interpreter.
637 * Alas, a lot of stuff may still be alive now that will be cleaned
638 * up later.
639 */
640 if (Py_GETENV("PYTHONDUMPREFS"))
641 _Py_PrintReferences(stderr);
642#endif /* Py_TRACE_REFS */
643
644 /* Clear interpreter state and all thread states. */
645 PyInterpreterState_Clear(interp);
646
647 /* Now we decref the exception classes. After this point nothing
648 can raise an exception. That's okay, because each Fini() method
649 below has been checked to make sure no exceptions are ever
650 raised.
651 */
652
653 _PyExc_Fini();
654
655 /* Sundry finalizers */
656 PyMethod_Fini();
657 PyFrame_Fini();
658 PyCFunction_Fini();
659 PyTuple_Fini();
660 PyList_Fini();
661 PySet_Fini();
662 PyBytes_Fini();
663 PyByteArray_Fini();
664 PyLong_Fini();
665 PyFloat_Fini();
666 PyDict_Fini();
667 PySlice_Fini();
668 _PyGC_Fini();
669 _PyRandom_Fini();
670
671 /* Cleanup Unicode implementation */
672 _PyUnicode_Fini();
673
674 /* reset file system default encoding */
675 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
676 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
677 Py_FileSystemDefaultEncoding = NULL;
678 }
679
680 /* XXX Still allocated:
681 - various static ad-hoc pointers to interned strings
682 - int and float free list blocks
683 - whatever various modules and libraries allocate
684 */
685
686 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
687
688 /* Cleanup auto-thread-state */
689#ifdef WITH_THREAD
690 _PyGILState_Fini();
691#endif /* WITH_THREAD */
692
693 /* Delete current thread. After this, many C API calls become crashy. */
694 PyThreadState_Swap(NULL);
695 PyInterpreterState_Delete(interp);
696
697#ifdef Py_TRACE_REFS
698 /* Display addresses (& refcnts) of all objects still alive.
699 * An address can be used to find the repr of the object, printed
700 * above by _Py_PrintReferences.
701 */
702 if (Py_GETENV("PYTHONDUMPREFS"))
703 _Py_PrintReferenceAddresses(stderr);
704#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +0100705#ifdef WITH_PYMALLOC
706 if (_PyMem_PymallocEnabled()) {
707 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
708 if (opt != NULL && *opt != '\0')
709 _PyObject_DebugMallocStats(stderr);
710 }
Nick Coghland6009512014-11-20 21:39:37 +1000711#endif
712
713 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000714 return status;
715}
716
717void
718Py_Finalize(void)
719{
720 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000721}
722
723/* Create and initialize a new interpreter and thread, and return the
724 new thread. This requires that Py_Initialize() has been called
725 first.
726
727 Unsuccessful initialization yields a NULL pointer. Note that *no*
728 exception information is available even in this case -- the
729 exception information is held in the thread, and there is no
730 thread.
731
732 Locking: as above.
733
734*/
735
736PyThreadState *
737Py_NewInterpreter(void)
738{
739 PyInterpreterState *interp;
740 PyThreadState *tstate, *save_tstate;
741 PyObject *bimod, *sysmod;
742
743 if (!initialized)
744 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
745
746 interp = PyInterpreterState_New();
747 if (interp == NULL)
748 return NULL;
749
750 tstate = PyThreadState_New(interp);
751 if (tstate == NULL) {
752 PyInterpreterState_Delete(interp);
753 return NULL;
754 }
755
756 save_tstate = PyThreadState_Swap(tstate);
757
758 /* XXX The following is lax in error checking */
759
760 interp->modules = PyDict_New();
761
762 bimod = _PyImport_FindBuiltin("builtins");
763 if (bimod != NULL) {
764 interp->builtins = PyModule_GetDict(bimod);
765 if (interp->builtins == NULL)
766 goto handle_error;
767 Py_INCREF(interp->builtins);
768 }
769
770 /* initialize builtin exceptions */
771 _PyExc_Init(bimod);
772
773 sysmod = _PyImport_FindBuiltin("sys");
774 if (bimod != NULL && sysmod != NULL) {
775 PyObject *pstderr;
776
777 interp->sysdict = PyModule_GetDict(sysmod);
778 if (interp->sysdict == NULL)
779 goto handle_error;
780 Py_INCREF(interp->sysdict);
781 PySys_SetPath(Py_GetPath());
782 PyDict_SetItemString(interp->sysdict, "modules",
783 interp->modules);
784 /* Set up a preliminary stderr printer until we have enough
785 infrastructure for the io module in place. */
786 pstderr = PyFile_NewStdPrinter(fileno(stderr));
787 if (pstderr == NULL)
788 Py_FatalError("Py_Initialize: can't set preliminary stderr");
789 _PySys_SetObjectId(&PyId_stderr, pstderr);
790 PySys_SetObject("__stderr__", pstderr);
791 Py_DECREF(pstderr);
792
793 _PyImportHooks_Init();
794
795 import_init(interp, sysmod);
796
797 if (initfsencoding(interp) < 0)
798 goto handle_error;
799
800 if (initstdio() < 0)
801 Py_FatalError(
Georg Brandl4b5b0622016-01-18 08:00:15 +0100802 "Py_Initialize: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000803 initmain(interp);
804 if (!Py_NoSiteFlag)
805 initsite();
806 }
807
808 if (!PyErr_Occurred())
809 return tstate;
810
811handle_error:
812 /* Oops, it didn't work. Undo it all. */
813
814 PyErr_PrintEx(0);
815 PyThreadState_Clear(tstate);
816 PyThreadState_Swap(save_tstate);
817 PyThreadState_Delete(tstate);
818 PyInterpreterState_Delete(interp);
819
820 return NULL;
821}
822
823/* Delete an interpreter and its last thread. This requires that the
824 given thread state is current, that the thread has no remaining
825 frames, and that it is its interpreter's only remaining thread.
826 It is a fatal error to violate these constraints.
827
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000828 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +1000829 everything, regardless.)
830
831 Locking: as above.
832
833*/
834
835void
836Py_EndInterpreter(PyThreadState *tstate)
837{
838 PyInterpreterState *interp = tstate->interp;
839
840 if (tstate != PyThreadState_GET())
841 Py_FatalError("Py_EndInterpreter: thread is not current");
842 if (tstate->frame != NULL)
843 Py_FatalError("Py_EndInterpreter: thread still has a frame");
844
845 wait_for_thread_shutdown();
846
847 if (tstate != interp->tstate_head || tstate->next != NULL)
848 Py_FatalError("Py_EndInterpreter: not the last thread");
849
850 PyImport_Cleanup();
851 PyInterpreterState_Clear(interp);
852 PyThreadState_Swap(NULL);
853 PyInterpreterState_Delete(interp);
854}
855
856#ifdef MS_WINDOWS
857static wchar_t *progname = L"python";
858#else
859static wchar_t *progname = L"python3";
860#endif
861
862void
863Py_SetProgramName(wchar_t *pn)
864{
865 if (pn && *pn)
866 progname = pn;
867}
868
869wchar_t *
870Py_GetProgramName(void)
871{
872 return progname;
873}
874
875static wchar_t *default_home = NULL;
876static wchar_t env_home[MAXPATHLEN+1];
877
878void
879Py_SetPythonHome(wchar_t *home)
880{
881 default_home = home;
882}
883
884wchar_t *
885Py_GetPythonHome(void)
886{
887 wchar_t *home = default_home;
888 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
889 char* chome = Py_GETENV("PYTHONHOME");
890 if (chome) {
891 size_t size = Py_ARRAY_LENGTH(env_home);
892 size_t r = mbstowcs(env_home, chome, size);
893 if (r != (size_t)-1 && r < size)
894 home = env_home;
895 }
896
897 }
898 return home;
899}
900
901/* Create __main__ module */
902
903static void
904initmain(PyInterpreterState *interp)
905{
906 PyObject *m, *d, *loader;
907 m = PyImport_AddModule("__main__");
908 if (m == NULL)
909 Py_FatalError("can't create __main__ module");
910 d = PyModule_GetDict(m);
911 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
912 PyObject *bimod = PyImport_ImportModule("builtins");
913 if (bimod == NULL) {
914 Py_FatalError("Failed to retrieve builtins module");
915 }
916 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
917 Py_FatalError("Failed to initialize __main__.__builtins__");
918 }
919 Py_DECREF(bimod);
920 }
921 /* Main is a little special - imp.is_builtin("__main__") will return
922 * False, but BuiltinImporter is still the most appropriate initial
923 * setting for its __loader__ attribute. A more suitable value will
924 * be set if __main__ gets further initialized later in the startup
925 * process.
926 */
927 loader = PyDict_GetItemString(d, "__loader__");
928 if (loader == NULL || loader == Py_None) {
929 PyObject *loader = PyObject_GetAttrString(interp->importlib,
930 "BuiltinImporter");
931 if (loader == NULL) {
932 Py_FatalError("Failed to retrieve BuiltinImporter");
933 }
934 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
935 Py_FatalError("Failed to initialize __main__.__loader__");
936 }
937 Py_DECREF(loader);
938 }
939}
940
941static int
942initfsencoding(PyInterpreterState *interp)
943{
944 PyObject *codec;
945
946 if (Py_FileSystemDefaultEncoding == NULL)
947 {
948 Py_FileSystemDefaultEncoding = get_locale_encoding();
949 if (Py_FileSystemDefaultEncoding == NULL)
950 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
951
952 Py_HasFileSystemDefaultEncoding = 0;
953 interp->fscodec_initialized = 1;
954 return 0;
955 }
956
957 /* the encoding is mbcs, utf-8 or ascii */
958 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
959 if (!codec) {
960 /* Such error can only occurs in critical situations: no more
961 * memory, import a module of the standard library failed,
962 * etc. */
963 return -1;
964 }
965 Py_DECREF(codec);
966 interp->fscodec_initialized = 1;
967 return 0;
968}
969
970/* Import the site module (not into __main__ though) */
971
972static void
973initsite(void)
974{
975 PyObject *m;
976 m = PyImport_ImportModule("site");
977 if (m == NULL) {
978 fprintf(stderr, "Failed to import the site module\n");
979 PyErr_Print();
980 Py_Finalize();
981 exit(1);
982 }
983 else {
984 Py_DECREF(m);
985 }
986}
987
Victor Stinner874dbe82015-09-04 17:29:57 +0200988/* Check if a file descriptor is valid or not.
989 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
990static int
991is_valid_fd(int fd)
992{
993 int fd2;
994 if (fd < 0 || !_PyVerify_fd(fd))
995 return 0;
996 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +0200997 /* Prefer dup() over fstat(). fstat() can require input/output whereas
998 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
999 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001000 fd2 = dup(fd);
1001 if (fd2 >= 0)
1002 close(fd2);
1003 _Py_END_SUPPRESS_IPH
1004 return fd2 >= 0;
1005}
1006
1007/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001008static PyObject*
1009create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001010 int fd, int write_mode, const char* name,
1011 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001012{
1013 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1014 const char* mode;
1015 const char* newline;
1016 PyObject *line_buffering;
1017 int buffering, isatty;
1018 _Py_IDENTIFIER(open);
1019 _Py_IDENTIFIER(isatty);
1020 _Py_IDENTIFIER(TextIOWrapper);
1021 _Py_IDENTIFIER(mode);
1022
Victor Stinner874dbe82015-09-04 17:29:57 +02001023 if (!is_valid_fd(fd))
1024 Py_RETURN_NONE;
1025
Nick Coghland6009512014-11-20 21:39:37 +10001026 /* stdin is always opened in buffered mode, first because it shouldn't
1027 make a difference in common use cases, second because TextIOWrapper
1028 depends on the presence of a read1() method which only exists on
1029 buffered streams.
1030 */
1031 if (Py_UnbufferedStdioFlag && write_mode)
1032 buffering = 0;
1033 else
1034 buffering = -1;
1035 if (write_mode)
1036 mode = "wb";
1037 else
1038 mode = "rb";
1039 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1040 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001041 Py_None, Py_None, /* encoding, errors */
1042 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001043 if (buf == NULL)
1044 goto error;
1045
1046 if (buffering) {
1047 _Py_IDENTIFIER(raw);
1048 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1049 if (raw == NULL)
1050 goto error;
1051 }
1052 else {
1053 raw = buf;
1054 Py_INCREF(raw);
1055 }
1056
1057 text = PyUnicode_FromString(name);
1058 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1059 goto error;
1060 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1061 if (res == NULL)
1062 goto error;
1063 isatty = PyObject_IsTrue(res);
1064 Py_DECREF(res);
1065 if (isatty == -1)
1066 goto error;
1067 if (isatty || Py_UnbufferedStdioFlag)
1068 line_buffering = Py_True;
1069 else
1070 line_buffering = Py_False;
1071
1072 Py_CLEAR(raw);
1073 Py_CLEAR(text);
1074
1075#ifdef MS_WINDOWS
1076 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1077 newlines to "\n".
1078 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1079 newline = NULL;
1080#else
1081 /* sys.stdin: split lines at "\n".
1082 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1083 newline = "\n";
1084#endif
1085
1086 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1087 buf, encoding, errors,
1088 newline, line_buffering);
1089 Py_CLEAR(buf);
1090 if (stream == NULL)
1091 goto error;
1092
1093 if (write_mode)
1094 mode = "w";
1095 else
1096 mode = "r";
1097 text = PyUnicode_FromString(mode);
1098 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1099 goto error;
1100 Py_CLEAR(text);
1101 return stream;
1102
1103error:
1104 Py_XDECREF(buf);
1105 Py_XDECREF(stream);
1106 Py_XDECREF(text);
1107 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001108
Victor Stinner874dbe82015-09-04 17:29:57 +02001109 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1110 /* Issue #24891: the file descriptor was closed after the first
1111 is_valid_fd() check was called. Ignore the OSError and set the
1112 stream to None. */
1113 PyErr_Clear();
1114 Py_RETURN_NONE;
1115 }
1116 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001117}
1118
1119/* Initialize sys.stdin, stdout, stderr and builtins.open */
1120static int
1121initstdio(void)
1122{
1123 PyObject *iomod = NULL, *wrapper;
1124 PyObject *bimod = NULL;
1125 PyObject *m;
1126 PyObject *std = NULL;
1127 int status = 0, fd;
1128 PyObject * encoding_attr;
1129 char *pythonioencoding = NULL, *encoding, *errors;
1130
1131 /* Hack to avoid a nasty recursion issue when Python is invoked
1132 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1133 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1134 goto error;
1135 }
1136 Py_DECREF(m);
1137
1138 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1139 goto error;
1140 }
1141 Py_DECREF(m);
1142
1143 if (!(bimod = PyImport_ImportModule("builtins"))) {
1144 goto error;
1145 }
1146
1147 if (!(iomod = PyImport_ImportModule("io"))) {
1148 goto error;
1149 }
1150 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1151 goto error;
1152 }
1153
1154 /* Set builtins.open */
1155 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1156 Py_DECREF(wrapper);
1157 goto error;
1158 }
1159 Py_DECREF(wrapper);
1160
1161 encoding = _Py_StandardStreamEncoding;
1162 errors = _Py_StandardStreamErrors;
1163 if (!encoding || !errors) {
1164 if (!errors) {
1165 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1166 stdin and stdout use the surrogateescape error handler by
1167 default, instead of the strict error handler. */
1168 char *loc = setlocale(LC_CTYPE, NULL);
1169 if (loc != NULL && strcmp(loc, "C") == 0)
1170 errors = "surrogateescape";
1171 }
1172
1173 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1174 if (pythonioencoding) {
1175 char *err;
1176 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1177 if (pythonioencoding == NULL) {
1178 PyErr_NoMemory();
1179 goto error;
1180 }
1181 err = strchr(pythonioencoding, ':');
1182 if (err) {
1183 *err = '\0';
1184 err++;
1185 if (*err && !_Py_StandardStreamErrors) {
1186 errors = err;
1187 }
1188 }
1189 if (*pythonioencoding && !encoding) {
1190 encoding = pythonioencoding;
1191 }
1192 }
1193 }
1194
1195 /* Set sys.stdin */
1196 fd = fileno(stdin);
1197 /* Under some conditions stdin, stdout and stderr may not be connected
1198 * and fileno() may point to an invalid file descriptor. For example
1199 * GUI apps don't have valid standard streams by default.
1200 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001201 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1202 if (std == NULL)
1203 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001204 PySys_SetObject("__stdin__", std);
1205 _PySys_SetObjectId(&PyId_stdin, std);
1206 Py_DECREF(std);
1207
1208 /* Set sys.stdout */
1209 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001210 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1211 if (std == NULL)
1212 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001213 PySys_SetObject("__stdout__", std);
1214 _PySys_SetObjectId(&PyId_stdout, std);
1215 Py_DECREF(std);
1216
1217#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1218 /* Set sys.stderr, replaces the preliminary stderr */
1219 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001220 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1221 if (std == NULL)
1222 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001223
1224 /* Same as hack above, pre-import stderr's codec to avoid recursion
1225 when import.c tries to write to stderr in verbose mode. */
1226 encoding_attr = PyObject_GetAttrString(std, "encoding");
1227 if (encoding_attr != NULL) {
1228 const char * std_encoding;
1229 std_encoding = _PyUnicode_AsString(encoding_attr);
1230 if (std_encoding != NULL) {
1231 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1232 Py_XDECREF(codec_info);
1233 }
1234 Py_DECREF(encoding_attr);
1235 }
1236 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1237
1238 if (PySys_SetObject("__stderr__", std) < 0) {
1239 Py_DECREF(std);
1240 goto error;
1241 }
1242 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1243 Py_DECREF(std);
1244 goto error;
1245 }
1246 Py_DECREF(std);
1247#endif
1248
1249 if (0) {
1250 error:
1251 status = -1;
1252 }
1253
1254 /* We won't need them anymore. */
1255 if (_Py_StandardStreamEncoding) {
1256 PyMem_RawFree(_Py_StandardStreamEncoding);
1257 _Py_StandardStreamEncoding = NULL;
1258 }
1259 if (_Py_StandardStreamErrors) {
1260 PyMem_RawFree(_Py_StandardStreamErrors);
1261 _Py_StandardStreamErrors = NULL;
1262 }
1263 PyMem_Free(pythonioencoding);
1264 Py_XDECREF(bimod);
1265 Py_XDECREF(iomod);
1266 return status;
1267}
1268
1269
Victor Stinner10dc4842015-03-24 12:01:30 +01001270static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001271_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001272{
Victor Stinner10dc4842015-03-24 12:01:30 +01001273 PyThreadState *tstate;
1274
Benjamin Peterson55c14352015-04-06 09:59:23 -04001275#ifdef WITH_THREAD
Victor Stinner10dc4842015-03-24 12:01:30 +01001276 /* PyGILState_GetThisThreadState() works even if the GIL was released */
1277 tstate = PyGILState_GetThisThreadState();
Benjamin Peterson55c14352015-04-06 09:59:23 -04001278#else
1279 tstate = PyThreadState_GET();
1280#endif
Victor Stinner10dc4842015-03-24 12:01:30 +01001281 if (tstate == NULL) {
1282 /* _Py_DumpTracebackThreads() requires the thread state to display
1283 * frames */
1284 return;
1285 }
1286
1287 fputc('\n', stderr);
1288 fflush(stderr);
1289
1290 /* display the current Python stack */
1291 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
1292}
Victor Stinner791da1c2016-03-14 16:53:12 +01001293
1294/* Print the current exception (if an exception is set) with its traceback,
1295 or display the current Python stack.
1296
1297 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1298 called on catastrophic cases.
1299
1300 Return 1 if the traceback was displayed, 0 otherwise. */
1301
1302static int
1303_Py_FatalError_PrintExc(int fd)
1304{
1305 PyObject *ferr, *res;
1306 PyObject *exception, *v, *tb;
1307 int has_tb;
1308
1309 if (PyThreadState_GET() == NULL) {
1310 /* The GIL is released: trying to acquire it is likely to deadlock,
1311 just give up. */
1312 return 0;
1313 }
1314
1315 PyErr_Fetch(&exception, &v, &tb);
1316 if (exception == NULL) {
1317 /* No current exception */
1318 return 0;
1319 }
1320
1321 ferr = _PySys_GetObjectId(&PyId_stderr);
1322 if (ferr == NULL || ferr == Py_None) {
1323 /* sys.stderr is not set yet or set to None,
1324 no need to try to display the exception */
1325 return 0;
1326 }
1327
1328 PyErr_NormalizeException(&exception, &v, &tb);
1329 if (tb == NULL) {
1330 tb = Py_None;
1331 Py_INCREF(tb);
1332 }
1333 PyException_SetTraceback(v, tb);
1334 if (exception == NULL) {
1335 /* PyErr_NormalizeException() failed */
1336 return 0;
1337 }
1338
1339 has_tb = (tb != Py_None);
1340 PyErr_Display(exception, v, tb);
1341 Py_XDECREF(exception);
1342 Py_XDECREF(v);
1343 Py_XDECREF(tb);
1344
1345 /* sys.stderr may be buffered: call sys.stderr.flush() */
1346 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1347 if (res == NULL)
1348 PyErr_Clear();
1349 else
1350 Py_DECREF(res);
1351
1352 return has_tb;
1353}
1354
Nick Coghland6009512014-11-20 21:39:37 +10001355/* Print fatal error message and abort */
1356
1357void
1358Py_FatalError(const char *msg)
1359{
1360 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001361 static int reentrant = 0;
1362#ifdef MS_WINDOWS
1363 size_t len;
1364 WCHAR* buffer;
1365 size_t i;
1366#endif
1367
1368 if (reentrant) {
1369 /* Py_FatalError() caused a second fatal error.
1370 Example: flush_std_files() raises a recursion error. */
1371 goto exit;
1372 }
1373 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001374
1375 fprintf(stderr, "Fatal Python error: %s\n", msg);
1376 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001377
Victor Stinnere0deff32015-03-24 13:46:18 +01001378 /* Print the exception (if an exception is set) with its traceback,
1379 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001380 if (!_Py_FatalError_PrintExc(fd))
1381 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001382
Victor Stinner791da1c2016-03-14 16:53:12 +01001383 /* Check if the current Python thread hold the GIL */
1384 if (PyThreadState_GET() != NULL) {
1385 /* Flush sys.stdout and sys.stderr */
1386 flush_std_files();
1387 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001388
Victor Stinner10dc4842015-03-24 12:01:30 +01001389 /* The main purpose of faulthandler is to display the traceback. We already
Victor Stinnere0deff32015-03-24 13:46:18 +01001390 * did our best to display it. So faulthandler can now be disabled.
1391 * (Don't trigger it on abort().) */
Victor Stinner10dc4842015-03-24 12:01:30 +01001392 _PyFaulthandler_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001393
1394#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001395 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001396
Victor Stinner53345a42015-03-25 01:55:14 +01001397 /* Convert the message to wchar_t. This uses a simple one-to-one
1398 conversion, assuming that the this error message actually uses ASCII
1399 only. If this ceases to be true, we will have to convert. */
1400 buffer = alloca( (len+1) * (sizeof *buffer));
1401 for( i=0; i<=len; ++i)
1402 buffer[i] = msg[i];
1403 OutputDebugStringW(L"Fatal Python error: ");
1404 OutputDebugStringW(buffer);
1405 OutputDebugStringW(L"\n");
1406#endif /* MS_WINDOWS */
1407
1408exit:
1409#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001410 DebugBreak();
1411#endif
Nick Coghland6009512014-11-20 21:39:37 +10001412 abort();
1413}
1414
1415/* Clean up and exit */
1416
1417#ifdef WITH_THREAD
1418#include "pythread.h"
1419#endif
1420
1421static void (*pyexitfunc)(void) = NULL;
1422/* For the atexit module. */
1423void _Py_PyAtExit(void (*func)(void))
1424{
1425 pyexitfunc = func;
1426}
1427
1428static void
1429call_py_exitfuncs(void)
1430{
1431 if (pyexitfunc == NULL)
1432 return;
1433
1434 (*pyexitfunc)();
1435 PyErr_Clear();
1436}
1437
1438/* Wait until threading._shutdown completes, provided
1439 the threading module was imported in the first place.
1440 The shutdown routine will wait until all non-daemon
1441 "threading" threads have completed. */
1442static void
1443wait_for_thread_shutdown(void)
1444{
1445#ifdef WITH_THREAD
1446 _Py_IDENTIFIER(_shutdown);
1447 PyObject *result;
1448 PyThreadState *tstate = PyThreadState_GET();
1449 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1450 "threading");
1451 if (threading == NULL) {
1452 /* threading not imported */
1453 PyErr_Clear();
1454 return;
1455 }
1456 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1457 if (result == NULL) {
1458 PyErr_WriteUnraisable(threading);
1459 }
1460 else {
1461 Py_DECREF(result);
1462 }
1463 Py_DECREF(threading);
1464#endif
1465}
1466
1467#define NEXITFUNCS 32
1468static void (*exitfuncs[NEXITFUNCS])(void);
1469static int nexitfuncs = 0;
1470
1471int Py_AtExit(void (*func)(void))
1472{
1473 if (nexitfuncs >= NEXITFUNCS)
1474 return -1;
1475 exitfuncs[nexitfuncs++] = func;
1476 return 0;
1477}
1478
1479static void
1480call_ll_exitfuncs(void)
1481{
1482 while (nexitfuncs > 0)
1483 (*exitfuncs[--nexitfuncs])();
1484
1485 fflush(stdout);
1486 fflush(stderr);
1487}
1488
1489void
1490Py_Exit(int sts)
1491{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001492 if (Py_FinalizeEx() < 0) {
1493 sts = 120;
1494 }
Nick Coghland6009512014-11-20 21:39:37 +10001495
1496 exit(sts);
1497}
1498
1499static void
1500initsigs(void)
1501{
1502#ifdef SIGPIPE
1503 PyOS_setsig(SIGPIPE, SIG_IGN);
1504#endif
1505#ifdef SIGXFZ
1506 PyOS_setsig(SIGXFZ, SIG_IGN);
1507#endif
1508#ifdef SIGXFSZ
1509 PyOS_setsig(SIGXFSZ, SIG_IGN);
1510#endif
1511 PyOS_InitInterrupts(); /* May imply initsignal() */
1512 if (PyErr_Occurred()) {
1513 Py_FatalError("Py_Initialize: can't import signal");
1514 }
1515}
1516
1517
1518/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1519 *
1520 * All of the code in this function must only use async-signal-safe functions,
1521 * listed at `man 7 signal` or
1522 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1523 */
1524void
1525_Py_RestoreSignals(void)
1526{
1527#ifdef SIGPIPE
1528 PyOS_setsig(SIGPIPE, SIG_DFL);
1529#endif
1530#ifdef SIGXFZ
1531 PyOS_setsig(SIGXFZ, SIG_DFL);
1532#endif
1533#ifdef SIGXFSZ
1534 PyOS_setsig(SIGXFSZ, SIG_DFL);
1535#endif
1536}
1537
1538
1539/*
1540 * The file descriptor fd is considered ``interactive'' if either
1541 * a) isatty(fd) is TRUE, or
1542 * b) the -i flag was given, and the filename associated with
1543 * the descriptor is NULL or "<stdin>" or "???".
1544 */
1545int
1546Py_FdIsInteractive(FILE *fp, const char *filename)
1547{
1548 if (isatty((int)fileno(fp)))
1549 return 1;
1550 if (!Py_InteractiveFlag)
1551 return 0;
1552 return (filename == NULL) ||
1553 (strcmp(filename, "<stdin>") == 0) ||
1554 (strcmp(filename, "???") == 0);
1555}
1556
1557
Nick Coghland6009512014-11-20 21:39:37 +10001558/* Wrappers around sigaction() or signal(). */
1559
1560PyOS_sighandler_t
1561PyOS_getsig(int sig)
1562{
1563#ifdef HAVE_SIGACTION
1564 struct sigaction context;
1565 if (sigaction(sig, NULL, &context) == -1)
1566 return SIG_ERR;
1567 return context.sa_handler;
1568#else
1569 PyOS_sighandler_t handler;
1570/* Special signal handling for the secure CRT in Visual Studio 2005 */
1571#if defined(_MSC_VER) && _MSC_VER >= 1400
1572 switch (sig) {
1573 /* Only these signals are valid */
1574 case SIGINT:
1575 case SIGILL:
1576 case SIGFPE:
1577 case SIGSEGV:
1578 case SIGTERM:
1579 case SIGBREAK:
1580 case SIGABRT:
1581 break;
1582 /* Don't call signal() with other values or it will assert */
1583 default:
1584 return SIG_ERR;
1585 }
1586#endif /* _MSC_VER && _MSC_VER >= 1400 */
1587 handler = signal(sig, SIG_IGN);
1588 if (handler != SIG_ERR)
1589 signal(sig, handler);
1590 return handler;
1591#endif
1592}
1593
1594/*
1595 * All of the code in this function must only use async-signal-safe functions,
1596 * listed at `man 7 signal` or
1597 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1598 */
1599PyOS_sighandler_t
1600PyOS_setsig(int sig, PyOS_sighandler_t handler)
1601{
1602#ifdef HAVE_SIGACTION
1603 /* Some code in Modules/signalmodule.c depends on sigaction() being
1604 * used here if HAVE_SIGACTION is defined. Fix that if this code
1605 * changes to invalidate that assumption.
1606 */
1607 struct sigaction context, ocontext;
1608 context.sa_handler = handler;
1609 sigemptyset(&context.sa_mask);
1610 context.sa_flags = 0;
1611 if (sigaction(sig, &context, &ocontext) == -1)
1612 return SIG_ERR;
1613 return ocontext.sa_handler;
1614#else
1615 PyOS_sighandler_t oldhandler;
1616 oldhandler = signal(sig, handler);
1617#ifdef HAVE_SIGINTERRUPT
1618 siginterrupt(sig, 1);
1619#endif
1620 return oldhandler;
1621#endif
1622}
1623
1624#ifdef __cplusplus
1625}
1626#endif