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