blob: 640271fd20b7090d2041c150a2d2d7dc7ad5d4cf [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"
Steve Dower39294992016-08-30 21:22:36 -070034
35extern PyTypeObject PyWindowsConsoleIO_Type;
36#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
39_Py_IDENTIFIER(flush);
40_Py_IDENTIFIER(name);
41_Py_IDENTIFIER(stdin);
42_Py_IDENTIFIER(stdout);
43_Py_IDENTIFIER(stderr);
44
45#ifdef __cplusplus
46extern "C" {
47#endif
48
49extern wchar_t *Py_GetPath(void);
50
51extern grammar _PyParser_Grammar; /* From graminit.c */
52
53/* Forward */
54static void initmain(PyInterpreterState *interp);
55static int initfsencoding(PyInterpreterState *interp);
56static void initsite(void);
57static int initstdio(void);
58static void initsigs(void);
59static void call_py_exitfuncs(void);
60static void wait_for_thread_shutdown(void);
61static void call_ll_exitfuncs(void);
62extern int _PyUnicode_Init(void);
63extern int _PyStructSequence_Init(void);
64extern void _PyUnicode_Fini(void);
65extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
67extern int _PyFaulthandler_Init(void);
68extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
70extern int _PyTraceMalloc_Init(void);
71extern int _PyTraceMalloc_Fini(void);
72
73#ifdef WITH_THREAD
74extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
75extern void _PyGILState_Fini(void);
76#endif /* WITH_THREAD */
77
78/* Global configuration variable declarations are in pydebug.h */
79/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
80int Py_DebugFlag; /* Needed by parser.c */
81int Py_VerboseFlag; /* Needed by import.c */
82int Py_QuietFlag; /* Needed by sysmodule.c */
83int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
84int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
85int Py_OptimizeFlag = 0; /* Needed by compile.c */
86int Py_NoSiteFlag; /* Suppress 'import site' */
87int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
88int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
89int Py_FrozenFlag; /* Needed by getpath.c */
90int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang16416c22017-03-11 14:07:30 +080091int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
93int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
94int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
95int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070096#ifdef MS_WINDOWS
97int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -070098int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -070099#endif
Nick Coghland6009512014-11-20 21:39:37 +1000100
101PyThreadState *_Py_Finalizing = NULL;
102
103/* Hack to force loading of object files */
104int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
105 PyOS_mystrnicmp; /* Python/pystrcmp.o */
106
107/* PyModule_GetWarningsModule is no longer necessary as of 2.6
108since _warnings is builtin. This API should not be used. */
109PyObject *
110PyModule_GetWarningsModule(void)
111{
112 return PyImport_ImportModule("warnings");
113}
114
115static int initialized = 0;
116
117/* API to access the initialized flag -- useful for esoteric use */
118
119int
120Py_IsInitialized(void)
121{
122 return initialized;
123}
124
125/* Helper to allow an embedding application to override the normal
126 * mechanism that attempts to figure out an appropriate IO encoding
127 */
128
129static char *_Py_StandardStreamEncoding = NULL;
130static char *_Py_StandardStreamErrors = NULL;
131
132int
133Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
134{
135 if (Py_IsInitialized()) {
136 /* This is too late to have any effect */
137 return -1;
138 }
139 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
140 * initialised yet.
141 *
142 * However, the raw memory allocators are initialised appropriately
143 * as C static variables, so _PyMem_RawStrdup is OK even though
144 * Py_Initialize hasn't been called yet.
145 */
146 if (encoding) {
147 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
148 if (!_Py_StandardStreamEncoding) {
149 return -2;
150 }
151 }
152 if (errors) {
153 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
154 if (!_Py_StandardStreamErrors) {
155 if (_Py_StandardStreamEncoding) {
156 PyMem_RawFree(_Py_StandardStreamEncoding);
157 }
158 return -3;
159 }
160 }
Steve Dower39294992016-08-30 21:22:36 -0700161#ifdef MS_WINDOWS
162 if (_Py_StandardStreamEncoding) {
163 /* Overriding the stream encoding implies legacy streams */
164 Py_LegacyWindowsStdioFlag = 1;
165 }
166#endif
Nick Coghland6009512014-11-20 21:39:37 +1000167 return 0;
168}
169
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000170/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
171 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000172 initializations fail, a fatal error is issued and the function does
173 not return. On return, the first thread and interpreter state have
174 been created.
175
176 Locking: you must hold the interpreter lock while calling this.
177 (If the lock has not yet been initialized, that's equivalent to
178 having the lock, but you cannot use multiple threads.)
179
180*/
181
182static int
183add_flag(int flag, const char *envs)
184{
185 int env = atoi(envs);
186 if (flag < env)
187 flag = env;
188 if (flag < 1)
189 flag = 1;
190 return flag;
191}
192
193static char*
194get_codec_name(const char *encoding)
195{
196 char *name_utf8, *name_str;
197 PyObject *codec, *name = NULL;
198
199 codec = _PyCodec_Lookup(encoding);
200 if (!codec)
201 goto error;
202
203 name = _PyObject_GetAttrId(codec, &PyId_name);
204 Py_CLEAR(codec);
205 if (!name)
206 goto error;
207
Serhiy Storchaka06515832016-11-20 09:13:07 +0200208 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000209 if (name_utf8 == NULL)
210 goto error;
211 name_str = _PyMem_RawStrdup(name_utf8);
212 Py_DECREF(name);
213 if (name_str == NULL) {
214 PyErr_NoMemory();
215 return NULL;
216 }
217 return name_str;
218
219error:
220 Py_XDECREF(codec);
221 Py_XDECREF(name);
222 return NULL;
223}
224
225static char*
226get_locale_encoding(void)
227{
228#ifdef MS_WINDOWS
229 char codepage[100];
230 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
231 return get_codec_name(codepage);
232#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
233 char* codeset = nl_langinfo(CODESET);
234 if (!codeset || codeset[0] == '\0') {
235 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
236 return NULL;
237 }
238 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200239#elif defined(__ANDROID__)
240 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000241#else
242 PyErr_SetNone(PyExc_NotImplementedError);
243 return NULL;
244#endif
245}
246
247static void
248import_init(PyInterpreterState *interp, PyObject *sysmod)
249{
250 PyObject *importlib;
251 PyObject *impmod;
252 PyObject *sys_modules;
253 PyObject *value;
254
255 /* Import _importlib through its frozen version, _frozen_importlib. */
256 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
257 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
258 }
259 else if (Py_VerboseFlag) {
260 PySys_FormatStderr("import _frozen_importlib # frozen\n");
261 }
262 importlib = PyImport_AddModule("_frozen_importlib");
263 if (importlib == NULL) {
264 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
265 "sys.modules");
266 }
267 interp->importlib = importlib;
268 Py_INCREF(interp->importlib);
269
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300270 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
271 if (interp->import_func == NULL)
272 Py_FatalError("Py_Initialize: __import__ not found");
273 Py_INCREF(interp->import_func);
274
Victor Stinnercd6e6942015-09-18 09:11:57 +0200275 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000276 impmod = PyInit_imp();
277 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200278 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000279 }
280 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200281 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000282 }
283 sys_modules = PyImport_GetModuleDict();
284 if (Py_VerboseFlag) {
285 PySys_FormatStderr("import sys # builtin\n");
286 }
287 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
288 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
289 }
290
Victor Stinnercd6e6942015-09-18 09:11:57 +0200291 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000292 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
293 if (value == NULL) {
294 PyErr_Print();
295 Py_FatalError("Py_Initialize: importlib install failed");
296 }
297 Py_DECREF(value);
298 Py_DECREF(impmod);
299
300 _PyImportZip_Init();
301}
302
303
304void
305_Py_InitializeEx_Private(int install_sigs, int install_importlib)
306{
307 PyInterpreterState *interp;
308 PyThreadState *tstate;
309 PyObject *bimod, *sysmod, *pstderr;
310 char *p;
311 extern void _Py_ReadyTypes(void);
312
313 if (initialized)
314 return;
315 initialized = 1;
316 _Py_Finalizing = NULL;
317
Xavier de Gayeb445ad72016-11-16 07:24:20 +0100318#ifdef HAVE_SETLOCALE
Nick Coghland6009512014-11-20 21:39:37 +1000319 /* Set up the LC_CTYPE locale, so we can obtain
320 the locale's charset without having to switch
321 locales. */
322 setlocale(LC_CTYPE, "");
323#endif
324
325 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
326 Py_DebugFlag = add_flag(Py_DebugFlag, p);
327 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
328 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
329 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
330 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
331 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
332 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
333 /* The variable is only tested for existence here; _PyRandom_Init will
334 check its value further. */
335 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
336 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700337#ifdef MS_WINDOWS
338 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
339 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700340 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
341 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700342#endif
Nick Coghland6009512014-11-20 21:39:37 +1000343
344 _PyRandom_Init();
345
346 interp = PyInterpreterState_New();
347 if (interp == NULL)
348 Py_FatalError("Py_Initialize: can't make first interpreter");
349
350 tstate = PyThreadState_New(interp);
351 if (tstate == NULL)
352 Py_FatalError("Py_Initialize: can't make first thread");
353 (void) PyThreadState_Swap(tstate);
354
355#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000356 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000357 destroying the GIL might fail when it is being referenced from
358 another running thread (see issue #9901).
359 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000360 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000361 _PyEval_FiniThreads();
362
363 /* Auto-thread-state API */
364 _PyGILState_Init(interp, tstate);
365#endif /* WITH_THREAD */
366
367 _Py_ReadyTypes();
368
369 if (!_PyFrame_Init())
370 Py_FatalError("Py_Initialize: can't init frames");
371
372 if (!_PyLong_Init())
373 Py_FatalError("Py_Initialize: can't init longs");
374
375 if (!PyByteArray_Init())
376 Py_FatalError("Py_Initialize: can't init bytearray");
377
378 if (!_PyFloat_Init())
379 Py_FatalError("Py_Initialize: can't init float");
380
381 interp->modules = PyDict_New();
382 if (interp->modules == NULL)
383 Py_FatalError("Py_Initialize: can't make modules dictionary");
384
385 /* Init Unicode implementation; relies on the codec registry */
386 if (_PyUnicode_Init() < 0)
387 Py_FatalError("Py_Initialize: can't initialize unicode");
388 if (_PyStructSequence_Init() < 0)
389 Py_FatalError("Py_Initialize: can't initialize structseq");
390
391 bimod = _PyBuiltin_Init();
392 if (bimod == NULL)
393 Py_FatalError("Py_Initialize: can't initialize builtins modules");
394 _PyImport_FixupBuiltin(bimod, "builtins");
395 interp->builtins = PyModule_GetDict(bimod);
396 if (interp->builtins == NULL)
397 Py_FatalError("Py_Initialize: can't initialize builtins dict");
398 Py_INCREF(interp->builtins);
399
400 /* initialize builtin exceptions */
401 _PyExc_Init(bimod);
402
403 sysmod = _PySys_Init();
404 if (sysmod == NULL)
405 Py_FatalError("Py_Initialize: can't initialize sys");
406 interp->sysdict = PyModule_GetDict(sysmod);
407 if (interp->sysdict == NULL)
408 Py_FatalError("Py_Initialize: can't initialize sys dict");
409 Py_INCREF(interp->sysdict);
410 _PyImport_FixupBuiltin(sysmod, "sys");
411 PySys_SetPath(Py_GetPath());
412 PyDict_SetItemString(interp->sysdict, "modules",
413 interp->modules);
414
415 /* Set up a preliminary stderr printer until we have enough
416 infrastructure for the io module in place. */
417 pstderr = PyFile_NewStdPrinter(fileno(stderr));
418 if (pstderr == NULL)
419 Py_FatalError("Py_Initialize: can't set preliminary stderr");
420 _PySys_SetObjectId(&PyId_stderr, pstderr);
421 PySys_SetObject("__stderr__", pstderr);
422 Py_DECREF(pstderr);
423
424 _PyImport_Init();
425
426 _PyImportHooks_Init();
427
428 /* Initialize _warnings. */
429 _PyWarnings_Init();
430
431 if (!install_importlib)
432 return;
433
Victor Stinner13019fd2015-04-03 13:10:54 +0200434 if (_PyTime_Init() < 0)
435 Py_FatalError("Py_Initialize: can't initialize time");
436
Nick Coghland6009512014-11-20 21:39:37 +1000437 import_init(interp, sysmod);
438
439 /* initialize the faulthandler module */
440 if (_PyFaulthandler_Init())
441 Py_FatalError("Py_Initialize: can't initialize faulthandler");
442
Nick Coghland6009512014-11-20 21:39:37 +1000443 if (initfsencoding(interp) < 0)
444 Py_FatalError("Py_Initialize: unable to load the file system codec");
445
446 if (install_sigs)
447 initsigs(); /* Signal handling stuff, including initintr() */
448
449 if (_PyTraceMalloc_Init() < 0)
450 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
451
452 initmain(interp); /* Module __main__ */
453 if (initstdio() < 0)
454 Py_FatalError(
455 "Py_Initialize: can't initialize sys standard streams");
456
457 /* Initialize warnings. */
458 if (PySys_HasWarnOptions()) {
459 PyObject *warnings_module = PyImport_ImportModule("warnings");
460 if (warnings_module == NULL) {
461 fprintf(stderr, "'import warnings' failed; traceback:\n");
462 PyErr_Print();
463 }
464 Py_XDECREF(warnings_module);
465 }
466
467 if (!Py_NoSiteFlag)
468 initsite(); /* Module site */
469}
470
471void
472Py_InitializeEx(int install_sigs)
473{
474 _Py_InitializeEx_Private(install_sigs, 1);
475}
476
477void
478Py_Initialize(void)
479{
480 Py_InitializeEx(1);
481}
482
483
484#ifdef COUNT_ALLOCS
485extern void dump_counts(FILE*);
486#endif
487
488/* Flush stdout and stderr */
489
490static int
491file_is_closed(PyObject *fobj)
492{
493 int r;
494 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
495 if (tmp == NULL) {
496 PyErr_Clear();
497 return 0;
498 }
499 r = PyObject_IsTrue(tmp);
500 Py_DECREF(tmp);
501 if (r < 0)
502 PyErr_Clear();
503 return r > 0;
504}
505
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000506static int
Nick Coghland6009512014-11-20 21:39:37 +1000507flush_std_files(void)
508{
509 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
510 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
511 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000512 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000513
514 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700515 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000516 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000517 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000518 status = -1;
519 }
Nick Coghland6009512014-11-20 21:39:37 +1000520 else
521 Py_DECREF(tmp);
522 }
523
524 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700525 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000526 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000527 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000528 status = -1;
529 }
Nick Coghland6009512014-11-20 21:39:37 +1000530 else
531 Py_DECREF(tmp);
532 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000533
534 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000535}
536
537/* Undo the effect of Py_Initialize().
538
539 Beware: if multiple interpreter and/or thread states exist, these
540 are not wiped out; only the current thread and interpreter state
541 are deleted. But since everything else is deleted, those other
542 interpreter and thread states should no longer be used.
543
544 (XXX We should do better, e.g. wipe out all interpreters and
545 threads.)
546
547 Locking: as above.
548
549*/
550
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000551int
552Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000553{
554 PyInterpreterState *interp;
555 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000556 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000557
558 if (!initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000559 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000560
561 wait_for_thread_shutdown();
562
563 /* The interpreter is still entirely intact at this point, and the
564 * exit funcs may be relying on that. In particular, if some thread
565 * or exit func is still waiting to do an import, the import machinery
566 * expects Py_IsInitialized() to return true. So don't say the
567 * interpreter is uninitialized until after the exit funcs have run.
568 * Note that Threading.py uses an exit func to do a join on all the
569 * threads created thru it, so this also protects pending imports in
570 * the threads created via Threading.
571 */
572 call_py_exitfuncs();
573
574 /* Get current thread state and interpreter pointer */
575 tstate = PyThreadState_GET();
576 interp = tstate->interp;
577
578 /* Remaining threads (e.g. daemon threads) will automatically exit
579 after taking the GIL (in PyEval_RestoreThread()). */
580 _Py_Finalizing = tstate;
581 initialized = 0;
582
Victor Stinnere0deff32015-03-24 13:46:18 +0100583 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000584 if (flush_std_files() < 0) {
585 status = -1;
586 }
Nick Coghland6009512014-11-20 21:39:37 +1000587
588 /* Disable signal handling */
589 PyOS_FiniInterrupts();
590
591 /* Collect garbage. This may call finalizers; it's nice to call these
592 * before all modules are destroyed.
593 * XXX If a __del__ or weakref callback is triggered here, and tries to
594 * XXX import a module, bad things can happen, because Python no
595 * XXX longer believes it's initialized.
596 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
597 * XXX is easy to provoke that way. I've also seen, e.g.,
598 * XXX Exception exceptions.ImportError: 'No module named sha'
599 * XXX in <function callback at 0x008F5718> ignored
600 * XXX but I'm unclear on exactly how that one happens. In any case,
601 * XXX I haven't seen a real-life report of either of these.
602 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700603 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000604#ifdef COUNT_ALLOCS
605 /* With COUNT_ALLOCS, it helps to run GC multiple times:
606 each collection might release some types from the type
607 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700608 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000609 /* nothing */;
610#endif
611 /* Destroy all modules */
612 PyImport_Cleanup();
613
Victor Stinnere0deff32015-03-24 13:46:18 +0100614 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000615 if (flush_std_files() < 0) {
616 status = -1;
617 }
Nick Coghland6009512014-11-20 21:39:37 +1000618
619 /* Collect final garbage. This disposes of cycles created by
620 * class definitions, for example.
621 * XXX This is disabled because it caused too many problems. If
622 * XXX a __del__ or weakref callback triggers here, Python code has
623 * XXX a hard time running, because even the sys module has been
624 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
625 * XXX One symptom is a sequence of information-free messages
626 * XXX coming from threads (if a __del__ or callback is invoked,
627 * XXX other threads can execute too, and any exception they encounter
628 * XXX triggers a comedy of errors as subsystem after subsystem
629 * XXX fails to find what it *expects* to find in sys to help report
630 * XXX the exception and consequent unexpected failures). I've also
631 * XXX seen segfaults then, after adding print statements to the
632 * XXX Python code getting called.
633 */
634#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -0700635 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000636#endif
637
638 /* Disable tracemalloc after all Python objects have been destroyed,
639 so it is possible to use tracemalloc in objects destructor. */
640 _PyTraceMalloc_Fini();
641
642 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
643 _PyImport_Fini();
644
645 /* Cleanup typeobject.c's internal caches. */
646 _PyType_Fini();
647
648 /* unload faulthandler module */
649 _PyFaulthandler_Fini();
650
651 /* Debugging stuff */
652#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300653 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +1000654#endif
655 /* dump hash stats */
656 _PyHash_Fini();
657
658 _PY_DEBUG_PRINT_TOTAL_REFS();
659
660#ifdef Py_TRACE_REFS
661 /* Display all objects still alive -- this can invoke arbitrary
662 * __repr__ overrides, so requires a mostly-intact interpreter.
663 * Alas, a lot of stuff may still be alive now that will be cleaned
664 * up later.
665 */
666 if (Py_GETENV("PYTHONDUMPREFS"))
667 _Py_PrintReferences(stderr);
668#endif /* Py_TRACE_REFS */
669
670 /* Clear interpreter state and all thread states. */
671 PyInterpreterState_Clear(interp);
672
673 /* Now we decref the exception classes. After this point nothing
674 can raise an exception. That's okay, because each Fini() method
675 below has been checked to make sure no exceptions are ever
676 raised.
677 */
678
679 _PyExc_Fini();
680
681 /* Sundry finalizers */
682 PyMethod_Fini();
683 PyFrame_Fini();
684 PyCFunction_Fini();
685 PyTuple_Fini();
686 PyList_Fini();
687 PySet_Fini();
688 PyBytes_Fini();
689 PyByteArray_Fini();
690 PyLong_Fini();
691 PyFloat_Fini();
692 PyDict_Fini();
693 PySlice_Fini();
694 _PyGC_Fini();
695 _PyRandom_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +0300696 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -0700697 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +1000698
699 /* Cleanup Unicode implementation */
700 _PyUnicode_Fini();
701
702 /* reset file system default encoding */
703 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
704 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
705 Py_FileSystemDefaultEncoding = NULL;
706 }
707
708 /* XXX Still allocated:
709 - various static ad-hoc pointers to interned strings
710 - int and float free list blocks
711 - whatever various modules and libraries allocate
712 */
713
714 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
715
716 /* Cleanup auto-thread-state */
717#ifdef WITH_THREAD
718 _PyGILState_Fini();
719#endif /* WITH_THREAD */
720
721 /* Delete current thread. After this, many C API calls become crashy. */
722 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +0100723
Nick Coghland6009512014-11-20 21:39:37 +1000724 PyInterpreterState_Delete(interp);
725
726#ifdef Py_TRACE_REFS
727 /* Display addresses (& refcnts) of all objects still alive.
728 * An address can be used to find the repr of the object, printed
729 * above by _Py_PrintReferences.
730 */
731 if (Py_GETENV("PYTHONDUMPREFS"))
732 _Py_PrintReferenceAddresses(stderr);
733#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +0100734#ifdef WITH_PYMALLOC
735 if (_PyMem_PymallocEnabled()) {
736 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
737 if (opt != NULL && *opt != '\0')
738 _PyObject_DebugMallocStats(stderr);
739 }
Nick Coghland6009512014-11-20 21:39:37 +1000740#endif
741
742 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000743 return status;
744}
745
746void
747Py_Finalize(void)
748{
749 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000750}
751
752/* Create and initialize a new interpreter and thread, and return the
753 new thread. This requires that Py_Initialize() has been called
754 first.
755
756 Unsuccessful initialization yields a NULL pointer. Note that *no*
757 exception information is available even in this case -- the
758 exception information is held in the thread, and there is no
759 thread.
760
761 Locking: as above.
762
763*/
764
765PyThreadState *
766Py_NewInterpreter(void)
767{
768 PyInterpreterState *interp;
769 PyThreadState *tstate, *save_tstate;
770 PyObject *bimod, *sysmod;
771
772 if (!initialized)
773 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
774
Victor Stinnerd7292b52016-06-17 12:29:00 +0200775#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +0100776 /* Issue #10915, #15751: The GIL API doesn't work with multiple
777 interpreters: disable PyGILState_Check(). */
778 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +0300779#endif
Victor Stinner8a1be612016-03-14 22:07:55 +0100780
Nick Coghland6009512014-11-20 21:39:37 +1000781 interp = PyInterpreterState_New();
782 if (interp == NULL)
783 return NULL;
784
785 tstate = PyThreadState_New(interp);
786 if (tstate == NULL) {
787 PyInterpreterState_Delete(interp);
788 return NULL;
789 }
790
791 save_tstate = PyThreadState_Swap(tstate);
792
793 /* XXX The following is lax in error checking */
794
795 interp->modules = PyDict_New();
796
797 bimod = _PyImport_FindBuiltin("builtins");
798 if (bimod != NULL) {
799 interp->builtins = PyModule_GetDict(bimod);
800 if (interp->builtins == NULL)
801 goto handle_error;
802 Py_INCREF(interp->builtins);
803 }
804
805 /* initialize builtin exceptions */
806 _PyExc_Init(bimod);
807
808 sysmod = _PyImport_FindBuiltin("sys");
809 if (bimod != NULL && sysmod != NULL) {
810 PyObject *pstderr;
811
812 interp->sysdict = PyModule_GetDict(sysmod);
813 if (interp->sysdict == NULL)
814 goto handle_error;
815 Py_INCREF(interp->sysdict);
816 PySys_SetPath(Py_GetPath());
817 PyDict_SetItemString(interp->sysdict, "modules",
818 interp->modules);
819 /* Set up a preliminary stderr printer until we have enough
820 infrastructure for the io module in place. */
821 pstderr = PyFile_NewStdPrinter(fileno(stderr));
822 if (pstderr == NULL)
823 Py_FatalError("Py_Initialize: can't set preliminary stderr");
824 _PySys_SetObjectId(&PyId_stderr, pstderr);
825 PySys_SetObject("__stderr__", pstderr);
826 Py_DECREF(pstderr);
827
828 _PyImportHooks_Init();
829
830 import_init(interp, sysmod);
831
832 if (initfsencoding(interp) < 0)
833 goto handle_error;
834
835 if (initstdio() < 0)
836 Py_FatalError(
Georg Brandl4b5b0622016-01-18 08:00:15 +0100837 "Py_Initialize: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000838 initmain(interp);
839 if (!Py_NoSiteFlag)
840 initsite();
841 }
842
843 if (!PyErr_Occurred())
844 return tstate;
845
846handle_error:
847 /* Oops, it didn't work. Undo it all. */
848
849 PyErr_PrintEx(0);
850 PyThreadState_Clear(tstate);
851 PyThreadState_Swap(save_tstate);
852 PyThreadState_Delete(tstate);
853 PyInterpreterState_Delete(interp);
854
855 return NULL;
856}
857
858/* Delete an interpreter and its last thread. This requires that the
859 given thread state is current, that the thread has no remaining
860 frames, and that it is its interpreter's only remaining thread.
861 It is a fatal error to violate these constraints.
862
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000863 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +1000864 everything, regardless.)
865
866 Locking: as above.
867
868*/
869
870void
871Py_EndInterpreter(PyThreadState *tstate)
872{
873 PyInterpreterState *interp = tstate->interp;
874
875 if (tstate != PyThreadState_GET())
876 Py_FatalError("Py_EndInterpreter: thread is not current");
877 if (tstate->frame != NULL)
878 Py_FatalError("Py_EndInterpreter: thread still has a frame");
879
880 wait_for_thread_shutdown();
881
882 if (tstate != interp->tstate_head || tstate->next != NULL)
883 Py_FatalError("Py_EndInterpreter: not the last thread");
884
885 PyImport_Cleanup();
886 PyInterpreterState_Clear(interp);
887 PyThreadState_Swap(NULL);
888 PyInterpreterState_Delete(interp);
889}
890
891#ifdef MS_WINDOWS
892static wchar_t *progname = L"python";
893#else
894static wchar_t *progname = L"python3";
895#endif
896
897void
898Py_SetProgramName(wchar_t *pn)
899{
900 if (pn && *pn)
901 progname = pn;
902}
903
904wchar_t *
905Py_GetProgramName(void)
906{
907 return progname;
908}
909
910static wchar_t *default_home = NULL;
911static wchar_t env_home[MAXPATHLEN+1];
912
913void
914Py_SetPythonHome(wchar_t *home)
915{
916 default_home = home;
917}
918
919wchar_t *
920Py_GetPythonHome(void)
921{
922 wchar_t *home = default_home;
923 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
924 char* chome = Py_GETENV("PYTHONHOME");
925 if (chome) {
926 size_t size = Py_ARRAY_LENGTH(env_home);
927 size_t r = mbstowcs(env_home, chome, size);
928 if (r != (size_t)-1 && r < size)
929 home = env_home;
930 }
931
932 }
933 return home;
934}
935
936/* Create __main__ module */
937
938static void
939initmain(PyInterpreterState *interp)
940{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700941 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +1000942 m = PyImport_AddModule("__main__");
943 if (m == NULL)
944 Py_FatalError("can't create __main__ module");
945 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700946 ann_dict = PyDict_New();
947 if ((ann_dict == NULL) ||
948 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
949 Py_FatalError("Failed to initialize __main__.__annotations__");
950 }
951 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +1000952 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
953 PyObject *bimod = PyImport_ImportModule("builtins");
954 if (bimod == NULL) {
955 Py_FatalError("Failed to retrieve builtins module");
956 }
957 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
958 Py_FatalError("Failed to initialize __main__.__builtins__");
959 }
960 Py_DECREF(bimod);
961 }
962 /* Main is a little special - imp.is_builtin("__main__") will return
963 * False, but BuiltinImporter is still the most appropriate initial
964 * setting for its __loader__ attribute. A more suitable value will
965 * be set if __main__ gets further initialized later in the startup
966 * process.
967 */
968 loader = PyDict_GetItemString(d, "__loader__");
969 if (loader == NULL || loader == Py_None) {
970 PyObject *loader = PyObject_GetAttrString(interp->importlib,
971 "BuiltinImporter");
972 if (loader == NULL) {
973 Py_FatalError("Failed to retrieve BuiltinImporter");
974 }
975 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
976 Py_FatalError("Failed to initialize __main__.__loader__");
977 }
978 Py_DECREF(loader);
979 }
980}
981
982static int
983initfsencoding(PyInterpreterState *interp)
984{
985 PyObject *codec;
986
Steve Dowercc16be82016-09-08 10:35:16 -0700987#ifdef MS_WINDOWS
988 if (Py_LegacyWindowsFSEncodingFlag)
989 {
990 Py_FileSystemDefaultEncoding = "mbcs";
991 Py_FileSystemDefaultEncodeErrors = "replace";
992 }
993 else
994 {
995 Py_FileSystemDefaultEncoding = "utf-8";
996 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
997 }
998#else
Nick Coghland6009512014-11-20 21:39:37 +1000999 if (Py_FileSystemDefaultEncoding == NULL)
1000 {
1001 Py_FileSystemDefaultEncoding = get_locale_encoding();
1002 if (Py_FileSystemDefaultEncoding == NULL)
1003 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1004
1005 Py_HasFileSystemDefaultEncoding = 0;
1006 interp->fscodec_initialized = 1;
1007 return 0;
1008 }
Steve Dowercc16be82016-09-08 10:35:16 -07001009#endif
Nick Coghland6009512014-11-20 21:39:37 +10001010
1011 /* the encoding is mbcs, utf-8 or ascii */
1012 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1013 if (!codec) {
1014 /* Such error can only occurs in critical situations: no more
1015 * memory, import a module of the standard library failed,
1016 * etc. */
1017 return -1;
1018 }
1019 Py_DECREF(codec);
1020 interp->fscodec_initialized = 1;
1021 return 0;
1022}
1023
1024/* Import the site module (not into __main__ though) */
1025
1026static void
1027initsite(void)
1028{
1029 PyObject *m;
1030 m = PyImport_ImportModule("site");
1031 if (m == NULL) {
1032 fprintf(stderr, "Failed to import the site module\n");
1033 PyErr_Print();
1034 Py_Finalize();
1035 exit(1);
1036 }
1037 else {
1038 Py_DECREF(m);
1039 }
1040}
1041
Victor Stinner874dbe82015-09-04 17:29:57 +02001042/* Check if a file descriptor is valid or not.
1043 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1044static int
1045is_valid_fd(int fd)
1046{
Victor Stinner31906b42017-05-04 13:21:10 +02001047#ifdef __APPLE__
1048 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1049 and the other side of the pipe is closed, dup(1) succeed, whereas
1050 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1051 such error. */
1052 struct stat st;
1053 return (fstat(fd, &st) == 0);
1054#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001055 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001056 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001057 return 0;
1058 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001059 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1060 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1061 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001062 fd2 = dup(fd);
1063 if (fd2 >= 0)
1064 close(fd2);
1065 _Py_END_SUPPRESS_IPH
1066 return fd2 >= 0;
Victor Stinner31906b42017-05-04 13:21:10 +02001067#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001068}
1069
1070/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001071static PyObject*
1072create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001073 int fd, int write_mode, const char* name,
1074 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001075{
1076 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1077 const char* mode;
1078 const char* newline;
1079 PyObject *line_buffering;
1080 int buffering, isatty;
1081 _Py_IDENTIFIER(open);
1082 _Py_IDENTIFIER(isatty);
1083 _Py_IDENTIFIER(TextIOWrapper);
1084 _Py_IDENTIFIER(mode);
1085
Victor Stinner874dbe82015-09-04 17:29:57 +02001086 if (!is_valid_fd(fd))
1087 Py_RETURN_NONE;
1088
Nick Coghland6009512014-11-20 21:39:37 +10001089 /* stdin is always opened in buffered mode, first because it shouldn't
1090 make a difference in common use cases, second because TextIOWrapper
1091 depends on the presence of a read1() method which only exists on
1092 buffered streams.
1093 */
1094 if (Py_UnbufferedStdioFlag && write_mode)
1095 buffering = 0;
1096 else
1097 buffering = -1;
1098 if (write_mode)
1099 mode = "wb";
1100 else
1101 mode = "rb";
1102 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1103 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001104 Py_None, Py_None, /* encoding, errors */
1105 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001106 if (buf == NULL)
1107 goto error;
1108
1109 if (buffering) {
1110 _Py_IDENTIFIER(raw);
1111 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1112 if (raw == NULL)
1113 goto error;
1114 }
1115 else {
1116 raw = buf;
1117 Py_INCREF(raw);
1118 }
1119
Steve Dower39294992016-08-30 21:22:36 -07001120#ifdef MS_WINDOWS
1121 /* Windows console IO is always UTF-8 encoded */
1122 if (PyWindowsConsoleIO_Check(raw))
1123 encoding = "utf-8";
1124#endif
1125
Nick Coghland6009512014-11-20 21:39:37 +10001126 text = PyUnicode_FromString(name);
1127 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1128 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001129 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001130 if (res == NULL)
1131 goto error;
1132 isatty = PyObject_IsTrue(res);
1133 Py_DECREF(res);
1134 if (isatty == -1)
1135 goto error;
1136 if (isatty || Py_UnbufferedStdioFlag)
1137 line_buffering = Py_True;
1138 else
1139 line_buffering = Py_False;
1140
1141 Py_CLEAR(raw);
1142 Py_CLEAR(text);
1143
1144#ifdef MS_WINDOWS
1145 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1146 newlines to "\n".
1147 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1148 newline = NULL;
1149#else
1150 /* sys.stdin: split lines at "\n".
1151 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1152 newline = "\n";
1153#endif
1154
1155 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1156 buf, encoding, errors,
1157 newline, line_buffering);
1158 Py_CLEAR(buf);
1159 if (stream == NULL)
1160 goto error;
1161
1162 if (write_mode)
1163 mode = "w";
1164 else
1165 mode = "r";
1166 text = PyUnicode_FromString(mode);
1167 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1168 goto error;
1169 Py_CLEAR(text);
1170 return stream;
1171
1172error:
1173 Py_XDECREF(buf);
1174 Py_XDECREF(stream);
1175 Py_XDECREF(text);
1176 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001177
Victor Stinner874dbe82015-09-04 17:29:57 +02001178 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1179 /* Issue #24891: the file descriptor was closed after the first
1180 is_valid_fd() check was called. Ignore the OSError and set the
1181 stream to None. */
1182 PyErr_Clear();
1183 Py_RETURN_NONE;
1184 }
1185 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001186}
1187
1188/* Initialize sys.stdin, stdout, stderr and builtins.open */
1189static int
1190initstdio(void)
1191{
1192 PyObject *iomod = NULL, *wrapper;
1193 PyObject *bimod = NULL;
1194 PyObject *m;
1195 PyObject *std = NULL;
1196 int status = 0, fd;
1197 PyObject * encoding_attr;
1198 char *pythonioencoding = NULL, *encoding, *errors;
1199
1200 /* Hack to avoid a nasty recursion issue when Python is invoked
1201 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1202 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1203 goto error;
1204 }
1205 Py_DECREF(m);
1206
1207 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1208 goto error;
1209 }
1210 Py_DECREF(m);
1211
1212 if (!(bimod = PyImport_ImportModule("builtins"))) {
1213 goto error;
1214 }
1215
1216 if (!(iomod = PyImport_ImportModule("io"))) {
1217 goto error;
1218 }
1219 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1220 goto error;
1221 }
1222
1223 /* Set builtins.open */
1224 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1225 Py_DECREF(wrapper);
1226 goto error;
1227 }
1228 Py_DECREF(wrapper);
1229
1230 encoding = _Py_StandardStreamEncoding;
1231 errors = _Py_StandardStreamErrors;
1232 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001233 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1234 if (pythonioencoding) {
1235 char *err;
1236 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1237 if (pythonioencoding == NULL) {
1238 PyErr_NoMemory();
1239 goto error;
1240 }
1241 err = strchr(pythonioencoding, ':');
1242 if (err) {
1243 *err = '\0';
1244 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001245 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001246 errors = err;
1247 }
1248 }
1249 if (*pythonioencoding && !encoding) {
1250 encoding = pythonioencoding;
1251 }
1252 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001253 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1254 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1255 stdin and stdout use the surrogateescape error handler by
1256 default, instead of the strict error handler. */
1257 char *loc = setlocale(LC_CTYPE, NULL);
1258 if (loc != NULL && strcmp(loc, "C") == 0)
1259 errors = "surrogateescape";
1260 }
Nick Coghland6009512014-11-20 21:39:37 +10001261 }
1262
1263 /* Set sys.stdin */
1264 fd = fileno(stdin);
1265 /* Under some conditions stdin, stdout and stderr may not be connected
1266 * and fileno() may point to an invalid file descriptor. For example
1267 * GUI apps don't have valid standard streams by default.
1268 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001269 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1270 if (std == NULL)
1271 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001272 PySys_SetObject("__stdin__", std);
1273 _PySys_SetObjectId(&PyId_stdin, std);
1274 Py_DECREF(std);
1275
1276 /* Set sys.stdout */
1277 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001278 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1279 if (std == NULL)
1280 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001281 PySys_SetObject("__stdout__", std);
1282 _PySys_SetObjectId(&PyId_stdout, std);
1283 Py_DECREF(std);
1284
1285#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1286 /* Set sys.stderr, replaces the preliminary stderr */
1287 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001288 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1289 if (std == NULL)
1290 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001291
1292 /* Same as hack above, pre-import stderr's codec to avoid recursion
1293 when import.c tries to write to stderr in verbose mode. */
1294 encoding_attr = PyObject_GetAttrString(std, "encoding");
1295 if (encoding_attr != NULL) {
1296 const char * std_encoding;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001297 std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001298 if (std_encoding != NULL) {
1299 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1300 Py_XDECREF(codec_info);
1301 }
1302 Py_DECREF(encoding_attr);
1303 }
1304 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1305
1306 if (PySys_SetObject("__stderr__", std) < 0) {
1307 Py_DECREF(std);
1308 goto error;
1309 }
1310 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1311 Py_DECREF(std);
1312 goto error;
1313 }
1314 Py_DECREF(std);
1315#endif
1316
1317 if (0) {
1318 error:
1319 status = -1;
1320 }
1321
1322 /* We won't need them anymore. */
1323 if (_Py_StandardStreamEncoding) {
1324 PyMem_RawFree(_Py_StandardStreamEncoding);
1325 _Py_StandardStreamEncoding = NULL;
1326 }
1327 if (_Py_StandardStreamErrors) {
1328 PyMem_RawFree(_Py_StandardStreamErrors);
1329 _Py_StandardStreamErrors = NULL;
1330 }
1331 PyMem_Free(pythonioencoding);
1332 Py_XDECREF(bimod);
1333 Py_XDECREF(iomod);
1334 return status;
1335}
1336
1337
Victor Stinner10dc4842015-03-24 12:01:30 +01001338static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001339_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001340{
Victor Stinner10dc4842015-03-24 12:01:30 +01001341 fputc('\n', stderr);
1342 fflush(stderr);
1343
1344 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001345 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001346}
Victor Stinner791da1c2016-03-14 16:53:12 +01001347
1348/* Print the current exception (if an exception is set) with its traceback,
1349 or display the current Python stack.
1350
1351 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1352 called on catastrophic cases.
1353
1354 Return 1 if the traceback was displayed, 0 otherwise. */
1355
1356static int
1357_Py_FatalError_PrintExc(int fd)
1358{
1359 PyObject *ferr, *res;
1360 PyObject *exception, *v, *tb;
1361 int has_tb;
1362
1363 if (PyThreadState_GET() == NULL) {
1364 /* The GIL is released: trying to acquire it is likely to deadlock,
1365 just give up. */
1366 return 0;
1367 }
1368
1369 PyErr_Fetch(&exception, &v, &tb);
1370 if (exception == NULL) {
1371 /* No current exception */
1372 return 0;
1373 }
1374
1375 ferr = _PySys_GetObjectId(&PyId_stderr);
1376 if (ferr == NULL || ferr == Py_None) {
1377 /* sys.stderr is not set yet or set to None,
1378 no need to try to display the exception */
1379 return 0;
1380 }
1381
1382 PyErr_NormalizeException(&exception, &v, &tb);
1383 if (tb == NULL) {
1384 tb = Py_None;
1385 Py_INCREF(tb);
1386 }
1387 PyException_SetTraceback(v, tb);
1388 if (exception == NULL) {
1389 /* PyErr_NormalizeException() failed */
1390 return 0;
1391 }
1392
1393 has_tb = (tb != Py_None);
1394 PyErr_Display(exception, v, tb);
1395 Py_XDECREF(exception);
1396 Py_XDECREF(v);
1397 Py_XDECREF(tb);
1398
1399 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001400 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001401 if (res == NULL)
1402 PyErr_Clear();
1403 else
1404 Py_DECREF(res);
1405
1406 return has_tb;
1407}
1408
Nick Coghland6009512014-11-20 21:39:37 +10001409/* Print fatal error message and abort */
1410
1411void
1412Py_FatalError(const char *msg)
1413{
1414 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001415 static int reentrant = 0;
1416#ifdef MS_WINDOWS
1417 size_t len;
1418 WCHAR* buffer;
1419 size_t i;
1420#endif
1421
1422 if (reentrant) {
1423 /* Py_FatalError() caused a second fatal error.
1424 Example: flush_std_files() raises a recursion error. */
1425 goto exit;
1426 }
1427 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001428
1429 fprintf(stderr, "Fatal Python error: %s\n", msg);
1430 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001431
Victor Stinnere0deff32015-03-24 13:46:18 +01001432 /* Print the exception (if an exception is set) with its traceback,
1433 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001434 if (!_Py_FatalError_PrintExc(fd))
1435 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001436
Victor Stinner2025d782016-03-16 23:19:15 +01001437 /* The main purpose of faulthandler is to display the traceback. We already
1438 * did our best to display it. So faulthandler can now be disabled.
1439 * (Don't trigger it on abort().) */
1440 _PyFaulthandler_Fini();
1441
Victor Stinner791da1c2016-03-14 16:53:12 +01001442 /* Check if the current Python thread hold the GIL */
1443 if (PyThreadState_GET() != NULL) {
1444 /* Flush sys.stdout and sys.stderr */
1445 flush_std_files();
1446 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001447
Nick Coghland6009512014-11-20 21:39:37 +10001448#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001449 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001450
Victor Stinner53345a42015-03-25 01:55:14 +01001451 /* Convert the message to wchar_t. This uses a simple one-to-one
1452 conversion, assuming that the this error message actually uses ASCII
1453 only. If this ceases to be true, we will have to convert. */
1454 buffer = alloca( (len+1) * (sizeof *buffer));
1455 for( i=0; i<=len; ++i)
1456 buffer[i] = msg[i];
1457 OutputDebugStringW(L"Fatal Python error: ");
1458 OutputDebugStringW(buffer);
1459 OutputDebugStringW(L"\n");
1460#endif /* MS_WINDOWS */
1461
1462exit:
1463#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001464 DebugBreak();
1465#endif
Nick Coghland6009512014-11-20 21:39:37 +10001466 abort();
1467}
1468
1469/* Clean up and exit */
1470
1471#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001472# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001473#endif
1474
1475static void (*pyexitfunc)(void) = NULL;
1476/* For the atexit module. */
1477void _Py_PyAtExit(void (*func)(void))
1478{
1479 pyexitfunc = func;
1480}
1481
1482static void
1483call_py_exitfuncs(void)
1484{
1485 if (pyexitfunc == NULL)
1486 return;
1487
1488 (*pyexitfunc)();
1489 PyErr_Clear();
1490}
1491
1492/* Wait until threading._shutdown completes, provided
1493 the threading module was imported in the first place.
1494 The shutdown routine will wait until all non-daemon
1495 "threading" threads have completed. */
1496static void
1497wait_for_thread_shutdown(void)
1498{
1499#ifdef WITH_THREAD
1500 _Py_IDENTIFIER(_shutdown);
1501 PyObject *result;
1502 PyThreadState *tstate = PyThreadState_GET();
1503 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1504 "threading");
1505 if (threading == NULL) {
1506 /* threading not imported */
1507 PyErr_Clear();
1508 return;
1509 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001510 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001511 if (result == NULL) {
1512 PyErr_WriteUnraisable(threading);
1513 }
1514 else {
1515 Py_DECREF(result);
1516 }
1517 Py_DECREF(threading);
1518#endif
1519}
1520
1521#define NEXITFUNCS 32
1522static void (*exitfuncs[NEXITFUNCS])(void);
1523static int nexitfuncs = 0;
1524
1525int Py_AtExit(void (*func)(void))
1526{
1527 if (nexitfuncs >= NEXITFUNCS)
1528 return -1;
1529 exitfuncs[nexitfuncs++] = func;
1530 return 0;
1531}
1532
1533static void
1534call_ll_exitfuncs(void)
1535{
1536 while (nexitfuncs > 0)
1537 (*exitfuncs[--nexitfuncs])();
1538
1539 fflush(stdout);
1540 fflush(stderr);
1541}
1542
1543void
1544Py_Exit(int sts)
1545{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001546 if (Py_FinalizeEx() < 0) {
1547 sts = 120;
1548 }
Nick Coghland6009512014-11-20 21:39:37 +10001549
1550 exit(sts);
1551}
1552
1553static void
1554initsigs(void)
1555{
1556#ifdef SIGPIPE
1557 PyOS_setsig(SIGPIPE, SIG_IGN);
1558#endif
1559#ifdef SIGXFZ
1560 PyOS_setsig(SIGXFZ, SIG_IGN);
1561#endif
1562#ifdef SIGXFSZ
1563 PyOS_setsig(SIGXFSZ, SIG_IGN);
1564#endif
1565 PyOS_InitInterrupts(); /* May imply initsignal() */
1566 if (PyErr_Occurred()) {
1567 Py_FatalError("Py_Initialize: can't import signal");
1568 }
1569}
1570
1571
1572/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1573 *
1574 * All of the code in this function must only use async-signal-safe functions,
1575 * listed at `man 7 signal` or
1576 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1577 */
1578void
1579_Py_RestoreSignals(void)
1580{
1581#ifdef SIGPIPE
1582 PyOS_setsig(SIGPIPE, SIG_DFL);
1583#endif
1584#ifdef SIGXFZ
1585 PyOS_setsig(SIGXFZ, SIG_DFL);
1586#endif
1587#ifdef SIGXFSZ
1588 PyOS_setsig(SIGXFSZ, SIG_DFL);
1589#endif
1590}
1591
1592
1593/*
1594 * The file descriptor fd is considered ``interactive'' if either
1595 * a) isatty(fd) is TRUE, or
1596 * b) the -i flag was given, and the filename associated with
1597 * the descriptor is NULL or "<stdin>" or "???".
1598 */
1599int
1600Py_FdIsInteractive(FILE *fp, const char *filename)
1601{
1602 if (isatty((int)fileno(fp)))
1603 return 1;
1604 if (!Py_InteractiveFlag)
1605 return 0;
1606 return (filename == NULL) ||
1607 (strcmp(filename, "<stdin>") == 0) ||
1608 (strcmp(filename, "???") == 0);
1609}
1610
1611
Nick Coghland6009512014-11-20 21:39:37 +10001612/* Wrappers around sigaction() or signal(). */
1613
1614PyOS_sighandler_t
1615PyOS_getsig(int sig)
1616{
1617#ifdef HAVE_SIGACTION
1618 struct sigaction context;
1619 if (sigaction(sig, NULL, &context) == -1)
1620 return SIG_ERR;
1621 return context.sa_handler;
1622#else
1623 PyOS_sighandler_t handler;
1624/* Special signal handling for the secure CRT in Visual Studio 2005 */
1625#if defined(_MSC_VER) && _MSC_VER >= 1400
1626 switch (sig) {
1627 /* Only these signals are valid */
1628 case SIGINT:
1629 case SIGILL:
1630 case SIGFPE:
1631 case SIGSEGV:
1632 case SIGTERM:
1633 case SIGBREAK:
1634 case SIGABRT:
1635 break;
1636 /* Don't call signal() with other values or it will assert */
1637 default:
1638 return SIG_ERR;
1639 }
1640#endif /* _MSC_VER && _MSC_VER >= 1400 */
1641 handler = signal(sig, SIG_IGN);
1642 if (handler != SIG_ERR)
1643 signal(sig, handler);
1644 return handler;
1645#endif
1646}
1647
1648/*
1649 * All of the code in this function must only use async-signal-safe functions,
1650 * listed at `man 7 signal` or
1651 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1652 */
1653PyOS_sighandler_t
1654PyOS_setsig(int sig, PyOS_sighandler_t handler)
1655{
1656#ifdef HAVE_SIGACTION
1657 /* Some code in Modules/signalmodule.c depends on sigaction() being
1658 * used here if HAVE_SIGACTION is defined. Fix that if this code
1659 * changes to invalidate that assumption.
1660 */
1661 struct sigaction context, ocontext;
1662 context.sa_handler = handler;
1663 sigemptyset(&context.sa_mask);
1664 context.sa_flags = 0;
1665 if (sigaction(sig, &context, &ocontext) == -1)
1666 return SIG_ERR;
1667 return ocontext.sa_handler;
1668#else
1669 PyOS_sighandler_t oldhandler;
1670 oldhandler = signal(sig, handler);
1671#ifdef HAVE_SIGINTERRUPT
1672 siginterrupt(sig, 1);
1673#endif
1674 return oldhandler;
1675#endif
1676}
1677
1678#ifdef __cplusplus
1679}
1680#endif