blob: e9db7f6351dee35d6f320cce1209a58a4686bfcb [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
7#include "grammar.h"
8#include "node.h"
9#include "token.h"
10#include "parsetok.h"
11#include "errcode.h"
12#include "code.h"
13#include "symtable.h"
14#include "ast.h"
15#include "marshal.h"
16#include "osdefs.h"
17#include <locale.h>
18
19#ifdef HAVE_SIGNAL_H
20#include <signal.h>
21#endif
22
23#ifdef MS_WINDOWS
24#include "malloc.h" /* for alloca */
25#endif
26
27#ifdef HAVE_LANGINFO_H
28#include <langinfo.h>
29#endif
30
31#ifdef MS_WINDOWS
32#undef BYTE
33#include "windows.h"
34#endif
35
36_Py_IDENTIFIER(flush);
37_Py_IDENTIFIER(name);
38_Py_IDENTIFIER(stdin);
39_Py_IDENTIFIER(stdout);
40_Py_IDENTIFIER(stderr);
41
42#ifdef __cplusplus
43extern "C" {
44#endif
45
46extern wchar_t *Py_GetPath(void);
47
48extern grammar _PyParser_Grammar; /* From graminit.c */
49
50/* Forward */
51static void initmain(PyInterpreterState *interp);
52static int initfsencoding(PyInterpreterState *interp);
53static void initsite(void);
54static int initstdio(void);
55static void initsigs(void);
56static void call_py_exitfuncs(void);
57static void wait_for_thread_shutdown(void);
58static void call_ll_exitfuncs(void);
59extern int _PyUnicode_Init(void);
60extern int _PyStructSequence_Init(void);
61extern void _PyUnicode_Fini(void);
62extern int _PyLong_Init(void);
63extern void PyLong_Fini(void);
64extern int _PyFaulthandler_Init(void);
65extern void _PyFaulthandler_Fini(void);
66extern void _PyHash_Fini(void);
67extern int _PyTraceMalloc_Init(void);
68extern int _PyTraceMalloc_Fini(void);
69
70#ifdef WITH_THREAD
71extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
72extern void _PyGILState_Fini(void);
73#endif /* WITH_THREAD */
74
75/* Global configuration variable declarations are in pydebug.h */
76/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
77int Py_DebugFlag; /* Needed by parser.c */
78int Py_VerboseFlag; /* Needed by import.c */
79int Py_QuietFlag; /* Needed by sysmodule.c */
80int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
81int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
82int Py_OptimizeFlag = 0; /* Needed by compile.c */
83int Py_NoSiteFlag; /* Suppress 'import site' */
84int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
85int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
86int Py_FrozenFlag; /* Needed by getpath.c */
87int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
88int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
89int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
90int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
91int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
92int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
93
94PyThreadState *_Py_Finalizing = NULL;
95
96/* Hack to force loading of object files */
97int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
98 PyOS_mystrnicmp; /* Python/pystrcmp.o */
99
100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
104{
105 return PyImport_ImportModule("warnings");
106}
107
108static int initialized = 0;
109
110/* API to access the initialized flag -- useful for esoteric use */
111
112int
113Py_IsInitialized(void)
114{
115 return initialized;
116}
117
118/* Helper to allow an embedding application to override the normal
119 * mechanism that attempts to figure out an appropriate IO encoding
120 */
121
122static char *_Py_StandardStreamEncoding = NULL;
123static char *_Py_StandardStreamErrors = NULL;
124
125int
126Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
127{
128 if (Py_IsInitialized()) {
129 /* This is too late to have any effect */
130 return -1;
131 }
132 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
133 * initialised yet.
134 *
135 * However, the raw memory allocators are initialised appropriately
136 * as C static variables, so _PyMem_RawStrdup is OK even though
137 * Py_Initialize hasn't been called yet.
138 */
139 if (encoding) {
140 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
141 if (!_Py_StandardStreamEncoding) {
142 return -2;
143 }
144 }
145 if (errors) {
146 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
147 if (!_Py_StandardStreamErrors) {
148 if (_Py_StandardStreamEncoding) {
149 PyMem_RawFree(_Py_StandardStreamEncoding);
150 }
151 return -3;
152 }
153 }
154 return 0;
155}
156
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000157/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
158 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000159 initializations fail, a fatal error is issued and the function does
160 not return. On return, the first thread and interpreter state have
161 been created.
162
163 Locking: you must hold the interpreter lock while calling this.
164 (If the lock has not yet been initialized, that's equivalent to
165 having the lock, but you cannot use multiple threads.)
166
167*/
168
169static int
170add_flag(int flag, const char *envs)
171{
172 int env = atoi(envs);
173 if (flag < env)
174 flag = env;
175 if (flag < 1)
176 flag = 1;
177 return flag;
178}
179
180static char*
181get_codec_name(const char *encoding)
182{
183 char *name_utf8, *name_str;
184 PyObject *codec, *name = NULL;
185
186 codec = _PyCodec_Lookup(encoding);
187 if (!codec)
188 goto error;
189
190 name = _PyObject_GetAttrId(codec, &PyId_name);
191 Py_CLEAR(codec);
192 if (!name)
193 goto error;
194
195 name_utf8 = _PyUnicode_AsString(name);
196 if (name_utf8 == NULL)
197 goto error;
198 name_str = _PyMem_RawStrdup(name_utf8);
199 Py_DECREF(name);
200 if (name_str == NULL) {
201 PyErr_NoMemory();
202 return NULL;
203 }
204 return name_str;
205
206error:
207 Py_XDECREF(codec);
208 Py_XDECREF(name);
209 return NULL;
210}
211
212static char*
213get_locale_encoding(void)
214{
215#ifdef MS_WINDOWS
216 char codepage[100];
217 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
218 return get_codec_name(codepage);
219#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
220 char* codeset = nl_langinfo(CODESET);
221 if (!codeset || codeset[0] == '\0') {
222 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
223 return NULL;
224 }
225 return get_codec_name(codeset);
226#else
227 PyErr_SetNone(PyExc_NotImplementedError);
228 return NULL;
229#endif
230}
231
232static void
233import_init(PyInterpreterState *interp, PyObject *sysmod)
234{
235 PyObject *importlib;
236 PyObject *impmod;
237 PyObject *sys_modules;
238 PyObject *value;
239
240 /* Import _importlib through its frozen version, _frozen_importlib. */
241 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
242 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
243 }
244 else if (Py_VerboseFlag) {
245 PySys_FormatStderr("import _frozen_importlib # frozen\n");
246 }
247 importlib = PyImport_AddModule("_frozen_importlib");
248 if (importlib == NULL) {
249 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
250 "sys.modules");
251 }
252 interp->importlib = importlib;
253 Py_INCREF(interp->importlib);
254
Victor Stinnercd6e6942015-09-18 09:11:57 +0200255 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000256 impmod = PyInit_imp();
257 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200258 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000259 }
260 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200261 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000262 }
263 sys_modules = PyImport_GetModuleDict();
264 if (Py_VerboseFlag) {
265 PySys_FormatStderr("import sys # builtin\n");
266 }
267 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
268 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
269 }
270
Victor Stinnercd6e6942015-09-18 09:11:57 +0200271 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000272 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
273 if (value == NULL) {
274 PyErr_Print();
275 Py_FatalError("Py_Initialize: importlib install failed");
276 }
277 Py_DECREF(value);
278 Py_DECREF(impmod);
279
280 _PyImportZip_Init();
281}
282
283
284void
285_Py_InitializeEx_Private(int install_sigs, int install_importlib)
286{
287 PyInterpreterState *interp;
288 PyThreadState *tstate;
289 PyObject *bimod, *sysmod, *pstderr;
290 char *p;
291 extern void _Py_ReadyTypes(void);
292
293 if (initialized)
294 return;
295 initialized = 1;
296 _Py_Finalizing = NULL;
297
298#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
299 /* Set up the LC_CTYPE locale, so we can obtain
300 the locale's charset without having to switch
301 locales. */
302 setlocale(LC_CTYPE, "");
303#endif
304
305 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
306 Py_DebugFlag = add_flag(Py_DebugFlag, p);
307 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
308 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
309 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
310 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
311 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
312 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
313 /* The variable is only tested for existence here; _PyRandom_Init will
314 check its value further. */
315 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
316 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
317
318 _PyRandom_Init();
319
320 interp = PyInterpreterState_New();
321 if (interp == NULL)
322 Py_FatalError("Py_Initialize: can't make first interpreter");
323
324 tstate = PyThreadState_New(interp);
325 if (tstate == NULL)
326 Py_FatalError("Py_Initialize: can't make first thread");
327 (void) PyThreadState_Swap(tstate);
328
329#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000330 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000331 destroying the GIL might fail when it is being referenced from
332 another running thread (see issue #9901).
333 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000334 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000335 _PyEval_FiniThreads();
336
337 /* Auto-thread-state API */
338 _PyGILState_Init(interp, tstate);
339#endif /* WITH_THREAD */
340
341 _Py_ReadyTypes();
342
343 if (!_PyFrame_Init())
344 Py_FatalError("Py_Initialize: can't init frames");
345
346 if (!_PyLong_Init())
347 Py_FatalError("Py_Initialize: can't init longs");
348
349 if (!PyByteArray_Init())
350 Py_FatalError("Py_Initialize: can't init bytearray");
351
352 if (!_PyFloat_Init())
353 Py_FatalError("Py_Initialize: can't init float");
354
355 interp->modules = PyDict_New();
356 if (interp->modules == NULL)
357 Py_FatalError("Py_Initialize: can't make modules dictionary");
358
359 /* Init Unicode implementation; relies on the codec registry */
360 if (_PyUnicode_Init() < 0)
361 Py_FatalError("Py_Initialize: can't initialize unicode");
362 if (_PyStructSequence_Init() < 0)
363 Py_FatalError("Py_Initialize: can't initialize structseq");
364
365 bimod = _PyBuiltin_Init();
366 if (bimod == NULL)
367 Py_FatalError("Py_Initialize: can't initialize builtins modules");
368 _PyImport_FixupBuiltin(bimod, "builtins");
369 interp->builtins = PyModule_GetDict(bimod);
370 if (interp->builtins == NULL)
371 Py_FatalError("Py_Initialize: can't initialize builtins dict");
372 Py_INCREF(interp->builtins);
373
374 /* initialize builtin exceptions */
375 _PyExc_Init(bimod);
376
377 sysmod = _PySys_Init();
378 if (sysmod == NULL)
379 Py_FatalError("Py_Initialize: can't initialize sys");
380 interp->sysdict = PyModule_GetDict(sysmod);
381 if (interp->sysdict == NULL)
382 Py_FatalError("Py_Initialize: can't initialize sys dict");
383 Py_INCREF(interp->sysdict);
384 _PyImport_FixupBuiltin(sysmod, "sys");
385 PySys_SetPath(Py_GetPath());
386 PyDict_SetItemString(interp->sysdict, "modules",
387 interp->modules);
388
389 /* Set up a preliminary stderr printer until we have enough
390 infrastructure for the io module in place. */
391 pstderr = PyFile_NewStdPrinter(fileno(stderr));
392 if (pstderr == NULL)
393 Py_FatalError("Py_Initialize: can't set preliminary stderr");
394 _PySys_SetObjectId(&PyId_stderr, pstderr);
395 PySys_SetObject("__stderr__", pstderr);
396 Py_DECREF(pstderr);
397
398 _PyImport_Init();
399
400 _PyImportHooks_Init();
401
402 /* Initialize _warnings. */
403 _PyWarnings_Init();
404
405 if (!install_importlib)
406 return;
407
Victor Stinner13019fd2015-04-03 13:10:54 +0200408 if (_PyTime_Init() < 0)
409 Py_FatalError("Py_Initialize: can't initialize time");
410
Nick Coghland6009512014-11-20 21:39:37 +1000411 import_init(interp, sysmod);
412
413 /* initialize the faulthandler module */
414 if (_PyFaulthandler_Init())
415 Py_FatalError("Py_Initialize: can't initialize faulthandler");
416
Nick Coghland6009512014-11-20 21:39:37 +1000417 if (initfsencoding(interp) < 0)
418 Py_FatalError("Py_Initialize: unable to load the file system codec");
419
420 if (install_sigs)
421 initsigs(); /* Signal handling stuff, including initintr() */
422
423 if (_PyTraceMalloc_Init() < 0)
424 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
425
426 initmain(interp); /* Module __main__ */
427 if (initstdio() < 0)
428 Py_FatalError(
429 "Py_Initialize: can't initialize sys standard streams");
430
431 /* Initialize warnings. */
432 if (PySys_HasWarnOptions()) {
433 PyObject *warnings_module = PyImport_ImportModule("warnings");
434 if (warnings_module == NULL) {
435 fprintf(stderr, "'import warnings' failed; traceback:\n");
436 PyErr_Print();
437 }
438 Py_XDECREF(warnings_module);
439 }
440
441 if (!Py_NoSiteFlag)
442 initsite(); /* Module site */
443}
444
445void
446Py_InitializeEx(int install_sigs)
447{
448 _Py_InitializeEx_Private(install_sigs, 1);
449}
450
451void
452Py_Initialize(void)
453{
454 Py_InitializeEx(1);
455}
456
457
458#ifdef COUNT_ALLOCS
459extern void dump_counts(FILE*);
460#endif
461
462/* Flush stdout and stderr */
463
464static int
465file_is_closed(PyObject *fobj)
466{
467 int r;
468 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
469 if (tmp == NULL) {
470 PyErr_Clear();
471 return 0;
472 }
473 r = PyObject_IsTrue(tmp);
474 Py_DECREF(tmp);
475 if (r < 0)
476 PyErr_Clear();
477 return r > 0;
478}
479
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000480static int
Nick Coghland6009512014-11-20 21:39:37 +1000481flush_std_files(void)
482{
483 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
484 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
485 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000486 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000487
488 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
489 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000490 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000491 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000492 status = -1;
493 }
Nick Coghland6009512014-11-20 21:39:37 +1000494 else
495 Py_DECREF(tmp);
496 }
497
498 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
499 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000500 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000501 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000502 status = -1;
503 }
Nick Coghland6009512014-11-20 21:39:37 +1000504 else
505 Py_DECREF(tmp);
506 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000507
508 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000509}
510
511/* Undo the effect of Py_Initialize().
512
513 Beware: if multiple interpreter and/or thread states exist, these
514 are not wiped out; only the current thread and interpreter state
515 are deleted. But since everything else is deleted, those other
516 interpreter and thread states should no longer be used.
517
518 (XXX We should do better, e.g. wipe out all interpreters and
519 threads.)
520
521 Locking: as above.
522
523*/
524
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000525int
526Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000527{
528 PyInterpreterState *interp;
529 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000530 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000531
532 if (!initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000533 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000534
535 wait_for_thread_shutdown();
536
537 /* The interpreter is still entirely intact at this point, and the
538 * exit funcs may be relying on that. In particular, if some thread
539 * or exit func is still waiting to do an import, the import machinery
540 * expects Py_IsInitialized() to return true. So don't say the
541 * interpreter is uninitialized until after the exit funcs have run.
542 * Note that Threading.py uses an exit func to do a join on all the
543 * threads created thru it, so this also protects pending imports in
544 * the threads created via Threading.
545 */
546 call_py_exitfuncs();
547
548 /* Get current thread state and interpreter pointer */
549 tstate = PyThreadState_GET();
550 interp = tstate->interp;
551
552 /* Remaining threads (e.g. daemon threads) will automatically exit
553 after taking the GIL (in PyEval_RestoreThread()). */
554 _Py_Finalizing = tstate;
555 initialized = 0;
556
Victor Stinnere0deff32015-03-24 13:46:18 +0100557 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000558 if (flush_std_files() < 0) {
559 status = -1;
560 }
Nick Coghland6009512014-11-20 21:39:37 +1000561
562 /* Disable signal handling */
563 PyOS_FiniInterrupts();
564
565 /* Collect garbage. This may call finalizers; it's nice to call these
566 * before all modules are destroyed.
567 * XXX If a __del__ or weakref callback is triggered here, and tries to
568 * XXX import a module, bad things can happen, because Python no
569 * XXX longer believes it's initialized.
570 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
571 * XXX is easy to provoke that way. I've also seen, e.g.,
572 * XXX Exception exceptions.ImportError: 'No module named sha'
573 * XXX in <function callback at 0x008F5718> ignored
574 * XXX but I'm unclear on exactly how that one happens. In any case,
575 * XXX I haven't seen a real-life report of either of these.
576 */
577 PyGC_Collect();
578#ifdef COUNT_ALLOCS
579 /* With COUNT_ALLOCS, it helps to run GC multiple times:
580 each collection might release some types from the type
581 list, so they become garbage. */
582 while (PyGC_Collect() > 0)
583 /* nothing */;
584#endif
585 /* Destroy all modules */
586 PyImport_Cleanup();
587
Victor Stinnere0deff32015-03-24 13:46:18 +0100588 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000589 if (flush_std_files() < 0) {
590 status = -1;
591 }
Nick Coghland6009512014-11-20 21:39:37 +1000592
593 /* Collect final garbage. This disposes of cycles created by
594 * class definitions, for example.
595 * XXX This is disabled because it caused too many problems. If
596 * XXX a __del__ or weakref callback triggers here, Python code has
597 * XXX a hard time running, because even the sys module has been
598 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
599 * XXX One symptom is a sequence of information-free messages
600 * XXX coming from threads (if a __del__ or callback is invoked,
601 * XXX other threads can execute too, and any exception they encounter
602 * XXX triggers a comedy of errors as subsystem after subsystem
603 * XXX fails to find what it *expects* to find in sys to help report
604 * XXX the exception and consequent unexpected failures). I've also
605 * XXX seen segfaults then, after adding print statements to the
606 * XXX Python code getting called.
607 */
608#if 0
609 PyGC_Collect();
610#endif
611
612 /* Disable tracemalloc after all Python objects have been destroyed,
613 so it is possible to use tracemalloc in objects destructor. */
614 _PyTraceMalloc_Fini();
615
616 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
617 _PyImport_Fini();
618
619 /* Cleanup typeobject.c's internal caches. */
620 _PyType_Fini();
621
622 /* unload faulthandler module */
623 _PyFaulthandler_Fini();
624
625 /* Debugging stuff */
626#ifdef COUNT_ALLOCS
627 dump_counts(stdout);
628#endif
629 /* dump hash stats */
630 _PyHash_Fini();
631
632 _PY_DEBUG_PRINT_TOTAL_REFS();
633
634#ifdef Py_TRACE_REFS
635 /* Display all objects still alive -- this can invoke arbitrary
636 * __repr__ overrides, so requires a mostly-intact interpreter.
637 * Alas, a lot of stuff may still be alive now that will be cleaned
638 * up later.
639 */
640 if (Py_GETENV("PYTHONDUMPREFS"))
641 _Py_PrintReferences(stderr);
642#endif /* Py_TRACE_REFS */
643
644 /* Clear interpreter state and all thread states. */
645 PyInterpreterState_Clear(interp);
646
647 /* Now we decref the exception classes. After this point nothing
648 can raise an exception. That's okay, because each Fini() method
649 below has been checked to make sure no exceptions are ever
650 raised.
651 */
652
653 _PyExc_Fini();
654
655 /* Sundry finalizers */
656 PyMethod_Fini();
657 PyFrame_Fini();
658 PyCFunction_Fini();
659 PyTuple_Fini();
660 PyList_Fini();
661 PySet_Fini();
662 PyBytes_Fini();
663 PyByteArray_Fini();
664 PyLong_Fini();
665 PyFloat_Fini();
666 PyDict_Fini();
667 PySlice_Fini();
668 _PyGC_Fini();
669 _PyRandom_Fini();
670
671 /* Cleanup Unicode implementation */
672 _PyUnicode_Fini();
673
674 /* reset file system default encoding */
675 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
676 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
677 Py_FileSystemDefaultEncoding = NULL;
678 }
679
680 /* XXX Still allocated:
681 - various static ad-hoc pointers to interned strings
682 - int and float free list blocks
683 - whatever various modules and libraries allocate
684 */
685
686 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
687
688 /* Cleanup auto-thread-state */
689#ifdef WITH_THREAD
690 _PyGILState_Fini();
691#endif /* WITH_THREAD */
692
693 /* Delete current thread. After this, many C API calls become crashy. */
694 PyThreadState_Swap(NULL);
695 PyInterpreterState_Delete(interp);
696
697#ifdef Py_TRACE_REFS
698 /* Display addresses (& refcnts) of all objects still alive.
699 * An address can be used to find the repr of the object, printed
700 * above by _Py_PrintReferences.
701 */
702 if (Py_GETENV("PYTHONDUMPREFS"))
703 _Py_PrintReferenceAddresses(stderr);
704#endif /* Py_TRACE_REFS */
705#ifdef PYMALLOC_DEBUG
706 if (Py_GETENV("PYTHONMALLOCSTATS"))
707 _PyObject_DebugMallocStats(stderr);
708#endif
709
710 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000711 return status;
712}
713
714void
715Py_Finalize(void)
716{
717 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000718}
719
720/* Create and initialize a new interpreter and thread, and return the
721 new thread. This requires that Py_Initialize() has been called
722 first.
723
724 Unsuccessful initialization yields a NULL pointer. Note that *no*
725 exception information is available even in this case -- the
726 exception information is held in the thread, and there is no
727 thread.
728
729 Locking: as above.
730
731*/
732
733PyThreadState *
734Py_NewInterpreter(void)
735{
736 PyInterpreterState *interp;
737 PyThreadState *tstate, *save_tstate;
738 PyObject *bimod, *sysmod;
739
740 if (!initialized)
741 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
742
743 interp = PyInterpreterState_New();
744 if (interp == NULL)
745 return NULL;
746
747 tstate = PyThreadState_New(interp);
748 if (tstate == NULL) {
749 PyInterpreterState_Delete(interp);
750 return NULL;
751 }
752
753 save_tstate = PyThreadState_Swap(tstate);
754
755 /* XXX The following is lax in error checking */
756
757 interp->modules = PyDict_New();
758
759 bimod = _PyImport_FindBuiltin("builtins");
760 if (bimod != NULL) {
761 interp->builtins = PyModule_GetDict(bimod);
762 if (interp->builtins == NULL)
763 goto handle_error;
764 Py_INCREF(interp->builtins);
765 }
766
767 /* initialize builtin exceptions */
768 _PyExc_Init(bimod);
769
770 sysmod = _PyImport_FindBuiltin("sys");
771 if (bimod != NULL && sysmod != NULL) {
772 PyObject *pstderr;
773
774 interp->sysdict = PyModule_GetDict(sysmod);
775 if (interp->sysdict == NULL)
776 goto handle_error;
777 Py_INCREF(interp->sysdict);
778 PySys_SetPath(Py_GetPath());
779 PyDict_SetItemString(interp->sysdict, "modules",
780 interp->modules);
781 /* Set up a preliminary stderr printer until we have enough
782 infrastructure for the io module in place. */
783 pstderr = PyFile_NewStdPrinter(fileno(stderr));
784 if (pstderr == NULL)
785 Py_FatalError("Py_Initialize: can't set preliminary stderr");
786 _PySys_SetObjectId(&PyId_stderr, pstderr);
787 PySys_SetObject("__stderr__", pstderr);
788 Py_DECREF(pstderr);
789
790 _PyImportHooks_Init();
791
792 import_init(interp, sysmod);
793
794 if (initfsencoding(interp) < 0)
795 goto handle_error;
796
797 if (initstdio() < 0)
798 Py_FatalError(
Georg Brandl4b5b0622016-01-18 08:00:15 +0100799 "Py_Initialize: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000800 initmain(interp);
801 if (!Py_NoSiteFlag)
802 initsite();
803 }
804
805 if (!PyErr_Occurred())
806 return tstate;
807
808handle_error:
809 /* Oops, it didn't work. Undo it all. */
810
811 PyErr_PrintEx(0);
812 PyThreadState_Clear(tstate);
813 PyThreadState_Swap(save_tstate);
814 PyThreadState_Delete(tstate);
815 PyInterpreterState_Delete(interp);
816
817 return NULL;
818}
819
820/* Delete an interpreter and its last thread. This requires that the
821 given thread state is current, that the thread has no remaining
822 frames, and that it is its interpreter's only remaining thread.
823 It is a fatal error to violate these constraints.
824
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000825 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +1000826 everything, regardless.)
827
828 Locking: as above.
829
830*/
831
832void
833Py_EndInterpreter(PyThreadState *tstate)
834{
835 PyInterpreterState *interp = tstate->interp;
836
837 if (tstate != PyThreadState_GET())
838 Py_FatalError("Py_EndInterpreter: thread is not current");
839 if (tstate->frame != NULL)
840 Py_FatalError("Py_EndInterpreter: thread still has a frame");
841
842 wait_for_thread_shutdown();
843
844 if (tstate != interp->tstate_head || tstate->next != NULL)
845 Py_FatalError("Py_EndInterpreter: not the last thread");
846
847 PyImport_Cleanup();
848 PyInterpreterState_Clear(interp);
849 PyThreadState_Swap(NULL);
850 PyInterpreterState_Delete(interp);
851}
852
853#ifdef MS_WINDOWS
854static wchar_t *progname = L"python";
855#else
856static wchar_t *progname = L"python3";
857#endif
858
859void
860Py_SetProgramName(wchar_t *pn)
861{
862 if (pn && *pn)
863 progname = pn;
864}
865
866wchar_t *
867Py_GetProgramName(void)
868{
869 return progname;
870}
871
872static wchar_t *default_home = NULL;
873static wchar_t env_home[MAXPATHLEN+1];
874
875void
876Py_SetPythonHome(wchar_t *home)
877{
878 default_home = home;
879}
880
881wchar_t *
882Py_GetPythonHome(void)
883{
884 wchar_t *home = default_home;
885 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
886 char* chome = Py_GETENV("PYTHONHOME");
887 if (chome) {
888 size_t size = Py_ARRAY_LENGTH(env_home);
889 size_t r = mbstowcs(env_home, chome, size);
890 if (r != (size_t)-1 && r < size)
891 home = env_home;
892 }
893
894 }
895 return home;
896}
897
898/* Create __main__ module */
899
900static void
901initmain(PyInterpreterState *interp)
902{
903 PyObject *m, *d, *loader;
904 m = PyImport_AddModule("__main__");
905 if (m == NULL)
906 Py_FatalError("can't create __main__ module");
907 d = PyModule_GetDict(m);
908 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
909 PyObject *bimod = PyImport_ImportModule("builtins");
910 if (bimod == NULL) {
911 Py_FatalError("Failed to retrieve builtins module");
912 }
913 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
914 Py_FatalError("Failed to initialize __main__.__builtins__");
915 }
916 Py_DECREF(bimod);
917 }
918 /* Main is a little special - imp.is_builtin("__main__") will return
919 * False, but BuiltinImporter is still the most appropriate initial
920 * setting for its __loader__ attribute. A more suitable value will
921 * be set if __main__ gets further initialized later in the startup
922 * process.
923 */
924 loader = PyDict_GetItemString(d, "__loader__");
925 if (loader == NULL || loader == Py_None) {
926 PyObject *loader = PyObject_GetAttrString(interp->importlib,
927 "BuiltinImporter");
928 if (loader == NULL) {
929 Py_FatalError("Failed to retrieve BuiltinImporter");
930 }
931 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
932 Py_FatalError("Failed to initialize __main__.__loader__");
933 }
934 Py_DECREF(loader);
935 }
936}
937
938static int
939initfsencoding(PyInterpreterState *interp)
940{
941 PyObject *codec;
942
943 if (Py_FileSystemDefaultEncoding == NULL)
944 {
945 Py_FileSystemDefaultEncoding = get_locale_encoding();
946 if (Py_FileSystemDefaultEncoding == NULL)
947 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
948
949 Py_HasFileSystemDefaultEncoding = 0;
950 interp->fscodec_initialized = 1;
951 return 0;
952 }
953
954 /* the encoding is mbcs, utf-8 or ascii */
955 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
956 if (!codec) {
957 /* Such error can only occurs in critical situations: no more
958 * memory, import a module of the standard library failed,
959 * etc. */
960 return -1;
961 }
962 Py_DECREF(codec);
963 interp->fscodec_initialized = 1;
964 return 0;
965}
966
967/* Import the site module (not into __main__ though) */
968
969static void
970initsite(void)
971{
972 PyObject *m;
973 m = PyImport_ImportModule("site");
974 if (m == NULL) {
975 fprintf(stderr, "Failed to import the site module\n");
976 PyErr_Print();
977 Py_Finalize();
978 exit(1);
979 }
980 else {
981 Py_DECREF(m);
982 }
983}
984
Victor Stinner874dbe82015-09-04 17:29:57 +0200985/* Check if a file descriptor is valid or not.
986 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
987static int
988is_valid_fd(int fd)
989{
990 int fd2;
991 if (fd < 0 || !_PyVerify_fd(fd))
992 return 0;
993 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +0200994 /* Prefer dup() over fstat(). fstat() can require input/output whereas
995 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
996 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +0200997 fd2 = dup(fd);
998 if (fd2 >= 0)
999 close(fd2);
1000 _Py_END_SUPPRESS_IPH
1001 return fd2 >= 0;
1002}
1003
1004/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001005static PyObject*
1006create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001007 int fd, int write_mode, const char* name,
1008 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001009{
1010 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1011 const char* mode;
1012 const char* newline;
1013 PyObject *line_buffering;
1014 int buffering, isatty;
1015 _Py_IDENTIFIER(open);
1016 _Py_IDENTIFIER(isatty);
1017 _Py_IDENTIFIER(TextIOWrapper);
1018 _Py_IDENTIFIER(mode);
1019
Victor Stinner874dbe82015-09-04 17:29:57 +02001020 if (!is_valid_fd(fd))
1021 Py_RETURN_NONE;
1022
Nick Coghland6009512014-11-20 21:39:37 +10001023 /* stdin is always opened in buffered mode, first because it shouldn't
1024 make a difference in common use cases, second because TextIOWrapper
1025 depends on the presence of a read1() method which only exists on
1026 buffered streams.
1027 */
1028 if (Py_UnbufferedStdioFlag && write_mode)
1029 buffering = 0;
1030 else
1031 buffering = -1;
1032 if (write_mode)
1033 mode = "wb";
1034 else
1035 mode = "rb";
1036 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1037 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001038 Py_None, Py_None, /* encoding, errors */
1039 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001040 if (buf == NULL)
1041 goto error;
1042
1043 if (buffering) {
1044 _Py_IDENTIFIER(raw);
1045 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1046 if (raw == NULL)
1047 goto error;
1048 }
1049 else {
1050 raw = buf;
1051 Py_INCREF(raw);
1052 }
1053
1054 text = PyUnicode_FromString(name);
1055 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1056 goto error;
1057 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1058 if (res == NULL)
1059 goto error;
1060 isatty = PyObject_IsTrue(res);
1061 Py_DECREF(res);
1062 if (isatty == -1)
1063 goto error;
1064 if (isatty || Py_UnbufferedStdioFlag)
1065 line_buffering = Py_True;
1066 else
1067 line_buffering = Py_False;
1068
1069 Py_CLEAR(raw);
1070 Py_CLEAR(text);
1071
1072#ifdef MS_WINDOWS
1073 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1074 newlines to "\n".
1075 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1076 newline = NULL;
1077#else
1078 /* sys.stdin: split lines at "\n".
1079 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1080 newline = "\n";
1081#endif
1082
1083 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1084 buf, encoding, errors,
1085 newline, line_buffering);
1086 Py_CLEAR(buf);
1087 if (stream == NULL)
1088 goto error;
1089
1090 if (write_mode)
1091 mode = "w";
1092 else
1093 mode = "r";
1094 text = PyUnicode_FromString(mode);
1095 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1096 goto error;
1097 Py_CLEAR(text);
1098 return stream;
1099
1100error:
1101 Py_XDECREF(buf);
1102 Py_XDECREF(stream);
1103 Py_XDECREF(text);
1104 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001105
Victor Stinner874dbe82015-09-04 17:29:57 +02001106 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1107 /* Issue #24891: the file descriptor was closed after the first
1108 is_valid_fd() check was called. Ignore the OSError and set the
1109 stream to None. */
1110 PyErr_Clear();
1111 Py_RETURN_NONE;
1112 }
1113 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001114}
1115
1116/* Initialize sys.stdin, stdout, stderr and builtins.open */
1117static int
1118initstdio(void)
1119{
1120 PyObject *iomod = NULL, *wrapper;
1121 PyObject *bimod = NULL;
1122 PyObject *m;
1123 PyObject *std = NULL;
1124 int status = 0, fd;
1125 PyObject * encoding_attr;
1126 char *pythonioencoding = NULL, *encoding, *errors;
1127
1128 /* Hack to avoid a nasty recursion issue when Python is invoked
1129 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1130 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1131 goto error;
1132 }
1133 Py_DECREF(m);
1134
1135 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1136 goto error;
1137 }
1138 Py_DECREF(m);
1139
1140 if (!(bimod = PyImport_ImportModule("builtins"))) {
1141 goto error;
1142 }
1143
1144 if (!(iomod = PyImport_ImportModule("io"))) {
1145 goto error;
1146 }
1147 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1148 goto error;
1149 }
1150
1151 /* Set builtins.open */
1152 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1153 Py_DECREF(wrapper);
1154 goto error;
1155 }
1156 Py_DECREF(wrapper);
1157
1158 encoding = _Py_StandardStreamEncoding;
1159 errors = _Py_StandardStreamErrors;
1160 if (!encoding || !errors) {
1161 if (!errors) {
1162 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1163 stdin and stdout use the surrogateescape error handler by
1164 default, instead of the strict error handler. */
1165 char *loc = setlocale(LC_CTYPE, NULL);
1166 if (loc != NULL && strcmp(loc, "C") == 0)
1167 errors = "surrogateescape";
1168 }
1169
1170 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1171 if (pythonioencoding) {
1172 char *err;
1173 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1174 if (pythonioencoding == NULL) {
1175 PyErr_NoMemory();
1176 goto error;
1177 }
1178 err = strchr(pythonioencoding, ':');
1179 if (err) {
1180 *err = '\0';
1181 err++;
1182 if (*err && !_Py_StandardStreamErrors) {
1183 errors = err;
1184 }
1185 }
1186 if (*pythonioencoding && !encoding) {
1187 encoding = pythonioencoding;
1188 }
1189 }
1190 }
1191
1192 /* Set sys.stdin */
1193 fd = fileno(stdin);
1194 /* Under some conditions stdin, stdout and stderr may not be connected
1195 * and fileno() may point to an invalid file descriptor. For example
1196 * GUI apps don't have valid standard streams by default.
1197 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001198 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1199 if (std == NULL)
1200 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001201 PySys_SetObject("__stdin__", std);
1202 _PySys_SetObjectId(&PyId_stdin, std);
1203 Py_DECREF(std);
1204
1205 /* Set sys.stdout */
1206 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001207 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1208 if (std == NULL)
1209 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001210 PySys_SetObject("__stdout__", std);
1211 _PySys_SetObjectId(&PyId_stdout, std);
1212 Py_DECREF(std);
1213
1214#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1215 /* Set sys.stderr, replaces the preliminary stderr */
1216 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001217 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1218 if (std == NULL)
1219 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001220
1221 /* Same as hack above, pre-import stderr's codec to avoid recursion
1222 when import.c tries to write to stderr in verbose mode. */
1223 encoding_attr = PyObject_GetAttrString(std, "encoding");
1224 if (encoding_attr != NULL) {
1225 const char * std_encoding;
1226 std_encoding = _PyUnicode_AsString(encoding_attr);
1227 if (std_encoding != NULL) {
1228 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1229 Py_XDECREF(codec_info);
1230 }
1231 Py_DECREF(encoding_attr);
1232 }
1233 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1234
1235 if (PySys_SetObject("__stderr__", std) < 0) {
1236 Py_DECREF(std);
1237 goto error;
1238 }
1239 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1240 Py_DECREF(std);
1241 goto error;
1242 }
1243 Py_DECREF(std);
1244#endif
1245
1246 if (0) {
1247 error:
1248 status = -1;
1249 }
1250
1251 /* We won't need them anymore. */
1252 if (_Py_StandardStreamEncoding) {
1253 PyMem_RawFree(_Py_StandardStreamEncoding);
1254 _Py_StandardStreamEncoding = NULL;
1255 }
1256 if (_Py_StandardStreamErrors) {
1257 PyMem_RawFree(_Py_StandardStreamErrors);
1258 _Py_StandardStreamErrors = NULL;
1259 }
1260 PyMem_Free(pythonioencoding);
1261 Py_XDECREF(bimod);
1262 Py_XDECREF(iomod);
1263 return status;
1264}
1265
1266
Victor Stinner10dc4842015-03-24 12:01:30 +01001267/* Print the current exception (if an exception is set) with its traceback,
1268 * or display the current Python stack.
1269 *
1270 * Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1271 * called on catastrophic cases. */
1272
1273static void
1274_Py_PrintFatalError(int fd)
1275{
Victor Stinnere0deff32015-03-24 13:46:18 +01001276 PyObject *ferr, *res;
Victor Stinner10dc4842015-03-24 12:01:30 +01001277 PyObject *exception, *v, *tb;
1278 int has_tb;
1279 PyThreadState *tstate;
1280
1281 PyErr_Fetch(&exception, &v, &tb);
1282 if (exception == NULL) {
1283 /* No current exception */
1284 goto display_stack;
1285 }
1286
Victor Stinnere0deff32015-03-24 13:46:18 +01001287 ferr = _PySys_GetObjectId(&PyId_stderr);
1288 if (ferr == NULL || ferr == Py_None) {
1289 /* sys.stderr is not set yet or set to None,
1290 no need to try to display the exception */
1291 goto display_stack;
1292 }
1293
Victor Stinner10dc4842015-03-24 12:01:30 +01001294 PyErr_NormalizeException(&exception, &v, &tb);
1295 if (tb == NULL) {
1296 tb = Py_None;
1297 Py_INCREF(tb);
1298 }
1299 PyException_SetTraceback(v, tb);
1300 if (exception == NULL) {
Victor Stinnere0deff32015-03-24 13:46:18 +01001301 /* PyErr_NormalizeException() failed */
Victor Stinner10dc4842015-03-24 12:01:30 +01001302 goto display_stack;
1303 }
1304
Christian Heimese8e42832015-04-16 17:25:45 +02001305 has_tb = (tb != Py_None);
Victor Stinner10dc4842015-03-24 12:01:30 +01001306 PyErr_Display(exception, v, tb);
1307 Py_XDECREF(exception);
1308 Py_XDECREF(v);
1309 Py_XDECREF(tb);
Victor Stinnere0deff32015-03-24 13:46:18 +01001310
1311 /* sys.stderr may be buffered: call sys.stderr.flush() */
1312 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1313 if (res == NULL)
1314 PyErr_Clear();
1315 else
1316 Py_DECREF(res);
1317
Victor Stinner10dc4842015-03-24 12:01:30 +01001318 if (has_tb)
1319 return;
1320
1321display_stack:
Benjamin Peterson55c14352015-04-06 09:59:23 -04001322#ifdef WITH_THREAD
Victor Stinner10dc4842015-03-24 12:01:30 +01001323 /* PyGILState_GetThisThreadState() works even if the GIL was released */
1324 tstate = PyGILState_GetThisThreadState();
Benjamin Peterson55c14352015-04-06 09:59:23 -04001325#else
1326 tstate = PyThreadState_GET();
1327#endif
Victor Stinner10dc4842015-03-24 12:01:30 +01001328 if (tstate == NULL) {
1329 /* _Py_DumpTracebackThreads() requires the thread state to display
1330 * frames */
1331 return;
1332 }
1333
1334 fputc('\n', stderr);
1335 fflush(stderr);
1336
1337 /* display the current Python stack */
1338 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
1339}
Nick Coghland6009512014-11-20 21:39:37 +10001340/* Print fatal error message and abort */
1341
1342void
1343Py_FatalError(const char *msg)
1344{
1345 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001346 static int reentrant = 0;
1347#ifdef MS_WINDOWS
1348 size_t len;
1349 WCHAR* buffer;
1350 size_t i;
1351#endif
1352
1353 if (reentrant) {
1354 /* Py_FatalError() caused a second fatal error.
1355 Example: flush_std_files() raises a recursion error. */
1356 goto exit;
1357 }
1358 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001359
1360 fprintf(stderr, "Fatal Python error: %s\n", msg);
1361 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001362
Victor Stinnere0deff32015-03-24 13:46:18 +01001363 /* Print the exception (if an exception is set) with its traceback,
1364 * or display the current Python stack. */
Victor Stinner10dc4842015-03-24 12:01:30 +01001365 _Py_PrintFatalError(fd);
1366
Victor Stinnere0deff32015-03-24 13:46:18 +01001367 /* Flush sys.stdout and sys.stderr */
1368 flush_std_files();
1369
Victor Stinner10dc4842015-03-24 12:01:30 +01001370 /* The main purpose of faulthandler is to display the traceback. We already
Victor Stinnere0deff32015-03-24 13:46:18 +01001371 * did our best to display it. So faulthandler can now be disabled.
1372 * (Don't trigger it on abort().) */
Victor Stinner10dc4842015-03-24 12:01:30 +01001373 _PyFaulthandler_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001374
1375#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001376 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001377
Victor Stinner53345a42015-03-25 01:55:14 +01001378 /* Convert the message to wchar_t. This uses a simple one-to-one
1379 conversion, assuming that the this error message actually uses ASCII
1380 only. If this ceases to be true, we will have to convert. */
1381 buffer = alloca( (len+1) * (sizeof *buffer));
1382 for( i=0; i<=len; ++i)
1383 buffer[i] = msg[i];
1384 OutputDebugStringW(L"Fatal Python error: ");
1385 OutputDebugStringW(buffer);
1386 OutputDebugStringW(L"\n");
1387#endif /* MS_WINDOWS */
1388
1389exit:
1390#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001391 DebugBreak();
1392#endif
Nick Coghland6009512014-11-20 21:39:37 +10001393 abort();
1394}
1395
1396/* Clean up and exit */
1397
1398#ifdef WITH_THREAD
1399#include "pythread.h"
1400#endif
1401
1402static void (*pyexitfunc)(void) = NULL;
1403/* For the atexit module. */
1404void _Py_PyAtExit(void (*func)(void))
1405{
1406 pyexitfunc = func;
1407}
1408
1409static void
1410call_py_exitfuncs(void)
1411{
1412 if (pyexitfunc == NULL)
1413 return;
1414
1415 (*pyexitfunc)();
1416 PyErr_Clear();
1417}
1418
1419/* Wait until threading._shutdown completes, provided
1420 the threading module was imported in the first place.
1421 The shutdown routine will wait until all non-daemon
1422 "threading" threads have completed. */
1423static void
1424wait_for_thread_shutdown(void)
1425{
1426#ifdef WITH_THREAD
1427 _Py_IDENTIFIER(_shutdown);
1428 PyObject *result;
1429 PyThreadState *tstate = PyThreadState_GET();
1430 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1431 "threading");
1432 if (threading == NULL) {
1433 /* threading not imported */
1434 PyErr_Clear();
1435 return;
1436 }
1437 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1438 if (result == NULL) {
1439 PyErr_WriteUnraisable(threading);
1440 }
1441 else {
1442 Py_DECREF(result);
1443 }
1444 Py_DECREF(threading);
1445#endif
1446}
1447
1448#define NEXITFUNCS 32
1449static void (*exitfuncs[NEXITFUNCS])(void);
1450static int nexitfuncs = 0;
1451
1452int Py_AtExit(void (*func)(void))
1453{
1454 if (nexitfuncs >= NEXITFUNCS)
1455 return -1;
1456 exitfuncs[nexitfuncs++] = func;
1457 return 0;
1458}
1459
1460static void
1461call_ll_exitfuncs(void)
1462{
1463 while (nexitfuncs > 0)
1464 (*exitfuncs[--nexitfuncs])();
1465
1466 fflush(stdout);
1467 fflush(stderr);
1468}
1469
1470void
1471Py_Exit(int sts)
1472{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001473 if (Py_FinalizeEx() < 0) {
1474 sts = 120;
1475 }
Nick Coghland6009512014-11-20 21:39:37 +10001476
1477 exit(sts);
1478}
1479
1480static void
1481initsigs(void)
1482{
1483#ifdef SIGPIPE
1484 PyOS_setsig(SIGPIPE, SIG_IGN);
1485#endif
1486#ifdef SIGXFZ
1487 PyOS_setsig(SIGXFZ, SIG_IGN);
1488#endif
1489#ifdef SIGXFSZ
1490 PyOS_setsig(SIGXFSZ, SIG_IGN);
1491#endif
1492 PyOS_InitInterrupts(); /* May imply initsignal() */
1493 if (PyErr_Occurred()) {
1494 Py_FatalError("Py_Initialize: can't import signal");
1495 }
1496}
1497
1498
1499/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1500 *
1501 * All of the code in this function must only use async-signal-safe functions,
1502 * listed at `man 7 signal` or
1503 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1504 */
1505void
1506_Py_RestoreSignals(void)
1507{
1508#ifdef SIGPIPE
1509 PyOS_setsig(SIGPIPE, SIG_DFL);
1510#endif
1511#ifdef SIGXFZ
1512 PyOS_setsig(SIGXFZ, SIG_DFL);
1513#endif
1514#ifdef SIGXFSZ
1515 PyOS_setsig(SIGXFSZ, SIG_DFL);
1516#endif
1517}
1518
1519
1520/*
1521 * The file descriptor fd is considered ``interactive'' if either
1522 * a) isatty(fd) is TRUE, or
1523 * b) the -i flag was given, and the filename associated with
1524 * the descriptor is NULL or "<stdin>" or "???".
1525 */
1526int
1527Py_FdIsInteractive(FILE *fp, const char *filename)
1528{
1529 if (isatty((int)fileno(fp)))
1530 return 1;
1531 if (!Py_InteractiveFlag)
1532 return 0;
1533 return (filename == NULL) ||
1534 (strcmp(filename, "<stdin>") == 0) ||
1535 (strcmp(filename, "???") == 0);
1536}
1537
1538
Nick Coghland6009512014-11-20 21:39:37 +10001539/* Wrappers around sigaction() or signal(). */
1540
1541PyOS_sighandler_t
1542PyOS_getsig(int sig)
1543{
1544#ifdef HAVE_SIGACTION
1545 struct sigaction context;
1546 if (sigaction(sig, NULL, &context) == -1)
1547 return SIG_ERR;
1548 return context.sa_handler;
1549#else
1550 PyOS_sighandler_t handler;
1551/* Special signal handling for the secure CRT in Visual Studio 2005 */
1552#if defined(_MSC_VER) && _MSC_VER >= 1400
1553 switch (sig) {
1554 /* Only these signals are valid */
1555 case SIGINT:
1556 case SIGILL:
1557 case SIGFPE:
1558 case SIGSEGV:
1559 case SIGTERM:
1560 case SIGBREAK:
1561 case SIGABRT:
1562 break;
1563 /* Don't call signal() with other values or it will assert */
1564 default:
1565 return SIG_ERR;
1566 }
1567#endif /* _MSC_VER && _MSC_VER >= 1400 */
1568 handler = signal(sig, SIG_IGN);
1569 if (handler != SIG_ERR)
1570 signal(sig, handler);
1571 return handler;
1572#endif
1573}
1574
1575/*
1576 * All of the code in this function must only use async-signal-safe functions,
1577 * listed at `man 7 signal` or
1578 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1579 */
1580PyOS_sighandler_t
1581PyOS_setsig(int sig, PyOS_sighandler_t handler)
1582{
1583#ifdef HAVE_SIGACTION
1584 /* Some code in Modules/signalmodule.c depends on sigaction() being
1585 * used here if HAVE_SIGACTION is defined. Fix that if this code
1586 * changes to invalidate that assumption.
1587 */
1588 struct sigaction context, ocontext;
1589 context.sa_handler = handler;
1590 sigemptyset(&context.sa_mask);
1591 context.sa_flags = 0;
1592 if (sigaction(sig, &context, &ocontext) == -1)
1593 return SIG_ERR;
1594 return ocontext.sa_handler;
1595#else
1596 PyOS_sighandler_t oldhandler;
1597 oldhandler = signal(sig, handler);
1598#ifdef HAVE_SIGINTERRUPT
1599 siginterrupt(sig, 1);
1600#endif
1601 return oldhandler;
1602#endif
1603}
1604
1605#ifdef __cplusplus
1606}
1607#endif