blob: dc855513cae0446c15e4a70ac3d989f08d34d665 [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);
Stefan Krah144da4e2016-04-26 01:56:50 +0200226#elif defined(__ANDROID__)
227 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000228#else
229 PyErr_SetNone(PyExc_NotImplementedError);
230 return NULL;
231#endif
232}
233
234static void
235import_init(PyInterpreterState *interp, PyObject *sysmod)
236{
237 PyObject *importlib;
238 PyObject *impmod;
239 PyObject *sys_modules;
240 PyObject *value;
241
242 /* Import _importlib through its frozen version, _frozen_importlib. */
243 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
244 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
245 }
246 else if (Py_VerboseFlag) {
247 PySys_FormatStderr("import _frozen_importlib # frozen\n");
248 }
249 importlib = PyImport_AddModule("_frozen_importlib");
250 if (importlib == NULL) {
251 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
252 "sys.modules");
253 }
254 interp->importlib = importlib;
255 Py_INCREF(interp->importlib);
256
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300257 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
258 if (interp->import_func == NULL)
259 Py_FatalError("Py_Initialize: __import__ not found");
260 Py_INCREF(interp->import_func);
261
Victor Stinnercd6e6942015-09-18 09:11:57 +0200262 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000263 impmod = PyInit_imp();
264 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200265 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000266 }
267 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200268 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000269 }
270 sys_modules = PyImport_GetModuleDict();
271 if (Py_VerboseFlag) {
272 PySys_FormatStderr("import sys # builtin\n");
273 }
274 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
275 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
276 }
277
Victor Stinnercd6e6942015-09-18 09:11:57 +0200278 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000279 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
280 if (value == NULL) {
281 PyErr_Print();
282 Py_FatalError("Py_Initialize: importlib install failed");
283 }
284 Py_DECREF(value);
285 Py_DECREF(impmod);
286
287 _PyImportZip_Init();
288}
289
290
291void
292_Py_InitializeEx_Private(int install_sigs, int install_importlib)
293{
294 PyInterpreterState *interp;
295 PyThreadState *tstate;
296 PyObject *bimod, *sysmod, *pstderr;
297 char *p;
298 extern void _Py_ReadyTypes(void);
299
300 if (initialized)
301 return;
302 initialized = 1;
303 _Py_Finalizing = NULL;
304
305#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
306 /* Set up the LC_CTYPE locale, so we can obtain
307 the locale's charset without having to switch
308 locales. */
309 setlocale(LC_CTYPE, "");
310#endif
311
312 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
313 Py_DebugFlag = add_flag(Py_DebugFlag, p);
314 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
315 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
316 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
317 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
318 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
319 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
320 /* The variable is only tested for existence here; _PyRandom_Init will
321 check its value further. */
322 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
323 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
324
325 _PyRandom_Init();
326
327 interp = PyInterpreterState_New();
328 if (interp == NULL)
329 Py_FatalError("Py_Initialize: can't make first interpreter");
330
331 tstate = PyThreadState_New(interp);
332 if (tstate == NULL)
333 Py_FatalError("Py_Initialize: can't make first thread");
334 (void) PyThreadState_Swap(tstate);
335
336#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000337 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000338 destroying the GIL might fail when it is being referenced from
339 another running thread (see issue #9901).
340 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000341 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000342 _PyEval_FiniThreads();
343
344 /* Auto-thread-state API */
345 _PyGILState_Init(interp, tstate);
346#endif /* WITH_THREAD */
347
348 _Py_ReadyTypes();
349
350 if (!_PyFrame_Init())
351 Py_FatalError("Py_Initialize: can't init frames");
352
353 if (!_PyLong_Init())
354 Py_FatalError("Py_Initialize: can't init longs");
355
356 if (!PyByteArray_Init())
357 Py_FatalError("Py_Initialize: can't init bytearray");
358
359 if (!_PyFloat_Init())
360 Py_FatalError("Py_Initialize: can't init float");
361
362 interp->modules = PyDict_New();
363 if (interp->modules == NULL)
364 Py_FatalError("Py_Initialize: can't make modules dictionary");
365
366 /* Init Unicode implementation; relies on the codec registry */
367 if (_PyUnicode_Init() < 0)
368 Py_FatalError("Py_Initialize: can't initialize unicode");
369 if (_PyStructSequence_Init() < 0)
370 Py_FatalError("Py_Initialize: can't initialize structseq");
371
372 bimod = _PyBuiltin_Init();
373 if (bimod == NULL)
374 Py_FatalError("Py_Initialize: can't initialize builtins modules");
375 _PyImport_FixupBuiltin(bimod, "builtins");
376 interp->builtins = PyModule_GetDict(bimod);
377 if (interp->builtins == NULL)
378 Py_FatalError("Py_Initialize: can't initialize builtins dict");
379 Py_INCREF(interp->builtins);
380
381 /* initialize builtin exceptions */
382 _PyExc_Init(bimod);
383
384 sysmod = _PySys_Init();
385 if (sysmod == NULL)
386 Py_FatalError("Py_Initialize: can't initialize sys");
387 interp->sysdict = PyModule_GetDict(sysmod);
388 if (interp->sysdict == NULL)
389 Py_FatalError("Py_Initialize: can't initialize sys dict");
390 Py_INCREF(interp->sysdict);
391 _PyImport_FixupBuiltin(sysmod, "sys");
392 PySys_SetPath(Py_GetPath());
393 PyDict_SetItemString(interp->sysdict, "modules",
394 interp->modules);
395
396 /* Set up a preliminary stderr printer until we have enough
397 infrastructure for the io module in place. */
398 pstderr = PyFile_NewStdPrinter(fileno(stderr));
399 if (pstderr == NULL)
400 Py_FatalError("Py_Initialize: can't set preliminary stderr");
401 _PySys_SetObjectId(&PyId_stderr, pstderr);
402 PySys_SetObject("__stderr__", pstderr);
403 Py_DECREF(pstderr);
404
405 _PyImport_Init();
406
407 _PyImportHooks_Init();
408
409 /* Initialize _warnings. */
410 _PyWarnings_Init();
411
412 if (!install_importlib)
413 return;
414
Victor Stinner13019fd2015-04-03 13:10:54 +0200415 if (_PyTime_Init() < 0)
416 Py_FatalError("Py_Initialize: can't initialize time");
417
Nick Coghland6009512014-11-20 21:39:37 +1000418 import_init(interp, sysmod);
419
420 /* initialize the faulthandler module */
421 if (_PyFaulthandler_Init())
422 Py_FatalError("Py_Initialize: can't initialize faulthandler");
423
Nick Coghland6009512014-11-20 21:39:37 +1000424 if (initfsencoding(interp) < 0)
425 Py_FatalError("Py_Initialize: unable to load the file system codec");
426
427 if (install_sigs)
428 initsigs(); /* Signal handling stuff, including initintr() */
429
430 if (_PyTraceMalloc_Init() < 0)
431 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
432
433 initmain(interp); /* Module __main__ */
434 if (initstdio() < 0)
435 Py_FatalError(
436 "Py_Initialize: can't initialize sys standard streams");
437
438 /* Initialize warnings. */
439 if (PySys_HasWarnOptions()) {
440 PyObject *warnings_module = PyImport_ImportModule("warnings");
441 if (warnings_module == NULL) {
442 fprintf(stderr, "'import warnings' failed; traceback:\n");
443 PyErr_Print();
444 }
445 Py_XDECREF(warnings_module);
446 }
447
448 if (!Py_NoSiteFlag)
449 initsite(); /* Module site */
450}
451
452void
453Py_InitializeEx(int install_sigs)
454{
455 _Py_InitializeEx_Private(install_sigs, 1);
456}
457
458void
459Py_Initialize(void)
460{
461 Py_InitializeEx(1);
462}
463
464
465#ifdef COUNT_ALLOCS
466extern void dump_counts(FILE*);
467#endif
468
469/* Flush stdout and stderr */
470
471static int
472file_is_closed(PyObject *fobj)
473{
474 int r;
475 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
476 if (tmp == NULL) {
477 PyErr_Clear();
478 return 0;
479 }
480 r = PyObject_IsTrue(tmp);
481 Py_DECREF(tmp);
482 if (r < 0)
483 PyErr_Clear();
484 return r > 0;
485}
486
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000487static int
Nick Coghland6009512014-11-20 21:39:37 +1000488flush_std_files(void)
489{
490 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
491 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
492 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000493 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000494
495 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
496 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000497 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000498 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000499 status = -1;
500 }
Nick Coghland6009512014-11-20 21:39:37 +1000501 else
502 Py_DECREF(tmp);
503 }
504
505 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
506 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000507 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000508 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000509 status = -1;
510 }
Nick Coghland6009512014-11-20 21:39:37 +1000511 else
512 Py_DECREF(tmp);
513 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000514
515 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000516}
517
518/* Undo the effect of Py_Initialize().
519
520 Beware: if multiple interpreter and/or thread states exist, these
521 are not wiped out; only the current thread and interpreter state
522 are deleted. But since everything else is deleted, those other
523 interpreter and thread states should no longer be used.
524
525 (XXX We should do better, e.g. wipe out all interpreters and
526 threads.)
527
528 Locking: as above.
529
530*/
531
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000532int
533Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000534{
535 PyInterpreterState *interp;
536 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000537 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000538
539 if (!initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000540 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000541
542 wait_for_thread_shutdown();
543
544 /* The interpreter is still entirely intact at this point, and the
545 * exit funcs may be relying on that. In particular, if some thread
546 * or exit func is still waiting to do an import, the import machinery
547 * expects Py_IsInitialized() to return true. So don't say the
548 * interpreter is uninitialized until after the exit funcs have run.
549 * Note that Threading.py uses an exit func to do a join on all the
550 * threads created thru it, so this also protects pending imports in
551 * the threads created via Threading.
552 */
553 call_py_exitfuncs();
554
555 /* Get current thread state and interpreter pointer */
556 tstate = PyThreadState_GET();
557 interp = tstate->interp;
558
559 /* Remaining threads (e.g. daemon threads) will automatically exit
560 after taking the GIL (in PyEval_RestoreThread()). */
561 _Py_Finalizing = tstate;
562 initialized = 0;
563
Victor Stinnere0deff32015-03-24 13:46:18 +0100564 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000565 if (flush_std_files() < 0) {
566 status = -1;
567 }
Nick Coghland6009512014-11-20 21:39:37 +1000568
569 /* Disable signal handling */
570 PyOS_FiniInterrupts();
571
572 /* Collect garbage. This may call finalizers; it's nice to call these
573 * before all modules are destroyed.
574 * XXX If a __del__ or weakref callback is triggered here, and tries to
575 * XXX import a module, bad things can happen, because Python no
576 * XXX longer believes it's initialized.
577 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
578 * XXX is easy to provoke that way. I've also seen, e.g.,
579 * XXX Exception exceptions.ImportError: 'No module named sha'
580 * XXX in <function callback at 0x008F5718> ignored
581 * XXX but I'm unclear on exactly how that one happens. In any case,
582 * XXX I haven't seen a real-life report of either of these.
583 */
584 PyGC_Collect();
585#ifdef COUNT_ALLOCS
586 /* With COUNT_ALLOCS, it helps to run GC multiple times:
587 each collection might release some types from the type
588 list, so they become garbage. */
589 while (PyGC_Collect() > 0)
590 /* nothing */;
591#endif
592 /* Destroy all modules */
593 PyImport_Cleanup();
594
Victor Stinnere0deff32015-03-24 13:46:18 +0100595 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000596 if (flush_std_files() < 0) {
597 status = -1;
598 }
Nick Coghland6009512014-11-20 21:39:37 +1000599
600 /* Collect final garbage. This disposes of cycles created by
601 * class definitions, for example.
602 * XXX This is disabled because it caused too many problems. If
603 * XXX a __del__ or weakref callback triggers here, Python code has
604 * XXX a hard time running, because even the sys module has been
605 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
606 * XXX One symptom is a sequence of information-free messages
607 * XXX coming from threads (if a __del__ or callback is invoked,
608 * XXX other threads can execute too, and any exception they encounter
609 * XXX triggers a comedy of errors as subsystem after subsystem
610 * XXX fails to find what it *expects* to find in sys to help report
611 * XXX the exception and consequent unexpected failures). I've also
612 * XXX seen segfaults then, after adding print statements to the
613 * XXX Python code getting called.
614 */
615#if 0
616 PyGC_Collect();
617#endif
618
619 /* Disable tracemalloc after all Python objects have been destroyed,
620 so it is possible to use tracemalloc in objects destructor. */
621 _PyTraceMalloc_Fini();
622
623 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
624 _PyImport_Fini();
625
626 /* Cleanup typeobject.c's internal caches. */
627 _PyType_Fini();
628
629 /* unload faulthandler module */
630 _PyFaulthandler_Fini();
631
632 /* Debugging stuff */
633#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300634 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +1000635#endif
636 /* dump hash stats */
637 _PyHash_Fini();
638
639 _PY_DEBUG_PRINT_TOTAL_REFS();
640
641#ifdef Py_TRACE_REFS
642 /* Display all objects still alive -- this can invoke arbitrary
643 * __repr__ overrides, so requires a mostly-intact interpreter.
644 * Alas, a lot of stuff may still be alive now that will be cleaned
645 * up later.
646 */
647 if (Py_GETENV("PYTHONDUMPREFS"))
648 _Py_PrintReferences(stderr);
649#endif /* Py_TRACE_REFS */
650
651 /* Clear interpreter state and all thread states. */
652 PyInterpreterState_Clear(interp);
653
654 /* Now we decref the exception classes. After this point nothing
655 can raise an exception. That's okay, because each Fini() method
656 below has been checked to make sure no exceptions are ever
657 raised.
658 */
659
660 _PyExc_Fini();
661
662 /* Sundry finalizers */
663 PyMethod_Fini();
664 PyFrame_Fini();
665 PyCFunction_Fini();
666 PyTuple_Fini();
667 PyList_Fini();
668 PySet_Fini();
669 PyBytes_Fini();
670 PyByteArray_Fini();
671 PyLong_Fini();
672 PyFloat_Fini();
673 PyDict_Fini();
674 PySlice_Fini();
675 _PyGC_Fini();
676 _PyRandom_Fini();
677
678 /* Cleanup Unicode implementation */
679 _PyUnicode_Fini();
680
681 /* reset file system default encoding */
682 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
683 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
684 Py_FileSystemDefaultEncoding = NULL;
685 }
686
687 /* XXX Still allocated:
688 - various static ad-hoc pointers to interned strings
689 - int and float free list blocks
690 - whatever various modules and libraries allocate
691 */
692
693 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
694
695 /* Cleanup auto-thread-state */
696#ifdef WITH_THREAD
697 _PyGILState_Fini();
698#endif /* WITH_THREAD */
699
700 /* Delete current thread. After this, many C API calls become crashy. */
701 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +0100702
Nick Coghland6009512014-11-20 21:39:37 +1000703 PyInterpreterState_Delete(interp);
704
705#ifdef Py_TRACE_REFS
706 /* Display addresses (& refcnts) of all objects still alive.
707 * An address can be used to find the repr of the object, printed
708 * above by _Py_PrintReferences.
709 */
710 if (Py_GETENV("PYTHONDUMPREFS"))
711 _Py_PrintReferenceAddresses(stderr);
712#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +0100713#ifdef WITH_PYMALLOC
714 if (_PyMem_PymallocEnabled()) {
715 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
716 if (opt != NULL && *opt != '\0')
717 _PyObject_DebugMallocStats(stderr);
718 }
Nick Coghland6009512014-11-20 21:39:37 +1000719#endif
720
721 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000722 return status;
723}
724
725void
726Py_Finalize(void)
727{
728 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000729}
730
731/* Create and initialize a new interpreter and thread, and return the
732 new thread. This requires that Py_Initialize() has been called
733 first.
734
735 Unsuccessful initialization yields a NULL pointer. Note that *no*
736 exception information is available even in this case -- the
737 exception information is held in the thread, and there is no
738 thread.
739
740 Locking: as above.
741
742*/
743
744PyThreadState *
745Py_NewInterpreter(void)
746{
747 PyInterpreterState *interp;
748 PyThreadState *tstate, *save_tstate;
749 PyObject *bimod, *sysmod;
750
751 if (!initialized)
752 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
753
Victor Stinnerd7292b52016-06-17 12:29:00 +0200754#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +0100755 /* Issue #10915, #15751: The GIL API doesn't work with multiple
756 interpreters: disable PyGILState_Check(). */
757 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +0300758#endif
Victor Stinner8a1be612016-03-14 22:07:55 +0100759
Nick Coghland6009512014-11-20 21:39:37 +1000760 interp = PyInterpreterState_New();
761 if (interp == NULL)
762 return NULL;
763
764 tstate = PyThreadState_New(interp);
765 if (tstate == NULL) {
766 PyInterpreterState_Delete(interp);
767 return NULL;
768 }
769
770 save_tstate = PyThreadState_Swap(tstate);
771
772 /* XXX The following is lax in error checking */
773
774 interp->modules = PyDict_New();
775
776 bimod = _PyImport_FindBuiltin("builtins");
777 if (bimod != NULL) {
778 interp->builtins = PyModule_GetDict(bimod);
779 if (interp->builtins == NULL)
780 goto handle_error;
781 Py_INCREF(interp->builtins);
782 }
783
784 /* initialize builtin exceptions */
785 _PyExc_Init(bimod);
786
787 sysmod = _PyImport_FindBuiltin("sys");
788 if (bimod != NULL && sysmod != NULL) {
789 PyObject *pstderr;
790
791 interp->sysdict = PyModule_GetDict(sysmod);
792 if (interp->sysdict == NULL)
793 goto handle_error;
794 Py_INCREF(interp->sysdict);
795 PySys_SetPath(Py_GetPath());
796 PyDict_SetItemString(interp->sysdict, "modules",
797 interp->modules);
798 /* Set up a preliminary stderr printer until we have enough
799 infrastructure for the io module in place. */
800 pstderr = PyFile_NewStdPrinter(fileno(stderr));
801 if (pstderr == NULL)
802 Py_FatalError("Py_Initialize: can't set preliminary stderr");
803 _PySys_SetObjectId(&PyId_stderr, pstderr);
804 PySys_SetObject("__stderr__", pstderr);
805 Py_DECREF(pstderr);
806
807 _PyImportHooks_Init();
808
809 import_init(interp, sysmod);
810
811 if (initfsencoding(interp) < 0)
812 goto handle_error;
813
814 if (initstdio() < 0)
815 Py_FatalError(
Georg Brandl4b5b0622016-01-18 08:00:15 +0100816 "Py_Initialize: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000817 initmain(interp);
818 if (!Py_NoSiteFlag)
819 initsite();
820 }
821
822 if (!PyErr_Occurred())
823 return tstate;
824
825handle_error:
826 /* Oops, it didn't work. Undo it all. */
827
828 PyErr_PrintEx(0);
829 PyThreadState_Clear(tstate);
830 PyThreadState_Swap(save_tstate);
831 PyThreadState_Delete(tstate);
832 PyInterpreterState_Delete(interp);
833
834 return NULL;
835}
836
837/* Delete an interpreter and its last thread. This requires that the
838 given thread state is current, that the thread has no remaining
839 frames, and that it is its interpreter's only remaining thread.
840 It is a fatal error to violate these constraints.
841
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000842 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +1000843 everything, regardless.)
844
845 Locking: as above.
846
847*/
848
849void
850Py_EndInterpreter(PyThreadState *tstate)
851{
852 PyInterpreterState *interp = tstate->interp;
853
854 if (tstate != PyThreadState_GET())
855 Py_FatalError("Py_EndInterpreter: thread is not current");
856 if (tstate->frame != NULL)
857 Py_FatalError("Py_EndInterpreter: thread still has a frame");
858
859 wait_for_thread_shutdown();
860
861 if (tstate != interp->tstate_head || tstate->next != NULL)
862 Py_FatalError("Py_EndInterpreter: not the last thread");
863
864 PyImport_Cleanup();
865 PyInterpreterState_Clear(interp);
866 PyThreadState_Swap(NULL);
867 PyInterpreterState_Delete(interp);
868}
869
870#ifdef MS_WINDOWS
871static wchar_t *progname = L"python";
872#else
873static wchar_t *progname = L"python3";
874#endif
875
876void
877Py_SetProgramName(wchar_t *pn)
878{
879 if (pn && *pn)
880 progname = pn;
881}
882
883wchar_t *
884Py_GetProgramName(void)
885{
886 return progname;
887}
888
889static wchar_t *default_home = NULL;
890static wchar_t env_home[MAXPATHLEN+1];
891
892void
893Py_SetPythonHome(wchar_t *home)
894{
895 default_home = home;
896}
897
898wchar_t *
899Py_GetPythonHome(void)
900{
901 wchar_t *home = default_home;
902 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
903 char* chome = Py_GETENV("PYTHONHOME");
904 if (chome) {
905 size_t size = Py_ARRAY_LENGTH(env_home);
906 size_t r = mbstowcs(env_home, chome, size);
907 if (r != (size_t)-1 && r < size)
908 home = env_home;
909 }
910
911 }
912 return home;
913}
914
915/* Create __main__ module */
916
917static void
918initmain(PyInterpreterState *interp)
919{
920 PyObject *m, *d, *loader;
921 m = PyImport_AddModule("__main__");
922 if (m == NULL)
923 Py_FatalError("can't create __main__ module");
924 d = PyModule_GetDict(m);
925 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
926 PyObject *bimod = PyImport_ImportModule("builtins");
927 if (bimod == NULL) {
928 Py_FatalError("Failed to retrieve builtins module");
929 }
930 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
931 Py_FatalError("Failed to initialize __main__.__builtins__");
932 }
933 Py_DECREF(bimod);
934 }
935 /* Main is a little special - imp.is_builtin("__main__") will return
936 * False, but BuiltinImporter is still the most appropriate initial
937 * setting for its __loader__ attribute. A more suitable value will
938 * be set if __main__ gets further initialized later in the startup
939 * process.
940 */
941 loader = PyDict_GetItemString(d, "__loader__");
942 if (loader == NULL || loader == Py_None) {
943 PyObject *loader = PyObject_GetAttrString(interp->importlib,
944 "BuiltinImporter");
945 if (loader == NULL) {
946 Py_FatalError("Failed to retrieve BuiltinImporter");
947 }
948 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
949 Py_FatalError("Failed to initialize __main__.__loader__");
950 }
951 Py_DECREF(loader);
952 }
953}
954
955static int
956initfsencoding(PyInterpreterState *interp)
957{
958 PyObject *codec;
959
960 if (Py_FileSystemDefaultEncoding == NULL)
961 {
962 Py_FileSystemDefaultEncoding = get_locale_encoding();
963 if (Py_FileSystemDefaultEncoding == NULL)
964 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
965
966 Py_HasFileSystemDefaultEncoding = 0;
967 interp->fscodec_initialized = 1;
968 return 0;
969 }
970
971 /* the encoding is mbcs, utf-8 or ascii */
972 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
973 if (!codec) {
974 /* Such error can only occurs in critical situations: no more
975 * memory, import a module of the standard library failed,
976 * etc. */
977 return -1;
978 }
979 Py_DECREF(codec);
980 interp->fscodec_initialized = 1;
981 return 0;
982}
983
984/* Import the site module (not into __main__ though) */
985
986static void
987initsite(void)
988{
989 PyObject *m;
990 m = PyImport_ImportModule("site");
991 if (m == NULL) {
992 fprintf(stderr, "Failed to import the site module\n");
993 PyErr_Print();
994 Py_Finalize();
995 exit(1);
996 }
997 else {
998 Py_DECREF(m);
999 }
1000}
1001
Victor Stinner874dbe82015-09-04 17:29:57 +02001002/* Check if a file descriptor is valid or not.
1003 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1004static int
1005is_valid_fd(int fd)
1006{
1007 int fd2;
1008 if (fd < 0 || !_PyVerify_fd(fd))
1009 return 0;
1010 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001011 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1012 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1013 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001014 fd2 = dup(fd);
1015 if (fd2 >= 0)
1016 close(fd2);
1017 _Py_END_SUPPRESS_IPH
1018 return fd2 >= 0;
1019}
1020
1021/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001022static PyObject*
1023create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001024 int fd, int write_mode, const char* name,
1025 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001026{
1027 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1028 const char* mode;
1029 const char* newline;
1030 PyObject *line_buffering;
1031 int buffering, isatty;
1032 _Py_IDENTIFIER(open);
1033 _Py_IDENTIFIER(isatty);
1034 _Py_IDENTIFIER(TextIOWrapper);
1035 _Py_IDENTIFIER(mode);
1036
Victor Stinner874dbe82015-09-04 17:29:57 +02001037 if (!is_valid_fd(fd))
1038 Py_RETURN_NONE;
1039
Nick Coghland6009512014-11-20 21:39:37 +10001040 /* stdin is always opened in buffered mode, first because it shouldn't
1041 make a difference in common use cases, second because TextIOWrapper
1042 depends on the presence of a read1() method which only exists on
1043 buffered streams.
1044 */
1045 if (Py_UnbufferedStdioFlag && write_mode)
1046 buffering = 0;
1047 else
1048 buffering = -1;
1049 if (write_mode)
1050 mode = "wb";
1051 else
1052 mode = "rb";
1053 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1054 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001055 Py_None, Py_None, /* encoding, errors */
1056 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001057 if (buf == NULL)
1058 goto error;
1059
1060 if (buffering) {
1061 _Py_IDENTIFIER(raw);
1062 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1063 if (raw == NULL)
1064 goto error;
1065 }
1066 else {
1067 raw = buf;
1068 Py_INCREF(raw);
1069 }
1070
1071 text = PyUnicode_FromString(name);
1072 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1073 goto error;
1074 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1075 if (res == NULL)
1076 goto error;
1077 isatty = PyObject_IsTrue(res);
1078 Py_DECREF(res);
1079 if (isatty == -1)
1080 goto error;
1081 if (isatty || Py_UnbufferedStdioFlag)
1082 line_buffering = Py_True;
1083 else
1084 line_buffering = Py_False;
1085
1086 Py_CLEAR(raw);
1087 Py_CLEAR(text);
1088
1089#ifdef MS_WINDOWS
1090 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1091 newlines to "\n".
1092 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1093 newline = NULL;
1094#else
1095 /* sys.stdin: split lines at "\n".
1096 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1097 newline = "\n";
1098#endif
1099
1100 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1101 buf, encoding, errors,
1102 newline, line_buffering);
1103 Py_CLEAR(buf);
1104 if (stream == NULL)
1105 goto error;
1106
1107 if (write_mode)
1108 mode = "w";
1109 else
1110 mode = "r";
1111 text = PyUnicode_FromString(mode);
1112 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1113 goto error;
1114 Py_CLEAR(text);
1115 return stream;
1116
1117error:
1118 Py_XDECREF(buf);
1119 Py_XDECREF(stream);
1120 Py_XDECREF(text);
1121 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001122
Victor Stinner874dbe82015-09-04 17:29:57 +02001123 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1124 /* Issue #24891: the file descriptor was closed after the first
1125 is_valid_fd() check was called. Ignore the OSError and set the
1126 stream to None. */
1127 PyErr_Clear();
1128 Py_RETURN_NONE;
1129 }
1130 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001131}
1132
1133/* Initialize sys.stdin, stdout, stderr and builtins.open */
1134static int
1135initstdio(void)
1136{
1137 PyObject *iomod = NULL, *wrapper;
1138 PyObject *bimod = NULL;
1139 PyObject *m;
1140 PyObject *std = NULL;
1141 int status = 0, fd;
1142 PyObject * encoding_attr;
1143 char *pythonioencoding = NULL, *encoding, *errors;
1144
1145 /* Hack to avoid a nasty recursion issue when Python is invoked
1146 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1147 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1148 goto error;
1149 }
1150 Py_DECREF(m);
1151
1152 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1153 goto error;
1154 }
1155 Py_DECREF(m);
1156
1157 if (!(bimod = PyImport_ImportModule("builtins"))) {
1158 goto error;
1159 }
1160
1161 if (!(iomod = PyImport_ImportModule("io"))) {
1162 goto error;
1163 }
1164 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1165 goto error;
1166 }
1167
1168 /* Set builtins.open */
1169 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1170 Py_DECREF(wrapper);
1171 goto error;
1172 }
1173 Py_DECREF(wrapper);
1174
1175 encoding = _Py_StandardStreamEncoding;
1176 errors = _Py_StandardStreamErrors;
1177 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001178 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1179 if (pythonioencoding) {
1180 char *err;
1181 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1182 if (pythonioencoding == NULL) {
1183 PyErr_NoMemory();
1184 goto error;
1185 }
1186 err = strchr(pythonioencoding, ':');
1187 if (err) {
1188 *err = '\0';
1189 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001190 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001191 errors = err;
1192 }
1193 }
1194 if (*pythonioencoding && !encoding) {
1195 encoding = pythonioencoding;
1196 }
1197 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001198 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1199 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1200 stdin and stdout use the surrogateescape error handler by
1201 default, instead of the strict error handler. */
1202 char *loc = setlocale(LC_CTYPE, NULL);
1203 if (loc != NULL && strcmp(loc, "C") == 0)
1204 errors = "surrogateescape";
1205 }
Nick Coghland6009512014-11-20 21:39:37 +10001206 }
1207
1208 /* Set sys.stdin */
1209 fd = fileno(stdin);
1210 /* Under some conditions stdin, stdout and stderr may not be connected
1211 * and fileno() may point to an invalid file descriptor. For example
1212 * GUI apps don't have valid standard streams by default.
1213 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001214 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1215 if (std == NULL)
1216 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001217 PySys_SetObject("__stdin__", std);
1218 _PySys_SetObjectId(&PyId_stdin, std);
1219 Py_DECREF(std);
1220
1221 /* Set sys.stdout */
1222 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001223 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1224 if (std == NULL)
1225 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001226 PySys_SetObject("__stdout__", std);
1227 _PySys_SetObjectId(&PyId_stdout, std);
1228 Py_DECREF(std);
1229
1230#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1231 /* Set sys.stderr, replaces the preliminary stderr */
1232 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001233 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1234 if (std == NULL)
1235 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001236
1237 /* Same as hack above, pre-import stderr's codec to avoid recursion
1238 when import.c tries to write to stderr in verbose mode. */
1239 encoding_attr = PyObject_GetAttrString(std, "encoding");
1240 if (encoding_attr != NULL) {
1241 const char * std_encoding;
1242 std_encoding = _PyUnicode_AsString(encoding_attr);
1243 if (std_encoding != NULL) {
1244 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1245 Py_XDECREF(codec_info);
1246 }
1247 Py_DECREF(encoding_attr);
1248 }
1249 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1250
1251 if (PySys_SetObject("__stderr__", std) < 0) {
1252 Py_DECREF(std);
1253 goto error;
1254 }
1255 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1256 Py_DECREF(std);
1257 goto error;
1258 }
1259 Py_DECREF(std);
1260#endif
1261
1262 if (0) {
1263 error:
1264 status = -1;
1265 }
1266
1267 /* We won't need them anymore. */
1268 if (_Py_StandardStreamEncoding) {
1269 PyMem_RawFree(_Py_StandardStreamEncoding);
1270 _Py_StandardStreamEncoding = NULL;
1271 }
1272 if (_Py_StandardStreamErrors) {
1273 PyMem_RawFree(_Py_StandardStreamErrors);
1274 _Py_StandardStreamErrors = NULL;
1275 }
1276 PyMem_Free(pythonioencoding);
1277 Py_XDECREF(bimod);
1278 Py_XDECREF(iomod);
1279 return status;
1280}
1281
1282
Victor Stinner10dc4842015-03-24 12:01:30 +01001283static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001284_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001285{
Victor Stinner10dc4842015-03-24 12:01:30 +01001286 fputc('\n', stderr);
1287 fflush(stderr);
1288
1289 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001290 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001291}
Victor Stinner791da1c2016-03-14 16:53:12 +01001292
1293/* Print the current exception (if an exception is set) with its traceback,
1294 or display the current Python stack.
1295
1296 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1297 called on catastrophic cases.
1298
1299 Return 1 if the traceback was displayed, 0 otherwise. */
1300
1301static int
1302_Py_FatalError_PrintExc(int fd)
1303{
1304 PyObject *ferr, *res;
1305 PyObject *exception, *v, *tb;
1306 int has_tb;
1307
1308 if (PyThreadState_GET() == NULL) {
1309 /* The GIL is released: trying to acquire it is likely to deadlock,
1310 just give up. */
1311 return 0;
1312 }
1313
1314 PyErr_Fetch(&exception, &v, &tb);
1315 if (exception == NULL) {
1316 /* No current exception */
1317 return 0;
1318 }
1319
1320 ferr = _PySys_GetObjectId(&PyId_stderr);
1321 if (ferr == NULL || ferr == Py_None) {
1322 /* sys.stderr is not set yet or set to None,
1323 no need to try to display the exception */
1324 return 0;
1325 }
1326
1327 PyErr_NormalizeException(&exception, &v, &tb);
1328 if (tb == NULL) {
1329 tb = Py_None;
1330 Py_INCREF(tb);
1331 }
1332 PyException_SetTraceback(v, tb);
1333 if (exception == NULL) {
1334 /* PyErr_NormalizeException() failed */
1335 return 0;
1336 }
1337
1338 has_tb = (tb != Py_None);
1339 PyErr_Display(exception, v, tb);
1340 Py_XDECREF(exception);
1341 Py_XDECREF(v);
1342 Py_XDECREF(tb);
1343
1344 /* sys.stderr may be buffered: call sys.stderr.flush() */
1345 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1346 if (res == NULL)
1347 PyErr_Clear();
1348 else
1349 Py_DECREF(res);
1350
1351 return has_tb;
1352}
1353
Nick Coghland6009512014-11-20 21:39:37 +10001354/* Print fatal error message and abort */
1355
1356void
1357Py_FatalError(const char *msg)
1358{
1359 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001360 static int reentrant = 0;
1361#ifdef MS_WINDOWS
1362 size_t len;
1363 WCHAR* buffer;
1364 size_t i;
1365#endif
1366
1367 if (reentrant) {
1368 /* Py_FatalError() caused a second fatal error.
1369 Example: flush_std_files() raises a recursion error. */
1370 goto exit;
1371 }
1372 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001373
1374 fprintf(stderr, "Fatal Python error: %s\n", msg);
1375 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001376
Victor Stinnere0deff32015-03-24 13:46:18 +01001377 /* Print the exception (if an exception is set) with its traceback,
1378 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001379 if (!_Py_FatalError_PrintExc(fd))
1380 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001381
Victor Stinner2025d782016-03-16 23:19:15 +01001382 /* The main purpose of faulthandler is to display the traceback. We already
1383 * did our best to display it. So faulthandler can now be disabled.
1384 * (Don't trigger it on abort().) */
1385 _PyFaulthandler_Fini();
1386
Victor Stinner791da1c2016-03-14 16:53:12 +01001387 /* Check if the current Python thread hold the GIL */
1388 if (PyThreadState_GET() != NULL) {
1389 /* Flush sys.stdout and sys.stderr */
1390 flush_std_files();
1391 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001392
Nick Coghland6009512014-11-20 21:39:37 +10001393#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001394 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001395
Victor Stinner53345a42015-03-25 01:55:14 +01001396 /* Convert the message to wchar_t. This uses a simple one-to-one
1397 conversion, assuming that the this error message actually uses ASCII
1398 only. If this ceases to be true, we will have to convert. */
1399 buffer = alloca( (len+1) * (sizeof *buffer));
1400 for( i=0; i<=len; ++i)
1401 buffer[i] = msg[i];
1402 OutputDebugStringW(L"Fatal Python error: ");
1403 OutputDebugStringW(buffer);
1404 OutputDebugStringW(L"\n");
1405#endif /* MS_WINDOWS */
1406
1407exit:
1408#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001409 DebugBreak();
1410#endif
Nick Coghland6009512014-11-20 21:39:37 +10001411 abort();
1412}
1413
1414/* Clean up and exit */
1415
1416#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001417# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001418#endif
1419
1420static void (*pyexitfunc)(void) = NULL;
1421/* For the atexit module. */
1422void _Py_PyAtExit(void (*func)(void))
1423{
1424 pyexitfunc = func;
1425}
1426
1427static void
1428call_py_exitfuncs(void)
1429{
1430 if (pyexitfunc == NULL)
1431 return;
1432
1433 (*pyexitfunc)();
1434 PyErr_Clear();
1435}
1436
1437/* Wait until threading._shutdown completes, provided
1438 the threading module was imported in the first place.
1439 The shutdown routine will wait until all non-daemon
1440 "threading" threads have completed. */
1441static void
1442wait_for_thread_shutdown(void)
1443{
1444#ifdef WITH_THREAD
1445 _Py_IDENTIFIER(_shutdown);
1446 PyObject *result;
1447 PyThreadState *tstate = PyThreadState_GET();
1448 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1449 "threading");
1450 if (threading == NULL) {
1451 /* threading not imported */
1452 PyErr_Clear();
1453 return;
1454 }
1455 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1456 if (result == NULL) {
1457 PyErr_WriteUnraisable(threading);
1458 }
1459 else {
1460 Py_DECREF(result);
1461 }
1462 Py_DECREF(threading);
1463#endif
1464}
1465
1466#define NEXITFUNCS 32
1467static void (*exitfuncs[NEXITFUNCS])(void);
1468static int nexitfuncs = 0;
1469
1470int Py_AtExit(void (*func)(void))
1471{
1472 if (nexitfuncs >= NEXITFUNCS)
1473 return -1;
1474 exitfuncs[nexitfuncs++] = func;
1475 return 0;
1476}
1477
1478static void
1479call_ll_exitfuncs(void)
1480{
1481 while (nexitfuncs > 0)
1482 (*exitfuncs[--nexitfuncs])();
1483
1484 fflush(stdout);
1485 fflush(stderr);
1486}
1487
1488void
1489Py_Exit(int sts)
1490{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001491 if (Py_FinalizeEx() < 0) {
1492 sts = 120;
1493 }
Nick Coghland6009512014-11-20 21:39:37 +10001494
1495 exit(sts);
1496}
1497
1498static void
1499initsigs(void)
1500{
1501#ifdef SIGPIPE
1502 PyOS_setsig(SIGPIPE, SIG_IGN);
1503#endif
1504#ifdef SIGXFZ
1505 PyOS_setsig(SIGXFZ, SIG_IGN);
1506#endif
1507#ifdef SIGXFSZ
1508 PyOS_setsig(SIGXFSZ, SIG_IGN);
1509#endif
1510 PyOS_InitInterrupts(); /* May imply initsignal() */
1511 if (PyErr_Occurred()) {
1512 Py_FatalError("Py_Initialize: can't import signal");
1513 }
1514}
1515
1516
1517/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1518 *
1519 * All of the code in this function must only use async-signal-safe functions,
1520 * listed at `man 7 signal` or
1521 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1522 */
1523void
1524_Py_RestoreSignals(void)
1525{
1526#ifdef SIGPIPE
1527 PyOS_setsig(SIGPIPE, SIG_DFL);
1528#endif
1529#ifdef SIGXFZ
1530 PyOS_setsig(SIGXFZ, SIG_DFL);
1531#endif
1532#ifdef SIGXFSZ
1533 PyOS_setsig(SIGXFSZ, SIG_DFL);
1534#endif
1535}
1536
1537
1538/*
1539 * The file descriptor fd is considered ``interactive'' if either
1540 * a) isatty(fd) is TRUE, or
1541 * b) the -i flag was given, and the filename associated with
1542 * the descriptor is NULL or "<stdin>" or "???".
1543 */
1544int
1545Py_FdIsInteractive(FILE *fp, const char *filename)
1546{
1547 if (isatty((int)fileno(fp)))
1548 return 1;
1549 if (!Py_InteractiveFlag)
1550 return 0;
1551 return (filename == NULL) ||
1552 (strcmp(filename, "<stdin>") == 0) ||
1553 (strcmp(filename, "???") == 0);
1554}
1555
1556
Nick Coghland6009512014-11-20 21:39:37 +10001557/* Wrappers around sigaction() or signal(). */
1558
1559PyOS_sighandler_t
1560PyOS_getsig(int sig)
1561{
1562#ifdef HAVE_SIGACTION
1563 struct sigaction context;
1564 if (sigaction(sig, NULL, &context) == -1)
1565 return SIG_ERR;
1566 return context.sa_handler;
1567#else
1568 PyOS_sighandler_t handler;
1569/* Special signal handling for the secure CRT in Visual Studio 2005 */
1570#if defined(_MSC_VER) && _MSC_VER >= 1400
1571 switch (sig) {
1572 /* Only these signals are valid */
1573 case SIGINT:
1574 case SIGILL:
1575 case SIGFPE:
1576 case SIGSEGV:
1577 case SIGTERM:
1578 case SIGBREAK:
1579 case SIGABRT:
1580 break;
1581 /* Don't call signal() with other values or it will assert */
1582 default:
1583 return SIG_ERR;
1584 }
1585#endif /* _MSC_VER && _MSC_VER >= 1400 */
1586 handler = signal(sig, SIG_IGN);
1587 if (handler != SIG_ERR)
1588 signal(sig, handler);
1589 return handler;
1590#endif
1591}
1592
1593/*
1594 * All of the code in this function must only use async-signal-safe functions,
1595 * listed at `man 7 signal` or
1596 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1597 */
1598PyOS_sighandler_t
1599PyOS_setsig(int sig, PyOS_sighandler_t handler)
1600{
1601#ifdef HAVE_SIGACTION
1602 /* Some code in Modules/signalmodule.c depends on sigaction() being
1603 * used here if HAVE_SIGACTION is defined. Fix that if this code
1604 * changes to invalidate that assumption.
1605 */
1606 struct sigaction context, ocontext;
1607 context.sa_handler = handler;
1608 sigemptyset(&context.sa_mask);
1609 context.sa_flags = 0;
1610 if (sigaction(sig, &context, &ocontext) == -1)
1611 return SIG_ERR;
1612 return ocontext.sa_handler;
1613#else
1614 PyOS_sighandler_t oldhandler;
1615 oldhandler = signal(sig, handler);
1616#ifdef HAVE_SIGINTERRUPT
1617 siginterrupt(sig, 1);
1618#endif
1619 return oldhandler;
1620#endif
1621}
1622
1623#ifdef __cplusplus
1624}
1625#endif