blob: 72a00e671f1799620d598d15da0c423f853d2b87 [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 Stinnerd7292b52016-06-17 12:29:00 +0200749#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +0100750 /* Issue #10915, #15751: The GIL API doesn't work with multiple
751 interpreters: disable PyGILState_Check(). */
752 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +0300753#endif
Victor Stinner8a1be612016-03-14 22:07:55 +0100754
Nick Coghland6009512014-11-20 21:39:37 +1000755 interp = PyInterpreterState_New();
756 if (interp == NULL)
757 return NULL;
758
759 tstate = PyThreadState_New(interp);
760 if (tstate == NULL) {
761 PyInterpreterState_Delete(interp);
762 return NULL;
763 }
764
765 save_tstate = PyThreadState_Swap(tstate);
766
767 /* XXX The following is lax in error checking */
768
769 interp->modules = PyDict_New();
770
771 bimod = _PyImport_FindBuiltin("builtins");
772 if (bimod != NULL) {
773 interp->builtins = PyModule_GetDict(bimod);
774 if (interp->builtins == NULL)
775 goto handle_error;
776 Py_INCREF(interp->builtins);
777 }
778
779 /* initialize builtin exceptions */
780 _PyExc_Init(bimod);
781
782 sysmod = _PyImport_FindBuiltin("sys");
783 if (bimod != NULL && sysmod != NULL) {
784 PyObject *pstderr;
785
786 interp->sysdict = PyModule_GetDict(sysmod);
787 if (interp->sysdict == NULL)
788 goto handle_error;
789 Py_INCREF(interp->sysdict);
790 PySys_SetPath(Py_GetPath());
791 PyDict_SetItemString(interp->sysdict, "modules",
792 interp->modules);
793 /* Set up a preliminary stderr printer until we have enough
794 infrastructure for the io module in place. */
795 pstderr = PyFile_NewStdPrinter(fileno(stderr));
796 if (pstderr == NULL)
797 Py_FatalError("Py_Initialize: can't set preliminary stderr");
798 _PySys_SetObjectId(&PyId_stderr, pstderr);
799 PySys_SetObject("__stderr__", pstderr);
800 Py_DECREF(pstderr);
801
802 _PyImportHooks_Init();
803
804 import_init(interp, sysmod);
805
806 if (initfsencoding(interp) < 0)
807 goto handle_error;
808
809 if (initstdio() < 0)
810 Py_FatalError(
Georg Brandl4b5b0622016-01-18 08:00:15 +0100811 "Py_Initialize: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000812 initmain(interp);
813 if (!Py_NoSiteFlag)
814 initsite();
815 }
816
817 if (!PyErr_Occurred())
818 return tstate;
819
820handle_error:
821 /* Oops, it didn't work. Undo it all. */
822
823 PyErr_PrintEx(0);
824 PyThreadState_Clear(tstate);
825 PyThreadState_Swap(save_tstate);
826 PyThreadState_Delete(tstate);
827 PyInterpreterState_Delete(interp);
828
829 return NULL;
830}
831
832/* Delete an interpreter and its last thread. This requires that the
833 given thread state is current, that the thread has no remaining
834 frames, and that it is its interpreter's only remaining thread.
835 It is a fatal error to violate these constraints.
836
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000837 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +1000838 everything, regardless.)
839
840 Locking: as above.
841
842*/
843
844void
845Py_EndInterpreter(PyThreadState *tstate)
846{
847 PyInterpreterState *interp = tstate->interp;
848
849 if (tstate != PyThreadState_GET())
850 Py_FatalError("Py_EndInterpreter: thread is not current");
851 if (tstate->frame != NULL)
852 Py_FatalError("Py_EndInterpreter: thread still has a frame");
853
854 wait_for_thread_shutdown();
855
856 if (tstate != interp->tstate_head || tstate->next != NULL)
857 Py_FatalError("Py_EndInterpreter: not the last thread");
858
859 PyImport_Cleanup();
860 PyInterpreterState_Clear(interp);
861 PyThreadState_Swap(NULL);
862 PyInterpreterState_Delete(interp);
863}
864
865#ifdef MS_WINDOWS
866static wchar_t *progname = L"python";
867#else
868static wchar_t *progname = L"python3";
869#endif
870
871void
872Py_SetProgramName(wchar_t *pn)
873{
874 if (pn && *pn)
875 progname = pn;
876}
877
878wchar_t *
879Py_GetProgramName(void)
880{
881 return progname;
882}
883
884static wchar_t *default_home = NULL;
885static wchar_t env_home[MAXPATHLEN+1];
886
887void
888Py_SetPythonHome(wchar_t *home)
889{
890 default_home = home;
891}
892
893wchar_t *
894Py_GetPythonHome(void)
895{
896 wchar_t *home = default_home;
897 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
898 char* chome = Py_GETENV("PYTHONHOME");
899 if (chome) {
900 size_t size = Py_ARRAY_LENGTH(env_home);
901 size_t r = mbstowcs(env_home, chome, size);
902 if (r != (size_t)-1 && r < size)
903 home = env_home;
904 }
905
906 }
907 return home;
908}
909
910/* Create __main__ module */
911
912static void
913initmain(PyInterpreterState *interp)
914{
915 PyObject *m, *d, *loader;
916 m = PyImport_AddModule("__main__");
917 if (m == NULL)
918 Py_FatalError("can't create __main__ module");
919 d = PyModule_GetDict(m);
920 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
921 PyObject *bimod = PyImport_ImportModule("builtins");
922 if (bimod == NULL) {
923 Py_FatalError("Failed to retrieve builtins module");
924 }
925 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
926 Py_FatalError("Failed to initialize __main__.__builtins__");
927 }
928 Py_DECREF(bimod);
929 }
930 /* Main is a little special - imp.is_builtin("__main__") will return
931 * False, but BuiltinImporter is still the most appropriate initial
932 * setting for its __loader__ attribute. A more suitable value will
933 * be set if __main__ gets further initialized later in the startup
934 * process.
935 */
936 loader = PyDict_GetItemString(d, "__loader__");
937 if (loader == NULL || loader == Py_None) {
938 PyObject *loader = PyObject_GetAttrString(interp->importlib,
939 "BuiltinImporter");
940 if (loader == NULL) {
941 Py_FatalError("Failed to retrieve BuiltinImporter");
942 }
943 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
944 Py_FatalError("Failed to initialize __main__.__loader__");
945 }
946 Py_DECREF(loader);
947 }
948}
949
950static int
951initfsencoding(PyInterpreterState *interp)
952{
953 PyObject *codec;
954
955 if (Py_FileSystemDefaultEncoding == NULL)
956 {
957 Py_FileSystemDefaultEncoding = get_locale_encoding();
958 if (Py_FileSystemDefaultEncoding == NULL)
959 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
960
961 Py_HasFileSystemDefaultEncoding = 0;
962 interp->fscodec_initialized = 1;
963 return 0;
964 }
965
966 /* the encoding is mbcs, utf-8 or ascii */
967 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
968 if (!codec) {
969 /* Such error can only occurs in critical situations: no more
970 * memory, import a module of the standard library failed,
971 * etc. */
972 return -1;
973 }
974 Py_DECREF(codec);
975 interp->fscodec_initialized = 1;
976 return 0;
977}
978
979/* Import the site module (not into __main__ though) */
980
981static void
982initsite(void)
983{
984 PyObject *m;
985 m = PyImport_ImportModule("site");
986 if (m == NULL) {
987 fprintf(stderr, "Failed to import the site module\n");
988 PyErr_Print();
989 Py_Finalize();
990 exit(1);
991 }
992 else {
993 Py_DECREF(m);
994 }
995}
996
Victor Stinner874dbe82015-09-04 17:29:57 +0200997/* Check if a file descriptor is valid or not.
998 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
999static int
1000is_valid_fd(int fd)
1001{
1002 int fd2;
1003 if (fd < 0 || !_PyVerify_fd(fd))
1004 return 0;
1005 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001006 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1007 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1008 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001009 fd2 = dup(fd);
1010 if (fd2 >= 0)
1011 close(fd2);
1012 _Py_END_SUPPRESS_IPH
1013 return fd2 >= 0;
1014}
1015
1016/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001017static PyObject*
1018create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001019 int fd, int write_mode, const char* name,
1020 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001021{
1022 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1023 const char* mode;
1024 const char* newline;
1025 PyObject *line_buffering;
1026 int buffering, isatty;
1027 _Py_IDENTIFIER(open);
1028 _Py_IDENTIFIER(isatty);
1029 _Py_IDENTIFIER(TextIOWrapper);
1030 _Py_IDENTIFIER(mode);
1031
Victor Stinner874dbe82015-09-04 17:29:57 +02001032 if (!is_valid_fd(fd))
1033 Py_RETURN_NONE;
1034
Nick Coghland6009512014-11-20 21:39:37 +10001035 /* stdin is always opened in buffered mode, first because it shouldn't
1036 make a difference in common use cases, second because TextIOWrapper
1037 depends on the presence of a read1() method which only exists on
1038 buffered streams.
1039 */
1040 if (Py_UnbufferedStdioFlag && write_mode)
1041 buffering = 0;
1042 else
1043 buffering = -1;
1044 if (write_mode)
1045 mode = "wb";
1046 else
1047 mode = "rb";
1048 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1049 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001050 Py_None, Py_None, /* encoding, errors */
1051 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001052 if (buf == NULL)
1053 goto error;
1054
1055 if (buffering) {
1056 _Py_IDENTIFIER(raw);
1057 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1058 if (raw == NULL)
1059 goto error;
1060 }
1061 else {
1062 raw = buf;
1063 Py_INCREF(raw);
1064 }
1065
1066 text = PyUnicode_FromString(name);
1067 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1068 goto error;
1069 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1070 if (res == NULL)
1071 goto error;
1072 isatty = PyObject_IsTrue(res);
1073 Py_DECREF(res);
1074 if (isatty == -1)
1075 goto error;
1076 if (isatty || Py_UnbufferedStdioFlag)
1077 line_buffering = Py_True;
1078 else
1079 line_buffering = Py_False;
1080
1081 Py_CLEAR(raw);
1082 Py_CLEAR(text);
1083
1084#ifdef MS_WINDOWS
1085 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1086 newlines to "\n".
1087 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1088 newline = NULL;
1089#else
1090 /* sys.stdin: split lines at "\n".
1091 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1092 newline = "\n";
1093#endif
1094
1095 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1096 buf, encoding, errors,
1097 newline, line_buffering);
1098 Py_CLEAR(buf);
1099 if (stream == NULL)
1100 goto error;
1101
1102 if (write_mode)
1103 mode = "w";
1104 else
1105 mode = "r";
1106 text = PyUnicode_FromString(mode);
1107 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1108 goto error;
1109 Py_CLEAR(text);
1110 return stream;
1111
1112error:
1113 Py_XDECREF(buf);
1114 Py_XDECREF(stream);
1115 Py_XDECREF(text);
1116 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001117
Victor Stinner874dbe82015-09-04 17:29:57 +02001118 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1119 /* Issue #24891: the file descriptor was closed after the first
1120 is_valid_fd() check was called. Ignore the OSError and set the
1121 stream to None. */
1122 PyErr_Clear();
1123 Py_RETURN_NONE;
1124 }
1125 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001126}
1127
1128/* Initialize sys.stdin, stdout, stderr and builtins.open */
1129static int
1130initstdio(void)
1131{
1132 PyObject *iomod = NULL, *wrapper;
1133 PyObject *bimod = NULL;
1134 PyObject *m;
1135 PyObject *std = NULL;
1136 int status = 0, fd;
1137 PyObject * encoding_attr;
1138 char *pythonioencoding = NULL, *encoding, *errors;
1139
1140 /* Hack to avoid a nasty recursion issue when Python is invoked
1141 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1142 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1143 goto error;
1144 }
1145 Py_DECREF(m);
1146
1147 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1148 goto error;
1149 }
1150 Py_DECREF(m);
1151
1152 if (!(bimod = PyImport_ImportModule("builtins"))) {
1153 goto error;
1154 }
1155
1156 if (!(iomod = PyImport_ImportModule("io"))) {
1157 goto error;
1158 }
1159 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1160 goto error;
1161 }
1162
1163 /* Set builtins.open */
1164 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1165 Py_DECREF(wrapper);
1166 goto error;
1167 }
1168 Py_DECREF(wrapper);
1169
1170 encoding = _Py_StandardStreamEncoding;
1171 errors = _Py_StandardStreamErrors;
1172 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001173 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1174 if (pythonioencoding) {
1175 char *err;
1176 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1177 if (pythonioencoding == NULL) {
1178 PyErr_NoMemory();
1179 goto error;
1180 }
1181 err = strchr(pythonioencoding, ':');
1182 if (err) {
1183 *err = '\0';
1184 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001185 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001186 errors = err;
1187 }
1188 }
1189 if (*pythonioencoding && !encoding) {
1190 encoding = pythonioencoding;
1191 }
1192 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001193 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1194 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1195 stdin and stdout use the surrogateescape error handler by
1196 default, instead of the strict error handler. */
1197 char *loc = setlocale(LC_CTYPE, NULL);
1198 if (loc != NULL && strcmp(loc, "C") == 0)
1199 errors = "surrogateescape";
1200 }
Nick Coghland6009512014-11-20 21:39:37 +10001201 }
1202
1203 /* Set sys.stdin */
1204 fd = fileno(stdin);
1205 /* Under some conditions stdin, stdout and stderr may not be connected
1206 * and fileno() may point to an invalid file descriptor. For example
1207 * GUI apps don't have valid standard streams by default.
1208 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001209 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1210 if (std == NULL)
1211 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001212 PySys_SetObject("__stdin__", std);
1213 _PySys_SetObjectId(&PyId_stdin, std);
1214 Py_DECREF(std);
1215
1216 /* Set sys.stdout */
1217 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001218 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1219 if (std == NULL)
1220 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001221 PySys_SetObject("__stdout__", std);
1222 _PySys_SetObjectId(&PyId_stdout, std);
1223 Py_DECREF(std);
1224
1225#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1226 /* Set sys.stderr, replaces the preliminary stderr */
1227 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001228 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1229 if (std == NULL)
1230 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001231
1232 /* Same as hack above, pre-import stderr's codec to avoid recursion
1233 when import.c tries to write to stderr in verbose mode. */
1234 encoding_attr = PyObject_GetAttrString(std, "encoding");
1235 if (encoding_attr != NULL) {
1236 const char * std_encoding;
1237 std_encoding = _PyUnicode_AsString(encoding_attr);
1238 if (std_encoding != NULL) {
1239 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1240 Py_XDECREF(codec_info);
1241 }
1242 Py_DECREF(encoding_attr);
1243 }
1244 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1245
1246 if (PySys_SetObject("__stderr__", std) < 0) {
1247 Py_DECREF(std);
1248 goto error;
1249 }
1250 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1251 Py_DECREF(std);
1252 goto error;
1253 }
1254 Py_DECREF(std);
1255#endif
1256
1257 if (0) {
1258 error:
1259 status = -1;
1260 }
1261
1262 /* We won't need them anymore. */
1263 if (_Py_StandardStreamEncoding) {
1264 PyMem_RawFree(_Py_StandardStreamEncoding);
1265 _Py_StandardStreamEncoding = NULL;
1266 }
1267 if (_Py_StandardStreamErrors) {
1268 PyMem_RawFree(_Py_StandardStreamErrors);
1269 _Py_StandardStreamErrors = NULL;
1270 }
1271 PyMem_Free(pythonioencoding);
1272 Py_XDECREF(bimod);
1273 Py_XDECREF(iomod);
1274 return status;
1275}
1276
1277
Victor Stinner10dc4842015-03-24 12:01:30 +01001278static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001279_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001280{
Victor Stinner10dc4842015-03-24 12:01:30 +01001281 fputc('\n', stderr);
1282 fflush(stderr);
1283
1284 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001285 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001286}
Victor Stinner791da1c2016-03-14 16:53:12 +01001287
1288/* Print the current exception (if an exception is set) with its traceback,
1289 or display the current Python stack.
1290
1291 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1292 called on catastrophic cases.
1293
1294 Return 1 if the traceback was displayed, 0 otherwise. */
1295
1296static int
1297_Py_FatalError_PrintExc(int fd)
1298{
1299 PyObject *ferr, *res;
1300 PyObject *exception, *v, *tb;
1301 int has_tb;
1302
1303 if (PyThreadState_GET() == NULL) {
1304 /* The GIL is released: trying to acquire it is likely to deadlock,
1305 just give up. */
1306 return 0;
1307 }
1308
1309 PyErr_Fetch(&exception, &v, &tb);
1310 if (exception == NULL) {
1311 /* No current exception */
1312 return 0;
1313 }
1314
1315 ferr = _PySys_GetObjectId(&PyId_stderr);
1316 if (ferr == NULL || ferr == Py_None) {
1317 /* sys.stderr is not set yet or set to None,
1318 no need to try to display the exception */
1319 return 0;
1320 }
1321
1322 PyErr_NormalizeException(&exception, &v, &tb);
1323 if (tb == NULL) {
1324 tb = Py_None;
1325 Py_INCREF(tb);
1326 }
1327 PyException_SetTraceback(v, tb);
1328 if (exception == NULL) {
1329 /* PyErr_NormalizeException() failed */
1330 return 0;
1331 }
1332
1333 has_tb = (tb != Py_None);
1334 PyErr_Display(exception, v, tb);
1335 Py_XDECREF(exception);
1336 Py_XDECREF(v);
1337 Py_XDECREF(tb);
1338
1339 /* sys.stderr may be buffered: call sys.stderr.flush() */
1340 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1341 if (res == NULL)
1342 PyErr_Clear();
1343 else
1344 Py_DECREF(res);
1345
1346 return has_tb;
1347}
1348
Nick Coghland6009512014-11-20 21:39:37 +10001349/* Print fatal error message and abort */
1350
1351void
1352Py_FatalError(const char *msg)
1353{
1354 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001355 static int reentrant = 0;
1356#ifdef MS_WINDOWS
1357 size_t len;
1358 WCHAR* buffer;
1359 size_t i;
1360#endif
1361
1362 if (reentrant) {
1363 /* Py_FatalError() caused a second fatal error.
1364 Example: flush_std_files() raises a recursion error. */
1365 goto exit;
1366 }
1367 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001368
1369 fprintf(stderr, "Fatal Python error: %s\n", msg);
1370 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001371
Victor Stinnere0deff32015-03-24 13:46:18 +01001372 /* Print the exception (if an exception is set) with its traceback,
1373 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001374 if (!_Py_FatalError_PrintExc(fd))
1375 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001376
Victor Stinner2025d782016-03-16 23:19:15 +01001377 /* The main purpose of faulthandler is to display the traceback. We already
1378 * did our best to display it. So faulthandler can now be disabled.
1379 * (Don't trigger it on abort().) */
1380 _PyFaulthandler_Fini();
1381
Victor Stinner791da1c2016-03-14 16:53:12 +01001382 /* Check if the current Python thread hold the GIL */
1383 if (PyThreadState_GET() != NULL) {
1384 /* Flush sys.stdout and sys.stderr */
1385 flush_std_files();
1386 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001387
Nick Coghland6009512014-11-20 21:39:37 +10001388#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001389 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001390
Victor Stinner53345a42015-03-25 01:55:14 +01001391 /* Convert the message to wchar_t. This uses a simple one-to-one
1392 conversion, assuming that the this error message actually uses ASCII
1393 only. If this ceases to be true, we will have to convert. */
1394 buffer = alloca( (len+1) * (sizeof *buffer));
1395 for( i=0; i<=len; ++i)
1396 buffer[i] = msg[i];
1397 OutputDebugStringW(L"Fatal Python error: ");
1398 OutputDebugStringW(buffer);
1399 OutputDebugStringW(L"\n");
1400#endif /* MS_WINDOWS */
1401
1402exit:
1403#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001404 DebugBreak();
1405#endif
Nick Coghland6009512014-11-20 21:39:37 +10001406 abort();
1407}
1408
1409/* Clean up and exit */
1410
1411#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001412# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001413#endif
1414
1415static void (*pyexitfunc)(void) = NULL;
1416/* For the atexit module. */
1417void _Py_PyAtExit(void (*func)(void))
1418{
1419 pyexitfunc = func;
1420}
1421
1422static void
1423call_py_exitfuncs(void)
1424{
1425 if (pyexitfunc == NULL)
1426 return;
1427
1428 (*pyexitfunc)();
1429 PyErr_Clear();
1430}
1431
1432/* Wait until threading._shutdown completes, provided
1433 the threading module was imported in the first place.
1434 The shutdown routine will wait until all non-daemon
1435 "threading" threads have completed. */
1436static void
1437wait_for_thread_shutdown(void)
1438{
1439#ifdef WITH_THREAD
1440 _Py_IDENTIFIER(_shutdown);
1441 PyObject *result;
1442 PyThreadState *tstate = PyThreadState_GET();
1443 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1444 "threading");
1445 if (threading == NULL) {
1446 /* threading not imported */
1447 PyErr_Clear();
1448 return;
1449 }
1450 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1451 if (result == NULL) {
1452 PyErr_WriteUnraisable(threading);
1453 }
1454 else {
1455 Py_DECREF(result);
1456 }
1457 Py_DECREF(threading);
1458#endif
1459}
1460
1461#define NEXITFUNCS 32
1462static void (*exitfuncs[NEXITFUNCS])(void);
1463static int nexitfuncs = 0;
1464
1465int Py_AtExit(void (*func)(void))
1466{
1467 if (nexitfuncs >= NEXITFUNCS)
1468 return -1;
1469 exitfuncs[nexitfuncs++] = func;
1470 return 0;
1471}
1472
1473static void
1474call_ll_exitfuncs(void)
1475{
1476 while (nexitfuncs > 0)
1477 (*exitfuncs[--nexitfuncs])();
1478
1479 fflush(stdout);
1480 fflush(stderr);
1481}
1482
1483void
1484Py_Exit(int sts)
1485{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001486 if (Py_FinalizeEx() < 0) {
1487 sts = 120;
1488 }
Nick Coghland6009512014-11-20 21:39:37 +10001489
1490 exit(sts);
1491}
1492
1493static void
1494initsigs(void)
1495{
1496#ifdef SIGPIPE
1497 PyOS_setsig(SIGPIPE, SIG_IGN);
1498#endif
1499#ifdef SIGXFZ
1500 PyOS_setsig(SIGXFZ, SIG_IGN);
1501#endif
1502#ifdef SIGXFSZ
1503 PyOS_setsig(SIGXFSZ, SIG_IGN);
1504#endif
1505 PyOS_InitInterrupts(); /* May imply initsignal() */
1506 if (PyErr_Occurred()) {
1507 Py_FatalError("Py_Initialize: can't import signal");
1508 }
1509}
1510
1511
1512/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1513 *
1514 * All of the code in this function must only use async-signal-safe functions,
1515 * listed at `man 7 signal` or
1516 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1517 */
1518void
1519_Py_RestoreSignals(void)
1520{
1521#ifdef SIGPIPE
1522 PyOS_setsig(SIGPIPE, SIG_DFL);
1523#endif
1524#ifdef SIGXFZ
1525 PyOS_setsig(SIGXFZ, SIG_DFL);
1526#endif
1527#ifdef SIGXFSZ
1528 PyOS_setsig(SIGXFSZ, SIG_DFL);
1529#endif
1530}
1531
1532
1533/*
1534 * The file descriptor fd is considered ``interactive'' if either
1535 * a) isatty(fd) is TRUE, or
1536 * b) the -i flag was given, and the filename associated with
1537 * the descriptor is NULL or "<stdin>" or "???".
1538 */
1539int
1540Py_FdIsInteractive(FILE *fp, const char *filename)
1541{
1542 if (isatty((int)fileno(fp)))
1543 return 1;
1544 if (!Py_InteractiveFlag)
1545 return 0;
1546 return (filename == NULL) ||
1547 (strcmp(filename, "<stdin>") == 0) ||
1548 (strcmp(filename, "???") == 0);
1549}
1550
1551
Nick Coghland6009512014-11-20 21:39:37 +10001552/* Wrappers around sigaction() or signal(). */
1553
1554PyOS_sighandler_t
1555PyOS_getsig(int sig)
1556{
1557#ifdef HAVE_SIGACTION
1558 struct sigaction context;
1559 if (sigaction(sig, NULL, &context) == -1)
1560 return SIG_ERR;
1561 return context.sa_handler;
1562#else
1563 PyOS_sighandler_t handler;
1564/* Special signal handling for the secure CRT in Visual Studio 2005 */
1565#if defined(_MSC_VER) && _MSC_VER >= 1400
1566 switch (sig) {
1567 /* Only these signals are valid */
1568 case SIGINT:
1569 case SIGILL:
1570 case SIGFPE:
1571 case SIGSEGV:
1572 case SIGTERM:
1573 case SIGBREAK:
1574 case SIGABRT:
1575 break;
1576 /* Don't call signal() with other values or it will assert */
1577 default:
1578 return SIG_ERR;
1579 }
1580#endif /* _MSC_VER && _MSC_VER >= 1400 */
1581 handler = signal(sig, SIG_IGN);
1582 if (handler != SIG_ERR)
1583 signal(sig, handler);
1584 return handler;
1585#endif
1586}
1587
1588/*
1589 * All of the code in this function must only use async-signal-safe functions,
1590 * listed at `man 7 signal` or
1591 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1592 */
1593PyOS_sighandler_t
1594PyOS_setsig(int sig, PyOS_sighandler_t handler)
1595{
1596#ifdef HAVE_SIGACTION
1597 /* Some code in Modules/signalmodule.c depends on sigaction() being
1598 * used here if HAVE_SIGACTION is defined. Fix that if this code
1599 * changes to invalidate that assumption.
1600 */
1601 struct sigaction context, ocontext;
1602 context.sa_handler = handler;
1603 sigemptyset(&context.sa_mask);
1604 context.sa_flags = 0;
1605 if (sigaction(sig, &context, &ocontext) == -1)
1606 return SIG_ERR;
1607 return ocontext.sa_handler;
1608#else
1609 PyOS_sighandler_t oldhandler;
1610 oldhandler = signal(sig, handler);
1611#ifdef HAVE_SIGINTERRUPT
1612 siginterrupt(sig, 1);
1613#endif
1614 return oldhandler;
1615#endif
1616}
1617
1618#ifdef __cplusplus
1619}
1620#endif