blob: b7c98225641176fba43d125bcb2ea5de384faaee [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);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
74#ifdef WITH_THREAD
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
79/* Global configuration variable declarations are in pydebug.h */
80/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
81int Py_DebugFlag; /* Needed by parser.c */
82int Py_VerboseFlag; /* Needed by import.c */
83int Py_QuietFlag; /* Needed by sysmodule.c */
84int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
85int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
86int Py_OptimizeFlag = 0; /* Needed by compile.c */
87int Py_NoSiteFlag; /* Suppress 'import site' */
88int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
89int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
90int Py_FrozenFlag; /* Needed by getpath.c */
91int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +080092int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
94int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
95int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
96int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070097#ifdef MS_WINDOWS
98int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -070099int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700100#endif
Nick Coghland6009512014-11-20 21:39:37 +1000101
102PyThreadState *_Py_Finalizing = NULL;
103
104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
121int _Py_CoreInitialized = 0;
122int _Py_Initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000123
Eric Snow1abcf672017-05-23 21:46:51 -0700124int
125_Py_IsCoreInitialized(void)
126{
127 return _Py_CoreInitialized;
128}
Nick Coghland6009512014-11-20 21:39:37 +1000129
130int
131Py_IsInitialized(void)
132{
Eric Snow1abcf672017-05-23 21:46:51 -0700133 return _Py_Initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000134}
135
136/* Helper to allow an embedding application to override the normal
137 * mechanism that attempts to figure out an appropriate IO encoding
138 */
139
140static char *_Py_StandardStreamEncoding = NULL;
141static char *_Py_StandardStreamErrors = NULL;
142
143int
144Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
145{
146 if (Py_IsInitialized()) {
147 /* This is too late to have any effect */
148 return -1;
149 }
150 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
151 * initialised yet.
152 *
153 * However, the raw memory allocators are initialised appropriately
154 * as C static variables, so _PyMem_RawStrdup is OK even though
155 * Py_Initialize hasn't been called yet.
156 */
157 if (encoding) {
158 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
159 if (!_Py_StandardStreamEncoding) {
160 return -2;
161 }
162 }
163 if (errors) {
164 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
165 if (!_Py_StandardStreamErrors) {
166 if (_Py_StandardStreamEncoding) {
167 PyMem_RawFree(_Py_StandardStreamEncoding);
168 }
169 return -3;
170 }
171 }
Steve Dower39294992016-08-30 21:22:36 -0700172#ifdef MS_WINDOWS
173 if (_Py_StandardStreamEncoding) {
174 /* Overriding the stream encoding implies legacy streams */
175 Py_LegacyWindowsStdioFlag = 1;
176 }
177#endif
Nick Coghland6009512014-11-20 21:39:37 +1000178 return 0;
179}
180
Nick Coghlan6ea41862017-06-11 13:16:15 +1000181
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000182/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
183 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000184 initializations fail, a fatal error is issued and the function does
185 not return. On return, the first thread and interpreter state have
186 been created.
187
188 Locking: you must hold the interpreter lock while calling this.
189 (If the lock has not yet been initialized, that's equivalent to
190 having the lock, but you cannot use multiple threads.)
191
192*/
193
194static int
195add_flag(int flag, const char *envs)
196{
197 int env = atoi(envs);
198 if (flag < env)
199 flag = env;
200 if (flag < 1)
201 flag = 1;
202 return flag;
203}
204
205static char*
206get_codec_name(const char *encoding)
207{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200208 const char *name_utf8;
209 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000210 PyObject *codec, *name = NULL;
211
212 codec = _PyCodec_Lookup(encoding);
213 if (!codec)
214 goto error;
215
216 name = _PyObject_GetAttrId(codec, &PyId_name);
217 Py_CLEAR(codec);
218 if (!name)
219 goto error;
220
Serhiy Storchaka06515832016-11-20 09:13:07 +0200221 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000222 if (name_utf8 == NULL)
223 goto error;
224 name_str = _PyMem_RawStrdup(name_utf8);
225 Py_DECREF(name);
226 if (name_str == NULL) {
227 PyErr_NoMemory();
228 return NULL;
229 }
230 return name_str;
231
232error:
233 Py_XDECREF(codec);
234 Py_XDECREF(name);
235 return NULL;
236}
237
238static char*
239get_locale_encoding(void)
240{
241#ifdef MS_WINDOWS
242 char codepage[100];
243 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
244 return get_codec_name(codepage);
245#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
246 char* codeset = nl_langinfo(CODESET);
247 if (!codeset || codeset[0] == '\0') {
248 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
249 return NULL;
250 }
251 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200252#elif defined(__ANDROID__)
253 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000254#else
255 PyErr_SetNone(PyExc_NotImplementedError);
256 return NULL;
257#endif
258}
259
260static void
Eric Snow1abcf672017-05-23 21:46:51 -0700261initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000262{
263 PyObject *importlib;
264 PyObject *impmod;
265 PyObject *sys_modules;
266 PyObject *value;
267
268 /* Import _importlib through its frozen version, _frozen_importlib. */
269 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
270 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
271 }
272 else if (Py_VerboseFlag) {
273 PySys_FormatStderr("import _frozen_importlib # frozen\n");
274 }
275 importlib = PyImport_AddModule("_frozen_importlib");
276 if (importlib == NULL) {
277 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
278 "sys.modules");
279 }
280 interp->importlib = importlib;
281 Py_INCREF(interp->importlib);
282
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300283 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
284 if (interp->import_func == NULL)
285 Py_FatalError("Py_Initialize: __import__ not found");
286 Py_INCREF(interp->import_func);
287
Victor Stinnercd6e6942015-09-18 09:11:57 +0200288 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000289 impmod = PyInit_imp();
290 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200291 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000292 }
293 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200294 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000295 }
296 sys_modules = PyImport_GetModuleDict();
297 if (Py_VerboseFlag) {
298 PySys_FormatStderr("import sys # builtin\n");
299 }
300 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
301 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
302 }
303
Victor Stinnercd6e6942015-09-18 09:11:57 +0200304 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000305 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200306 if (value != NULL) {
307 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700308 value = PyObject_CallMethod(importlib,
309 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200310 }
Nick Coghland6009512014-11-20 21:39:37 +1000311 if (value == NULL) {
312 PyErr_Print();
313 Py_FatalError("Py_Initialize: importlib install failed");
314 }
315 Py_DECREF(value);
316 Py_DECREF(impmod);
317
318 _PyImportZip_Init();
319}
320
Eric Snow1abcf672017-05-23 21:46:51 -0700321static void
322initexternalimport(PyInterpreterState *interp)
323{
324 PyObject *value;
325 value = PyObject_CallMethod(interp->importlib,
326 "_install_external_importers", "");
327 if (value == NULL) {
328 PyErr_Print();
329 Py_FatalError("Py_EndInitialization: external importer setup failed");
330 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200331 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700332}
Nick Coghland6009512014-11-20 21:39:37 +1000333
Nick Coghlan6ea41862017-06-11 13:16:15 +1000334/* Helper functions to better handle the legacy C locale
335 *
336 * The legacy C locale assumes ASCII as the default text encoding, which
337 * causes problems not only for the CPython runtime, but also other
338 * components like GNU readline.
339 *
340 * Accordingly, when the CLI detects it, it attempts to coerce it to a
341 * more capable UTF-8 based alternative as follows:
342 *
343 * if (_Py_LegacyLocaleDetected()) {
344 * _Py_CoerceLegacyLocale();
345 * }
346 *
347 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
348 *
349 * Locale coercion also impacts the default error handler for the standard
350 * streams: while the usual default is "strict", the default for the legacy
351 * C locale and for any of the coercion target locales is "surrogateescape".
352 */
353
354int
355_Py_LegacyLocaleDetected(void)
356{
357#ifndef MS_WINDOWS
358 /* On non-Windows systems, the C locale is considered a legacy locale */
359 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
360 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
361#else
362 /* Windows uses code pages instead of locales, so no locale is legacy */
363 return 0;
364#endif
365}
366
367typedef struct _CandidateLocale {
368 const char *locale_name; /* The locale to try as a coercion target */
369} _LocaleCoercionTarget;
370
371static _LocaleCoercionTarget _TARGET_LOCALES[] = {
372 {"C.UTF-8"},
373 {"C.utf8"},
374 {"UTF-8"},
375 {NULL}
376};
377
378static char *
379get_default_standard_stream_error_handler(void)
380{
381 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
382 if (ctype_loc != NULL) {
383 /* "surrogateescape" is the default in the legacy C locale */
384 if (strcmp(ctype_loc, "C") == 0) {
385 return "surrogateescape";
386 }
387
388#ifdef PY_COERCE_C_LOCALE
389 /* "surrogateescape" is the default in locale coercion target locales */
390 const _LocaleCoercionTarget *target = NULL;
391 for (target = _TARGET_LOCALES; target->locale_name; target++) {
392 if (strcmp(ctype_loc, target->locale_name) == 0) {
393 return "surrogateescape";
394 }
395 }
396#endif
397 }
398
399 /* Otherwise return NULL to request the typical default error handler */
400 return NULL;
401}
402
403#ifdef PY_COERCE_C_LOCALE
404static const char *_C_LOCALE_COERCION_WARNING =
405 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
406 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
407
408static void
409_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
410{
411 const char *newloc = target->locale_name;
412
413 /* Reset locale back to currently configured defaults */
414 setlocale(LC_ALL, "");
415
416 /* Set the relevant locale environment variable */
417 if (setenv("LC_CTYPE", newloc, 1)) {
418 fprintf(stderr,
419 "Error setting LC_CTYPE, skipping C locale coercion\n");
420 return;
421 }
422 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
423
424 /* Reconfigure with the overridden environment variables */
425 setlocale(LC_ALL, "");
426}
427#endif
428
429void
430_Py_CoerceLegacyLocale(void)
431{
432#ifdef PY_COERCE_C_LOCALE
433 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
434 * the locale settings *before* we try to do anything with the command
435 * line arguments. For cross-platform debugging purposes, we also need
436 * to give end users a way to force even scripts that are otherwise
437 * isolated from their environment to use the legacy ASCII-centric C
438 * locale.
439 *
440 * Ignoring -E and -I is safe from a security perspective, as we only use
441 * the setting to turn *off* the implicit locale coercion, and anyone with
442 * access to the process environment already has the ability to set
443 * `LC_ALL=C` to override the C level locale settings anyway.
444 */
445 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
446 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
447 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
448 const char *locale_override = getenv("LC_ALL");
449 if (locale_override == NULL || *locale_override == '\0') {
450 /* LC_ALL is also not set (or is set to an empty string) */
451 const _LocaleCoercionTarget *target = NULL;
452 for (target = _TARGET_LOCALES; target->locale_name; target++) {
453 const char *new_locale = setlocale(LC_CTYPE,
454 target->locale_name);
455 if (new_locale != NULL) {
456 /* Successfully configured locale, so make it the default */
457 _coerce_default_locale_settings(target);
458 return;
459 }
460 }
461 }
462 }
463 /* No C locale warning here, as Py_Initialize will emit one later */
464#endif
465}
466
467
468#ifdef PY_WARN_ON_C_LOCALE
469static const char *_C_LOCALE_WARNING =
470 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
471 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
472 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
473 "locales is recommended.\n";
474
475static void
476_emit_stderr_warning_for_c_locale(void)
477{
478 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
479 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
480 if (_Py_LegacyLocaleDetected()) {
481 fprintf(stderr, "%s", _C_LOCALE_WARNING);
482 }
483 }
484}
485#endif
486
Eric Snow1abcf672017-05-23 21:46:51 -0700487
488/* Global initializations. Can be undone by Py_Finalize(). Don't
489 call this twice without an intervening Py_Finalize() call.
490
491 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
492 must have a corresponding call to Py_Finalize.
493
494 Locking: you must hold the interpreter lock while calling these APIs.
495 (If the lock has not yet been initialized, that's equivalent to
496 having the lock, but you cannot use multiple threads.)
497
498*/
499
500/* Begin interpreter initialization
501 *
502 * On return, the first thread and interpreter state have been created,
503 * but the compiler, signal handling, multithreading and
504 * multiple interpreter support, and codec infrastructure are not yet
505 * available.
506 *
507 * The import system will support builtin and frozen modules only.
508 * The only supported io is writing to sys.stderr
509 *
510 * If any operation invoked by this function fails, a fatal error is
511 * issued and the function does not return.
512 *
513 * Any code invoked from this function should *not* assume it has access
514 * to the Python C API (unless the API is explicitly listed as being
515 * safe to call without calling Py_Initialize first)
516 */
517
518/* TODO: Progresively move functionality from Py_BeginInitialization to
519 * Py_ReadConfig and Py_EndInitialization
520 */
521
522void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000523{
524 PyInterpreterState *interp;
525 PyThreadState *tstate;
526 PyObject *bimod, *sysmod, *pstderr;
527 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700528 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700529 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000530
Eric Snow1abcf672017-05-23 21:46:51 -0700531 if (config != NULL) {
532 core_config = *config;
533 }
534
535 if (_Py_Initialized) {
536 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
537 }
538 if (_Py_CoreInitialized) {
539 Py_FatalError("Py_InitializeCore: runtime core already initialized");
540 }
541
542 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
543 * threads behave a little more gracefully at interpreter shutdown.
544 * We clobber it here so the new interpreter can start with a clean
545 * slate.
546 *
547 * However, this may still lead to misbehaviour if there are daemon
548 * threads still hanging around from a previous Py_Initialize/Finalize
549 * pair :(
550 */
Nick Coghland6009512014-11-20 21:39:37 +1000551 _Py_Finalizing = NULL;
552
Nick Coghlan6ea41862017-06-11 13:16:15 +1000553#ifdef __ANDROID__
554 /* Passing "" to setlocale() on Android requests the C locale rather
555 * than checking environment variables, so request C.UTF-8 explicitly
556 */
557 setlocale(LC_CTYPE, "C.UTF-8");
558#else
559#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000560 /* Set up the LC_CTYPE locale, so we can obtain
561 the locale's charset without having to switch
562 locales. */
563 setlocale(LC_CTYPE, "");
Nick Coghlan6ea41862017-06-11 13:16:15 +1000564#ifdef PY_WARN_ON_C_LOCALE
565 _emit_stderr_warning_for_c_locale();
566#endif
567#endif
Nick Coghland6009512014-11-20 21:39:37 +1000568#endif
569
570 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
571 Py_DebugFlag = add_flag(Py_DebugFlag, p);
572 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
573 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
574 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
575 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
576 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
577 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700578 /* The variable is only tested for existence here;
579 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000580 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
581 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700582#ifdef MS_WINDOWS
583 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
584 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700585 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
586 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700587#endif
Nick Coghland6009512014-11-20 21:39:37 +1000588
Eric Snow1abcf672017-05-23 21:46:51 -0700589 _Py_HashRandomization_Init(&core_config);
590 if (!core_config.use_hash_seed || core_config.hash_seed) {
591 /* Random or non-zero hash seed */
592 Py_HashRandomizationFlag = 1;
593 }
Nick Coghland6009512014-11-20 21:39:37 +1000594
Eric Snowe3774162017-05-22 19:46:40 -0700595 _PyInterpreterState_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000596 interp = PyInterpreterState_New();
597 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700598 Py_FatalError("Py_InitializeCore: can't make main interpreter");
599 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700600 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000601
602 tstate = PyThreadState_New(interp);
603 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700604 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000605 (void) PyThreadState_Swap(tstate);
606
607#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000608 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000609 destroying the GIL might fail when it is being referenced from
610 another running thread (see issue #9901).
611 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000612 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000613 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000614 /* Auto-thread-state API */
615 _PyGILState_Init(interp, tstate);
616#endif /* WITH_THREAD */
617
618 _Py_ReadyTypes();
619
620 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700621 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000622
623 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700624 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000625
626 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700627 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000628
629 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700630 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000631
632 interp->modules = PyDict_New();
633 if (interp->modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700634 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000635
636 /* Init Unicode implementation; relies on the codec registry */
637 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700638 Py_FatalError("Py_InitializeCore: can't initialize unicode");
639
Nick Coghland6009512014-11-20 21:39:37 +1000640 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700641 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000642
643 bimod = _PyBuiltin_Init();
644 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700645 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Nick Coghland6009512014-11-20 21:39:37 +1000646 _PyImport_FixupBuiltin(bimod, "builtins");
647 interp->builtins = PyModule_GetDict(bimod);
648 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700649 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000650 Py_INCREF(interp->builtins);
651
652 /* initialize builtin exceptions */
653 _PyExc_Init(bimod);
654
Eric Snow6b4be192017-05-22 21:36:03 -0700655 sysmod = _PySys_BeginInit();
Nick Coghland6009512014-11-20 21:39:37 +1000656 if (sysmod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700657 Py_FatalError("Py_InitializeCore: can't initialize sys");
Nick Coghland6009512014-11-20 21:39:37 +1000658 interp->sysdict = PyModule_GetDict(sysmod);
659 if (interp->sysdict == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700660 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
Nick Coghland6009512014-11-20 21:39:37 +1000661 Py_INCREF(interp->sysdict);
662 _PyImport_FixupBuiltin(sysmod, "sys");
Nick Coghland6009512014-11-20 21:39:37 +1000663 PyDict_SetItemString(interp->sysdict, "modules",
664 interp->modules);
665
666 /* Set up a preliminary stderr printer until we have enough
667 infrastructure for the io module in place. */
668 pstderr = PyFile_NewStdPrinter(fileno(stderr));
669 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700670 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000671 _PySys_SetObjectId(&PyId_stderr, pstderr);
672 PySys_SetObject("__stderr__", pstderr);
673 Py_DECREF(pstderr);
674
675 _PyImport_Init();
676
677 _PyImportHooks_Init();
678
679 /* Initialize _warnings. */
680 _PyWarnings_Init();
681
Eric Snow1abcf672017-05-23 21:46:51 -0700682 /* This call sets up builtin and frozen import support */
683 if (!interp->core_config._disable_importlib) {
684 initimport(interp, sysmod);
685 }
686
687 /* Only when we get here is the runtime core fully initialized */
688 _Py_CoreInitialized = 1;
689}
690
Eric Snowc7ec9982017-05-23 23:00:52 -0700691/* Read configuration settings from standard locations
692 *
693 * This function doesn't make any changes to the interpreter state - it
694 * merely populates any missing configuration settings. This allows an
695 * embedding application to completely override a config option by
696 * setting it before calling this function, or else modify the default
697 * setting before passing the fully populated config to Py_EndInitialization.
698 *
699 * More advanced selective initialization tricks are possible by calling
700 * this function multiple times with various preconfigured settings.
701 */
702
703int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
704{
705 /* Signal handlers are installed by default */
706 if (config->install_signal_handlers < 0) {
707 config->install_signal_handlers = 1;
708 }
709
710 return 0;
711}
712
713/* Update interpreter state based on supplied configuration settings
714 *
715 * After calling this function, most of the restrictions on the interpreter
716 * are lifted. The only remaining incomplete settings are those related
717 * to the main module (sys.argv[0], __main__ metadata)
718 *
719 * Calling this when the interpreter is not initializing, is already
720 * initialized or without a valid current thread state is a fatal error.
721 * Other errors should be reported as normal Python exceptions with a
722 * non-zero return code.
723 */
724int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700725{
726 PyInterpreterState *interp;
727 PyThreadState *tstate;
728
Eric Snowc7ec9982017-05-23 23:00:52 -0700729 if (!_Py_CoreInitialized) {
730 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
731 }
732 if (_Py_Initialized) {
733 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
734 }
735
Eric Snow1abcf672017-05-23 21:46:51 -0700736 /* Get current thread state and interpreter pointer */
737 tstate = PyThreadState_GET();
738 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700739 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700740 interp = tstate->interp;
741 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700742 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700743
744 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700745 interp->config = *config;
746
Eric Snow1abcf672017-05-23 21:46:51 -0700747 if (interp->core_config._disable_importlib) {
748 /* Special mode for freeze_importlib: run with no import system
749 *
750 * This means anything which needs support from extension modules
751 * or pure Python code in the standard library won't work.
752 */
753 _Py_Initialized = 1;
754 return 0;
755 }
756 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000757
Victor Stinner13019fd2015-04-03 13:10:54 +0200758 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700759 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200760
Eric Snow1abcf672017-05-23 21:46:51 -0700761 /* Finish setting up the sys module and import system */
762 /* GetPath may initialize state that _PySys_EndInit locks
763 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700764 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700765 PySys_SetPath(Py_GetPath());
766 if (_PySys_EndInit(interp->sysdict) < 0)
767 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700768 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000769
770 /* initialize the faulthandler module */
771 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700772 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000773
Nick Coghland6009512014-11-20 21:39:37 +1000774 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700775 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000776
Eric Snowc7ec9982017-05-23 23:00:52 -0700777 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000778 initsigs(); /* Signal handling stuff, including initintr() */
779
780 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700781 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000782
783 initmain(interp); /* Module __main__ */
784 if (initstdio() < 0)
785 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700786 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000787
788 /* Initialize warnings. */
789 if (PySys_HasWarnOptions()) {
790 PyObject *warnings_module = PyImport_ImportModule("warnings");
791 if (warnings_module == NULL) {
792 fprintf(stderr, "'import warnings' failed; traceback:\n");
793 PyErr_Print();
794 }
795 Py_XDECREF(warnings_module);
796 }
797
Eric Snow1abcf672017-05-23 21:46:51 -0700798 _Py_Initialized = 1;
799
Nick Coghland6009512014-11-20 21:39:37 +1000800 if (!Py_NoSiteFlag)
801 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700802
Eric Snowc7ec9982017-05-23 23:00:52 -0700803 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000804}
805
Eric Snowc7ec9982017-05-23 23:00:52 -0700806#undef _INIT_DEBUG_PRINT
807
Nick Coghland6009512014-11-20 21:39:37 +1000808void
Eric Snow1abcf672017-05-23 21:46:51 -0700809_Py_InitializeEx_Private(int install_sigs, int install_importlib)
810{
811 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700812 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700813
814 /* TODO: Moar config options! */
815 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
816 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700817 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700818 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700819 /* TODO: Print any exceptions raised by these operations */
820 if (_Py_ReadMainInterpreterConfig(&config))
821 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
822 if (_Py_InitializeMainInterpreter(&config))
823 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700824}
825
826
827void
Nick Coghland6009512014-11-20 21:39:37 +1000828Py_InitializeEx(int install_sigs)
829{
830 _Py_InitializeEx_Private(install_sigs, 1);
831}
832
833void
834Py_Initialize(void)
835{
836 Py_InitializeEx(1);
837}
838
839
840#ifdef COUNT_ALLOCS
841extern void dump_counts(FILE*);
842#endif
843
844/* Flush stdout and stderr */
845
846static int
847file_is_closed(PyObject *fobj)
848{
849 int r;
850 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
851 if (tmp == NULL) {
852 PyErr_Clear();
853 return 0;
854 }
855 r = PyObject_IsTrue(tmp);
856 Py_DECREF(tmp);
857 if (r < 0)
858 PyErr_Clear();
859 return r > 0;
860}
861
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000862static int
Nick Coghland6009512014-11-20 21:39:37 +1000863flush_std_files(void)
864{
865 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
866 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
867 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000868 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000869
870 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700871 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000872 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000873 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000874 status = -1;
875 }
Nick Coghland6009512014-11-20 21:39:37 +1000876 else
877 Py_DECREF(tmp);
878 }
879
880 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700881 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000882 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000883 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000884 status = -1;
885 }
Nick Coghland6009512014-11-20 21:39:37 +1000886 else
887 Py_DECREF(tmp);
888 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000889
890 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000891}
892
893/* Undo the effect of Py_Initialize().
894
895 Beware: if multiple interpreter and/or thread states exist, these
896 are not wiped out; only the current thread and interpreter state
897 are deleted. But since everything else is deleted, those other
898 interpreter and thread states should no longer be used.
899
900 (XXX We should do better, e.g. wipe out all interpreters and
901 threads.)
902
903 Locking: as above.
904
905*/
906
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000907int
908Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000909{
910 PyInterpreterState *interp;
911 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000912 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000913
Eric Snow1abcf672017-05-23 21:46:51 -0700914 if (!_Py_Initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000915 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000916
917 wait_for_thread_shutdown();
918
919 /* The interpreter is still entirely intact at this point, and the
920 * exit funcs may be relying on that. In particular, if some thread
921 * or exit func is still waiting to do an import, the import machinery
922 * expects Py_IsInitialized() to return true. So don't say the
923 * interpreter is uninitialized until after the exit funcs have run.
924 * Note that Threading.py uses an exit func to do a join on all the
925 * threads created thru it, so this also protects pending imports in
926 * the threads created via Threading.
927 */
928 call_py_exitfuncs();
929
930 /* Get current thread state and interpreter pointer */
931 tstate = PyThreadState_GET();
932 interp = tstate->interp;
933
934 /* Remaining threads (e.g. daemon threads) will automatically exit
935 after taking the GIL (in PyEval_RestoreThread()). */
936 _Py_Finalizing = tstate;
Eric Snow1abcf672017-05-23 21:46:51 -0700937 _Py_Initialized = 0;
938 _Py_CoreInitialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000939
Victor Stinnere0deff32015-03-24 13:46:18 +0100940 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000941 if (flush_std_files() < 0) {
942 status = -1;
943 }
Nick Coghland6009512014-11-20 21:39:37 +1000944
945 /* Disable signal handling */
946 PyOS_FiniInterrupts();
947
948 /* Collect garbage. This may call finalizers; it's nice to call these
949 * before all modules are destroyed.
950 * XXX If a __del__ or weakref callback is triggered here, and tries to
951 * XXX import a module, bad things can happen, because Python no
952 * XXX longer believes it's initialized.
953 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
954 * XXX is easy to provoke that way. I've also seen, e.g.,
955 * XXX Exception exceptions.ImportError: 'No module named sha'
956 * XXX in <function callback at 0x008F5718> ignored
957 * XXX but I'm unclear on exactly how that one happens. In any case,
958 * XXX I haven't seen a real-life report of either of these.
959 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700960 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000961#ifdef COUNT_ALLOCS
962 /* With COUNT_ALLOCS, it helps to run GC multiple times:
963 each collection might release some types from the type
964 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700965 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000966 /* nothing */;
967#endif
968 /* Destroy all modules */
969 PyImport_Cleanup();
970
Victor Stinnere0deff32015-03-24 13:46:18 +0100971 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000972 if (flush_std_files() < 0) {
973 status = -1;
974 }
Nick Coghland6009512014-11-20 21:39:37 +1000975
976 /* Collect final garbage. This disposes of cycles created by
977 * class definitions, for example.
978 * XXX This is disabled because it caused too many problems. If
979 * XXX a __del__ or weakref callback triggers here, Python code has
980 * XXX a hard time running, because even the sys module has been
981 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
982 * XXX One symptom is a sequence of information-free messages
983 * XXX coming from threads (if a __del__ or callback is invoked,
984 * XXX other threads can execute too, and any exception they encounter
985 * XXX triggers a comedy of errors as subsystem after subsystem
986 * XXX fails to find what it *expects* to find in sys to help report
987 * XXX the exception and consequent unexpected failures). I've also
988 * XXX seen segfaults then, after adding print statements to the
989 * XXX Python code getting called.
990 */
991#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -0700992 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000993#endif
994
995 /* Disable tracemalloc after all Python objects have been destroyed,
996 so it is possible to use tracemalloc in objects destructor. */
997 _PyTraceMalloc_Fini();
998
999 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1000 _PyImport_Fini();
1001
1002 /* Cleanup typeobject.c's internal caches. */
1003 _PyType_Fini();
1004
1005 /* unload faulthandler module */
1006 _PyFaulthandler_Fini();
1007
1008 /* Debugging stuff */
1009#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001010 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001011#endif
1012 /* dump hash stats */
1013 _PyHash_Fini();
1014
1015 _PY_DEBUG_PRINT_TOTAL_REFS();
1016
1017#ifdef Py_TRACE_REFS
1018 /* Display all objects still alive -- this can invoke arbitrary
1019 * __repr__ overrides, so requires a mostly-intact interpreter.
1020 * Alas, a lot of stuff may still be alive now that will be cleaned
1021 * up later.
1022 */
1023 if (Py_GETENV("PYTHONDUMPREFS"))
1024 _Py_PrintReferences(stderr);
1025#endif /* Py_TRACE_REFS */
1026
1027 /* Clear interpreter state and all thread states. */
1028 PyInterpreterState_Clear(interp);
1029
1030 /* Now we decref the exception classes. After this point nothing
1031 can raise an exception. That's okay, because each Fini() method
1032 below has been checked to make sure no exceptions are ever
1033 raised.
1034 */
1035
1036 _PyExc_Fini();
1037
1038 /* Sundry finalizers */
1039 PyMethod_Fini();
1040 PyFrame_Fini();
1041 PyCFunction_Fini();
1042 PyTuple_Fini();
1043 PyList_Fini();
1044 PySet_Fini();
1045 PyBytes_Fini();
1046 PyByteArray_Fini();
1047 PyLong_Fini();
1048 PyFloat_Fini();
1049 PyDict_Fini();
1050 PySlice_Fini();
1051 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001052 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001053 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001054 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001055
1056 /* Cleanup Unicode implementation */
1057 _PyUnicode_Fini();
1058
1059 /* reset file system default encoding */
1060 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1061 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1062 Py_FileSystemDefaultEncoding = NULL;
1063 }
1064
1065 /* XXX Still allocated:
1066 - various static ad-hoc pointers to interned strings
1067 - int and float free list blocks
1068 - whatever various modules and libraries allocate
1069 */
1070
1071 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1072
1073 /* Cleanup auto-thread-state */
1074#ifdef WITH_THREAD
1075 _PyGILState_Fini();
1076#endif /* WITH_THREAD */
1077
1078 /* Delete current thread. After this, many C API calls become crashy. */
1079 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001080
Nick Coghland6009512014-11-20 21:39:37 +10001081 PyInterpreterState_Delete(interp);
1082
1083#ifdef Py_TRACE_REFS
1084 /* Display addresses (& refcnts) of all objects still alive.
1085 * An address can be used to find the repr of the object, printed
1086 * above by _Py_PrintReferences.
1087 */
1088 if (Py_GETENV("PYTHONDUMPREFS"))
1089 _Py_PrintReferenceAddresses(stderr);
1090#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001091#ifdef WITH_PYMALLOC
1092 if (_PyMem_PymallocEnabled()) {
1093 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1094 if (opt != NULL && *opt != '\0')
1095 _PyObject_DebugMallocStats(stderr);
1096 }
Nick Coghland6009512014-11-20 21:39:37 +10001097#endif
1098
1099 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001100 return status;
1101}
1102
1103void
1104Py_Finalize(void)
1105{
1106 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001107}
1108
1109/* Create and initialize a new interpreter and thread, and return the
1110 new thread. This requires that Py_Initialize() has been called
1111 first.
1112
1113 Unsuccessful initialization yields a NULL pointer. Note that *no*
1114 exception information is available even in this case -- the
1115 exception information is held in the thread, and there is no
1116 thread.
1117
1118 Locking: as above.
1119
1120*/
1121
1122PyThreadState *
1123Py_NewInterpreter(void)
1124{
1125 PyInterpreterState *interp;
1126 PyThreadState *tstate, *save_tstate;
1127 PyObject *bimod, *sysmod;
1128
Eric Snow1abcf672017-05-23 21:46:51 -07001129 if (!_Py_Initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001130 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1131
Victor Stinnerd7292b52016-06-17 12:29:00 +02001132#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +01001133 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1134 interpreters: disable PyGILState_Check(). */
1135 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +03001136#endif
Victor Stinner8a1be612016-03-14 22:07:55 +01001137
Nick Coghland6009512014-11-20 21:39:37 +10001138 interp = PyInterpreterState_New();
1139 if (interp == NULL)
1140 return NULL;
1141
1142 tstate = PyThreadState_New(interp);
1143 if (tstate == NULL) {
1144 PyInterpreterState_Delete(interp);
1145 return NULL;
1146 }
1147
1148 save_tstate = PyThreadState_Swap(tstate);
1149
Eric Snow1abcf672017-05-23 21:46:51 -07001150 /* Copy the current interpreter config into the new interpreter */
1151 if (save_tstate != NULL) {
1152 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001153 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001154 } else {
1155 /* No current thread state, copy from the main interpreter */
1156 PyInterpreterState *main_interp = PyInterpreterState_Main();
1157 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001158 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001159 }
1160
Nick Coghland6009512014-11-20 21:39:37 +10001161 /* XXX The following is lax in error checking */
1162
1163 interp->modules = PyDict_New();
1164
1165 bimod = _PyImport_FindBuiltin("builtins");
1166 if (bimod != NULL) {
1167 interp->builtins = PyModule_GetDict(bimod);
1168 if (interp->builtins == NULL)
1169 goto handle_error;
1170 Py_INCREF(interp->builtins);
1171 }
1172
1173 /* initialize builtin exceptions */
1174 _PyExc_Init(bimod);
1175
1176 sysmod = _PyImport_FindBuiltin("sys");
1177 if (bimod != NULL && sysmod != NULL) {
1178 PyObject *pstderr;
1179
1180 interp->sysdict = PyModule_GetDict(sysmod);
1181 if (interp->sysdict == NULL)
1182 goto handle_error;
1183 Py_INCREF(interp->sysdict);
Eric Snow1abcf672017-05-23 21:46:51 -07001184 _PySys_EndInit(interp->sysdict);
Nick Coghland6009512014-11-20 21:39:37 +10001185 PySys_SetPath(Py_GetPath());
1186 PyDict_SetItemString(interp->sysdict, "modules",
1187 interp->modules);
1188 /* Set up a preliminary stderr printer until we have enough
1189 infrastructure for the io module in place. */
1190 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1191 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001192 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001193 _PySys_SetObjectId(&PyId_stderr, pstderr);
1194 PySys_SetObject("__stderr__", pstderr);
1195 Py_DECREF(pstderr);
1196
1197 _PyImportHooks_Init();
1198
Eric Snow1abcf672017-05-23 21:46:51 -07001199 initimport(interp, sysmod);
1200 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001201
1202 if (initfsencoding(interp) < 0)
1203 goto handle_error;
1204
1205 if (initstdio() < 0)
1206 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001207 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001208 initmain(interp);
1209 if (!Py_NoSiteFlag)
1210 initsite();
1211 }
1212
1213 if (!PyErr_Occurred())
1214 return tstate;
1215
1216handle_error:
1217 /* Oops, it didn't work. Undo it all. */
1218
1219 PyErr_PrintEx(0);
1220 PyThreadState_Clear(tstate);
1221 PyThreadState_Swap(save_tstate);
1222 PyThreadState_Delete(tstate);
1223 PyInterpreterState_Delete(interp);
1224
1225 return NULL;
1226}
1227
1228/* Delete an interpreter and its last thread. This requires that the
1229 given thread state is current, that the thread has no remaining
1230 frames, and that it is its interpreter's only remaining thread.
1231 It is a fatal error to violate these constraints.
1232
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001233 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001234 everything, regardless.)
1235
1236 Locking: as above.
1237
1238*/
1239
1240void
1241Py_EndInterpreter(PyThreadState *tstate)
1242{
1243 PyInterpreterState *interp = tstate->interp;
1244
1245 if (tstate != PyThreadState_GET())
1246 Py_FatalError("Py_EndInterpreter: thread is not current");
1247 if (tstate->frame != NULL)
1248 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1249
1250 wait_for_thread_shutdown();
1251
1252 if (tstate != interp->tstate_head || tstate->next != NULL)
1253 Py_FatalError("Py_EndInterpreter: not the last thread");
1254
1255 PyImport_Cleanup();
1256 PyInterpreterState_Clear(interp);
1257 PyThreadState_Swap(NULL);
1258 PyInterpreterState_Delete(interp);
1259}
1260
1261#ifdef MS_WINDOWS
1262static wchar_t *progname = L"python";
1263#else
1264static wchar_t *progname = L"python3";
1265#endif
1266
1267void
1268Py_SetProgramName(wchar_t *pn)
1269{
1270 if (pn && *pn)
1271 progname = pn;
1272}
1273
1274wchar_t *
1275Py_GetProgramName(void)
1276{
1277 return progname;
1278}
1279
1280static wchar_t *default_home = NULL;
1281static wchar_t env_home[MAXPATHLEN+1];
1282
1283void
1284Py_SetPythonHome(wchar_t *home)
1285{
1286 default_home = home;
1287}
1288
1289wchar_t *
1290Py_GetPythonHome(void)
1291{
1292 wchar_t *home = default_home;
1293 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1294 char* chome = Py_GETENV("PYTHONHOME");
1295 if (chome) {
1296 size_t size = Py_ARRAY_LENGTH(env_home);
1297 size_t r = mbstowcs(env_home, chome, size);
1298 if (r != (size_t)-1 && r < size)
1299 home = env_home;
1300 }
1301
1302 }
1303 return home;
1304}
1305
1306/* Create __main__ module */
1307
1308static void
1309initmain(PyInterpreterState *interp)
1310{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001311 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001312 m = PyImport_AddModule("__main__");
1313 if (m == NULL)
1314 Py_FatalError("can't create __main__ module");
1315 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001316 ann_dict = PyDict_New();
1317 if ((ann_dict == NULL) ||
1318 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1319 Py_FatalError("Failed to initialize __main__.__annotations__");
1320 }
1321 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001322 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1323 PyObject *bimod = PyImport_ImportModule("builtins");
1324 if (bimod == NULL) {
1325 Py_FatalError("Failed to retrieve builtins module");
1326 }
1327 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1328 Py_FatalError("Failed to initialize __main__.__builtins__");
1329 }
1330 Py_DECREF(bimod);
1331 }
1332 /* Main is a little special - imp.is_builtin("__main__") will return
1333 * False, but BuiltinImporter is still the most appropriate initial
1334 * setting for its __loader__ attribute. A more suitable value will
1335 * be set if __main__ gets further initialized later in the startup
1336 * process.
1337 */
1338 loader = PyDict_GetItemString(d, "__loader__");
1339 if (loader == NULL || loader == Py_None) {
1340 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1341 "BuiltinImporter");
1342 if (loader == NULL) {
1343 Py_FatalError("Failed to retrieve BuiltinImporter");
1344 }
1345 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1346 Py_FatalError("Failed to initialize __main__.__loader__");
1347 }
1348 Py_DECREF(loader);
1349 }
1350}
1351
1352static int
1353initfsencoding(PyInterpreterState *interp)
1354{
1355 PyObject *codec;
1356
Steve Dowercc16be82016-09-08 10:35:16 -07001357#ifdef MS_WINDOWS
1358 if (Py_LegacyWindowsFSEncodingFlag)
1359 {
1360 Py_FileSystemDefaultEncoding = "mbcs";
1361 Py_FileSystemDefaultEncodeErrors = "replace";
1362 }
1363 else
1364 {
1365 Py_FileSystemDefaultEncoding = "utf-8";
1366 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1367 }
1368#else
Nick Coghland6009512014-11-20 21:39:37 +10001369 if (Py_FileSystemDefaultEncoding == NULL)
1370 {
1371 Py_FileSystemDefaultEncoding = get_locale_encoding();
1372 if (Py_FileSystemDefaultEncoding == NULL)
1373 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1374
1375 Py_HasFileSystemDefaultEncoding = 0;
1376 interp->fscodec_initialized = 1;
1377 return 0;
1378 }
Steve Dowercc16be82016-09-08 10:35:16 -07001379#endif
Nick Coghland6009512014-11-20 21:39:37 +10001380
1381 /* the encoding is mbcs, utf-8 or ascii */
1382 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1383 if (!codec) {
1384 /* Such error can only occurs in critical situations: no more
1385 * memory, import a module of the standard library failed,
1386 * etc. */
1387 return -1;
1388 }
1389 Py_DECREF(codec);
1390 interp->fscodec_initialized = 1;
1391 return 0;
1392}
1393
1394/* Import the site module (not into __main__ though) */
1395
1396static void
1397initsite(void)
1398{
1399 PyObject *m;
1400 m = PyImport_ImportModule("site");
1401 if (m == NULL) {
1402 fprintf(stderr, "Failed to import the site module\n");
1403 PyErr_Print();
1404 Py_Finalize();
1405 exit(1);
1406 }
1407 else {
1408 Py_DECREF(m);
1409 }
1410}
1411
Victor Stinner874dbe82015-09-04 17:29:57 +02001412/* Check if a file descriptor is valid or not.
1413 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1414static int
1415is_valid_fd(int fd)
1416{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001417#ifdef __APPLE__
1418 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1419 and the other side of the pipe is closed, dup(1) succeed, whereas
1420 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1421 such error. */
1422 struct stat st;
1423 return (fstat(fd, &st) == 0);
1424#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001425 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001426 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001427 return 0;
1428 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001429 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1430 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1431 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001432 fd2 = dup(fd);
1433 if (fd2 >= 0)
1434 close(fd2);
1435 _Py_END_SUPPRESS_IPH
1436 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001437#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001438}
1439
1440/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001441static PyObject*
1442create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001443 int fd, int write_mode, const char* name,
1444 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001445{
1446 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1447 const char* mode;
1448 const char* newline;
1449 PyObject *line_buffering;
1450 int buffering, isatty;
1451 _Py_IDENTIFIER(open);
1452 _Py_IDENTIFIER(isatty);
1453 _Py_IDENTIFIER(TextIOWrapper);
1454 _Py_IDENTIFIER(mode);
1455
Victor Stinner874dbe82015-09-04 17:29:57 +02001456 if (!is_valid_fd(fd))
1457 Py_RETURN_NONE;
1458
Nick Coghland6009512014-11-20 21:39:37 +10001459 /* stdin is always opened in buffered mode, first because it shouldn't
1460 make a difference in common use cases, second because TextIOWrapper
1461 depends on the presence of a read1() method which only exists on
1462 buffered streams.
1463 */
1464 if (Py_UnbufferedStdioFlag && write_mode)
1465 buffering = 0;
1466 else
1467 buffering = -1;
1468 if (write_mode)
1469 mode = "wb";
1470 else
1471 mode = "rb";
1472 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1473 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001474 Py_None, Py_None, /* encoding, errors */
1475 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001476 if (buf == NULL)
1477 goto error;
1478
1479 if (buffering) {
1480 _Py_IDENTIFIER(raw);
1481 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1482 if (raw == NULL)
1483 goto error;
1484 }
1485 else {
1486 raw = buf;
1487 Py_INCREF(raw);
1488 }
1489
Steve Dower39294992016-08-30 21:22:36 -07001490#ifdef MS_WINDOWS
1491 /* Windows console IO is always UTF-8 encoded */
1492 if (PyWindowsConsoleIO_Check(raw))
1493 encoding = "utf-8";
1494#endif
1495
Nick Coghland6009512014-11-20 21:39:37 +10001496 text = PyUnicode_FromString(name);
1497 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1498 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001499 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001500 if (res == NULL)
1501 goto error;
1502 isatty = PyObject_IsTrue(res);
1503 Py_DECREF(res);
1504 if (isatty == -1)
1505 goto error;
1506 if (isatty || Py_UnbufferedStdioFlag)
1507 line_buffering = Py_True;
1508 else
1509 line_buffering = Py_False;
1510
1511 Py_CLEAR(raw);
1512 Py_CLEAR(text);
1513
1514#ifdef MS_WINDOWS
1515 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1516 newlines to "\n".
1517 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1518 newline = NULL;
1519#else
1520 /* sys.stdin: split lines at "\n".
1521 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1522 newline = "\n";
1523#endif
1524
1525 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1526 buf, encoding, errors,
1527 newline, line_buffering);
1528 Py_CLEAR(buf);
1529 if (stream == NULL)
1530 goto error;
1531
1532 if (write_mode)
1533 mode = "w";
1534 else
1535 mode = "r";
1536 text = PyUnicode_FromString(mode);
1537 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1538 goto error;
1539 Py_CLEAR(text);
1540 return stream;
1541
1542error:
1543 Py_XDECREF(buf);
1544 Py_XDECREF(stream);
1545 Py_XDECREF(text);
1546 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001547
Victor Stinner874dbe82015-09-04 17:29:57 +02001548 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1549 /* Issue #24891: the file descriptor was closed after the first
1550 is_valid_fd() check was called. Ignore the OSError and set the
1551 stream to None. */
1552 PyErr_Clear();
1553 Py_RETURN_NONE;
1554 }
1555 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001556}
1557
1558/* Initialize sys.stdin, stdout, stderr and builtins.open */
1559static int
1560initstdio(void)
1561{
1562 PyObject *iomod = NULL, *wrapper;
1563 PyObject *bimod = NULL;
1564 PyObject *m;
1565 PyObject *std = NULL;
1566 int status = 0, fd;
1567 PyObject * encoding_attr;
1568 char *pythonioencoding = NULL, *encoding, *errors;
1569
1570 /* Hack to avoid a nasty recursion issue when Python is invoked
1571 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1572 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1573 goto error;
1574 }
1575 Py_DECREF(m);
1576
1577 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1578 goto error;
1579 }
1580 Py_DECREF(m);
1581
1582 if (!(bimod = PyImport_ImportModule("builtins"))) {
1583 goto error;
1584 }
1585
1586 if (!(iomod = PyImport_ImportModule("io"))) {
1587 goto error;
1588 }
1589 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1590 goto error;
1591 }
1592
1593 /* Set builtins.open */
1594 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1595 Py_DECREF(wrapper);
1596 goto error;
1597 }
1598 Py_DECREF(wrapper);
1599
1600 encoding = _Py_StandardStreamEncoding;
1601 errors = _Py_StandardStreamErrors;
1602 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001603 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1604 if (pythonioencoding) {
1605 char *err;
1606 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1607 if (pythonioencoding == NULL) {
1608 PyErr_NoMemory();
1609 goto error;
1610 }
1611 err = strchr(pythonioencoding, ':');
1612 if (err) {
1613 *err = '\0';
1614 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001615 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001616 errors = err;
1617 }
1618 }
1619 if (*pythonioencoding && !encoding) {
1620 encoding = pythonioencoding;
1621 }
1622 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001623 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001624 /* Choose the default error handler based on the current locale */
1625 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001626 }
Nick Coghland6009512014-11-20 21:39:37 +10001627 }
1628
1629 /* Set sys.stdin */
1630 fd = fileno(stdin);
1631 /* Under some conditions stdin, stdout and stderr may not be connected
1632 * and fileno() may point to an invalid file descriptor. For example
1633 * GUI apps don't have valid standard streams by default.
1634 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001635 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1636 if (std == NULL)
1637 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001638 PySys_SetObject("__stdin__", std);
1639 _PySys_SetObjectId(&PyId_stdin, std);
1640 Py_DECREF(std);
1641
1642 /* Set sys.stdout */
1643 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001644 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1645 if (std == NULL)
1646 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001647 PySys_SetObject("__stdout__", std);
1648 _PySys_SetObjectId(&PyId_stdout, std);
1649 Py_DECREF(std);
1650
1651#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1652 /* Set sys.stderr, replaces the preliminary stderr */
1653 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001654 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1655 if (std == NULL)
1656 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001657
1658 /* Same as hack above, pre-import stderr's codec to avoid recursion
1659 when import.c tries to write to stderr in verbose mode. */
1660 encoding_attr = PyObject_GetAttrString(std, "encoding");
1661 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001662 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001663 if (std_encoding != NULL) {
1664 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1665 Py_XDECREF(codec_info);
1666 }
1667 Py_DECREF(encoding_attr);
1668 }
1669 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1670
1671 if (PySys_SetObject("__stderr__", std) < 0) {
1672 Py_DECREF(std);
1673 goto error;
1674 }
1675 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1676 Py_DECREF(std);
1677 goto error;
1678 }
1679 Py_DECREF(std);
1680#endif
1681
1682 if (0) {
1683 error:
1684 status = -1;
1685 }
1686
1687 /* We won't need them anymore. */
1688 if (_Py_StandardStreamEncoding) {
1689 PyMem_RawFree(_Py_StandardStreamEncoding);
1690 _Py_StandardStreamEncoding = NULL;
1691 }
1692 if (_Py_StandardStreamErrors) {
1693 PyMem_RawFree(_Py_StandardStreamErrors);
1694 _Py_StandardStreamErrors = NULL;
1695 }
1696 PyMem_Free(pythonioencoding);
1697 Py_XDECREF(bimod);
1698 Py_XDECREF(iomod);
1699 return status;
1700}
1701
1702
Victor Stinner10dc4842015-03-24 12:01:30 +01001703static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001704_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001705{
Victor Stinner10dc4842015-03-24 12:01:30 +01001706 fputc('\n', stderr);
1707 fflush(stderr);
1708
1709 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001710 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001711}
Victor Stinner791da1c2016-03-14 16:53:12 +01001712
1713/* Print the current exception (if an exception is set) with its traceback,
1714 or display the current Python stack.
1715
1716 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1717 called on catastrophic cases.
1718
1719 Return 1 if the traceback was displayed, 0 otherwise. */
1720
1721static int
1722_Py_FatalError_PrintExc(int fd)
1723{
1724 PyObject *ferr, *res;
1725 PyObject *exception, *v, *tb;
1726 int has_tb;
1727
1728 if (PyThreadState_GET() == NULL) {
1729 /* The GIL is released: trying to acquire it is likely to deadlock,
1730 just give up. */
1731 return 0;
1732 }
1733
1734 PyErr_Fetch(&exception, &v, &tb);
1735 if (exception == NULL) {
1736 /* No current exception */
1737 return 0;
1738 }
1739
1740 ferr = _PySys_GetObjectId(&PyId_stderr);
1741 if (ferr == NULL || ferr == Py_None) {
1742 /* sys.stderr is not set yet or set to None,
1743 no need to try to display the exception */
1744 return 0;
1745 }
1746
1747 PyErr_NormalizeException(&exception, &v, &tb);
1748 if (tb == NULL) {
1749 tb = Py_None;
1750 Py_INCREF(tb);
1751 }
1752 PyException_SetTraceback(v, tb);
1753 if (exception == NULL) {
1754 /* PyErr_NormalizeException() failed */
1755 return 0;
1756 }
1757
1758 has_tb = (tb != Py_None);
1759 PyErr_Display(exception, v, tb);
1760 Py_XDECREF(exception);
1761 Py_XDECREF(v);
1762 Py_XDECREF(tb);
1763
1764 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001765 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001766 if (res == NULL)
1767 PyErr_Clear();
1768 else
1769 Py_DECREF(res);
1770
1771 return has_tb;
1772}
1773
Nick Coghland6009512014-11-20 21:39:37 +10001774/* Print fatal error message and abort */
1775
1776void
1777Py_FatalError(const char *msg)
1778{
1779 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001780 static int reentrant = 0;
1781#ifdef MS_WINDOWS
1782 size_t len;
1783 WCHAR* buffer;
1784 size_t i;
1785#endif
1786
1787 if (reentrant) {
1788 /* Py_FatalError() caused a second fatal error.
1789 Example: flush_std_files() raises a recursion error. */
1790 goto exit;
1791 }
1792 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001793
1794 fprintf(stderr, "Fatal Python error: %s\n", msg);
1795 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001796
Victor Stinnere0deff32015-03-24 13:46:18 +01001797 /* Print the exception (if an exception is set) with its traceback,
1798 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001799 if (!_Py_FatalError_PrintExc(fd))
1800 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001801
Victor Stinner2025d782016-03-16 23:19:15 +01001802 /* The main purpose of faulthandler is to display the traceback. We already
1803 * did our best to display it. So faulthandler can now be disabled.
1804 * (Don't trigger it on abort().) */
1805 _PyFaulthandler_Fini();
1806
Victor Stinner791da1c2016-03-14 16:53:12 +01001807 /* Check if the current Python thread hold the GIL */
1808 if (PyThreadState_GET() != NULL) {
1809 /* Flush sys.stdout and sys.stderr */
1810 flush_std_files();
1811 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001812
Nick Coghland6009512014-11-20 21:39:37 +10001813#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001814 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001815
Victor Stinner53345a42015-03-25 01:55:14 +01001816 /* Convert the message to wchar_t. This uses a simple one-to-one
1817 conversion, assuming that the this error message actually uses ASCII
1818 only. If this ceases to be true, we will have to convert. */
1819 buffer = alloca( (len+1) * (sizeof *buffer));
1820 for( i=0; i<=len; ++i)
1821 buffer[i] = msg[i];
1822 OutputDebugStringW(L"Fatal Python error: ");
1823 OutputDebugStringW(buffer);
1824 OutputDebugStringW(L"\n");
1825#endif /* MS_WINDOWS */
1826
1827exit:
1828#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001829 DebugBreak();
1830#endif
Nick Coghland6009512014-11-20 21:39:37 +10001831 abort();
1832}
1833
1834/* Clean up and exit */
1835
1836#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001837# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001838#endif
1839
1840static void (*pyexitfunc)(void) = NULL;
1841/* For the atexit module. */
1842void _Py_PyAtExit(void (*func)(void))
1843{
1844 pyexitfunc = func;
1845}
1846
1847static void
1848call_py_exitfuncs(void)
1849{
1850 if (pyexitfunc == NULL)
1851 return;
1852
1853 (*pyexitfunc)();
1854 PyErr_Clear();
1855}
1856
1857/* Wait until threading._shutdown completes, provided
1858 the threading module was imported in the first place.
1859 The shutdown routine will wait until all non-daemon
1860 "threading" threads have completed. */
1861static void
1862wait_for_thread_shutdown(void)
1863{
1864#ifdef WITH_THREAD
1865 _Py_IDENTIFIER(_shutdown);
1866 PyObject *result;
1867 PyThreadState *tstate = PyThreadState_GET();
1868 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1869 "threading");
1870 if (threading == NULL) {
1871 /* threading not imported */
1872 PyErr_Clear();
1873 return;
1874 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001875 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001876 if (result == NULL) {
1877 PyErr_WriteUnraisable(threading);
1878 }
1879 else {
1880 Py_DECREF(result);
1881 }
1882 Py_DECREF(threading);
1883#endif
1884}
1885
1886#define NEXITFUNCS 32
1887static void (*exitfuncs[NEXITFUNCS])(void);
1888static int nexitfuncs = 0;
1889
1890int Py_AtExit(void (*func)(void))
1891{
1892 if (nexitfuncs >= NEXITFUNCS)
1893 return -1;
1894 exitfuncs[nexitfuncs++] = func;
1895 return 0;
1896}
1897
1898static void
1899call_ll_exitfuncs(void)
1900{
1901 while (nexitfuncs > 0)
1902 (*exitfuncs[--nexitfuncs])();
1903
1904 fflush(stdout);
1905 fflush(stderr);
1906}
1907
1908void
1909Py_Exit(int sts)
1910{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001911 if (Py_FinalizeEx() < 0) {
1912 sts = 120;
1913 }
Nick Coghland6009512014-11-20 21:39:37 +10001914
1915 exit(sts);
1916}
1917
1918static void
1919initsigs(void)
1920{
1921#ifdef SIGPIPE
1922 PyOS_setsig(SIGPIPE, SIG_IGN);
1923#endif
1924#ifdef SIGXFZ
1925 PyOS_setsig(SIGXFZ, SIG_IGN);
1926#endif
1927#ifdef SIGXFSZ
1928 PyOS_setsig(SIGXFSZ, SIG_IGN);
1929#endif
1930 PyOS_InitInterrupts(); /* May imply initsignal() */
1931 if (PyErr_Occurred()) {
1932 Py_FatalError("Py_Initialize: can't import signal");
1933 }
1934}
1935
1936
1937/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1938 *
1939 * All of the code in this function must only use async-signal-safe functions,
1940 * listed at `man 7 signal` or
1941 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1942 */
1943void
1944_Py_RestoreSignals(void)
1945{
1946#ifdef SIGPIPE
1947 PyOS_setsig(SIGPIPE, SIG_DFL);
1948#endif
1949#ifdef SIGXFZ
1950 PyOS_setsig(SIGXFZ, SIG_DFL);
1951#endif
1952#ifdef SIGXFSZ
1953 PyOS_setsig(SIGXFSZ, SIG_DFL);
1954#endif
1955}
1956
1957
1958/*
1959 * The file descriptor fd is considered ``interactive'' if either
1960 * a) isatty(fd) is TRUE, or
1961 * b) the -i flag was given, and the filename associated with
1962 * the descriptor is NULL or "<stdin>" or "???".
1963 */
1964int
1965Py_FdIsInteractive(FILE *fp, const char *filename)
1966{
1967 if (isatty((int)fileno(fp)))
1968 return 1;
1969 if (!Py_InteractiveFlag)
1970 return 0;
1971 return (filename == NULL) ||
1972 (strcmp(filename, "<stdin>") == 0) ||
1973 (strcmp(filename, "???") == 0);
1974}
1975
1976
Nick Coghland6009512014-11-20 21:39:37 +10001977/* Wrappers around sigaction() or signal(). */
1978
1979PyOS_sighandler_t
1980PyOS_getsig(int sig)
1981{
1982#ifdef HAVE_SIGACTION
1983 struct sigaction context;
1984 if (sigaction(sig, NULL, &context) == -1)
1985 return SIG_ERR;
1986 return context.sa_handler;
1987#else
1988 PyOS_sighandler_t handler;
1989/* Special signal handling for the secure CRT in Visual Studio 2005 */
1990#if defined(_MSC_VER) && _MSC_VER >= 1400
1991 switch (sig) {
1992 /* Only these signals are valid */
1993 case SIGINT:
1994 case SIGILL:
1995 case SIGFPE:
1996 case SIGSEGV:
1997 case SIGTERM:
1998 case SIGBREAK:
1999 case SIGABRT:
2000 break;
2001 /* Don't call signal() with other values or it will assert */
2002 default:
2003 return SIG_ERR;
2004 }
2005#endif /* _MSC_VER && _MSC_VER >= 1400 */
2006 handler = signal(sig, SIG_IGN);
2007 if (handler != SIG_ERR)
2008 signal(sig, handler);
2009 return handler;
2010#endif
2011}
2012
2013/*
2014 * All of the code in this function must only use async-signal-safe functions,
2015 * listed at `man 7 signal` or
2016 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2017 */
2018PyOS_sighandler_t
2019PyOS_setsig(int sig, PyOS_sighandler_t handler)
2020{
2021#ifdef HAVE_SIGACTION
2022 /* Some code in Modules/signalmodule.c depends on sigaction() being
2023 * used here if HAVE_SIGACTION is defined. Fix that if this code
2024 * changes to invalidate that assumption.
2025 */
2026 struct sigaction context, ocontext;
2027 context.sa_handler = handler;
2028 sigemptyset(&context.sa_mask);
2029 context.sa_flags = 0;
2030 if (sigaction(sig, &context, &ocontext) == -1)
2031 return SIG_ERR;
2032 return ocontext.sa_handler;
2033#else
2034 PyOS_sighandler_t oldhandler;
2035 oldhandler = signal(sig, handler);
2036#ifdef HAVE_SIGINTERRUPT
2037 siginterrupt(sig, 1);
2038#endif
2039 return oldhandler;
2040#endif
2041}
2042
2043#ifdef __cplusplus
2044}
2045#endif