blob: a4f7f823bc695dd82e431cd6573389eae6d89dc4 [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 */
91int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
92int 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{
1047 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001048 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001049 return 0;
1050 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001051 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1052 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1053 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001054 fd2 = dup(fd);
1055 if (fd2 >= 0)
1056 close(fd2);
1057 _Py_END_SUPPRESS_IPH
1058 return fd2 >= 0;
1059}
1060
1061/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001062static PyObject*
1063create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001064 int fd, int write_mode, const char* name,
1065 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001066{
1067 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1068 const char* mode;
1069 const char* newline;
1070 PyObject *line_buffering;
1071 int buffering, isatty;
1072 _Py_IDENTIFIER(open);
1073 _Py_IDENTIFIER(isatty);
1074 _Py_IDENTIFIER(TextIOWrapper);
1075 _Py_IDENTIFIER(mode);
1076
Victor Stinner874dbe82015-09-04 17:29:57 +02001077 if (!is_valid_fd(fd))
1078 Py_RETURN_NONE;
1079
Nick Coghland6009512014-11-20 21:39:37 +10001080 /* stdin is always opened in buffered mode, first because it shouldn't
1081 make a difference in common use cases, second because TextIOWrapper
1082 depends on the presence of a read1() method which only exists on
1083 buffered streams.
1084 */
1085 if (Py_UnbufferedStdioFlag && write_mode)
1086 buffering = 0;
1087 else
1088 buffering = -1;
1089 if (write_mode)
1090 mode = "wb";
1091 else
1092 mode = "rb";
1093 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1094 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001095 Py_None, Py_None, /* encoding, errors */
1096 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001097 if (buf == NULL)
1098 goto error;
1099
1100 if (buffering) {
1101 _Py_IDENTIFIER(raw);
1102 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1103 if (raw == NULL)
1104 goto error;
1105 }
1106 else {
1107 raw = buf;
1108 Py_INCREF(raw);
1109 }
1110
Steve Dower39294992016-08-30 21:22:36 -07001111#ifdef MS_WINDOWS
1112 /* Windows console IO is always UTF-8 encoded */
1113 if (PyWindowsConsoleIO_Check(raw))
1114 encoding = "utf-8";
1115#endif
1116
Nick Coghland6009512014-11-20 21:39:37 +10001117 text = PyUnicode_FromString(name);
1118 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1119 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001120 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001121 if (res == NULL)
1122 goto error;
1123 isatty = PyObject_IsTrue(res);
1124 Py_DECREF(res);
1125 if (isatty == -1)
1126 goto error;
1127 if (isatty || Py_UnbufferedStdioFlag)
1128 line_buffering = Py_True;
1129 else
1130 line_buffering = Py_False;
1131
1132 Py_CLEAR(raw);
1133 Py_CLEAR(text);
1134
1135#ifdef MS_WINDOWS
1136 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1137 newlines to "\n".
1138 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1139 newline = NULL;
1140#else
1141 /* sys.stdin: split lines at "\n".
1142 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1143 newline = "\n";
1144#endif
1145
1146 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1147 buf, encoding, errors,
1148 newline, line_buffering);
1149 Py_CLEAR(buf);
1150 if (stream == NULL)
1151 goto error;
1152
1153 if (write_mode)
1154 mode = "w";
1155 else
1156 mode = "r";
1157 text = PyUnicode_FromString(mode);
1158 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1159 goto error;
1160 Py_CLEAR(text);
1161 return stream;
1162
1163error:
1164 Py_XDECREF(buf);
1165 Py_XDECREF(stream);
1166 Py_XDECREF(text);
1167 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001168
Victor Stinner874dbe82015-09-04 17:29:57 +02001169 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1170 /* Issue #24891: the file descriptor was closed after the first
1171 is_valid_fd() check was called. Ignore the OSError and set the
1172 stream to None. */
1173 PyErr_Clear();
1174 Py_RETURN_NONE;
1175 }
1176 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001177}
1178
1179/* Initialize sys.stdin, stdout, stderr and builtins.open */
1180static int
1181initstdio(void)
1182{
1183 PyObject *iomod = NULL, *wrapper;
1184 PyObject *bimod = NULL;
1185 PyObject *m;
1186 PyObject *std = NULL;
1187 int status = 0, fd;
1188 PyObject * encoding_attr;
1189 char *pythonioencoding = NULL, *encoding, *errors;
1190
1191 /* Hack to avoid a nasty recursion issue when Python is invoked
1192 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1193 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1194 goto error;
1195 }
1196 Py_DECREF(m);
1197
1198 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1199 goto error;
1200 }
1201 Py_DECREF(m);
1202
1203 if (!(bimod = PyImport_ImportModule("builtins"))) {
1204 goto error;
1205 }
1206
1207 if (!(iomod = PyImport_ImportModule("io"))) {
1208 goto error;
1209 }
1210 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1211 goto error;
1212 }
1213
1214 /* Set builtins.open */
1215 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1216 Py_DECREF(wrapper);
1217 goto error;
1218 }
1219 Py_DECREF(wrapper);
1220
1221 encoding = _Py_StandardStreamEncoding;
1222 errors = _Py_StandardStreamErrors;
1223 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001224 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1225 if (pythonioencoding) {
1226 char *err;
1227 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1228 if (pythonioencoding == NULL) {
1229 PyErr_NoMemory();
1230 goto error;
1231 }
1232 err = strchr(pythonioencoding, ':');
1233 if (err) {
1234 *err = '\0';
1235 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001236 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001237 errors = err;
1238 }
1239 }
1240 if (*pythonioencoding && !encoding) {
1241 encoding = pythonioencoding;
1242 }
1243 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001244 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1245 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1246 stdin and stdout use the surrogateescape error handler by
1247 default, instead of the strict error handler. */
1248 char *loc = setlocale(LC_CTYPE, NULL);
1249 if (loc != NULL && strcmp(loc, "C") == 0)
1250 errors = "surrogateescape";
1251 }
Nick Coghland6009512014-11-20 21:39:37 +10001252 }
1253
1254 /* Set sys.stdin */
1255 fd = fileno(stdin);
1256 /* Under some conditions stdin, stdout and stderr may not be connected
1257 * and fileno() may point to an invalid file descriptor. For example
1258 * GUI apps don't have valid standard streams by default.
1259 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001260 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1261 if (std == NULL)
1262 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001263 PySys_SetObject("__stdin__", std);
1264 _PySys_SetObjectId(&PyId_stdin, std);
1265 Py_DECREF(std);
1266
1267 /* Set sys.stdout */
1268 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001269 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1270 if (std == NULL)
1271 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001272 PySys_SetObject("__stdout__", std);
1273 _PySys_SetObjectId(&PyId_stdout, std);
1274 Py_DECREF(std);
1275
1276#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1277 /* Set sys.stderr, replaces the preliminary stderr */
1278 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001279 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1280 if (std == NULL)
1281 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001282
1283 /* Same as hack above, pre-import stderr's codec to avoid recursion
1284 when import.c tries to write to stderr in verbose mode. */
1285 encoding_attr = PyObject_GetAttrString(std, "encoding");
1286 if (encoding_attr != NULL) {
1287 const char * std_encoding;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001288 std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001289 if (std_encoding != NULL) {
1290 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1291 Py_XDECREF(codec_info);
1292 }
1293 Py_DECREF(encoding_attr);
1294 }
1295 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1296
1297 if (PySys_SetObject("__stderr__", std) < 0) {
1298 Py_DECREF(std);
1299 goto error;
1300 }
1301 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1302 Py_DECREF(std);
1303 goto error;
1304 }
1305 Py_DECREF(std);
1306#endif
1307
1308 if (0) {
1309 error:
1310 status = -1;
1311 }
1312
1313 /* We won't need them anymore. */
1314 if (_Py_StandardStreamEncoding) {
1315 PyMem_RawFree(_Py_StandardStreamEncoding);
1316 _Py_StandardStreamEncoding = NULL;
1317 }
1318 if (_Py_StandardStreamErrors) {
1319 PyMem_RawFree(_Py_StandardStreamErrors);
1320 _Py_StandardStreamErrors = NULL;
1321 }
1322 PyMem_Free(pythonioencoding);
1323 Py_XDECREF(bimod);
1324 Py_XDECREF(iomod);
1325 return status;
1326}
1327
1328
Victor Stinner10dc4842015-03-24 12:01:30 +01001329static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001330_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001331{
Victor Stinner10dc4842015-03-24 12:01:30 +01001332 fputc('\n', stderr);
1333 fflush(stderr);
1334
1335 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001336 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001337}
Victor Stinner791da1c2016-03-14 16:53:12 +01001338
1339/* Print the current exception (if an exception is set) with its traceback,
1340 or display the current Python stack.
1341
1342 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1343 called on catastrophic cases.
1344
1345 Return 1 if the traceback was displayed, 0 otherwise. */
1346
1347static int
1348_Py_FatalError_PrintExc(int fd)
1349{
1350 PyObject *ferr, *res;
1351 PyObject *exception, *v, *tb;
1352 int has_tb;
1353
1354 if (PyThreadState_GET() == NULL) {
1355 /* The GIL is released: trying to acquire it is likely to deadlock,
1356 just give up. */
1357 return 0;
1358 }
1359
1360 PyErr_Fetch(&exception, &v, &tb);
1361 if (exception == NULL) {
1362 /* No current exception */
1363 return 0;
1364 }
1365
1366 ferr = _PySys_GetObjectId(&PyId_stderr);
1367 if (ferr == NULL || ferr == Py_None) {
1368 /* sys.stderr is not set yet or set to None,
1369 no need to try to display the exception */
1370 return 0;
1371 }
1372
1373 PyErr_NormalizeException(&exception, &v, &tb);
1374 if (tb == NULL) {
1375 tb = Py_None;
1376 Py_INCREF(tb);
1377 }
1378 PyException_SetTraceback(v, tb);
1379 if (exception == NULL) {
1380 /* PyErr_NormalizeException() failed */
1381 return 0;
1382 }
1383
1384 has_tb = (tb != Py_None);
1385 PyErr_Display(exception, v, tb);
1386 Py_XDECREF(exception);
1387 Py_XDECREF(v);
1388 Py_XDECREF(tb);
1389
1390 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001391 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001392 if (res == NULL)
1393 PyErr_Clear();
1394 else
1395 Py_DECREF(res);
1396
1397 return has_tb;
1398}
1399
Nick Coghland6009512014-11-20 21:39:37 +10001400/* Print fatal error message and abort */
1401
1402void
1403Py_FatalError(const char *msg)
1404{
1405 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001406 static int reentrant = 0;
1407#ifdef MS_WINDOWS
1408 size_t len;
1409 WCHAR* buffer;
1410 size_t i;
1411#endif
1412
1413 if (reentrant) {
1414 /* Py_FatalError() caused a second fatal error.
1415 Example: flush_std_files() raises a recursion error. */
1416 goto exit;
1417 }
1418 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001419
1420 fprintf(stderr, "Fatal Python error: %s\n", msg);
1421 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001422
Victor Stinnere0deff32015-03-24 13:46:18 +01001423 /* Print the exception (if an exception is set) with its traceback,
1424 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001425 if (!_Py_FatalError_PrintExc(fd))
1426 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001427
Victor Stinner2025d782016-03-16 23:19:15 +01001428 /* The main purpose of faulthandler is to display the traceback. We already
1429 * did our best to display it. So faulthandler can now be disabled.
1430 * (Don't trigger it on abort().) */
1431 _PyFaulthandler_Fini();
1432
Victor Stinner791da1c2016-03-14 16:53:12 +01001433 /* Check if the current Python thread hold the GIL */
1434 if (PyThreadState_GET() != NULL) {
1435 /* Flush sys.stdout and sys.stderr */
1436 flush_std_files();
1437 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001438
Nick Coghland6009512014-11-20 21:39:37 +10001439#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001440 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001441
Victor Stinner53345a42015-03-25 01:55:14 +01001442 /* Convert the message to wchar_t. This uses a simple one-to-one
1443 conversion, assuming that the this error message actually uses ASCII
1444 only. If this ceases to be true, we will have to convert. */
1445 buffer = alloca( (len+1) * (sizeof *buffer));
1446 for( i=0; i<=len; ++i)
1447 buffer[i] = msg[i];
1448 OutputDebugStringW(L"Fatal Python error: ");
1449 OutputDebugStringW(buffer);
1450 OutputDebugStringW(L"\n");
1451#endif /* MS_WINDOWS */
1452
1453exit:
1454#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001455 DebugBreak();
1456#endif
Nick Coghland6009512014-11-20 21:39:37 +10001457 abort();
1458}
1459
1460/* Clean up and exit */
1461
1462#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001463# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001464#endif
1465
1466static void (*pyexitfunc)(void) = NULL;
1467/* For the atexit module. */
1468void _Py_PyAtExit(void (*func)(void))
1469{
1470 pyexitfunc = func;
1471}
1472
1473static void
1474call_py_exitfuncs(void)
1475{
1476 if (pyexitfunc == NULL)
1477 return;
1478
1479 (*pyexitfunc)();
1480 PyErr_Clear();
1481}
1482
1483/* Wait until threading._shutdown completes, provided
1484 the threading module was imported in the first place.
1485 The shutdown routine will wait until all non-daemon
1486 "threading" threads have completed. */
1487static void
1488wait_for_thread_shutdown(void)
1489{
1490#ifdef WITH_THREAD
1491 _Py_IDENTIFIER(_shutdown);
1492 PyObject *result;
1493 PyThreadState *tstate = PyThreadState_GET();
1494 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1495 "threading");
1496 if (threading == NULL) {
1497 /* threading not imported */
1498 PyErr_Clear();
1499 return;
1500 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001501 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001502 if (result == NULL) {
1503 PyErr_WriteUnraisable(threading);
1504 }
1505 else {
1506 Py_DECREF(result);
1507 }
1508 Py_DECREF(threading);
1509#endif
1510}
1511
1512#define NEXITFUNCS 32
1513static void (*exitfuncs[NEXITFUNCS])(void);
1514static int nexitfuncs = 0;
1515
1516int Py_AtExit(void (*func)(void))
1517{
1518 if (nexitfuncs >= NEXITFUNCS)
1519 return -1;
1520 exitfuncs[nexitfuncs++] = func;
1521 return 0;
1522}
1523
1524static void
1525call_ll_exitfuncs(void)
1526{
1527 while (nexitfuncs > 0)
1528 (*exitfuncs[--nexitfuncs])();
1529
1530 fflush(stdout);
1531 fflush(stderr);
1532}
1533
1534void
1535Py_Exit(int sts)
1536{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001537 if (Py_FinalizeEx() < 0) {
1538 sts = 120;
1539 }
Nick Coghland6009512014-11-20 21:39:37 +10001540
1541 exit(sts);
1542}
1543
1544static void
1545initsigs(void)
1546{
1547#ifdef SIGPIPE
1548 PyOS_setsig(SIGPIPE, SIG_IGN);
1549#endif
1550#ifdef SIGXFZ
1551 PyOS_setsig(SIGXFZ, SIG_IGN);
1552#endif
1553#ifdef SIGXFSZ
1554 PyOS_setsig(SIGXFSZ, SIG_IGN);
1555#endif
1556 PyOS_InitInterrupts(); /* May imply initsignal() */
1557 if (PyErr_Occurred()) {
1558 Py_FatalError("Py_Initialize: can't import signal");
1559 }
1560}
1561
1562
1563/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1564 *
1565 * All of the code in this function must only use async-signal-safe functions,
1566 * listed at `man 7 signal` or
1567 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1568 */
1569void
1570_Py_RestoreSignals(void)
1571{
1572#ifdef SIGPIPE
1573 PyOS_setsig(SIGPIPE, SIG_DFL);
1574#endif
1575#ifdef SIGXFZ
1576 PyOS_setsig(SIGXFZ, SIG_DFL);
1577#endif
1578#ifdef SIGXFSZ
1579 PyOS_setsig(SIGXFSZ, SIG_DFL);
1580#endif
1581}
1582
1583
1584/*
1585 * The file descriptor fd is considered ``interactive'' if either
1586 * a) isatty(fd) is TRUE, or
1587 * b) the -i flag was given, and the filename associated with
1588 * the descriptor is NULL or "<stdin>" or "???".
1589 */
1590int
1591Py_FdIsInteractive(FILE *fp, const char *filename)
1592{
1593 if (isatty((int)fileno(fp)))
1594 return 1;
1595 if (!Py_InteractiveFlag)
1596 return 0;
1597 return (filename == NULL) ||
1598 (strcmp(filename, "<stdin>") == 0) ||
1599 (strcmp(filename, "???") == 0);
1600}
1601
1602
Nick Coghland6009512014-11-20 21:39:37 +10001603/* Wrappers around sigaction() or signal(). */
1604
1605PyOS_sighandler_t
1606PyOS_getsig(int sig)
1607{
1608#ifdef HAVE_SIGACTION
1609 struct sigaction context;
1610 if (sigaction(sig, NULL, &context) == -1)
1611 return SIG_ERR;
1612 return context.sa_handler;
1613#else
1614 PyOS_sighandler_t handler;
1615/* Special signal handling for the secure CRT in Visual Studio 2005 */
1616#if defined(_MSC_VER) && _MSC_VER >= 1400
1617 switch (sig) {
1618 /* Only these signals are valid */
1619 case SIGINT:
1620 case SIGILL:
1621 case SIGFPE:
1622 case SIGSEGV:
1623 case SIGTERM:
1624 case SIGBREAK:
1625 case SIGABRT:
1626 break;
1627 /* Don't call signal() with other values or it will assert */
1628 default:
1629 return SIG_ERR;
1630 }
1631#endif /* _MSC_VER && _MSC_VER >= 1400 */
1632 handler = signal(sig, SIG_IGN);
1633 if (handler != SIG_ERR)
1634 signal(sig, handler);
1635 return handler;
1636#endif
1637}
1638
1639/*
1640 * All of the code in this function must only use async-signal-safe functions,
1641 * listed at `man 7 signal` or
1642 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1643 */
1644PyOS_sighandler_t
1645PyOS_setsig(int sig, PyOS_sighandler_t handler)
1646{
1647#ifdef HAVE_SIGACTION
1648 /* Some code in Modules/signalmodule.c depends on sigaction() being
1649 * used here if HAVE_SIGACTION is defined. Fix that if this code
1650 * changes to invalidate that assumption.
1651 */
1652 struct sigaction context, ocontext;
1653 context.sa_handler = handler;
1654 sigemptyset(&context.sa_mask);
1655 context.sa_flags = 0;
1656 if (sigaction(sig, &context, &ocontext) == -1)
1657 return SIG_ERR;
1658 return ocontext.sa_handler;
1659#else
1660 PyOS_sighandler_t oldhandler;
1661 oldhandler = signal(sig, handler);
1662#ifdef HAVE_SIGINTERRUPT
1663 siginterrupt(sig, 1);
1664#endif
1665 return oldhandler;
1666#endif
1667}
1668
1669#ifdef __cplusplus
1670}
1671#endif