blob: 37ecc510c8fba4086c3bdf1311999b25e8eec92b [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"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner27e2d1f2018-11-01 00:52:28 +01007#include "pycore_context.h"
Victor Stinner353933e2018-11-23 13:08:26 +01008#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01009#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010010#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010011#include "pycore_pylifecycle.h"
12#include "pycore_pymem.h"
13#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100014#include "grammar.h"
15#include "node.h"
16#include "token.h"
17#include "parsetok.h"
18#include "errcode.h"
19#include "code.h"
20#include "symtable.h"
21#include "ast.h"
22#include "marshal.h"
23#include "osdefs.h"
24#include <locale.h>
25
26#ifdef HAVE_SIGNAL_H
27#include <signal.h>
28#endif
29
30#ifdef MS_WINDOWS
31#include "malloc.h" /* for alloca */
32#endif
33
34#ifdef HAVE_LANGINFO_H
35#include <langinfo.h>
36#endif
37
38#ifdef MS_WINDOWS
39#undef BYTE
40#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070041
42extern PyTypeObject PyWindowsConsoleIO_Type;
43#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100044#endif
45
46_Py_IDENTIFIER(flush);
47_Py_IDENTIFIER(name);
48_Py_IDENTIFIER(stdin);
49_Py_IDENTIFIER(stdout);
50_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060051_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100052
53#ifdef __cplusplus
54extern "C" {
55#endif
56
Nick Coghland6009512014-11-20 21:39:37 +100057extern grammar _PyParser_Grammar; /* From graminit.c */
58
59/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError add_main_module(PyInterpreterState *interp);
61static _PyInitError initfsencoding(PyInterpreterState *interp);
62static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010063static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080064static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010065static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100066static void wait_for_thread_shutdown(void);
67static void call_ll_exitfuncs(void);
Nick Coghland6009512014-11-20 21:39:37 +100068
Victor Stinnerf7e5b562017-11-15 15:48:08 -080069_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060070
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060072_PyRuntime_Initialize(void)
73{
74 /* XXX We only initialize once in the process, which aligns with
75 the static initialization of the former globals now found in
76 _PyRuntime. However, _PyRuntime *should* be initialized with
77 every Py_Initialize() call, but doing so breaks the runtime.
78 This is because the runtime state is not properly finalized
79 currently. */
80 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081 if (initialized) {
82 return _Py_INIT_OK();
83 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060084 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080085
86 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
88
89void
90_PyRuntime_Finalize(void)
91{
92 _PyRuntimeState_Fini(&_PyRuntime);
93}
94
95int
96_Py_IsFinalizing(void)
97{
98 return _PyRuntime.finalizing != NULL;
99}
100
Nick Coghland6009512014-11-20 21:39:37 +1000101/* Hack to force loading of object files */
102int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
103 PyOS_mystrnicmp; /* Python/pystrcmp.o */
104
105/* PyModule_GetWarningsModule is no longer necessary as of 2.6
106since _warnings is builtin. This API should not be used. */
107PyObject *
108PyModule_GetWarningsModule(void)
109{
110 return PyImport_ImportModule("warnings");
111}
112
Eric Snowc7ec9982017-05-23 23:00:52 -0700113
Eric Snow1abcf672017-05-23 21:46:51 -0700114/* APIs to access the initialization flags
115 *
116 * Can be called prior to Py_Initialize.
117 */
Nick Coghland6009512014-11-20 21:39:37 +1000118
Eric Snow1abcf672017-05-23 21:46:51 -0700119int
120_Py_IsCoreInitialized(void)
121{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700123}
Nick Coghland6009512014-11-20 21:39:37 +1000124
125int
126Py_IsInitialized(void)
127{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600128 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000129}
130
Nick Coghlan6ea41862017-06-11 13:16:15 +1000131
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000132/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
133 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000134 initializations fail, a fatal error is issued and the function does
135 not return. On return, the first thread and interpreter state have
136 been created.
137
138 Locking: you must hold the interpreter lock while calling this.
139 (If the lock has not yet been initialized, that's equivalent to
140 having the lock, but you cannot use multiple threads.)
141
142*/
143
Nick Coghland6009512014-11-20 21:39:37 +1000144static char*
145get_codec_name(const char *encoding)
146{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200147 const char *name_utf8;
148 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000149 PyObject *codec, *name = NULL;
150
151 codec = _PyCodec_Lookup(encoding);
152 if (!codec)
153 goto error;
154
155 name = _PyObject_GetAttrId(codec, &PyId_name);
156 Py_CLEAR(codec);
157 if (!name)
158 goto error;
159
Serhiy Storchaka06515832016-11-20 09:13:07 +0200160 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000161 if (name_utf8 == NULL)
162 goto error;
163 name_str = _PyMem_RawStrdup(name_utf8);
164 Py_DECREF(name);
165 if (name_str == NULL) {
166 PyErr_NoMemory();
167 return NULL;
168 }
169 return name_str;
170
171error:
172 Py_XDECREF(codec);
173 Py_XDECREF(name);
174 return NULL;
175}
176
Nick Coghland6009512014-11-20 21:39:37 +1000177
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800178static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700179initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000180{
181 PyObject *importlib;
182 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000183 PyObject *value;
184
185 /* Import _importlib through its frozen version, _frozen_importlib. */
186 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800187 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000188 }
189 else if (Py_VerboseFlag) {
190 PySys_FormatStderr("import _frozen_importlib # frozen\n");
191 }
192 importlib = PyImport_AddModule("_frozen_importlib");
193 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800194 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000195 }
196 interp->importlib = importlib;
197 Py_INCREF(interp->importlib);
198
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300199 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
200 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800201 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300202 Py_INCREF(interp->import_func);
203
Victor Stinnercd6e6942015-09-18 09:11:57 +0200204 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800205 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000206 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800207 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000208 }
209 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200210 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000211 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600212 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800213 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000214 }
215
Victor Stinnercd6e6942015-09-18 09:11:57 +0200216 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000217 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
218 if (value == NULL) {
219 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800220 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000221 }
222 Py_DECREF(value);
223 Py_DECREF(impmod);
224
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800225 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000226}
227
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800228static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700229initexternalimport(PyInterpreterState *interp)
230{
231 PyObject *value;
232 value = PyObject_CallMethod(interp->importlib,
233 "_install_external_importers", "");
234 if (value == NULL) {
235 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800236 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700237 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200238 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300239 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700240}
Nick Coghland6009512014-11-20 21:39:37 +1000241
Nick Coghlan6ea41862017-06-11 13:16:15 +1000242/* Helper functions to better handle the legacy C locale
243 *
244 * The legacy C locale assumes ASCII as the default text encoding, which
245 * causes problems not only for the CPython runtime, but also other
246 * components like GNU readline.
247 *
248 * Accordingly, when the CLI detects it, it attempts to coerce it to a
249 * more capable UTF-8 based alternative as follows:
250 *
251 * if (_Py_LegacyLocaleDetected()) {
252 * _Py_CoerceLegacyLocale();
253 * }
254 *
255 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
256 *
257 * Locale coercion also impacts the default error handler for the standard
258 * streams: while the usual default is "strict", the default for the legacy
259 * C locale and for any of the coercion target locales is "surrogateescape".
260 */
261
262int
263_Py_LegacyLocaleDetected(void)
264{
265#ifndef MS_WINDOWS
266 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000267 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
268 * the POSIX locale as a simple alias for the C locale, so
269 * we may also want to check for that explicitly.
270 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000271 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
272 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
273#else
274 /* Windows uses code pages instead of locales, so no locale is legacy */
275 return 0;
276#endif
277}
278
Nick Coghlaneb817952017-06-18 12:29:42 +1000279static const char *_C_LOCALE_WARNING =
280 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
281 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
282 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
283 "locales is recommended.\n";
284
Nick Coghlaneb817952017-06-18 12:29:42 +1000285static void
Victor Stinner94540602017-12-16 04:54:22 +0100286_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000287{
Victor Stinner06e76082018-09-19 14:56:36 -0700288 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200289 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000290 }
291}
292
Nick Coghlan6ea41862017-06-11 13:16:15 +1000293typedef struct _CandidateLocale {
294 const char *locale_name; /* The locale to try as a coercion target */
295} _LocaleCoercionTarget;
296
297static _LocaleCoercionTarget _TARGET_LOCALES[] = {
298 {"C.UTF-8"},
299 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000300 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301 {NULL}
302};
303
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200304
305int
306_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200308 const _LocaleCoercionTarget *target = NULL;
309 for (target = _TARGET_LOCALES; target->locale_name; target++) {
310 if (strcmp(ctype_loc, target->locale_name) == 0) {
311 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200313 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200314 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315}
316
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200317
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100319static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000320 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
321 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
322
323static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200324_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000325{
326 const char *newloc = target->locale_name;
327
328 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100329 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000330
331 /* Set the relevant locale environment variable */
332 if (setenv("LC_CTYPE", newloc, 1)) {
333 fprintf(stderr,
334 "Error setting LC_CTYPE, skipping C locale coercion\n");
335 return;
336 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200337 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100338 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000339 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000340
341 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100342 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000343}
344#endif
345
346void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200347_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000348{
349#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200350 char *oldloc = NULL;
351
352 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
353 if (oldloc == NULL) {
354 return;
355 }
356
Victor Stinner94540602017-12-16 04:54:22 +0100357 const char *locale_override = getenv("LC_ALL");
358 if (locale_override == NULL || *locale_override == '\0') {
359 /* LC_ALL is also not set (or is set to an empty string) */
360 const _LocaleCoercionTarget *target = NULL;
361 for (target = _TARGET_LOCALES; target->locale_name; target++) {
362 const char *new_locale = setlocale(LC_CTYPE,
363 target->locale_name);
364 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100365#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100366defined(HAVE_LANGINFO_H) && defined(CODESET)
367 /* Also ensure that nl_langinfo works in this locale */
368 char *codeset = nl_langinfo(CODESET);
369 if (!codeset || *codeset == '\0') {
370 /* CODESET is not set or empty, so skip coercion */
371 new_locale = NULL;
372 _Py_SetLocaleFromEnv(LC_CTYPE);
373 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000374 }
Victor Stinner94540602017-12-16 04:54:22 +0100375#endif
376 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200377 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200378 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000379 }
380 }
381 }
382 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200383
384 setlocale(LC_CTYPE, oldloc);
385
386done:
387 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000388#endif
389}
390
xdegaye1588be62017-11-12 12:45:59 +0100391/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
392 * isolate the idiosyncrasies of different libc implementations. It reads the
393 * appropriate environment variable and uses its value to select the locale for
394 * 'category'. */
395char *
396_Py_SetLocaleFromEnv(int category)
397{
Victor Stinner353933e2018-11-23 13:08:26 +0100398 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100399#ifdef __ANDROID__
400 const char *locale;
401 const char **pvar;
402#ifdef PY_COERCE_C_LOCALE
403 const char *coerce_c_locale;
404#endif
405 const char *utf8_locale = "C.UTF-8";
406 const char *env_var_set[] = {
407 "LC_ALL",
408 "LC_CTYPE",
409 "LANG",
410 NULL,
411 };
412
413 /* Android setlocale(category, "") doesn't check the environment variables
414 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
415 * check the environment variables listed in env_var_set. */
416 for (pvar=env_var_set; *pvar; pvar++) {
417 locale = getenv(*pvar);
418 if (locale != NULL && *locale != '\0') {
419 if (strcmp(locale, utf8_locale) == 0 ||
420 strcmp(locale, "en_US.UTF-8") == 0) {
421 return setlocale(category, utf8_locale);
422 }
423 return setlocale(category, "C");
424 }
425 }
426
427 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
428 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
429 * Quote from POSIX section "8.2 Internationalization Variables":
430 * "4. If the LANG environment variable is not set or is set to the empty
431 * string, the implementation-defined default locale shall be used." */
432
433#ifdef PY_COERCE_C_LOCALE
434 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
435 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
436 /* Some other ported code may check the environment variables (e.g. in
437 * extension modules), so we make sure that they match the locale
438 * configuration */
439 if (setenv("LC_CTYPE", utf8_locale, 1)) {
440 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
441 "environment variable to %s\n", utf8_locale);
442 }
443 }
444#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100445 res = setlocale(category, utf8_locale);
446#else /* !defined(__ANDROID__) */
447 res = setlocale(category, "");
448#endif
449 _Py_ResetForceASCII();
450 return res;
xdegaye1588be62017-11-12 12:45:59 +0100451}
452
Nick Coghlan6ea41862017-06-11 13:16:15 +1000453
Eric Snow1abcf672017-05-23 21:46:51 -0700454/* Global initializations. Can be undone by Py_Finalize(). Don't
455 call this twice without an intervening Py_Finalize() call.
456
Victor Stinner1dc6e392018-07-25 02:49:17 +0200457 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700458 must have a corresponding call to Py_Finalize.
459
460 Locking: you must hold the interpreter lock while calling these APIs.
461 (If the lock has not yet been initialized, that's equivalent to
462 having the lock, but you cannot use multiple threads.)
463
464*/
465
Victor Stinner1dc6e392018-07-25 02:49:17 +0200466static _PyInitError
467_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
468 const _PyCoreConfig *core_config)
469{
470 if (core_config->allocator != NULL) {
471 const char *allocator = _PyMem_GetAllocatorsName();
472 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
473 return _Py_INIT_USER_ERR("cannot modify memory allocator "
474 "after first Py_Initialize()");
475 }
476 }
477
478 _PyCoreConfig_SetGlobalConfig(core_config);
479
480 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
481 return _Py_INIT_ERR("failed to copy core config");
482 }
483 core_config = &interp->core_config;
484
485 if (core_config->_install_importlib) {
486 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
487 if (_Py_INIT_FAILED(err)) {
488 return err;
489 }
490 }
491 return _Py_INIT_OK();
492}
493
494
Eric Snow1abcf672017-05-23 21:46:51 -0700495/* Begin interpreter initialization
496 *
497 * On return, the first thread and interpreter state have been created,
498 * but the compiler, signal handling, multithreading and
499 * multiple interpreter support, and codec infrastructure are not yet
500 * available.
501 *
502 * The import system will support builtin and frozen modules only.
503 * The only supported io is writing to sys.stderr
504 *
505 * If any operation invoked by this function fails, a fatal error is
506 * issued and the function does not return.
507 *
508 * Any code invoked from this function should *not* assume it has access
509 * to the Python C API (unless the API is explicitly listed as being
510 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200511 *
512 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700513 */
514
Victor Stinner1dc6e392018-07-25 02:49:17 +0200515static _PyInitError
516_Py_InitializeCore_impl(PyInterpreterState **interp_p,
517 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000518{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200519 PyInterpreterState *interp;
520 _PyInitError err;
521
522 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
523 Py_Initialize() ignores the new configuration. */
524 if (_PyRuntime.core_initialized) {
Victor Stinner50b48572018-11-01 01:51:40 +0100525 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200526 if (!tstate) {
527 return _Py_INIT_ERR("failed to read thread state");
528 }
529
530 interp = tstate->interp;
531 if (interp == NULL) {
532 return _Py_INIT_ERR("can't make main interpreter");
533 }
534 *interp_p = interp;
535
536 return _Py_Initialize_ReconfigureCore(interp, core_config);
537 }
538
539 if (_PyRuntime.initialized) {
540 return _Py_INIT_ERR("main interpreter already initialized");
541 }
Victor Stinnerda273412017-12-15 01:46:02 +0100542
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200543 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000544
Victor Stinner1dc6e392018-07-25 02:49:17 +0200545 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800546 if (_Py_INIT_FAILED(err)) {
547 return err;
548 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600549
Victor Stinner31e99082017-12-20 23:41:38 +0100550 if (core_config->allocator != NULL) {
551 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
552 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
553 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800554 }
555
Eric Snow1abcf672017-05-23 21:46:51 -0700556 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
557 * threads behave a little more gracefully at interpreter shutdown.
558 * We clobber it here so the new interpreter can start with a clean
559 * slate.
560 *
561 * However, this may still lead to misbehaviour if there are daemon
562 * threads still hanging around from a previous Py_Initialize/Finalize
563 * pair :(
564 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600565 _PyRuntime.finalizing = NULL;
566
Victor Stinnerda273412017-12-15 01:46:02 +0100567 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800568 if (_Py_INIT_FAILED(err)) {
569 return err;
570 }
571
Victor Stinnera7368ac2017-11-15 18:11:45 -0800572 err = _PyInterpreterState_Enable(&_PyRuntime);
573 if (_Py_INIT_FAILED(err)) {
574 return err;
575 }
576
Victor Stinner1dc6e392018-07-25 02:49:17 +0200577 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100578 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800579 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100580 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200581 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100582
583 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
584 return _Py_INIT_ERR("failed to copy core config");
585 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200586 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000587
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200588 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000589 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800590 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000591 (void) PyThreadState_Swap(tstate);
592
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000593 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000594 destroying the GIL might fail when it is being referenced from
595 another running thread (see issue #9901).
596 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000597 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000598 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100599
Nick Coghland6009512014-11-20 21:39:37 +1000600 /* Auto-thread-state API */
601 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000602
Victor Stinner2914bb32018-01-29 11:57:45 +0100603 /* Create the GIL */
604 PyEval_InitThreads();
605
Nick Coghland6009512014-11-20 21:39:37 +1000606 _Py_ReadyTypes();
607
Nick Coghland6009512014-11-20 21:39:37 +1000608 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800609 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000610
611 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800612 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000613
614 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800615 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000616
Eric Snowd393c1b2017-09-14 12:18:12 -0600617 PyObject *modules = PyDict_New();
618 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800619 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600620 interp->modules = modules;
621
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200622 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800623 err = _PySys_BeginInit(&sysmod);
624 if (_Py_INIT_FAILED(err)) {
625 return err;
626 }
627
Eric Snowd393c1b2017-09-14 12:18:12 -0600628 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800629 if (interp->sysdict == NULL) {
630 return _Py_INIT_ERR("can't initialize sys dict");
631 }
632
Eric Snowd393c1b2017-09-14 12:18:12 -0600633 Py_INCREF(interp->sysdict);
634 PyDict_SetItemString(interp->sysdict, "modules", modules);
635 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000636
637 /* Init Unicode implementation; relies on the codec registry */
638 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800639 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700640
Nick Coghland6009512014-11-20 21:39:37 +1000641 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800642 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000643
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200644 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000645 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800646 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600647 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000648 interp->builtins = PyModule_GetDict(bimod);
649 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800650 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000651 Py_INCREF(interp->builtins);
652
653 /* initialize builtin exceptions */
654 _PyExc_Init(bimod);
655
Nick Coghland6009512014-11-20 21:39:37 +1000656 /* Set up a preliminary stderr printer until we have enough
657 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200658 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000659 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800660 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000661 _PySys_SetObjectId(&PyId_stderr, pstderr);
662 PySys_SetObject("__stderr__", pstderr);
663 Py_DECREF(pstderr);
664
Victor Stinner672b6ba2017-12-06 17:25:50 +0100665 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800666 if (_Py_INIT_FAILED(err)) {
667 return err;
668 }
Nick Coghland6009512014-11-20 21:39:37 +1000669
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800670 err = _PyImportHooks_Init();
671 if (_Py_INIT_FAILED(err)) {
672 return err;
673 }
Nick Coghland6009512014-11-20 21:39:37 +1000674
675 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100676 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100677 return _Py_INIT_ERR("can't initialize warnings");
678 }
Nick Coghland6009512014-11-20 21:39:37 +1000679
Yury Selivanovf23746a2018-01-22 19:11:18 -0500680 if (!_PyContext_Init())
681 return _Py_INIT_ERR("can't init context");
682
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200683 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200684 err = _PyCoreConfig_SetPathConfig(core_config);
685 if (_Py_INIT_FAILED(err)) {
686 return err;
687 }
688 }
689
Eric Snow1abcf672017-05-23 21:46:51 -0700690 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200691 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800692 err = initimport(interp, sysmod);
693 if (_Py_INIT_FAILED(err)) {
694 return err;
695 }
Eric Snow1abcf672017-05-23 21:46:51 -0700696 }
697
698 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600699 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800700 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700701}
702
Victor Stinner1dc6e392018-07-25 02:49:17 +0200703_PyInitError
704_Py_InitializeCore(PyInterpreterState **interp_p,
705 const _PyCoreConfig *src_config)
706{
707 assert(src_config != NULL);
708
Victor Stinner1dc6e392018-07-25 02:49:17 +0200709 PyMemAllocatorEx old_alloc;
710 _PyInitError err;
711
712 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
713 (and the input configuration is read only). */
714 _PyCoreConfig config = _PyCoreConfig_INIT;
715
Victor Stinner177d9212018-08-29 11:25:15 +0200716 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200717 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200718
Victor Stinner1dc6e392018-07-25 02:49:17 +0200719 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
720 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
721 err = _PyCoreConfig_Read(&config);
722 }
723 else {
724 err = _Py_INIT_ERR("failed to copy core config");
725 }
726 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
727
728 if (_Py_INIT_FAILED(err)) {
729 goto done;
730 }
731
732 err = _Py_InitializeCore_impl(interp_p, &config);
733
734done:
735 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
736 _PyCoreConfig_Clear(&config);
737 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
738
739 return err;
740}
741
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200742/* Py_Initialize() has already been called: update the main interpreter
743 configuration. Example of bpo-34008: Py_Main() called after
744 Py_Initialize(). */
745static _PyInitError
746_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
747 const _PyMainInterpreterConfig *config)
748{
749 if (config->argv != NULL) {
750 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
751 if (res < 0) {
752 return _Py_INIT_ERR("fail to set sys.argv");
753 }
754 }
755 return _Py_INIT_OK();
756}
757
Eric Snowc7ec9982017-05-23 23:00:52 -0700758/* Update interpreter state based on supplied configuration settings
759 *
760 * After calling this function, most of the restrictions on the interpreter
761 * are lifted. The only remaining incomplete settings are those related
762 * to the main module (sys.argv[0], __main__ metadata)
763 *
764 * Calling this when the interpreter is not initializing, is already
765 * initialized or without a valid current thread state is a fatal error.
766 * Other errors should be reported as normal Python exceptions with a
767 * non-zero return code.
768 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800769_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200770_Py_InitializeMainInterpreter(PyInterpreterState *interp,
771 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700772{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600773 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800774 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700775 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700776
Victor Stinner1dc6e392018-07-25 02:49:17 +0200777 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100778 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
779 return _Py_INIT_ERR("failed to copy main interpreter config");
780 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200781 config = &interp->config;
782 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700783
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200784 if (_PyRuntime.initialized) {
785 return _Py_ReconfigureMainInterpreter(interp, config);
786 }
787
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200788 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700789 /* Special mode for freeze_importlib: run with no import system
790 *
791 * This means anything which needs support from extension modules
792 * or pure Python code in the standard library won't work.
793 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600794 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800795 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700796 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100797
Victor Stinner33c377e2017-12-05 15:12:41 +0100798 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800799 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100800 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200801
Victor Stinnerfbca9082018-08-30 00:50:45 +0200802 if (_PySys_EndInit(interp->sysdict, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800803 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100804 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800805
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200806 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800807 if (_Py_INIT_FAILED(err)) {
808 return err;
809 }
Nick Coghland6009512014-11-20 21:39:37 +1000810
811 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200812 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800813 if (_Py_INIT_FAILED(err)) {
814 return err;
815 }
Nick Coghland6009512014-11-20 21:39:37 +1000816
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800817 err = initfsencoding(interp);
818 if (_Py_INIT_FAILED(err)) {
819 return err;
820 }
Nick Coghland6009512014-11-20 21:39:37 +1000821
Victor Stinner1f151112017-11-23 10:43:14 +0100822 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800823 err = initsigs(); /* Signal handling stuff, including initintr() */
824 if (_Py_INIT_FAILED(err)) {
825 return err;
826 }
827 }
Nick Coghland6009512014-11-20 21:39:37 +1000828
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200829 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800830 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200831 }
Nick Coghland6009512014-11-20 21:39:37 +1000832
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800833 err = add_main_module(interp);
834 if (_Py_INIT_FAILED(err)) {
835 return err;
836 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800837
Victor Stinner91106cd2017-12-13 12:29:09 +0100838 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800839 if (_Py_INIT_FAILED(err)) {
840 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800841 }
Nick Coghland6009512014-11-20 21:39:37 +1000842
843 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100844 PyObject *warnoptions = PySys_GetObject("warnoptions");
845 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100846 {
Nick Coghland6009512014-11-20 21:39:37 +1000847 PyObject *warnings_module = PyImport_ImportModule("warnings");
848 if (warnings_module == NULL) {
849 fprintf(stderr, "'import warnings' failed; traceback:\n");
850 PyErr_Print();
851 }
852 Py_XDECREF(warnings_module);
853 }
854
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600855 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700856
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200857 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800858 err = initsite(); /* Module site */
859 if (_Py_INIT_FAILED(err)) {
860 return err;
861 }
862 }
Victor Stinnercf215042018-08-29 22:56:06 +0200863
864#ifndef MS_WINDOWS
865 _emit_stderr_warning_for_legacy_locale(core_config);
866#endif
867
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800868 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000869}
870
Eric Snowc7ec9982017-05-23 23:00:52 -0700871#undef _INIT_DEBUG_PRINT
872
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800873_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200874_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700875{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700876 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800877 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200878 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800879 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200880 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800881 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200882 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100883
Victor Stinner9cfc0022017-12-20 19:36:46 +0100884 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200885 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100886 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200887 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800888 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100889 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800890 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200891 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800892 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200893 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700894}
895
896
897void
Nick Coghland6009512014-11-20 21:39:37 +1000898Py_InitializeEx(int install_sigs)
899{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200900 if (_PyRuntime.initialized) {
901 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
902 return;
903 }
904
905 _PyInitError err;
906 _PyCoreConfig config = _PyCoreConfig_INIT;
907 config.install_signal_handlers = install_sigs;
908
909 err = _Py_InitializeFromConfig(&config);
910 _PyCoreConfig_Clear(&config);
911
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800912 if (_Py_INIT_FAILED(err)) {
913 _Py_FatalInitError(err);
914 }
Nick Coghland6009512014-11-20 21:39:37 +1000915}
916
917void
918Py_Initialize(void)
919{
920 Py_InitializeEx(1);
921}
922
923
924#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000925extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000926#endif
927
928/* Flush stdout and stderr */
929
930static int
931file_is_closed(PyObject *fobj)
932{
933 int r;
934 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
935 if (tmp == NULL) {
936 PyErr_Clear();
937 return 0;
938 }
939 r = PyObject_IsTrue(tmp);
940 Py_DECREF(tmp);
941 if (r < 0)
942 PyErr_Clear();
943 return r > 0;
944}
945
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000946static int
Nick Coghland6009512014-11-20 21:39:37 +1000947flush_std_files(void)
948{
949 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
950 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
951 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000952 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000953
954 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700955 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000956 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000957 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000958 status = -1;
959 }
Nick Coghland6009512014-11-20 21:39:37 +1000960 else
961 Py_DECREF(tmp);
962 }
963
964 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700965 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000966 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000967 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000968 status = -1;
969 }
Nick Coghland6009512014-11-20 21:39:37 +1000970 else
971 Py_DECREF(tmp);
972 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000973
974 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000975}
976
977/* Undo the effect of Py_Initialize().
978
979 Beware: if multiple interpreter and/or thread states exist, these
980 are not wiped out; only the current thread and interpreter state
981 are deleted. But since everything else is deleted, those other
982 interpreter and thread states should no longer be used.
983
984 (XXX We should do better, e.g. wipe out all interpreters and
985 threads.)
986
987 Locking: as above.
988
989*/
990
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000991int
992Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000993{
994 PyInterpreterState *interp;
995 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000996 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000997
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600998 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000999 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001000
1001 wait_for_thread_shutdown();
1002
Marcel Plch776407f2017-12-20 11:17:58 +01001003 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001004 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001005 interp = tstate->interp;
1006
Nick Coghland6009512014-11-20 21:39:37 +10001007 /* The interpreter is still entirely intact at this point, and the
1008 * exit funcs may be relying on that. In particular, if some thread
1009 * or exit func is still waiting to do an import, the import machinery
1010 * expects Py_IsInitialized() to return true. So don't say the
1011 * interpreter is uninitialized until after the exit funcs have run.
1012 * Note that Threading.py uses an exit func to do a join on all the
1013 * threads created thru it, so this also protects pending imports in
1014 * the threads created via Threading.
1015 */
Nick Coghland6009512014-11-20 21:39:37 +10001016
Marcel Plch776407f2017-12-20 11:17:58 +01001017 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001018
Victor Stinnerda273412017-12-15 01:46:02 +01001019 /* Copy the core config, PyInterpreterState_Delete() free
1020 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001021#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001022 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001023#endif
1024#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001025 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001026#endif
1027#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001028 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001029#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001030
Nick Coghland6009512014-11-20 21:39:37 +10001031 /* Remaining threads (e.g. daemon threads) will automatically exit
1032 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001033 _PyRuntime.finalizing = tstate;
1034 _PyRuntime.initialized = 0;
1035 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001036
Victor Stinnere0deff32015-03-24 13:46:18 +01001037 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001038 if (flush_std_files() < 0) {
1039 status = -1;
1040 }
Nick Coghland6009512014-11-20 21:39:37 +10001041
1042 /* Disable signal handling */
1043 PyOS_FiniInterrupts();
1044
1045 /* Collect garbage. This may call finalizers; it's nice to call these
1046 * before all modules are destroyed.
1047 * XXX If a __del__ or weakref callback is triggered here, and tries to
1048 * XXX import a module, bad things can happen, because Python no
1049 * XXX longer believes it's initialized.
1050 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1051 * XXX is easy to provoke that way. I've also seen, e.g.,
1052 * XXX Exception exceptions.ImportError: 'No module named sha'
1053 * XXX in <function callback at 0x008F5718> ignored
1054 * XXX but I'm unclear on exactly how that one happens. In any case,
1055 * XXX I haven't seen a real-life report of either of these.
1056 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001057 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001058#ifdef COUNT_ALLOCS
1059 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1060 each collection might release some types from the type
1061 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001062 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001063 /* nothing */;
1064#endif
Eric Snowdae02762017-09-14 00:35:58 -07001065
Nick Coghland6009512014-11-20 21:39:37 +10001066 /* Destroy all modules */
1067 PyImport_Cleanup();
1068
Victor Stinnere0deff32015-03-24 13:46:18 +01001069 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001070 if (flush_std_files() < 0) {
1071 status = -1;
1072 }
Nick Coghland6009512014-11-20 21:39:37 +10001073
1074 /* Collect final garbage. This disposes of cycles created by
1075 * class definitions, for example.
1076 * XXX This is disabled because it caused too many problems. If
1077 * XXX a __del__ or weakref callback triggers here, Python code has
1078 * XXX a hard time running, because even the sys module has been
1079 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1080 * XXX One symptom is a sequence of information-free messages
1081 * XXX coming from threads (if a __del__ or callback is invoked,
1082 * XXX other threads can execute too, and any exception they encounter
1083 * XXX triggers a comedy of errors as subsystem after subsystem
1084 * XXX fails to find what it *expects* to find in sys to help report
1085 * XXX the exception and consequent unexpected failures). I've also
1086 * XXX seen segfaults then, after adding print statements to the
1087 * XXX Python code getting called.
1088 */
1089#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001090 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001091#endif
1092
1093 /* Disable tracemalloc after all Python objects have been destroyed,
1094 so it is possible to use tracemalloc in objects destructor. */
1095 _PyTraceMalloc_Fini();
1096
1097 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1098 _PyImport_Fini();
1099
1100 /* Cleanup typeobject.c's internal caches. */
1101 _PyType_Fini();
1102
1103 /* unload faulthandler module */
1104 _PyFaulthandler_Fini();
1105
1106 /* Debugging stuff */
1107#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001108 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001109#endif
1110 /* dump hash stats */
1111 _PyHash_Fini();
1112
Eric Snowdae02762017-09-14 00:35:58 -07001113#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001114 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001115 _PyDebug_PrintTotalRefs();
1116 }
Eric Snowdae02762017-09-14 00:35:58 -07001117#endif
Nick Coghland6009512014-11-20 21:39:37 +10001118
1119#ifdef Py_TRACE_REFS
1120 /* Display all objects still alive -- this can invoke arbitrary
1121 * __repr__ overrides, so requires a mostly-intact interpreter.
1122 * Alas, a lot of stuff may still be alive now that will be cleaned
1123 * up later.
1124 */
Victor Stinnerda273412017-12-15 01:46:02 +01001125 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001126 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001127 }
Nick Coghland6009512014-11-20 21:39:37 +10001128#endif /* Py_TRACE_REFS */
1129
1130 /* Clear interpreter state and all thread states. */
1131 PyInterpreterState_Clear(interp);
1132
1133 /* Now we decref the exception classes. After this point nothing
1134 can raise an exception. That's okay, because each Fini() method
1135 below has been checked to make sure no exceptions are ever
1136 raised.
1137 */
1138
1139 _PyExc_Fini();
1140
1141 /* Sundry finalizers */
1142 PyMethod_Fini();
1143 PyFrame_Fini();
1144 PyCFunction_Fini();
1145 PyTuple_Fini();
1146 PyList_Fini();
1147 PySet_Fini();
1148 PyBytes_Fini();
1149 PyByteArray_Fini();
1150 PyLong_Fini();
1151 PyFloat_Fini();
1152 PyDict_Fini();
1153 PySlice_Fini();
1154 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001155 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001156 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001157 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001158 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001159
1160 /* Cleanup Unicode implementation */
1161 _PyUnicode_Fini();
1162
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001163 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001164
1165 /* XXX Still allocated:
1166 - various static ad-hoc pointers to interned strings
1167 - int and float free list blocks
1168 - whatever various modules and libraries allocate
1169 */
1170
1171 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1172
1173 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001174 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001175
1176 /* Delete current thread. After this, many C API calls become crashy. */
1177 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001178
Nick Coghland6009512014-11-20 21:39:37 +10001179 PyInterpreterState_Delete(interp);
1180
1181#ifdef Py_TRACE_REFS
1182 /* Display addresses (& refcnts) of all objects still alive.
1183 * An address can be used to find the repr of the object, printed
1184 * above by _Py_PrintReferences.
1185 */
Victor Stinnerda273412017-12-15 01:46:02 +01001186 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001187 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001188 }
Nick Coghland6009512014-11-20 21:39:37 +10001189#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001190#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001191 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001192 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001193 }
Nick Coghland6009512014-11-20 21:39:37 +10001194#endif
1195
1196 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001197
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001198 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001199 return status;
1200}
1201
1202void
1203Py_Finalize(void)
1204{
1205 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001206}
1207
1208/* Create and initialize a new interpreter and thread, and return the
1209 new thread. This requires that Py_Initialize() has been called
1210 first.
1211
1212 Unsuccessful initialization yields a NULL pointer. Note that *no*
1213 exception information is available even in this case -- the
1214 exception information is held in the thread, and there is no
1215 thread.
1216
1217 Locking: as above.
1218
1219*/
1220
Victor Stinnera7368ac2017-11-15 18:11:45 -08001221static _PyInitError
1222new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001223{
1224 PyInterpreterState *interp;
1225 PyThreadState *tstate, *save_tstate;
1226 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001227 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001228
Victor Stinnera7368ac2017-11-15 18:11:45 -08001229 if (!_PyRuntime.initialized) {
1230 return _Py_INIT_ERR("Py_Initialize must be called first");
1231 }
Nick Coghland6009512014-11-20 21:39:37 +10001232
Victor Stinner8a1be612016-03-14 22:07:55 +01001233 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1234 interpreters: disable PyGILState_Check(). */
1235 _PyGILState_check_enabled = 0;
1236
Nick Coghland6009512014-11-20 21:39:37 +10001237 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001238 if (interp == NULL) {
1239 *tstate_p = NULL;
1240 return _Py_INIT_OK();
1241 }
Nick Coghland6009512014-11-20 21:39:37 +10001242
1243 tstate = PyThreadState_New(interp);
1244 if (tstate == NULL) {
1245 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001246 *tstate_p = NULL;
1247 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001248 }
1249
1250 save_tstate = PyThreadState_Swap(tstate);
1251
Eric Snow1abcf672017-05-23 21:46:51 -07001252 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001253 _PyCoreConfig *core_config;
1254 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001255 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001256 core_config = &save_tstate->interp->core_config;
1257 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001258 } else {
1259 /* No current thread state, copy from the main interpreter */
1260 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001261 core_config = &main_interp->core_config;
1262 config = &main_interp->config;
1263 }
1264
1265 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1266 return _Py_INIT_ERR("failed to copy core config");
1267 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001268 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001269 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1270 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001271 }
1272
Nick Coghland6009512014-11-20 21:39:37 +10001273 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001274 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001275 if (modules == NULL) {
1276 return _Py_INIT_ERR("can't make modules dictionary");
1277 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001278 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001279
Eric Snowd393c1b2017-09-14 12:18:12 -06001280 sysmod = _PyImport_FindBuiltin("sys", modules);
1281 if (sysmod != NULL) {
1282 interp->sysdict = PyModule_GetDict(sysmod);
1283 if (interp->sysdict == NULL)
1284 goto handle_error;
1285 Py_INCREF(interp->sysdict);
1286 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001287 _PySys_EndInit(interp->sysdict, interp);
Eric Snowd393c1b2017-09-14 12:18:12 -06001288 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001289 else if (PyErr_Occurred()) {
1290 goto handle_error;
1291 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001292
1293 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001294 if (bimod != NULL) {
1295 interp->builtins = PyModule_GetDict(bimod);
1296 if (interp->builtins == NULL)
1297 goto handle_error;
1298 Py_INCREF(interp->builtins);
1299 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001300 else if (PyErr_Occurred()) {
1301 goto handle_error;
1302 }
Nick Coghland6009512014-11-20 21:39:37 +10001303
1304 /* initialize builtin exceptions */
1305 _PyExc_Init(bimod);
1306
Nick Coghland6009512014-11-20 21:39:37 +10001307 if (bimod != NULL && sysmod != NULL) {
1308 PyObject *pstderr;
1309
Nick Coghland6009512014-11-20 21:39:37 +10001310 /* Set up a preliminary stderr printer until we have enough
1311 infrastructure for the io module in place. */
1312 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001313 if (pstderr == NULL) {
1314 return _Py_INIT_ERR("can't set preliminary stderr");
1315 }
Nick Coghland6009512014-11-20 21:39:37 +10001316 _PySys_SetObjectId(&PyId_stderr, pstderr);
1317 PySys_SetObject("__stderr__", pstderr);
1318 Py_DECREF(pstderr);
1319
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001320 err = _PyImportHooks_Init();
1321 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001322 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001323 }
Nick Coghland6009512014-11-20 21:39:37 +10001324
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001325 err = initimport(interp, sysmod);
1326 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001327 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001328 }
Nick Coghland6009512014-11-20 21:39:37 +10001329
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001330 err = initexternalimport(interp);
1331 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001332 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001333 }
Nick Coghland6009512014-11-20 21:39:37 +10001334
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001335 err = initfsencoding(interp);
1336 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001337 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001338 }
1339
Victor Stinner91106cd2017-12-13 12:29:09 +01001340 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001341 if (_Py_INIT_FAILED(err)) {
1342 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001343 }
1344
1345 err = add_main_module(interp);
1346 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001347 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001348 }
1349
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001350 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001351 err = initsite();
1352 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001353 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001354 }
1355 }
Nick Coghland6009512014-11-20 21:39:37 +10001356 }
1357
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358 if (PyErr_Occurred()) {
1359 goto handle_error;
1360 }
Nick Coghland6009512014-11-20 21:39:37 +10001361
Victor Stinnera7368ac2017-11-15 18:11:45 -08001362 *tstate_p = tstate;
1363 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001364
Nick Coghland6009512014-11-20 21:39:37 +10001365handle_error:
1366 /* Oops, it didn't work. Undo it all. */
1367
1368 PyErr_PrintEx(0);
1369 PyThreadState_Clear(tstate);
1370 PyThreadState_Swap(save_tstate);
1371 PyThreadState_Delete(tstate);
1372 PyInterpreterState_Delete(interp);
1373
Victor Stinnera7368ac2017-11-15 18:11:45 -08001374 *tstate_p = NULL;
1375 return _Py_INIT_OK();
1376}
1377
1378PyThreadState *
1379Py_NewInterpreter(void)
1380{
1381 PyThreadState *tstate;
1382 _PyInitError err = new_interpreter(&tstate);
1383 if (_Py_INIT_FAILED(err)) {
1384 _Py_FatalInitError(err);
1385 }
1386 return tstate;
1387
Nick Coghland6009512014-11-20 21:39:37 +10001388}
1389
1390/* Delete an interpreter and its last thread. This requires that the
1391 given thread state is current, that the thread has no remaining
1392 frames, and that it is its interpreter's only remaining thread.
1393 It is a fatal error to violate these constraints.
1394
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001395 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001396 everything, regardless.)
1397
1398 Locking: as above.
1399
1400*/
1401
1402void
1403Py_EndInterpreter(PyThreadState *tstate)
1404{
1405 PyInterpreterState *interp = tstate->interp;
1406
Victor Stinner50b48572018-11-01 01:51:40 +01001407 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001408 Py_FatalError("Py_EndInterpreter: thread is not current");
1409 if (tstate->frame != NULL)
1410 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1411
1412 wait_for_thread_shutdown();
1413
Marcel Plch776407f2017-12-20 11:17:58 +01001414 call_py_exitfuncs(interp);
1415
Nick Coghland6009512014-11-20 21:39:37 +10001416 if (tstate != interp->tstate_head || tstate->next != NULL)
1417 Py_FatalError("Py_EndInterpreter: not the last thread");
1418
1419 PyImport_Cleanup();
1420 PyInterpreterState_Clear(interp);
1421 PyThreadState_Swap(NULL);
1422 PyInterpreterState_Delete(interp);
1423}
1424
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001425/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001426
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001427static _PyInitError
1428add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001429{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001430 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001431 m = PyImport_AddModule("__main__");
1432 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001433 return _Py_INIT_ERR("can't create __main__ module");
1434
Nick Coghland6009512014-11-20 21:39:37 +10001435 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001436 ann_dict = PyDict_New();
1437 if ((ann_dict == NULL) ||
1438 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001439 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001440 }
1441 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001442
Nick Coghland6009512014-11-20 21:39:37 +10001443 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1444 PyObject *bimod = PyImport_ImportModule("builtins");
1445 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001446 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001447 }
1448 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001449 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001450 }
1451 Py_DECREF(bimod);
1452 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001453
Nick Coghland6009512014-11-20 21:39:37 +10001454 /* Main is a little special - imp.is_builtin("__main__") will return
1455 * False, but BuiltinImporter is still the most appropriate initial
1456 * setting for its __loader__ attribute. A more suitable value will
1457 * be set if __main__ gets further initialized later in the startup
1458 * process.
1459 */
1460 loader = PyDict_GetItemString(d, "__loader__");
1461 if (loader == NULL || loader == Py_None) {
1462 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1463 "BuiltinImporter");
1464 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001465 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001466 }
1467 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001468 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001469 }
1470 Py_DECREF(loader);
1471 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001472 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001473}
1474
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001475static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001476initfsencoding(PyInterpreterState *interp)
1477{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001478 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001479
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001480 char *encoding = get_codec_name(config->filesystem_encoding);
1481 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001482 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001483 memory, import a module of the standard library failed, etc. */
1484 return _Py_INIT_ERR("failed to get the Python codec "
1485 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001486 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001487
1488 /* Update the filesystem encoding to the normalized Python codec name.
1489 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1490 (Python codec name). */
1491 PyMem_RawFree(config->filesystem_encoding);
1492 config->filesystem_encoding = encoding;
1493
1494 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1495 global configuration variables. */
1496 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1497 config->filesystem_errors) < 0) {
1498 return _Py_INIT_NO_MEMORY();
1499 }
1500
1501 /* PyUnicode can now use the Python codec rather than C implementation
1502 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001503 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001504 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001505}
1506
1507/* Import the site module (not into __main__ though) */
1508
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001509static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001510initsite(void)
1511{
1512 PyObject *m;
1513 m = PyImport_ImportModule("site");
1514 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001516 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517 Py_DECREF(m);
1518 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001519}
1520
Victor Stinner874dbe82015-09-04 17:29:57 +02001521/* Check if a file descriptor is valid or not.
1522 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1523static int
1524is_valid_fd(int fd)
1525{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001526#ifdef __APPLE__
1527 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1528 and the other side of the pipe is closed, dup(1) succeed, whereas
1529 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1530 such error. */
1531 struct stat st;
1532 return (fstat(fd, &st) == 0);
1533#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001534 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001535 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001536 return 0;
1537 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001538 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1539 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1540 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001541 fd2 = dup(fd);
1542 if (fd2 >= 0)
1543 close(fd2);
1544 _Py_END_SUPPRESS_IPH
1545 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001546#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001547}
1548
1549/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001550static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001551create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001552 int fd, int write_mode, const char* name,
1553 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001554{
1555 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1556 const char* mode;
1557 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001558 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001559 int buffering, isatty;
1560 _Py_IDENTIFIER(open);
1561 _Py_IDENTIFIER(isatty);
1562 _Py_IDENTIFIER(TextIOWrapper);
1563 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001564 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001565
Victor Stinner874dbe82015-09-04 17:29:57 +02001566 if (!is_valid_fd(fd))
1567 Py_RETURN_NONE;
1568
Nick Coghland6009512014-11-20 21:39:37 +10001569 /* stdin is always opened in buffered mode, first because it shouldn't
1570 make a difference in common use cases, second because TextIOWrapper
1571 depends on the presence of a read1() method which only exists on
1572 buffered streams.
1573 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001574 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001575 buffering = 0;
1576 else
1577 buffering = -1;
1578 if (write_mode)
1579 mode = "wb";
1580 else
1581 mode = "rb";
1582 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1583 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001584 Py_None, Py_None, /* encoding, errors */
1585 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001586 if (buf == NULL)
1587 goto error;
1588
1589 if (buffering) {
1590 _Py_IDENTIFIER(raw);
1591 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1592 if (raw == NULL)
1593 goto error;
1594 }
1595 else {
1596 raw = buf;
1597 Py_INCREF(raw);
1598 }
1599
Steve Dower39294992016-08-30 21:22:36 -07001600#ifdef MS_WINDOWS
1601 /* Windows console IO is always UTF-8 encoded */
1602 if (PyWindowsConsoleIO_Check(raw))
1603 encoding = "utf-8";
1604#endif
1605
Nick Coghland6009512014-11-20 21:39:37 +10001606 text = PyUnicode_FromString(name);
1607 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1608 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001609 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001610 if (res == NULL)
1611 goto error;
1612 isatty = PyObject_IsTrue(res);
1613 Py_DECREF(res);
1614 if (isatty == -1)
1615 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001616 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001617 write_through = Py_True;
1618 else
1619 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001620 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001621 line_buffering = Py_True;
1622 else
1623 line_buffering = Py_False;
1624
1625 Py_CLEAR(raw);
1626 Py_CLEAR(text);
1627
1628#ifdef MS_WINDOWS
1629 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1630 newlines to "\n".
1631 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1632 newline = NULL;
1633#else
1634 /* sys.stdin: split lines at "\n".
1635 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1636 newline = "\n";
1637#endif
1638
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001639 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001640 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001641 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001642 Py_CLEAR(buf);
1643 if (stream == NULL)
1644 goto error;
1645
1646 if (write_mode)
1647 mode = "w";
1648 else
1649 mode = "r";
1650 text = PyUnicode_FromString(mode);
1651 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1652 goto error;
1653 Py_CLEAR(text);
1654 return stream;
1655
1656error:
1657 Py_XDECREF(buf);
1658 Py_XDECREF(stream);
1659 Py_XDECREF(text);
1660 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001661
Victor Stinner874dbe82015-09-04 17:29:57 +02001662 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1663 /* Issue #24891: the file descriptor was closed after the first
1664 is_valid_fd() check was called. Ignore the OSError and set the
1665 stream to None. */
1666 PyErr_Clear();
1667 Py_RETURN_NONE;
1668 }
1669 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001670}
1671
1672/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001673static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001674init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001675{
1676 PyObject *iomod = NULL, *wrapper;
1677 PyObject *bimod = NULL;
1678 PyObject *m;
1679 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001680 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001681 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001682 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001683 _PyCoreConfig *config = &interp->core_config;
1684
1685 char *codec_name = get_codec_name(config->stdio_encoding);
1686 if (codec_name == NULL) {
1687 return _Py_INIT_ERR("failed to get the Python codec name "
1688 "of the stdio encoding");
1689 }
1690 PyMem_RawFree(config->stdio_encoding);
1691 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001692
1693 /* Hack to avoid a nasty recursion issue when Python is invoked
1694 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1695 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1696 goto error;
1697 }
1698 Py_DECREF(m);
1699
1700 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1701 goto error;
1702 }
1703 Py_DECREF(m);
1704
1705 if (!(bimod = PyImport_ImportModule("builtins"))) {
1706 goto error;
1707 }
1708
1709 if (!(iomod = PyImport_ImportModule("io"))) {
1710 goto error;
1711 }
1712 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1713 goto error;
1714 }
1715
1716 /* Set builtins.open */
1717 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1718 Py_DECREF(wrapper);
1719 goto error;
1720 }
1721 Py_DECREF(wrapper);
1722
Nick Coghland6009512014-11-20 21:39:37 +10001723 /* Set sys.stdin */
1724 fd = fileno(stdin);
1725 /* Under some conditions stdin, stdout and stderr may not be connected
1726 * and fileno() may point to an invalid file descriptor. For example
1727 * GUI apps don't have valid standard streams by default.
1728 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001729 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001730 config->stdio_encoding,
1731 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001732 if (std == NULL)
1733 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001734 PySys_SetObject("__stdin__", std);
1735 _PySys_SetObjectId(&PyId_stdin, std);
1736 Py_DECREF(std);
1737
1738 /* Set sys.stdout */
1739 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001740 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001741 config->stdio_encoding,
1742 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001743 if (std == NULL)
1744 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001745 PySys_SetObject("__stdout__", std);
1746 _PySys_SetObjectId(&PyId_stdout, std);
1747 Py_DECREF(std);
1748
1749#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1750 /* Set sys.stderr, replaces the preliminary stderr */
1751 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001752 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001753 config->stdio_encoding,
1754 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001755 if (std == NULL)
1756 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001757
1758 /* Same as hack above, pre-import stderr's codec to avoid recursion
1759 when import.c tries to write to stderr in verbose mode. */
1760 encoding_attr = PyObject_GetAttrString(std, "encoding");
1761 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001762 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001763 if (std_encoding != NULL) {
1764 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1765 Py_XDECREF(codec_info);
1766 }
1767 Py_DECREF(encoding_attr);
1768 }
1769 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1770
1771 if (PySys_SetObject("__stderr__", std) < 0) {
1772 Py_DECREF(std);
1773 goto error;
1774 }
1775 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1776 Py_DECREF(std);
1777 goto error;
1778 }
1779 Py_DECREF(std);
1780#endif
1781
Victor Stinnera7368ac2017-11-15 18:11:45 -08001782 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001783
Victor Stinnera7368ac2017-11-15 18:11:45 -08001784error:
1785 res = _Py_INIT_ERR("can't initialize sys standard streams");
1786
1787done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001788 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001789
Nick Coghland6009512014-11-20 21:39:37 +10001790 Py_XDECREF(bimod);
1791 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001792 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001793}
1794
1795
Victor Stinner10dc4842015-03-24 12:01:30 +01001796static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001797_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001798{
Victor Stinner10dc4842015-03-24 12:01:30 +01001799 fputc('\n', stderr);
1800 fflush(stderr);
1801
1802 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001803 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001804}
Victor Stinner791da1c2016-03-14 16:53:12 +01001805
1806/* Print the current exception (if an exception is set) with its traceback,
1807 or display the current Python stack.
1808
1809 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1810 called on catastrophic cases.
1811
1812 Return 1 if the traceback was displayed, 0 otherwise. */
1813
1814static int
1815_Py_FatalError_PrintExc(int fd)
1816{
1817 PyObject *ferr, *res;
1818 PyObject *exception, *v, *tb;
1819 int has_tb;
1820
Victor Stinner791da1c2016-03-14 16:53:12 +01001821 PyErr_Fetch(&exception, &v, &tb);
1822 if (exception == NULL) {
1823 /* No current exception */
1824 return 0;
1825 }
1826
1827 ferr = _PySys_GetObjectId(&PyId_stderr);
1828 if (ferr == NULL || ferr == Py_None) {
1829 /* sys.stderr is not set yet or set to None,
1830 no need to try to display the exception */
1831 return 0;
1832 }
1833
1834 PyErr_NormalizeException(&exception, &v, &tb);
1835 if (tb == NULL) {
1836 tb = Py_None;
1837 Py_INCREF(tb);
1838 }
1839 PyException_SetTraceback(v, tb);
1840 if (exception == NULL) {
1841 /* PyErr_NormalizeException() failed */
1842 return 0;
1843 }
1844
1845 has_tb = (tb != Py_None);
1846 PyErr_Display(exception, v, tb);
1847 Py_XDECREF(exception);
1848 Py_XDECREF(v);
1849 Py_XDECREF(tb);
1850
1851 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001852 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001853 if (res == NULL)
1854 PyErr_Clear();
1855 else
1856 Py_DECREF(res);
1857
1858 return has_tb;
1859}
1860
Nick Coghland6009512014-11-20 21:39:37 +10001861/* Print fatal error message and abort */
1862
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001863#ifdef MS_WINDOWS
1864static void
1865fatal_output_debug(const char *msg)
1866{
1867 /* buffer of 256 bytes allocated on the stack */
1868 WCHAR buffer[256 / sizeof(WCHAR)];
1869 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1870 size_t msglen;
1871
1872 OutputDebugStringW(L"Fatal Python error: ");
1873
1874 msglen = strlen(msg);
1875 while (msglen) {
1876 size_t i;
1877
1878 if (buflen > msglen) {
1879 buflen = msglen;
1880 }
1881
1882 /* Convert the message to wchar_t. This uses a simple one-to-one
1883 conversion, assuming that the this error message actually uses
1884 ASCII only. If this ceases to be true, we will have to convert. */
1885 for (i=0; i < buflen; ++i) {
1886 buffer[i] = msg[i];
1887 }
1888 buffer[i] = L'\0';
1889 OutputDebugStringW(buffer);
1890
1891 msg += buflen;
1892 msglen -= buflen;
1893 }
1894 OutputDebugStringW(L"\n");
1895}
1896#endif
1897
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001898static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001899fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001900{
1901 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001902 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001903
1904 if (reentrant) {
1905 /* Py_FatalError() caused a second fatal error.
1906 Example: flush_std_files() raises a recursion error. */
1907 goto exit;
1908 }
1909 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001910
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001911 fprintf(stderr, "Fatal Python error: ");
1912 if (prefix) {
1913 fputs(prefix, stderr);
1914 fputs(": ", stderr);
1915 }
1916 if (msg) {
1917 fputs(msg, stderr);
1918 }
1919 else {
1920 fprintf(stderr, "<message not set>");
1921 }
1922 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001923 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001924
Victor Stinner3a228ab2018-11-01 00:26:41 +01001925 /* Check if the current thread has a Python thread state
1926 and holds the GIL */
1927 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
1928 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01001929 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01001930 if (tss_tstate != tstate) {
1931 /* The Python thread does not hold the GIL */
1932 tss_tstate = NULL;
1933 }
1934 }
1935 else {
1936 /* Py_FatalError() has been called from a C thread
1937 which has no Python thread state. */
1938 }
1939 int has_tstate_and_gil = (tss_tstate != NULL);
1940
1941 if (has_tstate_and_gil) {
1942 /* If an exception is set, print the exception with its traceback */
1943 if (!_Py_FatalError_PrintExc(fd)) {
1944 /* No exception is set, or an exception is set without traceback */
1945 _Py_FatalError_DumpTracebacks(fd);
1946 }
1947 }
1948 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01001949 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001950 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001951
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001952 /* The main purpose of faulthandler is to display the traceback.
1953 This function already did its best to display a traceback.
1954 Disable faulthandler to prevent writing a second traceback
1955 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001956 _PyFaulthandler_Fini();
1957
Victor Stinner791da1c2016-03-14 16:53:12 +01001958 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01001959 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001960 /* Flush sys.stdout and sys.stderr */
1961 flush_std_files();
1962 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001963
Nick Coghland6009512014-11-20 21:39:37 +10001964#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001965 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001966#endif /* MS_WINDOWS */
1967
1968exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001969 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01001970#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001971 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10001972#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001973 abort();
1974 }
1975 else {
1976 exit(status);
1977 }
1978}
1979
Victor Stinner19760862017-12-20 01:41:59 +01001980void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001981Py_FatalError(const char *msg)
1982{
1983 fatal_error(NULL, msg, -1);
1984}
1985
Victor Stinner19760862017-12-20 01:41:59 +01001986void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001987_Py_FatalInitError(_PyInitError err)
1988{
1989 /* On "user" error: exit with status 1.
1990 For all other errors, call abort(). */
1991 int status = err.user_err ? 1 : -1;
1992 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10001993}
1994
1995/* Clean up and exit */
1996
Victor Stinnerd7292b52016-06-17 12:29:00 +02001997# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001998
Nick Coghland6009512014-11-20 21:39:37 +10001999/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002000void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002001{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002002 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002003
Antoine Pitroufc5db952017-12-13 02:29:07 +01002004 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002005 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2006
2007 is->pyexitfunc = func;
2008 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002009}
2010
2011static void
Marcel Plch776407f2017-12-20 11:17:58 +01002012call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002013{
Marcel Plch776407f2017-12-20 11:17:58 +01002014 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002015 return;
2016
Marcel Plch776407f2017-12-20 11:17:58 +01002017 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002018 PyErr_Clear();
2019}
2020
2021/* Wait until threading._shutdown completes, provided
2022 the threading module was imported in the first place.
2023 The shutdown routine will wait until all non-daemon
2024 "threading" threads have completed. */
2025static void
2026wait_for_thread_shutdown(void)
2027{
Nick Coghland6009512014-11-20 21:39:37 +10002028 _Py_IDENTIFIER(_shutdown);
2029 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002030 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002031 if (threading == NULL) {
2032 /* threading not imported */
2033 PyErr_Clear();
2034 return;
2035 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002036 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002037 if (result == NULL) {
2038 PyErr_WriteUnraisable(threading);
2039 }
2040 else {
2041 Py_DECREF(result);
2042 }
2043 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002044}
2045
2046#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002047int Py_AtExit(void (*func)(void))
2048{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002049 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002050 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002051 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002052 return 0;
2053}
2054
2055static void
2056call_ll_exitfuncs(void)
2057{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002058 while (_PyRuntime.nexitfuncs > 0)
2059 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002060
2061 fflush(stdout);
2062 fflush(stderr);
2063}
2064
Victor Stinnercfc88312018-08-01 16:41:25 +02002065void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002066Py_Exit(int sts)
2067{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002068 if (Py_FinalizeEx() < 0) {
2069 sts = 120;
2070 }
Nick Coghland6009512014-11-20 21:39:37 +10002071
2072 exit(sts);
2073}
2074
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002075static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002076initsigs(void)
2077{
2078#ifdef SIGPIPE
2079 PyOS_setsig(SIGPIPE, SIG_IGN);
2080#endif
2081#ifdef SIGXFZ
2082 PyOS_setsig(SIGXFZ, SIG_IGN);
2083#endif
2084#ifdef SIGXFSZ
2085 PyOS_setsig(SIGXFSZ, SIG_IGN);
2086#endif
2087 PyOS_InitInterrupts(); /* May imply initsignal() */
2088 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002089 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002090 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002091 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002092}
2093
2094
2095/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2096 *
2097 * All of the code in this function must only use async-signal-safe functions,
2098 * listed at `man 7 signal` or
2099 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2100 */
2101void
2102_Py_RestoreSignals(void)
2103{
2104#ifdef SIGPIPE
2105 PyOS_setsig(SIGPIPE, SIG_DFL);
2106#endif
2107#ifdef SIGXFZ
2108 PyOS_setsig(SIGXFZ, SIG_DFL);
2109#endif
2110#ifdef SIGXFSZ
2111 PyOS_setsig(SIGXFSZ, SIG_DFL);
2112#endif
2113}
2114
2115
2116/*
2117 * The file descriptor fd is considered ``interactive'' if either
2118 * a) isatty(fd) is TRUE, or
2119 * b) the -i flag was given, and the filename associated with
2120 * the descriptor is NULL or "<stdin>" or "???".
2121 */
2122int
2123Py_FdIsInteractive(FILE *fp, const char *filename)
2124{
2125 if (isatty((int)fileno(fp)))
2126 return 1;
2127 if (!Py_InteractiveFlag)
2128 return 0;
2129 return (filename == NULL) ||
2130 (strcmp(filename, "<stdin>") == 0) ||
2131 (strcmp(filename, "???") == 0);
2132}
2133
2134
Nick Coghland6009512014-11-20 21:39:37 +10002135/* Wrappers around sigaction() or signal(). */
2136
2137PyOS_sighandler_t
2138PyOS_getsig(int sig)
2139{
2140#ifdef HAVE_SIGACTION
2141 struct sigaction context;
2142 if (sigaction(sig, NULL, &context) == -1)
2143 return SIG_ERR;
2144 return context.sa_handler;
2145#else
2146 PyOS_sighandler_t handler;
2147/* Special signal handling for the secure CRT in Visual Studio 2005 */
2148#if defined(_MSC_VER) && _MSC_VER >= 1400
2149 switch (sig) {
2150 /* Only these signals are valid */
2151 case SIGINT:
2152 case SIGILL:
2153 case SIGFPE:
2154 case SIGSEGV:
2155 case SIGTERM:
2156 case SIGBREAK:
2157 case SIGABRT:
2158 break;
2159 /* Don't call signal() with other values or it will assert */
2160 default:
2161 return SIG_ERR;
2162 }
2163#endif /* _MSC_VER && _MSC_VER >= 1400 */
2164 handler = signal(sig, SIG_IGN);
2165 if (handler != SIG_ERR)
2166 signal(sig, handler);
2167 return handler;
2168#endif
2169}
2170
2171/*
2172 * All of the code in this function must only use async-signal-safe functions,
2173 * listed at `man 7 signal` or
2174 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2175 */
2176PyOS_sighandler_t
2177PyOS_setsig(int sig, PyOS_sighandler_t handler)
2178{
2179#ifdef HAVE_SIGACTION
2180 /* Some code in Modules/signalmodule.c depends on sigaction() being
2181 * used here if HAVE_SIGACTION is defined. Fix that if this code
2182 * changes to invalidate that assumption.
2183 */
2184 struct sigaction context, ocontext;
2185 context.sa_handler = handler;
2186 sigemptyset(&context.sa_mask);
2187 context.sa_flags = 0;
2188 if (sigaction(sig, &context, &ocontext) == -1)
2189 return SIG_ERR;
2190 return ocontext.sa_handler;
2191#else
2192 PyOS_sighandler_t oldhandler;
2193 oldhandler = signal(sig, handler);
2194#ifdef HAVE_SIGINTERRUPT
2195 siginterrupt(sig, 1);
2196#endif
2197 return oldhandler;
2198#endif
2199}
2200
2201#ifdef __cplusplus
2202}
2203#endif