blob: 004feae7a07e4012863979f3b372b61e814f542c [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();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +0300677 _PyArg_Fini();
Nick Coghland6009512014-11-20 21:39:37 +1000678
679 /* Cleanup Unicode implementation */
680 _PyUnicode_Fini();
681
682 /* reset file system default encoding */
683 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
684 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
685 Py_FileSystemDefaultEncoding = NULL;
686 }
687
688 /* XXX Still allocated:
689 - various static ad-hoc pointers to interned strings
690 - int and float free list blocks
691 - whatever various modules and libraries allocate
692 */
693
694 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
695
696 /* Cleanup auto-thread-state */
697#ifdef WITH_THREAD
698 _PyGILState_Fini();
699#endif /* WITH_THREAD */
700
701 /* Delete current thread. After this, many C API calls become crashy. */
702 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +0100703
Nick Coghland6009512014-11-20 21:39:37 +1000704 PyInterpreterState_Delete(interp);
705
706#ifdef Py_TRACE_REFS
707 /* Display addresses (& refcnts) of all objects still alive.
708 * An address can be used to find the repr of the object, printed
709 * above by _Py_PrintReferences.
710 */
711 if (Py_GETENV("PYTHONDUMPREFS"))
712 _Py_PrintReferenceAddresses(stderr);
713#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +0100714#ifdef WITH_PYMALLOC
715 if (_PyMem_PymallocEnabled()) {
716 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
717 if (opt != NULL && *opt != '\0')
718 _PyObject_DebugMallocStats(stderr);
719 }
Nick Coghland6009512014-11-20 21:39:37 +1000720#endif
721
722 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000723 return status;
724}
725
726void
727Py_Finalize(void)
728{
729 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000730}
731
732/* Create and initialize a new interpreter and thread, and return the
733 new thread. This requires that Py_Initialize() has been called
734 first.
735
736 Unsuccessful initialization yields a NULL pointer. Note that *no*
737 exception information is available even in this case -- the
738 exception information is held in the thread, and there is no
739 thread.
740
741 Locking: as above.
742
743*/
744
745PyThreadState *
746Py_NewInterpreter(void)
747{
748 PyInterpreterState *interp;
749 PyThreadState *tstate, *save_tstate;
750 PyObject *bimod, *sysmod;
751
752 if (!initialized)
753 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
754
Victor Stinnerd7292b52016-06-17 12:29:00 +0200755#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +0100756 /* Issue #10915, #15751: The GIL API doesn't work with multiple
757 interpreters: disable PyGILState_Check(). */
758 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +0300759#endif
Victor Stinner8a1be612016-03-14 22:07:55 +0100760
Nick Coghland6009512014-11-20 21:39:37 +1000761 interp = PyInterpreterState_New();
762 if (interp == NULL)
763 return NULL;
764
765 tstate = PyThreadState_New(interp);
766 if (tstate == NULL) {
767 PyInterpreterState_Delete(interp);
768 return NULL;
769 }
770
771 save_tstate = PyThreadState_Swap(tstate);
772
773 /* XXX The following is lax in error checking */
774
775 interp->modules = PyDict_New();
776
777 bimod = _PyImport_FindBuiltin("builtins");
778 if (bimod != NULL) {
779 interp->builtins = PyModule_GetDict(bimod);
780 if (interp->builtins == NULL)
781 goto handle_error;
782 Py_INCREF(interp->builtins);
783 }
784
785 /* initialize builtin exceptions */
786 _PyExc_Init(bimod);
787
788 sysmod = _PyImport_FindBuiltin("sys");
789 if (bimod != NULL && sysmod != NULL) {
790 PyObject *pstderr;
791
792 interp->sysdict = PyModule_GetDict(sysmod);
793 if (interp->sysdict == NULL)
794 goto handle_error;
795 Py_INCREF(interp->sysdict);
796 PySys_SetPath(Py_GetPath());
797 PyDict_SetItemString(interp->sysdict, "modules",
798 interp->modules);
799 /* Set up a preliminary stderr printer until we have enough
800 infrastructure for the io module in place. */
801 pstderr = PyFile_NewStdPrinter(fileno(stderr));
802 if (pstderr == NULL)
803 Py_FatalError("Py_Initialize: can't set preliminary stderr");
804 _PySys_SetObjectId(&PyId_stderr, pstderr);
805 PySys_SetObject("__stderr__", pstderr);
806 Py_DECREF(pstderr);
807
808 _PyImportHooks_Init();
809
810 import_init(interp, sysmod);
811
812 if (initfsencoding(interp) < 0)
813 goto handle_error;
814
815 if (initstdio() < 0)
816 Py_FatalError(
Georg Brandl4b5b0622016-01-18 08:00:15 +0100817 "Py_Initialize: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000818 initmain(interp);
819 if (!Py_NoSiteFlag)
820 initsite();
821 }
822
823 if (!PyErr_Occurred())
824 return tstate;
825
826handle_error:
827 /* Oops, it didn't work. Undo it all. */
828
829 PyErr_PrintEx(0);
830 PyThreadState_Clear(tstate);
831 PyThreadState_Swap(save_tstate);
832 PyThreadState_Delete(tstate);
833 PyInterpreterState_Delete(interp);
834
835 return NULL;
836}
837
838/* Delete an interpreter and its last thread. This requires that the
839 given thread state is current, that the thread has no remaining
840 frames, and that it is its interpreter's only remaining thread.
841 It is a fatal error to violate these constraints.
842
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000843 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +1000844 everything, regardless.)
845
846 Locking: as above.
847
848*/
849
850void
851Py_EndInterpreter(PyThreadState *tstate)
852{
853 PyInterpreterState *interp = tstate->interp;
854
855 if (tstate != PyThreadState_GET())
856 Py_FatalError("Py_EndInterpreter: thread is not current");
857 if (tstate->frame != NULL)
858 Py_FatalError("Py_EndInterpreter: thread still has a frame");
859
860 wait_for_thread_shutdown();
861
862 if (tstate != interp->tstate_head || tstate->next != NULL)
863 Py_FatalError("Py_EndInterpreter: not the last thread");
864
865 PyImport_Cleanup();
866 PyInterpreterState_Clear(interp);
867 PyThreadState_Swap(NULL);
868 PyInterpreterState_Delete(interp);
869}
870
871#ifdef MS_WINDOWS
872static wchar_t *progname = L"python";
873#else
874static wchar_t *progname = L"python3";
875#endif
876
877void
878Py_SetProgramName(wchar_t *pn)
879{
880 if (pn && *pn)
881 progname = pn;
882}
883
884wchar_t *
885Py_GetProgramName(void)
886{
887 return progname;
888}
889
890static wchar_t *default_home = NULL;
891static wchar_t env_home[MAXPATHLEN+1];
892
893void
894Py_SetPythonHome(wchar_t *home)
895{
896 default_home = home;
897}
898
899wchar_t *
900Py_GetPythonHome(void)
901{
902 wchar_t *home = default_home;
903 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
904 char* chome = Py_GETENV("PYTHONHOME");
905 if (chome) {
906 size_t size = Py_ARRAY_LENGTH(env_home);
907 size_t r = mbstowcs(env_home, chome, size);
908 if (r != (size_t)-1 && r < size)
909 home = env_home;
910 }
911
912 }
913 return home;
914}
915
916/* Create __main__ module */
917
918static void
919initmain(PyInterpreterState *interp)
920{
921 PyObject *m, *d, *loader;
922 m = PyImport_AddModule("__main__");
923 if (m == NULL)
924 Py_FatalError("can't create __main__ module");
925 d = PyModule_GetDict(m);
926 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
927 PyObject *bimod = PyImport_ImportModule("builtins");
928 if (bimod == NULL) {
929 Py_FatalError("Failed to retrieve builtins module");
930 }
931 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
932 Py_FatalError("Failed to initialize __main__.__builtins__");
933 }
934 Py_DECREF(bimod);
935 }
936 /* Main is a little special - imp.is_builtin("__main__") will return
937 * False, but BuiltinImporter is still the most appropriate initial
938 * setting for its __loader__ attribute. A more suitable value will
939 * be set if __main__ gets further initialized later in the startup
940 * process.
941 */
942 loader = PyDict_GetItemString(d, "__loader__");
943 if (loader == NULL || loader == Py_None) {
944 PyObject *loader = PyObject_GetAttrString(interp->importlib,
945 "BuiltinImporter");
946 if (loader == NULL) {
947 Py_FatalError("Failed to retrieve BuiltinImporter");
948 }
949 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
950 Py_FatalError("Failed to initialize __main__.__loader__");
951 }
952 Py_DECREF(loader);
953 }
954}
955
956static int
957initfsencoding(PyInterpreterState *interp)
958{
959 PyObject *codec;
960
961 if (Py_FileSystemDefaultEncoding == NULL)
962 {
963 Py_FileSystemDefaultEncoding = get_locale_encoding();
964 if (Py_FileSystemDefaultEncoding == NULL)
965 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
966
967 Py_HasFileSystemDefaultEncoding = 0;
968 interp->fscodec_initialized = 1;
969 return 0;
970 }
971
972 /* the encoding is mbcs, utf-8 or ascii */
973 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
974 if (!codec) {
975 /* Such error can only occurs in critical situations: no more
976 * memory, import a module of the standard library failed,
977 * etc. */
978 return -1;
979 }
980 Py_DECREF(codec);
981 interp->fscodec_initialized = 1;
982 return 0;
983}
984
985/* Import the site module (not into __main__ though) */
986
987static void
988initsite(void)
989{
990 PyObject *m;
991 m = PyImport_ImportModule("site");
992 if (m == NULL) {
993 fprintf(stderr, "Failed to import the site module\n");
994 PyErr_Print();
995 Py_Finalize();
996 exit(1);
997 }
998 else {
999 Py_DECREF(m);
1000 }
1001}
1002
Victor Stinner874dbe82015-09-04 17:29:57 +02001003/* Check if a file descriptor is valid or not.
1004 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1005static int
1006is_valid_fd(int fd)
1007{
1008 int fd2;
1009 if (fd < 0 || !_PyVerify_fd(fd))
1010 return 0;
1011 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001012 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1013 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1014 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001015 fd2 = dup(fd);
1016 if (fd2 >= 0)
1017 close(fd2);
1018 _Py_END_SUPPRESS_IPH
1019 return fd2 >= 0;
1020}
1021
1022/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001023static PyObject*
1024create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001025 int fd, int write_mode, const char* name,
1026 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001027{
1028 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1029 const char* mode;
1030 const char* newline;
1031 PyObject *line_buffering;
1032 int buffering, isatty;
1033 _Py_IDENTIFIER(open);
1034 _Py_IDENTIFIER(isatty);
1035 _Py_IDENTIFIER(TextIOWrapper);
1036 _Py_IDENTIFIER(mode);
1037
Victor Stinner874dbe82015-09-04 17:29:57 +02001038 if (!is_valid_fd(fd))
1039 Py_RETURN_NONE;
1040
Nick Coghland6009512014-11-20 21:39:37 +10001041 /* stdin is always opened in buffered mode, first because it shouldn't
1042 make a difference in common use cases, second because TextIOWrapper
1043 depends on the presence of a read1() method which only exists on
1044 buffered streams.
1045 */
1046 if (Py_UnbufferedStdioFlag && write_mode)
1047 buffering = 0;
1048 else
1049 buffering = -1;
1050 if (write_mode)
1051 mode = "wb";
1052 else
1053 mode = "rb";
1054 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1055 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001056 Py_None, Py_None, /* encoding, errors */
1057 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001058 if (buf == NULL)
1059 goto error;
1060
1061 if (buffering) {
1062 _Py_IDENTIFIER(raw);
1063 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1064 if (raw == NULL)
1065 goto error;
1066 }
1067 else {
1068 raw = buf;
1069 Py_INCREF(raw);
1070 }
1071
1072 text = PyUnicode_FromString(name);
1073 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1074 goto error;
1075 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1076 if (res == NULL)
1077 goto error;
1078 isatty = PyObject_IsTrue(res);
1079 Py_DECREF(res);
1080 if (isatty == -1)
1081 goto error;
1082 if (isatty || Py_UnbufferedStdioFlag)
1083 line_buffering = Py_True;
1084 else
1085 line_buffering = Py_False;
1086
1087 Py_CLEAR(raw);
1088 Py_CLEAR(text);
1089
1090#ifdef MS_WINDOWS
1091 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1092 newlines to "\n".
1093 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1094 newline = NULL;
1095#else
1096 /* sys.stdin: split lines at "\n".
1097 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1098 newline = "\n";
1099#endif
1100
1101 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1102 buf, encoding, errors,
1103 newline, line_buffering);
1104 Py_CLEAR(buf);
1105 if (stream == NULL)
1106 goto error;
1107
1108 if (write_mode)
1109 mode = "w";
1110 else
1111 mode = "r";
1112 text = PyUnicode_FromString(mode);
1113 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1114 goto error;
1115 Py_CLEAR(text);
1116 return stream;
1117
1118error:
1119 Py_XDECREF(buf);
1120 Py_XDECREF(stream);
1121 Py_XDECREF(text);
1122 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001123
Victor Stinner874dbe82015-09-04 17:29:57 +02001124 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1125 /* Issue #24891: the file descriptor was closed after the first
1126 is_valid_fd() check was called. Ignore the OSError and set the
1127 stream to None. */
1128 PyErr_Clear();
1129 Py_RETURN_NONE;
1130 }
1131 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001132}
1133
1134/* Initialize sys.stdin, stdout, stderr and builtins.open */
1135static int
1136initstdio(void)
1137{
1138 PyObject *iomod = NULL, *wrapper;
1139 PyObject *bimod = NULL;
1140 PyObject *m;
1141 PyObject *std = NULL;
1142 int status = 0, fd;
1143 PyObject * encoding_attr;
1144 char *pythonioencoding = NULL, *encoding, *errors;
1145
1146 /* Hack to avoid a nasty recursion issue when Python is invoked
1147 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1148 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1149 goto error;
1150 }
1151 Py_DECREF(m);
1152
1153 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1154 goto error;
1155 }
1156 Py_DECREF(m);
1157
1158 if (!(bimod = PyImport_ImportModule("builtins"))) {
1159 goto error;
1160 }
1161
1162 if (!(iomod = PyImport_ImportModule("io"))) {
1163 goto error;
1164 }
1165 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1166 goto error;
1167 }
1168
1169 /* Set builtins.open */
1170 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1171 Py_DECREF(wrapper);
1172 goto error;
1173 }
1174 Py_DECREF(wrapper);
1175
1176 encoding = _Py_StandardStreamEncoding;
1177 errors = _Py_StandardStreamErrors;
1178 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001179 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1180 if (pythonioencoding) {
1181 char *err;
1182 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1183 if (pythonioencoding == NULL) {
1184 PyErr_NoMemory();
1185 goto error;
1186 }
1187 err = strchr(pythonioencoding, ':');
1188 if (err) {
1189 *err = '\0';
1190 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001191 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001192 errors = err;
1193 }
1194 }
1195 if (*pythonioencoding && !encoding) {
1196 encoding = pythonioencoding;
1197 }
1198 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001199 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1200 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1201 stdin and stdout use the surrogateescape error handler by
1202 default, instead of the strict error handler. */
1203 char *loc = setlocale(LC_CTYPE, NULL);
1204 if (loc != NULL && strcmp(loc, "C") == 0)
1205 errors = "surrogateescape";
1206 }
Nick Coghland6009512014-11-20 21:39:37 +10001207 }
1208
1209 /* Set sys.stdin */
1210 fd = fileno(stdin);
1211 /* Under some conditions stdin, stdout and stderr may not be connected
1212 * and fileno() may point to an invalid file descriptor. For example
1213 * GUI apps don't have valid standard streams by default.
1214 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001215 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1216 if (std == NULL)
1217 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001218 PySys_SetObject("__stdin__", std);
1219 _PySys_SetObjectId(&PyId_stdin, std);
1220 Py_DECREF(std);
1221
1222 /* Set sys.stdout */
1223 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001224 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1225 if (std == NULL)
1226 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001227 PySys_SetObject("__stdout__", std);
1228 _PySys_SetObjectId(&PyId_stdout, std);
1229 Py_DECREF(std);
1230
1231#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1232 /* Set sys.stderr, replaces the preliminary stderr */
1233 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001234 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1235 if (std == NULL)
1236 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001237
1238 /* Same as hack above, pre-import stderr's codec to avoid recursion
1239 when import.c tries to write to stderr in verbose mode. */
1240 encoding_attr = PyObject_GetAttrString(std, "encoding");
1241 if (encoding_attr != NULL) {
1242 const char * std_encoding;
1243 std_encoding = _PyUnicode_AsString(encoding_attr);
1244 if (std_encoding != NULL) {
1245 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1246 Py_XDECREF(codec_info);
1247 }
1248 Py_DECREF(encoding_attr);
1249 }
1250 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1251
1252 if (PySys_SetObject("__stderr__", std) < 0) {
1253 Py_DECREF(std);
1254 goto error;
1255 }
1256 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1257 Py_DECREF(std);
1258 goto error;
1259 }
1260 Py_DECREF(std);
1261#endif
1262
1263 if (0) {
1264 error:
1265 status = -1;
1266 }
1267
1268 /* We won't need them anymore. */
1269 if (_Py_StandardStreamEncoding) {
1270 PyMem_RawFree(_Py_StandardStreamEncoding);
1271 _Py_StandardStreamEncoding = NULL;
1272 }
1273 if (_Py_StandardStreamErrors) {
1274 PyMem_RawFree(_Py_StandardStreamErrors);
1275 _Py_StandardStreamErrors = NULL;
1276 }
1277 PyMem_Free(pythonioencoding);
1278 Py_XDECREF(bimod);
1279 Py_XDECREF(iomod);
1280 return status;
1281}
1282
1283
Victor Stinner10dc4842015-03-24 12:01:30 +01001284static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001285_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001286{
Victor Stinner10dc4842015-03-24 12:01:30 +01001287 fputc('\n', stderr);
1288 fflush(stderr);
1289
1290 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001291 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001292}
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 Stinner2025d782016-03-16 23:19:15 +01001383 /* The main purpose of faulthandler is to display the traceback. We already
1384 * did our best to display it. So faulthandler can now be disabled.
1385 * (Don't trigger it on abort().) */
1386 _PyFaulthandler_Fini();
1387
Victor Stinner791da1c2016-03-14 16:53:12 +01001388 /* Check if the current Python thread hold the GIL */
1389 if (PyThreadState_GET() != NULL) {
1390 /* Flush sys.stdout and sys.stderr */
1391 flush_std_files();
1392 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001393
Nick Coghland6009512014-11-20 21:39:37 +10001394#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
Victor Stinnerd7292b52016-06-17 12:29:00 +02001418# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001419#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