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