blob: 06030c330a082c433b7b8598cf2e408e76baab53 [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{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200196 const char *name_utf8;
197 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000198 PyObject *codec, *name = NULL;
199
200 codec = _PyCodec_Lookup(encoding);
201 if (!codec)
202 goto error;
203
204 name = _PyObject_GetAttrId(codec, &PyId_name);
205 Py_CLEAR(codec);
206 if (!name)
207 goto error;
208
Serhiy Storchaka06515832016-11-20 09:13:07 +0200209 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000210 if (name_utf8 == NULL)
211 goto error;
212 name_str = _PyMem_RawStrdup(name_utf8);
213 Py_DECREF(name);
214 if (name_str == NULL) {
215 PyErr_NoMemory();
216 return NULL;
217 }
218 return name_str;
219
220error:
221 Py_XDECREF(codec);
222 Py_XDECREF(name);
223 return NULL;
224}
225
226static char*
227get_locale_encoding(void)
228{
229#ifdef MS_WINDOWS
230 char codepage[100];
231 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
232 return get_codec_name(codepage);
233#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
234 char* codeset = nl_langinfo(CODESET);
235 if (!codeset || codeset[0] == '\0') {
236 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
237 return NULL;
238 }
239 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200240#elif defined(__ANDROID__)
241 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000242#else
243 PyErr_SetNone(PyExc_NotImplementedError);
244 return NULL;
245#endif
246}
247
248static void
249import_init(PyInterpreterState *interp, PyObject *sysmod)
250{
251 PyObject *importlib;
252 PyObject *impmod;
253 PyObject *sys_modules;
254 PyObject *value;
255
256 /* Import _importlib through its frozen version, _frozen_importlib. */
257 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
258 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
259 }
260 else if (Py_VerboseFlag) {
261 PySys_FormatStderr("import _frozen_importlib # frozen\n");
262 }
263 importlib = PyImport_AddModule("_frozen_importlib");
264 if (importlib == NULL) {
265 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
266 "sys.modules");
267 }
268 interp->importlib = importlib;
269 Py_INCREF(interp->importlib);
270
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300271 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
272 if (interp->import_func == NULL)
273 Py_FatalError("Py_Initialize: __import__ not found");
274 Py_INCREF(interp->import_func);
275
Victor Stinnercd6e6942015-09-18 09:11:57 +0200276 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000277 impmod = PyInit_imp();
278 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200279 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000280 }
281 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200282 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000283 }
284 sys_modules = PyImport_GetModuleDict();
285 if (Py_VerboseFlag) {
286 PySys_FormatStderr("import sys # builtin\n");
287 }
288 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
289 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
290 }
291
Victor Stinnercd6e6942015-09-18 09:11:57 +0200292 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000293 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
294 if (value == NULL) {
295 PyErr_Print();
296 Py_FatalError("Py_Initialize: importlib install failed");
297 }
298 Py_DECREF(value);
299 Py_DECREF(impmod);
300
301 _PyImportZip_Init();
302}
303
304
305void
306_Py_InitializeEx_Private(int install_sigs, int install_importlib)
307{
308 PyInterpreterState *interp;
309 PyThreadState *tstate;
310 PyObject *bimod, *sysmod, *pstderr;
311 char *p;
312 extern void _Py_ReadyTypes(void);
313
314 if (initialized)
315 return;
316 initialized = 1;
317 _Py_Finalizing = NULL;
318
Xavier de Gayeb445ad72016-11-16 07:24:20 +0100319#ifdef HAVE_SETLOCALE
Nick Coghland6009512014-11-20 21:39:37 +1000320 /* Set up the LC_CTYPE locale, so we can obtain
321 the locale's charset without having to switch
322 locales. */
323 setlocale(LC_CTYPE, "");
324#endif
325
326 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
327 Py_DebugFlag = add_flag(Py_DebugFlag, p);
328 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
329 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
330 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
331 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
332 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
333 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
334 /* The variable is only tested for existence here; _PyRandom_Init will
335 check its value further. */
336 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
337 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700338#ifdef MS_WINDOWS
339 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
340 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700341 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
342 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700343#endif
Nick Coghland6009512014-11-20 21:39:37 +1000344
345 _PyRandom_Init();
346
347 interp = PyInterpreterState_New();
348 if (interp == NULL)
349 Py_FatalError("Py_Initialize: can't make first interpreter");
350
351 tstate = PyThreadState_New(interp);
352 if (tstate == NULL)
353 Py_FatalError("Py_Initialize: can't make first thread");
354 (void) PyThreadState_Swap(tstate);
355
356#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000357 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000358 destroying the GIL might fail when it is being referenced from
359 another running thread (see issue #9901).
360 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000361 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000362 _PyEval_FiniThreads();
363
364 /* Auto-thread-state API */
365 _PyGILState_Init(interp, tstate);
366#endif /* WITH_THREAD */
367
368 _Py_ReadyTypes();
369
370 if (!_PyFrame_Init())
371 Py_FatalError("Py_Initialize: can't init frames");
372
373 if (!_PyLong_Init())
374 Py_FatalError("Py_Initialize: can't init longs");
375
376 if (!PyByteArray_Init())
377 Py_FatalError("Py_Initialize: can't init bytearray");
378
379 if (!_PyFloat_Init())
380 Py_FatalError("Py_Initialize: can't init float");
381
382 interp->modules = PyDict_New();
383 if (interp->modules == NULL)
384 Py_FatalError("Py_Initialize: can't make modules dictionary");
385
386 /* Init Unicode implementation; relies on the codec registry */
387 if (_PyUnicode_Init() < 0)
388 Py_FatalError("Py_Initialize: can't initialize unicode");
389 if (_PyStructSequence_Init() < 0)
390 Py_FatalError("Py_Initialize: can't initialize structseq");
391
392 bimod = _PyBuiltin_Init();
393 if (bimod == NULL)
394 Py_FatalError("Py_Initialize: can't initialize builtins modules");
395 _PyImport_FixupBuiltin(bimod, "builtins");
396 interp->builtins = PyModule_GetDict(bimod);
397 if (interp->builtins == NULL)
398 Py_FatalError("Py_Initialize: can't initialize builtins dict");
399 Py_INCREF(interp->builtins);
400
401 /* initialize builtin exceptions */
402 _PyExc_Init(bimod);
403
404 sysmod = _PySys_Init();
405 if (sysmod == NULL)
406 Py_FatalError("Py_Initialize: can't initialize sys");
407 interp->sysdict = PyModule_GetDict(sysmod);
408 if (interp->sysdict == NULL)
409 Py_FatalError("Py_Initialize: can't initialize sys dict");
410 Py_INCREF(interp->sysdict);
411 _PyImport_FixupBuiltin(sysmod, "sys");
412 PySys_SetPath(Py_GetPath());
413 PyDict_SetItemString(interp->sysdict, "modules",
414 interp->modules);
415
416 /* Set up a preliminary stderr printer until we have enough
417 infrastructure for the io module in place. */
418 pstderr = PyFile_NewStdPrinter(fileno(stderr));
419 if (pstderr == NULL)
420 Py_FatalError("Py_Initialize: can't set preliminary stderr");
421 _PySys_SetObjectId(&PyId_stderr, pstderr);
422 PySys_SetObject("__stderr__", pstderr);
423 Py_DECREF(pstderr);
424
425 _PyImport_Init();
426
427 _PyImportHooks_Init();
428
429 /* Initialize _warnings. */
430 _PyWarnings_Init();
431
432 if (!install_importlib)
433 return;
434
Victor Stinner13019fd2015-04-03 13:10:54 +0200435 if (_PyTime_Init() < 0)
436 Py_FatalError("Py_Initialize: can't initialize time");
437
Nick Coghland6009512014-11-20 21:39:37 +1000438 import_init(interp, sysmod);
439
440 /* initialize the faulthandler module */
441 if (_PyFaulthandler_Init())
442 Py_FatalError("Py_Initialize: can't initialize faulthandler");
443
Nick Coghland6009512014-11-20 21:39:37 +1000444 if (initfsencoding(interp) < 0)
445 Py_FatalError("Py_Initialize: unable to load the file system codec");
446
447 if (install_sigs)
448 initsigs(); /* Signal handling stuff, including initintr() */
449
450 if (_PyTraceMalloc_Init() < 0)
451 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
452
453 initmain(interp); /* Module __main__ */
454 if (initstdio() < 0)
455 Py_FatalError(
456 "Py_Initialize: can't initialize sys standard streams");
457
458 /* Initialize warnings. */
459 if (PySys_HasWarnOptions()) {
460 PyObject *warnings_module = PyImport_ImportModule("warnings");
461 if (warnings_module == NULL) {
462 fprintf(stderr, "'import warnings' failed; traceback:\n");
463 PyErr_Print();
464 }
465 Py_XDECREF(warnings_module);
466 }
467
468 if (!Py_NoSiteFlag)
469 initsite(); /* Module site */
470}
471
472void
473Py_InitializeEx(int install_sigs)
474{
475 _Py_InitializeEx_Private(install_sigs, 1);
476}
477
478void
479Py_Initialize(void)
480{
481 Py_InitializeEx(1);
482}
483
484
485#ifdef COUNT_ALLOCS
486extern void dump_counts(FILE*);
487#endif
488
489/* Flush stdout and stderr */
490
491static int
492file_is_closed(PyObject *fobj)
493{
494 int r;
495 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
496 if (tmp == NULL) {
497 PyErr_Clear();
498 return 0;
499 }
500 r = PyObject_IsTrue(tmp);
501 Py_DECREF(tmp);
502 if (r < 0)
503 PyErr_Clear();
504 return r > 0;
505}
506
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000507static int
Nick Coghland6009512014-11-20 21:39:37 +1000508flush_std_files(void)
509{
510 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
511 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
512 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000513 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000514
515 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700516 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000517 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000518 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000519 status = -1;
520 }
Nick Coghland6009512014-11-20 21:39:37 +1000521 else
522 Py_DECREF(tmp);
523 }
524
525 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700526 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000527 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000528 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000529 status = -1;
530 }
Nick Coghland6009512014-11-20 21:39:37 +1000531 else
532 Py_DECREF(tmp);
533 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000534
535 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000536}
537
538/* Undo the effect of Py_Initialize().
539
540 Beware: if multiple interpreter and/or thread states exist, these
541 are not wiped out; only the current thread and interpreter state
542 are deleted. But since everything else is deleted, those other
543 interpreter and thread states should no longer be used.
544
545 (XXX We should do better, e.g. wipe out all interpreters and
546 threads.)
547
548 Locking: as above.
549
550*/
551
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000552int
553Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000554{
555 PyInterpreterState *interp;
556 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000557 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000558
559 if (!initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000560 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000561
562 wait_for_thread_shutdown();
563
564 /* The interpreter is still entirely intact at this point, and the
565 * exit funcs may be relying on that. In particular, if some thread
566 * or exit func is still waiting to do an import, the import machinery
567 * expects Py_IsInitialized() to return true. So don't say the
568 * interpreter is uninitialized until after the exit funcs have run.
569 * Note that Threading.py uses an exit func to do a join on all the
570 * threads created thru it, so this also protects pending imports in
571 * the threads created via Threading.
572 */
573 call_py_exitfuncs();
574
575 /* Get current thread state and interpreter pointer */
576 tstate = PyThreadState_GET();
577 interp = tstate->interp;
578
579 /* Remaining threads (e.g. daemon threads) will automatically exit
580 after taking the GIL (in PyEval_RestoreThread()). */
581 _Py_Finalizing = tstate;
582 initialized = 0;
583
Victor Stinnere0deff32015-03-24 13:46:18 +0100584 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000585 if (flush_std_files() < 0) {
586 status = -1;
587 }
Nick Coghland6009512014-11-20 21:39:37 +1000588
589 /* Disable signal handling */
590 PyOS_FiniInterrupts();
591
592 /* Collect garbage. This may call finalizers; it's nice to call these
593 * before all modules are destroyed.
594 * XXX If a __del__ or weakref callback is triggered here, and tries to
595 * XXX import a module, bad things can happen, because Python no
596 * XXX longer believes it's initialized.
597 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
598 * XXX is easy to provoke that way. I've also seen, e.g.,
599 * XXX Exception exceptions.ImportError: 'No module named sha'
600 * XXX in <function callback at 0x008F5718> ignored
601 * XXX but I'm unclear on exactly how that one happens. In any case,
602 * XXX I haven't seen a real-life report of either of these.
603 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700604 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000605#ifdef COUNT_ALLOCS
606 /* With COUNT_ALLOCS, it helps to run GC multiple times:
607 each collection might release some types from the type
608 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700609 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000610 /* nothing */;
611#endif
612 /* Destroy all modules */
613 PyImport_Cleanup();
614
Victor Stinnere0deff32015-03-24 13:46:18 +0100615 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000616 if (flush_std_files() < 0) {
617 status = -1;
618 }
Nick Coghland6009512014-11-20 21:39:37 +1000619
620 /* Collect final garbage. This disposes of cycles created by
621 * class definitions, for example.
622 * XXX This is disabled because it caused too many problems. If
623 * XXX a __del__ or weakref callback triggers here, Python code has
624 * XXX a hard time running, because even the sys module has been
625 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
626 * XXX One symptom is a sequence of information-free messages
627 * XXX coming from threads (if a __del__ or callback is invoked,
628 * XXX other threads can execute too, and any exception they encounter
629 * XXX triggers a comedy of errors as subsystem after subsystem
630 * XXX fails to find what it *expects* to find in sys to help report
631 * XXX the exception and consequent unexpected failures). I've also
632 * XXX seen segfaults then, after adding print statements to the
633 * XXX Python code getting called.
634 */
635#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -0700636 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000637#endif
638
639 /* Disable tracemalloc after all Python objects have been destroyed,
640 so it is possible to use tracemalloc in objects destructor. */
641 _PyTraceMalloc_Fini();
642
643 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
644 _PyImport_Fini();
645
646 /* Cleanup typeobject.c's internal caches. */
647 _PyType_Fini();
648
649 /* unload faulthandler module */
650 _PyFaulthandler_Fini();
651
652 /* Debugging stuff */
653#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300654 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +1000655#endif
656 /* dump hash stats */
657 _PyHash_Fini();
658
659 _PY_DEBUG_PRINT_TOTAL_REFS();
660
661#ifdef Py_TRACE_REFS
662 /* Display all objects still alive -- this can invoke arbitrary
663 * __repr__ overrides, so requires a mostly-intact interpreter.
664 * Alas, a lot of stuff may still be alive now that will be cleaned
665 * up later.
666 */
667 if (Py_GETENV("PYTHONDUMPREFS"))
668 _Py_PrintReferences(stderr);
669#endif /* Py_TRACE_REFS */
670
671 /* Clear interpreter state and all thread states. */
672 PyInterpreterState_Clear(interp);
673
674 /* Now we decref the exception classes. After this point nothing
675 can raise an exception. That's okay, because each Fini() method
676 below has been checked to make sure no exceptions are ever
677 raised.
678 */
679
680 _PyExc_Fini();
681
682 /* Sundry finalizers */
683 PyMethod_Fini();
684 PyFrame_Fini();
685 PyCFunction_Fini();
686 PyTuple_Fini();
687 PyList_Fini();
688 PySet_Fini();
689 PyBytes_Fini();
690 PyByteArray_Fini();
691 PyLong_Fini();
692 PyFloat_Fini();
693 PyDict_Fini();
694 PySlice_Fini();
695 _PyGC_Fini();
696 _PyRandom_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +0300697 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -0700698 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +1000699
700 /* Cleanup Unicode implementation */
701 _PyUnicode_Fini();
702
703 /* reset file system default encoding */
704 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
705 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
706 Py_FileSystemDefaultEncoding = NULL;
707 }
708
709 /* XXX Still allocated:
710 - various static ad-hoc pointers to interned strings
711 - int and float free list blocks
712 - whatever various modules and libraries allocate
713 */
714
715 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
716
717 /* Cleanup auto-thread-state */
718#ifdef WITH_THREAD
719 _PyGILState_Fini();
720#endif /* WITH_THREAD */
721
722 /* Delete current thread. After this, many C API calls become crashy. */
723 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +0100724
Nick Coghland6009512014-11-20 21:39:37 +1000725 PyInterpreterState_Delete(interp);
726
727#ifdef Py_TRACE_REFS
728 /* Display addresses (& refcnts) of all objects still alive.
729 * An address can be used to find the repr of the object, printed
730 * above by _Py_PrintReferences.
731 */
732 if (Py_GETENV("PYTHONDUMPREFS"))
733 _Py_PrintReferenceAddresses(stderr);
734#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +0100735#ifdef WITH_PYMALLOC
736 if (_PyMem_PymallocEnabled()) {
737 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
738 if (opt != NULL && *opt != '\0')
739 _PyObject_DebugMallocStats(stderr);
740 }
Nick Coghland6009512014-11-20 21:39:37 +1000741#endif
742
743 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000744 return status;
745}
746
747void
748Py_Finalize(void)
749{
750 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000751}
752
753/* Create and initialize a new interpreter and thread, and return the
754 new thread. This requires that Py_Initialize() has been called
755 first.
756
757 Unsuccessful initialization yields a NULL pointer. Note that *no*
758 exception information is available even in this case -- the
759 exception information is held in the thread, and there is no
760 thread.
761
762 Locking: as above.
763
764*/
765
766PyThreadState *
767Py_NewInterpreter(void)
768{
769 PyInterpreterState *interp;
770 PyThreadState *tstate, *save_tstate;
771 PyObject *bimod, *sysmod;
772
773 if (!initialized)
774 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
775
Victor Stinnerd7292b52016-06-17 12:29:00 +0200776#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +0100777 /* Issue #10915, #15751: The GIL API doesn't work with multiple
778 interpreters: disable PyGILState_Check(). */
779 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +0300780#endif
Victor Stinner8a1be612016-03-14 22:07:55 +0100781
Nick Coghland6009512014-11-20 21:39:37 +1000782 interp = PyInterpreterState_New();
783 if (interp == NULL)
784 return NULL;
785
786 tstate = PyThreadState_New(interp);
787 if (tstate == NULL) {
788 PyInterpreterState_Delete(interp);
789 return NULL;
790 }
791
792 save_tstate = PyThreadState_Swap(tstate);
793
794 /* XXX The following is lax in error checking */
795
796 interp->modules = PyDict_New();
797
798 bimod = _PyImport_FindBuiltin("builtins");
799 if (bimod != NULL) {
800 interp->builtins = PyModule_GetDict(bimod);
801 if (interp->builtins == NULL)
802 goto handle_error;
803 Py_INCREF(interp->builtins);
804 }
805
806 /* initialize builtin exceptions */
807 _PyExc_Init(bimod);
808
809 sysmod = _PyImport_FindBuiltin("sys");
810 if (bimod != NULL && sysmod != NULL) {
811 PyObject *pstderr;
812
813 interp->sysdict = PyModule_GetDict(sysmod);
814 if (interp->sysdict == NULL)
815 goto handle_error;
816 Py_INCREF(interp->sysdict);
817 PySys_SetPath(Py_GetPath());
818 PyDict_SetItemString(interp->sysdict, "modules",
819 interp->modules);
820 /* Set up a preliminary stderr printer until we have enough
821 infrastructure for the io module in place. */
822 pstderr = PyFile_NewStdPrinter(fileno(stderr));
823 if (pstderr == NULL)
824 Py_FatalError("Py_Initialize: can't set preliminary stderr");
825 _PySys_SetObjectId(&PyId_stderr, pstderr);
826 PySys_SetObject("__stderr__", pstderr);
827 Py_DECREF(pstderr);
828
829 _PyImportHooks_Init();
830
831 import_init(interp, sysmod);
832
833 if (initfsencoding(interp) < 0)
834 goto handle_error;
835
836 if (initstdio() < 0)
837 Py_FatalError(
Georg Brandl4b5b0622016-01-18 08:00:15 +0100838 "Py_Initialize: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000839 initmain(interp);
840 if (!Py_NoSiteFlag)
841 initsite();
842 }
843
844 if (!PyErr_Occurred())
845 return tstate;
846
847handle_error:
848 /* Oops, it didn't work. Undo it all. */
849
850 PyErr_PrintEx(0);
851 PyThreadState_Clear(tstate);
852 PyThreadState_Swap(save_tstate);
853 PyThreadState_Delete(tstate);
854 PyInterpreterState_Delete(interp);
855
856 return NULL;
857}
858
859/* Delete an interpreter and its last thread. This requires that the
860 given thread state is current, that the thread has no remaining
861 frames, and that it is its interpreter's only remaining thread.
862 It is a fatal error to violate these constraints.
863
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000864 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +1000865 everything, regardless.)
866
867 Locking: as above.
868
869*/
870
871void
872Py_EndInterpreter(PyThreadState *tstate)
873{
874 PyInterpreterState *interp = tstate->interp;
875
876 if (tstate != PyThreadState_GET())
877 Py_FatalError("Py_EndInterpreter: thread is not current");
878 if (tstate->frame != NULL)
879 Py_FatalError("Py_EndInterpreter: thread still has a frame");
880
881 wait_for_thread_shutdown();
882
883 if (tstate != interp->tstate_head || tstate->next != NULL)
884 Py_FatalError("Py_EndInterpreter: not the last thread");
885
886 PyImport_Cleanup();
887 PyInterpreterState_Clear(interp);
888 PyThreadState_Swap(NULL);
889 PyInterpreterState_Delete(interp);
890}
891
892#ifdef MS_WINDOWS
893static wchar_t *progname = L"python";
894#else
895static wchar_t *progname = L"python3";
896#endif
897
898void
899Py_SetProgramName(wchar_t *pn)
900{
901 if (pn && *pn)
902 progname = pn;
903}
904
905wchar_t *
906Py_GetProgramName(void)
907{
908 return progname;
909}
910
911static wchar_t *default_home = NULL;
912static wchar_t env_home[MAXPATHLEN+1];
913
914void
915Py_SetPythonHome(wchar_t *home)
916{
917 default_home = home;
918}
919
920wchar_t *
921Py_GetPythonHome(void)
922{
923 wchar_t *home = default_home;
924 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
925 char* chome = Py_GETENV("PYTHONHOME");
926 if (chome) {
927 size_t size = Py_ARRAY_LENGTH(env_home);
928 size_t r = mbstowcs(env_home, chome, size);
929 if (r != (size_t)-1 && r < size)
930 home = env_home;
931 }
932
933 }
934 return home;
935}
936
937/* Create __main__ module */
938
939static void
940initmain(PyInterpreterState *interp)
941{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700942 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +1000943 m = PyImport_AddModule("__main__");
944 if (m == NULL)
945 Py_FatalError("can't create __main__ module");
946 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700947 ann_dict = PyDict_New();
948 if ((ann_dict == NULL) ||
949 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
950 Py_FatalError("Failed to initialize __main__.__annotations__");
951 }
952 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +1000953 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
954 PyObject *bimod = PyImport_ImportModule("builtins");
955 if (bimod == NULL) {
956 Py_FatalError("Failed to retrieve builtins module");
957 }
958 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
959 Py_FatalError("Failed to initialize __main__.__builtins__");
960 }
961 Py_DECREF(bimod);
962 }
963 /* Main is a little special - imp.is_builtin("__main__") will return
964 * False, but BuiltinImporter is still the most appropriate initial
965 * setting for its __loader__ attribute. A more suitable value will
966 * be set if __main__ gets further initialized later in the startup
967 * process.
968 */
969 loader = PyDict_GetItemString(d, "__loader__");
970 if (loader == NULL || loader == Py_None) {
971 PyObject *loader = PyObject_GetAttrString(interp->importlib,
972 "BuiltinImporter");
973 if (loader == NULL) {
974 Py_FatalError("Failed to retrieve BuiltinImporter");
975 }
976 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
977 Py_FatalError("Failed to initialize __main__.__loader__");
978 }
979 Py_DECREF(loader);
980 }
981}
982
983static int
984initfsencoding(PyInterpreterState *interp)
985{
986 PyObject *codec;
987
Steve Dowercc16be82016-09-08 10:35:16 -0700988#ifdef MS_WINDOWS
989 if (Py_LegacyWindowsFSEncodingFlag)
990 {
991 Py_FileSystemDefaultEncoding = "mbcs";
992 Py_FileSystemDefaultEncodeErrors = "replace";
993 }
994 else
995 {
996 Py_FileSystemDefaultEncoding = "utf-8";
997 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
998 }
999#else
Nick Coghland6009512014-11-20 21:39:37 +10001000 if (Py_FileSystemDefaultEncoding == NULL)
1001 {
1002 Py_FileSystemDefaultEncoding = get_locale_encoding();
1003 if (Py_FileSystemDefaultEncoding == NULL)
1004 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1005
1006 Py_HasFileSystemDefaultEncoding = 0;
1007 interp->fscodec_initialized = 1;
1008 return 0;
1009 }
Steve Dowercc16be82016-09-08 10:35:16 -07001010#endif
Nick Coghland6009512014-11-20 21:39:37 +10001011
1012 /* the encoding is mbcs, utf-8 or ascii */
1013 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1014 if (!codec) {
1015 /* Such error can only occurs in critical situations: no more
1016 * memory, import a module of the standard library failed,
1017 * etc. */
1018 return -1;
1019 }
1020 Py_DECREF(codec);
1021 interp->fscodec_initialized = 1;
1022 return 0;
1023}
1024
1025/* Import the site module (not into __main__ though) */
1026
1027static void
1028initsite(void)
1029{
1030 PyObject *m;
1031 m = PyImport_ImportModule("site");
1032 if (m == NULL) {
1033 fprintf(stderr, "Failed to import the site module\n");
1034 PyErr_Print();
1035 Py_Finalize();
1036 exit(1);
1037 }
1038 else {
1039 Py_DECREF(m);
1040 }
1041}
1042
Victor Stinner874dbe82015-09-04 17:29:57 +02001043/* Check if a file descriptor is valid or not.
1044 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1045static int
1046is_valid_fd(int fd)
1047{
1048 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001049 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001050 return 0;
1051 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001052 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1053 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1054 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001055 fd2 = dup(fd);
1056 if (fd2 >= 0)
1057 close(fd2);
1058 _Py_END_SUPPRESS_IPH
1059 return fd2 >= 0;
1060}
1061
1062/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001063static PyObject*
1064create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001065 int fd, int write_mode, const char* name,
1066 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001067{
1068 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1069 const char* mode;
1070 const char* newline;
1071 PyObject *line_buffering;
1072 int buffering, isatty;
1073 _Py_IDENTIFIER(open);
1074 _Py_IDENTIFIER(isatty);
1075 _Py_IDENTIFIER(TextIOWrapper);
1076 _Py_IDENTIFIER(mode);
1077
Victor Stinner874dbe82015-09-04 17:29:57 +02001078 if (!is_valid_fd(fd))
1079 Py_RETURN_NONE;
1080
Nick Coghland6009512014-11-20 21:39:37 +10001081 /* stdin is always opened in buffered mode, first because it shouldn't
1082 make a difference in common use cases, second because TextIOWrapper
1083 depends on the presence of a read1() method which only exists on
1084 buffered streams.
1085 */
1086 if (Py_UnbufferedStdioFlag && write_mode)
1087 buffering = 0;
1088 else
1089 buffering = -1;
1090 if (write_mode)
1091 mode = "wb";
1092 else
1093 mode = "rb";
1094 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1095 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001096 Py_None, Py_None, /* encoding, errors */
1097 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001098 if (buf == NULL)
1099 goto error;
1100
1101 if (buffering) {
1102 _Py_IDENTIFIER(raw);
1103 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1104 if (raw == NULL)
1105 goto error;
1106 }
1107 else {
1108 raw = buf;
1109 Py_INCREF(raw);
1110 }
1111
Steve Dower39294992016-08-30 21:22:36 -07001112#ifdef MS_WINDOWS
1113 /* Windows console IO is always UTF-8 encoded */
1114 if (PyWindowsConsoleIO_Check(raw))
1115 encoding = "utf-8";
1116#endif
1117
Nick Coghland6009512014-11-20 21:39:37 +10001118 text = PyUnicode_FromString(name);
1119 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1120 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001121 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001122 if (res == NULL)
1123 goto error;
1124 isatty = PyObject_IsTrue(res);
1125 Py_DECREF(res);
1126 if (isatty == -1)
1127 goto error;
1128 if (isatty || Py_UnbufferedStdioFlag)
1129 line_buffering = Py_True;
1130 else
1131 line_buffering = Py_False;
1132
1133 Py_CLEAR(raw);
1134 Py_CLEAR(text);
1135
1136#ifdef MS_WINDOWS
1137 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1138 newlines to "\n".
1139 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1140 newline = NULL;
1141#else
1142 /* sys.stdin: split lines at "\n".
1143 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1144 newline = "\n";
1145#endif
1146
1147 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1148 buf, encoding, errors,
1149 newline, line_buffering);
1150 Py_CLEAR(buf);
1151 if (stream == NULL)
1152 goto error;
1153
1154 if (write_mode)
1155 mode = "w";
1156 else
1157 mode = "r";
1158 text = PyUnicode_FromString(mode);
1159 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1160 goto error;
1161 Py_CLEAR(text);
1162 return stream;
1163
1164error:
1165 Py_XDECREF(buf);
1166 Py_XDECREF(stream);
1167 Py_XDECREF(text);
1168 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001169
Victor Stinner874dbe82015-09-04 17:29:57 +02001170 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1171 /* Issue #24891: the file descriptor was closed after the first
1172 is_valid_fd() check was called. Ignore the OSError and set the
1173 stream to None. */
1174 PyErr_Clear();
1175 Py_RETURN_NONE;
1176 }
1177 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001178}
1179
1180/* Initialize sys.stdin, stdout, stderr and builtins.open */
1181static int
1182initstdio(void)
1183{
1184 PyObject *iomod = NULL, *wrapper;
1185 PyObject *bimod = NULL;
1186 PyObject *m;
1187 PyObject *std = NULL;
1188 int status = 0, fd;
1189 PyObject * encoding_attr;
1190 char *pythonioencoding = NULL, *encoding, *errors;
1191
1192 /* Hack to avoid a nasty recursion issue when Python is invoked
1193 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1194 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1195 goto error;
1196 }
1197 Py_DECREF(m);
1198
1199 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1200 goto error;
1201 }
1202 Py_DECREF(m);
1203
1204 if (!(bimod = PyImport_ImportModule("builtins"))) {
1205 goto error;
1206 }
1207
1208 if (!(iomod = PyImport_ImportModule("io"))) {
1209 goto error;
1210 }
1211 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1212 goto error;
1213 }
1214
1215 /* Set builtins.open */
1216 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1217 Py_DECREF(wrapper);
1218 goto error;
1219 }
1220 Py_DECREF(wrapper);
1221
1222 encoding = _Py_StandardStreamEncoding;
1223 errors = _Py_StandardStreamErrors;
1224 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001225 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1226 if (pythonioencoding) {
1227 char *err;
1228 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1229 if (pythonioencoding == NULL) {
1230 PyErr_NoMemory();
1231 goto error;
1232 }
1233 err = strchr(pythonioencoding, ':');
1234 if (err) {
1235 *err = '\0';
1236 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001237 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001238 errors = err;
1239 }
1240 }
1241 if (*pythonioencoding && !encoding) {
1242 encoding = pythonioencoding;
1243 }
1244 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001245 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1246 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1247 stdin and stdout use the surrogateescape error handler by
1248 default, instead of the strict error handler. */
1249 char *loc = setlocale(LC_CTYPE, NULL);
1250 if (loc != NULL && strcmp(loc, "C") == 0)
1251 errors = "surrogateescape";
1252 }
Nick Coghland6009512014-11-20 21:39:37 +10001253 }
1254
1255 /* Set sys.stdin */
1256 fd = fileno(stdin);
1257 /* Under some conditions stdin, stdout and stderr may not be connected
1258 * and fileno() may point to an invalid file descriptor. For example
1259 * GUI apps don't have valid standard streams by default.
1260 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001261 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1262 if (std == NULL)
1263 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001264 PySys_SetObject("__stdin__", std);
1265 _PySys_SetObjectId(&PyId_stdin, std);
1266 Py_DECREF(std);
1267
1268 /* Set sys.stdout */
1269 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001270 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1271 if (std == NULL)
1272 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001273 PySys_SetObject("__stdout__", std);
1274 _PySys_SetObjectId(&PyId_stdout, std);
1275 Py_DECREF(std);
1276
1277#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1278 /* Set sys.stderr, replaces the preliminary stderr */
1279 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001280 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1281 if (std == NULL)
1282 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001283
1284 /* Same as hack above, pre-import stderr's codec to avoid recursion
1285 when import.c tries to write to stderr in verbose mode. */
1286 encoding_attr = PyObject_GetAttrString(std, "encoding");
1287 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001288 const char *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