blob: 86d87fb6030ad9ee85e4607f2438fb0a1c681dde [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
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100467_Py_Initialize_ReconfigureCore(PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200468 const _PyCoreConfig *core_config)
469{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100470 PyThreadState *tstate = _PyThreadState_GET();
471 if (!tstate) {
472 return _Py_INIT_ERR("failed to read thread state");
473 }
474
475 PyInterpreterState *interp = tstate->interp;
476 if (interp == NULL) {
477 return _Py_INIT_ERR("can't make main interpreter");
478 }
479 *interp_p = interp;
480
481 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
482 Py_Initialize() ignores the new configuration. */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200483 if (core_config->allocator != NULL) {
484 const char *allocator = _PyMem_GetAllocatorsName();
485 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
486 return _Py_INIT_USER_ERR("cannot modify memory allocator "
487 "after first Py_Initialize()");
488 }
489 }
490
491 _PyCoreConfig_SetGlobalConfig(core_config);
492
493 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
494 return _Py_INIT_ERR("failed to copy core config");
495 }
496 core_config = &interp->core_config;
497
498 if (core_config->_install_importlib) {
499 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
500 if (_Py_INIT_FAILED(err)) {
501 return err;
502 }
503 }
504 return _Py_INIT_OK();
505}
506
507
Victor Stinner1dc6e392018-07-25 02:49:17 +0200508static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100509pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000510{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200511 if (_PyRuntime.initialized) {
512 return _Py_INIT_ERR("main interpreter already initialized");
513 }
Victor Stinnerda273412017-12-15 01:46:02 +0100514
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200515 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000516
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800518 if (_Py_INIT_FAILED(err)) {
519 return err;
520 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600521
Victor Stinner31e99082017-12-20 23:41:38 +0100522 if (core_config->allocator != NULL) {
523 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
524 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
525 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800526 }
527
Eric Snow1abcf672017-05-23 21:46:51 -0700528 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
529 * threads behave a little more gracefully at interpreter shutdown.
530 * We clobber it here so the new interpreter can start with a clean
531 * slate.
532 *
533 * However, this may still lead to misbehaviour if there are daemon
534 * threads still hanging around from a previous Py_Initialize/Finalize
535 * pair :(
536 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600537 _PyRuntime.finalizing = NULL;
538
Victor Stinnerda273412017-12-15 01:46:02 +0100539 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800540 if (_Py_INIT_FAILED(err)) {
541 return err;
542 }
543
Victor Stinnera7368ac2017-11-15 18:11:45 -0800544 err = _PyInterpreterState_Enable(&_PyRuntime);
545 if (_Py_INIT_FAILED(err)) {
546 return err;
547 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100548 return _Py_INIT_OK();
549}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800550
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100551
552static _PyInitError
553pycore_create_interpreter(const _PyCoreConfig *core_config,
554 PyInterpreterState **interp_p)
555{
556 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100557 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800558 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100559 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200560 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100561
562 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
563 return _Py_INIT_ERR("failed to copy core config");
564 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200565 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000566
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200567 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000568 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800569 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000570 (void) PyThreadState_Swap(tstate);
571
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000572 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000573 destroying the GIL might fail when it is being referenced from
574 another running thread (see issue #9901).
575 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000576 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000577 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100578
Nick Coghland6009512014-11-20 21:39:37 +1000579 /* Auto-thread-state API */
580 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000581
Victor Stinner2914bb32018-01-29 11:57:45 +0100582 /* Create the GIL */
583 PyEval_InitThreads();
584
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100585 return _Py_INIT_OK();
586}
Nick Coghland6009512014-11-20 21:39:37 +1000587
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100588
589static _PyInitError
590pycore_init_types(void)
591{
592 _PyInitError err = _Py_ReadyTypes();
593 if (_Py_INIT_FAILED(err)) {
594 return err;
595 }
596
597 err = _PyUnicode_Init();
598 if (_Py_INIT_FAILED(err)) {
599 return err;
600 }
601
602 if (_PyStructSequence_Init() < 0) {
603 return _Py_INIT_ERR("can't initialize structseq");
604 }
605
606 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800607 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100608 }
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100610 err = _PyExc_Init();
611 if (_Py_INIT_FAILED(err)) {
612 return err;
613 }
614
615 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800616 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100617 }
Nick Coghland6009512014-11-20 21:39:37 +1000618
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100619 if (!_PyContext_Init()) {
620 return _Py_INIT_ERR("can't init context");
621 }
622 return _Py_INIT_OK();
623}
624
625
626static _PyInitError
627pycore_init_sys(PyInterpreterState *interp, PyObject **sysmod_p)
628{
Eric Snowd393c1b2017-09-14 12:18:12 -0600629 PyObject *modules = PyDict_New();
630 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800631 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600632 interp->modules = modules;
633
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200634 PyObject *sysmod;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100635 _PyInitError err = _PySys_BeginInit(&sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800636 if (_Py_INIT_FAILED(err)) {
637 return err;
638 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100639 *sysmod_p = sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800640
Eric Snowd393c1b2017-09-14 12:18:12 -0600641 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800642 if (interp->sysdict == NULL) {
643 return _Py_INIT_ERR("can't initialize sys dict");
644 }
645
Eric Snowd393c1b2017-09-14 12:18:12 -0600646 Py_INCREF(interp->sysdict);
647 PyDict_SetItemString(interp->sysdict, "modules", modules);
648 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000649
Nick Coghland6009512014-11-20 21:39:37 +1000650 /* Set up a preliminary stderr printer until we have enough
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100651 infrastructure for the io module in place.
652
653 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200654 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655 if (pstderr == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800656 return _Py_INIT_ERR("can't set preliminary stderr");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100657 }
Nick Coghland6009512014-11-20 21:39:37 +1000658 _PySys_SetObjectId(&PyId_stderr, pstderr);
659 PySys_SetObject("__stderr__", pstderr);
660 Py_DECREF(pstderr);
661
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100662 return _Py_INIT_OK();
663}
664
665
666static _PyInitError
667pycore_init_builtins(PyInterpreterState *interp)
668{
669 PyObject *bimod = _PyBuiltin_Init();
670 if (bimod == NULL) {
671 return _Py_INIT_ERR("can't initialize builtins modules");
672 }
673 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
674
675 interp->builtins = PyModule_GetDict(bimod);
676 if (interp->builtins == NULL) {
677 return _Py_INIT_ERR("can't initialize builtins dict");
678 }
679 Py_INCREF(interp->builtins);
680
681 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
682 if (_Py_INIT_FAILED(err)) {
683 return err;
684 }
685 return _Py_INIT_OK();
686}
687
688
689static _PyInitError
690pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
691{
692 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800693 if (_Py_INIT_FAILED(err)) {
694 return err;
695 }
Nick Coghland6009512014-11-20 21:39:37 +1000696
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800697 err = _PyImportHooks_Init();
698 if (_Py_INIT_FAILED(err)) {
699 return err;
700 }
Nick Coghland6009512014-11-20 21:39:37 +1000701
702 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100703 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100704 return _Py_INIT_ERR("can't initialize warnings");
705 }
Nick Coghland6009512014-11-20 21:39:37 +1000706
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100707 if (interp->core_config._install_importlib) {
708 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200709 if (_Py_INIT_FAILED(err)) {
710 return err;
711 }
712 }
713
Eric Snow1abcf672017-05-23 21:46:51 -0700714 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100715 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 err = initimport(interp, sysmod);
717 if (_Py_INIT_FAILED(err)) {
718 return err;
719 }
Eric Snow1abcf672017-05-23 21:46:51 -0700720 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100721 return _Py_INIT_OK();
722}
723
724
725static _PyInitError
726_Py_InitializeCore_impl(PyInterpreterState **interp_p,
727 const _PyCoreConfig *core_config)
728{
729 PyInterpreterState *interp;
730
731 _PyInitError err = pycore_init_runtime(core_config);
732 if (_Py_INIT_FAILED(err)) {
733 return err;
734 }
735
736 err = pycore_create_interpreter(core_config, &interp);
737 if (_Py_INIT_FAILED(err)) {
738 return err;
739 }
740 core_config = &interp->core_config;
741 *interp_p = interp;
742
743 err = pycore_init_types();
744 if (_Py_INIT_FAILED(err)) {
745 return err;
746 }
747
748 PyObject *sysmod;
749 err = pycore_init_sys(interp, &sysmod);
750 if (_Py_INIT_FAILED(err)) {
751 return err;
752 }
753
754 err = pycore_init_builtins(interp);
755 if (_Py_INIT_FAILED(err)) {
756 return err;
757 }
758
759 err = pycore_init_import_warnings(interp, sysmod);
760 if (_Py_INIT_FAILED(err)) {
761 return err;
762 }
Eric Snow1abcf672017-05-23 21:46:51 -0700763
764 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600765 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800766 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700767}
768
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100769/* Begin interpreter initialization
770 *
771 * On return, the first thread and interpreter state have been created,
772 * but the compiler, signal handling, multithreading and
773 * multiple interpreter support, and codec infrastructure are not yet
774 * available.
775 *
776 * The import system will support builtin and frozen modules only.
777 * The only supported io is writing to sys.stderr
778 *
779 * If any operation invoked by this function fails, a fatal error is
780 * issued and the function does not return.
781 *
782 * Any code invoked from this function should *not* assume it has access
783 * to the Python C API (unless the API is explicitly listed as being
784 * safe to call without calling Py_Initialize first)
785 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200786_PyInitError
787_Py_InitializeCore(PyInterpreterState **interp_p,
788 const _PyCoreConfig *src_config)
789{
790 assert(src_config != NULL);
791
Victor Stinner1dc6e392018-07-25 02:49:17 +0200792 PyMemAllocatorEx old_alloc;
793 _PyInitError err;
794
795 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
796 (and the input configuration is read only). */
797 _PyCoreConfig config = _PyCoreConfig_INIT;
798
Victor Stinner177d9212018-08-29 11:25:15 +0200799 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200800 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200801
Victor Stinner1dc6e392018-07-25 02:49:17 +0200802 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
803 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
804 err = _PyCoreConfig_Read(&config);
805 }
806 else {
807 err = _Py_INIT_ERR("failed to copy core config");
808 }
809 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
810
811 if (_Py_INIT_FAILED(err)) {
812 goto done;
813 }
814
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100815 if (!_PyRuntime.core_initialized) {
816 err = _Py_InitializeCore_impl(interp_p, &config);
817 }
818 else {
819 err = _Py_Initialize_ReconfigureCore(interp_p, &config);
820 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200821
822done:
823 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
824 _PyCoreConfig_Clear(&config);
825 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
826
827 return err;
828}
829
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200830/* Py_Initialize() has already been called: update the main interpreter
831 configuration. Example of bpo-34008: Py_Main() called after
832 Py_Initialize(). */
833static _PyInitError
834_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
835 const _PyMainInterpreterConfig *config)
836{
837 if (config->argv != NULL) {
838 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
839 if (res < 0) {
840 return _Py_INIT_ERR("fail to set sys.argv");
841 }
842 }
843 return _Py_INIT_OK();
844}
845
Eric Snowc7ec9982017-05-23 23:00:52 -0700846/* Update interpreter state based on supplied configuration settings
847 *
848 * After calling this function, most of the restrictions on the interpreter
849 * are lifted. The only remaining incomplete settings are those related
850 * to the main module (sys.argv[0], __main__ metadata)
851 *
852 * Calling this when the interpreter is not initializing, is already
853 * initialized or without a valid current thread state is a fatal error.
854 * Other errors should be reported as normal Python exceptions with a
855 * non-zero return code.
856 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800857_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200858_Py_InitializeMainInterpreter(PyInterpreterState *interp,
859 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700860{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600861 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800862 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700863 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700864
Victor Stinner1dc6e392018-07-25 02:49:17 +0200865 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100866 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
867 return _Py_INIT_ERR("failed to copy main interpreter config");
868 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200869 config = &interp->config;
870 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700871
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200872 if (_PyRuntime.initialized) {
873 return _Py_ReconfigureMainInterpreter(interp, config);
874 }
875
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200876 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700877 /* Special mode for freeze_importlib: run with no import system
878 *
879 * This means anything which needs support from extension modules
880 * or pure Python code in the standard library won't work.
881 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600882 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800883 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700884 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100885
Victor Stinner33c377e2017-12-05 15:12:41 +0100886 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800887 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100888 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200889
Victor Stinnerfbca9082018-08-30 00:50:45 +0200890 if (_PySys_EndInit(interp->sysdict, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800891 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100892 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800893
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200894 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895 if (_Py_INIT_FAILED(err)) {
896 return err;
897 }
Nick Coghland6009512014-11-20 21:39:37 +1000898
899 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200900 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800901 if (_Py_INIT_FAILED(err)) {
902 return err;
903 }
Nick Coghland6009512014-11-20 21:39:37 +1000904
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800905 err = initfsencoding(interp);
906 if (_Py_INIT_FAILED(err)) {
907 return err;
908 }
Nick Coghland6009512014-11-20 21:39:37 +1000909
Victor Stinner1f151112017-11-23 10:43:14 +0100910 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800911 err = initsigs(); /* Signal handling stuff, including initintr() */
912 if (_Py_INIT_FAILED(err)) {
913 return err;
914 }
915 }
Nick Coghland6009512014-11-20 21:39:37 +1000916
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200917 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800918 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200919 }
Nick Coghland6009512014-11-20 21:39:37 +1000920
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800921 err = add_main_module(interp);
922 if (_Py_INIT_FAILED(err)) {
923 return err;
924 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800925
Victor Stinner91106cd2017-12-13 12:29:09 +0100926 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800927 if (_Py_INIT_FAILED(err)) {
928 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929 }
Nick Coghland6009512014-11-20 21:39:37 +1000930
931 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100932 PyObject *warnoptions = PySys_GetObject("warnoptions");
933 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100934 {
Nick Coghland6009512014-11-20 21:39:37 +1000935 PyObject *warnings_module = PyImport_ImportModule("warnings");
936 if (warnings_module == NULL) {
937 fprintf(stderr, "'import warnings' failed; traceback:\n");
938 PyErr_Print();
939 }
940 Py_XDECREF(warnings_module);
941 }
942
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600943 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700944
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200945 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800946 err = initsite(); /* Module site */
947 if (_Py_INIT_FAILED(err)) {
948 return err;
949 }
950 }
Victor Stinnercf215042018-08-29 22:56:06 +0200951
952#ifndef MS_WINDOWS
953 _emit_stderr_warning_for_legacy_locale(core_config);
954#endif
955
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800956 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000957}
958
Eric Snowc7ec9982017-05-23 23:00:52 -0700959#undef _INIT_DEBUG_PRINT
960
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800961_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200962_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700963{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700964 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800965 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200966 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800967 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200968 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800969 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200970 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100971
Victor Stinner9cfc0022017-12-20 19:36:46 +0100972 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200973 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100974 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200975 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800976 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100977 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800978 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200979 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800980 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200981 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700982}
983
984
985void
Nick Coghland6009512014-11-20 21:39:37 +1000986Py_InitializeEx(int install_sigs)
987{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200988 if (_PyRuntime.initialized) {
989 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
990 return;
991 }
992
993 _PyInitError err;
994 _PyCoreConfig config = _PyCoreConfig_INIT;
995 config.install_signal_handlers = install_sigs;
996
997 err = _Py_InitializeFromConfig(&config);
998 _PyCoreConfig_Clear(&config);
999
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001000 if (_Py_INIT_FAILED(err)) {
1001 _Py_FatalInitError(err);
1002 }
Nick Coghland6009512014-11-20 21:39:37 +10001003}
1004
1005void
1006Py_Initialize(void)
1007{
1008 Py_InitializeEx(1);
1009}
1010
1011
1012#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001013extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001014#endif
1015
1016/* Flush stdout and stderr */
1017
1018static int
1019file_is_closed(PyObject *fobj)
1020{
1021 int r;
1022 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1023 if (tmp == NULL) {
1024 PyErr_Clear();
1025 return 0;
1026 }
1027 r = PyObject_IsTrue(tmp);
1028 Py_DECREF(tmp);
1029 if (r < 0)
1030 PyErr_Clear();
1031 return r > 0;
1032}
1033
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001034static int
Nick Coghland6009512014-11-20 21:39:37 +10001035flush_std_files(void)
1036{
1037 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1038 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1039 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001040 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001041
1042 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001043 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001044 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001045 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001046 status = -1;
1047 }
Nick Coghland6009512014-11-20 21:39:37 +10001048 else
1049 Py_DECREF(tmp);
1050 }
1051
1052 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001053 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001054 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001055 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001056 status = -1;
1057 }
Nick Coghland6009512014-11-20 21:39:37 +10001058 else
1059 Py_DECREF(tmp);
1060 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001061
1062 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001063}
1064
1065/* Undo the effect of Py_Initialize().
1066
1067 Beware: if multiple interpreter and/or thread states exist, these
1068 are not wiped out; only the current thread and interpreter state
1069 are deleted. But since everything else is deleted, those other
1070 interpreter and thread states should no longer be used.
1071
1072 (XXX We should do better, e.g. wipe out all interpreters and
1073 threads.)
1074
1075 Locking: as above.
1076
1077*/
1078
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001079int
1080Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001081{
1082 PyInterpreterState *interp;
1083 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001084 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001085
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001086 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001087 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001088
1089 wait_for_thread_shutdown();
1090
Marcel Plch776407f2017-12-20 11:17:58 +01001091 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001092 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001093 interp = tstate->interp;
1094
Nick Coghland6009512014-11-20 21:39:37 +10001095 /* The interpreter is still entirely intact at this point, and the
1096 * exit funcs may be relying on that. In particular, if some thread
1097 * or exit func is still waiting to do an import, the import machinery
1098 * expects Py_IsInitialized() to return true. So don't say the
1099 * interpreter is uninitialized until after the exit funcs have run.
1100 * Note that Threading.py uses an exit func to do a join on all the
1101 * threads created thru it, so this also protects pending imports in
1102 * the threads created via Threading.
1103 */
Nick Coghland6009512014-11-20 21:39:37 +10001104
Marcel Plch776407f2017-12-20 11:17:58 +01001105 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001106
Victor Stinnerda273412017-12-15 01:46:02 +01001107 /* Copy the core config, PyInterpreterState_Delete() free
1108 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001109#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001110 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001111#endif
1112#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001113 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001114#endif
1115#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001116 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001117#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001118
Nick Coghland6009512014-11-20 21:39:37 +10001119 /* Remaining threads (e.g. daemon threads) will automatically exit
1120 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001121 _PyRuntime.finalizing = tstate;
1122 _PyRuntime.initialized = 0;
1123 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001124
Victor Stinnere0deff32015-03-24 13:46:18 +01001125 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001126 if (flush_std_files() < 0) {
1127 status = -1;
1128 }
Nick Coghland6009512014-11-20 21:39:37 +10001129
1130 /* Disable signal handling */
1131 PyOS_FiniInterrupts();
1132
1133 /* Collect garbage. This may call finalizers; it's nice to call these
1134 * before all modules are destroyed.
1135 * XXX If a __del__ or weakref callback is triggered here, and tries to
1136 * XXX import a module, bad things can happen, because Python no
1137 * XXX longer believes it's initialized.
1138 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1139 * XXX is easy to provoke that way. I've also seen, e.g.,
1140 * XXX Exception exceptions.ImportError: 'No module named sha'
1141 * XXX in <function callback at 0x008F5718> ignored
1142 * XXX but I'm unclear on exactly how that one happens. In any case,
1143 * XXX I haven't seen a real-life report of either of these.
1144 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001145 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001146#ifdef COUNT_ALLOCS
1147 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1148 each collection might release some types from the type
1149 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001150 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001151 /* nothing */;
1152#endif
Eric Snowdae02762017-09-14 00:35:58 -07001153
Nick Coghland6009512014-11-20 21:39:37 +10001154 /* Destroy all modules */
1155 PyImport_Cleanup();
1156
Victor Stinnere0deff32015-03-24 13:46:18 +01001157 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001158 if (flush_std_files() < 0) {
1159 status = -1;
1160 }
Nick Coghland6009512014-11-20 21:39:37 +10001161
1162 /* Collect final garbage. This disposes of cycles created by
1163 * class definitions, for example.
1164 * XXX This is disabled because it caused too many problems. If
1165 * XXX a __del__ or weakref callback triggers here, Python code has
1166 * XXX a hard time running, because even the sys module has been
1167 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1168 * XXX One symptom is a sequence of information-free messages
1169 * XXX coming from threads (if a __del__ or callback is invoked,
1170 * XXX other threads can execute too, and any exception they encounter
1171 * XXX triggers a comedy of errors as subsystem after subsystem
1172 * XXX fails to find what it *expects* to find in sys to help report
1173 * XXX the exception and consequent unexpected failures). I've also
1174 * XXX seen segfaults then, after adding print statements to the
1175 * XXX Python code getting called.
1176 */
1177#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001178 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001179#endif
1180
1181 /* Disable tracemalloc after all Python objects have been destroyed,
1182 so it is possible to use tracemalloc in objects destructor. */
1183 _PyTraceMalloc_Fini();
1184
1185 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1186 _PyImport_Fini();
1187
1188 /* Cleanup typeobject.c's internal caches. */
1189 _PyType_Fini();
1190
1191 /* unload faulthandler module */
1192 _PyFaulthandler_Fini();
1193
1194 /* Debugging stuff */
1195#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001196 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001197#endif
1198 /* dump hash stats */
1199 _PyHash_Fini();
1200
Eric Snowdae02762017-09-14 00:35:58 -07001201#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001202 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001203 _PyDebug_PrintTotalRefs();
1204 }
Eric Snowdae02762017-09-14 00:35:58 -07001205#endif
Nick Coghland6009512014-11-20 21:39:37 +10001206
1207#ifdef Py_TRACE_REFS
1208 /* Display all objects still alive -- this can invoke arbitrary
1209 * __repr__ overrides, so requires a mostly-intact interpreter.
1210 * Alas, a lot of stuff may still be alive now that will be cleaned
1211 * up later.
1212 */
Victor Stinnerda273412017-12-15 01:46:02 +01001213 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001214 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001215 }
Nick Coghland6009512014-11-20 21:39:37 +10001216#endif /* Py_TRACE_REFS */
1217
1218 /* Clear interpreter state and all thread states. */
1219 PyInterpreterState_Clear(interp);
1220
1221 /* Now we decref the exception classes. After this point nothing
1222 can raise an exception. That's okay, because each Fini() method
1223 below has been checked to make sure no exceptions are ever
1224 raised.
1225 */
1226
1227 _PyExc_Fini();
1228
1229 /* Sundry finalizers */
1230 PyMethod_Fini();
1231 PyFrame_Fini();
1232 PyCFunction_Fini();
1233 PyTuple_Fini();
1234 PyList_Fini();
1235 PySet_Fini();
1236 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001237 PyLong_Fini();
1238 PyFloat_Fini();
1239 PyDict_Fini();
1240 PySlice_Fini();
1241 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001242 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001243 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001244 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001245 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001246
1247 /* Cleanup Unicode implementation */
1248 _PyUnicode_Fini();
1249
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001250 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001251
1252 /* XXX Still allocated:
1253 - various static ad-hoc pointers to interned strings
1254 - int and float free list blocks
1255 - whatever various modules and libraries allocate
1256 */
1257
1258 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1259
1260 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001261 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001262
1263 /* Delete current thread. After this, many C API calls become crashy. */
1264 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001265
Nick Coghland6009512014-11-20 21:39:37 +10001266 PyInterpreterState_Delete(interp);
1267
1268#ifdef Py_TRACE_REFS
1269 /* Display addresses (& refcnts) of all objects still alive.
1270 * An address can be used to find the repr of the object, printed
1271 * above by _Py_PrintReferences.
1272 */
Victor Stinnerda273412017-12-15 01:46:02 +01001273 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001274 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001275 }
Nick Coghland6009512014-11-20 21:39:37 +10001276#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001277#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001278 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001279 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001280 }
Nick Coghland6009512014-11-20 21:39:37 +10001281#endif
1282
1283 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001284
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001285 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001286 return status;
1287}
1288
1289void
1290Py_Finalize(void)
1291{
1292 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001293}
1294
1295/* Create and initialize a new interpreter and thread, and return the
1296 new thread. This requires that Py_Initialize() has been called
1297 first.
1298
1299 Unsuccessful initialization yields a NULL pointer. Note that *no*
1300 exception information is available even in this case -- the
1301 exception information is held in the thread, and there is no
1302 thread.
1303
1304 Locking: as above.
1305
1306*/
1307
Victor Stinnera7368ac2017-11-15 18:11:45 -08001308static _PyInitError
1309new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001310{
1311 PyInterpreterState *interp;
1312 PyThreadState *tstate, *save_tstate;
1313 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001314 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001315
Victor Stinnera7368ac2017-11-15 18:11:45 -08001316 if (!_PyRuntime.initialized) {
1317 return _Py_INIT_ERR("Py_Initialize must be called first");
1318 }
Nick Coghland6009512014-11-20 21:39:37 +10001319
Victor Stinner8a1be612016-03-14 22:07:55 +01001320 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1321 interpreters: disable PyGILState_Check(). */
1322 _PyGILState_check_enabled = 0;
1323
Nick Coghland6009512014-11-20 21:39:37 +10001324 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001325 if (interp == NULL) {
1326 *tstate_p = NULL;
1327 return _Py_INIT_OK();
1328 }
Nick Coghland6009512014-11-20 21:39:37 +10001329
1330 tstate = PyThreadState_New(interp);
1331 if (tstate == NULL) {
1332 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001333 *tstate_p = NULL;
1334 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001335 }
1336
1337 save_tstate = PyThreadState_Swap(tstate);
1338
Eric Snow1abcf672017-05-23 21:46:51 -07001339 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001340 _PyCoreConfig *core_config;
1341 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001342 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001343 core_config = &save_tstate->interp->core_config;
1344 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001345 } else {
1346 /* No current thread state, copy from the main interpreter */
1347 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001348 core_config = &main_interp->core_config;
1349 config = &main_interp->config;
1350 }
1351
1352 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1353 return _Py_INIT_ERR("failed to copy core config");
1354 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001355 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001356 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1357 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001358 }
1359
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001360 err = _PyExc_Init();
1361 if (_Py_INIT_FAILED(err)) {
1362 return err;
1363 }
1364
Nick Coghland6009512014-11-20 21:39:37 +10001365 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001366 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001367 if (modules == NULL) {
1368 return _Py_INIT_ERR("can't make modules dictionary");
1369 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001370 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001371
Eric Snowd393c1b2017-09-14 12:18:12 -06001372 sysmod = _PyImport_FindBuiltin("sys", modules);
1373 if (sysmod != NULL) {
1374 interp->sysdict = PyModule_GetDict(sysmod);
1375 if (interp->sysdict == NULL)
1376 goto handle_error;
1377 Py_INCREF(interp->sysdict);
1378 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001379 _PySys_EndInit(interp->sysdict, interp);
Eric Snowd393c1b2017-09-14 12:18:12 -06001380 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001381 else if (PyErr_Occurred()) {
1382 goto handle_error;
1383 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001384
1385 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001386 if (bimod != NULL) {
1387 interp->builtins = PyModule_GetDict(bimod);
1388 if (interp->builtins == NULL)
1389 goto handle_error;
1390 Py_INCREF(interp->builtins);
1391 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001392 else if (PyErr_Occurred()) {
1393 goto handle_error;
1394 }
Nick Coghland6009512014-11-20 21:39:37 +10001395
Nick Coghland6009512014-11-20 21:39:37 +10001396 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001397 err = _PyBuiltins_AddExceptions(bimod);
1398 if (_Py_INIT_FAILED(err)) {
1399 return err;
1400 }
Nick Coghland6009512014-11-20 21:39:37 +10001401
Nick Coghland6009512014-11-20 21:39:37 +10001402 /* Set up a preliminary stderr printer until we have enough
1403 infrastructure for the io module in place. */
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001404 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001405 if (pstderr == NULL) {
1406 return _Py_INIT_ERR("can't set preliminary stderr");
1407 }
Nick Coghland6009512014-11-20 21:39:37 +10001408 _PySys_SetObjectId(&PyId_stderr, pstderr);
1409 PySys_SetObject("__stderr__", pstderr);
1410 Py_DECREF(pstderr);
1411
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001412 err = _PyImportHooks_Init();
1413 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001414 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001415 }
Nick Coghland6009512014-11-20 21:39:37 +10001416
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001417 err = initimport(interp, sysmod);
1418 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001419 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001420 }
Nick Coghland6009512014-11-20 21:39:37 +10001421
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001422 err = initexternalimport(interp);
1423 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001424 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001425 }
Nick Coghland6009512014-11-20 21:39:37 +10001426
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001427 err = initfsencoding(interp);
1428 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001429 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001430 }
1431
Victor Stinner91106cd2017-12-13 12:29:09 +01001432 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001433 if (_Py_INIT_FAILED(err)) {
1434 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001435 }
1436
1437 err = add_main_module(interp);
1438 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001439 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001440 }
1441
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001442 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001443 err = initsite();
1444 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001445 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001446 }
1447 }
Nick Coghland6009512014-11-20 21:39:37 +10001448 }
1449
Victor Stinnera7368ac2017-11-15 18:11:45 -08001450 if (PyErr_Occurred()) {
1451 goto handle_error;
1452 }
Nick Coghland6009512014-11-20 21:39:37 +10001453
Victor Stinnera7368ac2017-11-15 18:11:45 -08001454 *tstate_p = tstate;
1455 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001456
Nick Coghland6009512014-11-20 21:39:37 +10001457handle_error:
1458 /* Oops, it didn't work. Undo it all. */
1459
1460 PyErr_PrintEx(0);
1461 PyThreadState_Clear(tstate);
1462 PyThreadState_Swap(save_tstate);
1463 PyThreadState_Delete(tstate);
1464 PyInterpreterState_Delete(interp);
1465
Victor Stinnera7368ac2017-11-15 18:11:45 -08001466 *tstate_p = NULL;
1467 return _Py_INIT_OK();
1468}
1469
1470PyThreadState *
1471Py_NewInterpreter(void)
1472{
1473 PyThreadState *tstate;
1474 _PyInitError err = new_interpreter(&tstate);
1475 if (_Py_INIT_FAILED(err)) {
1476 _Py_FatalInitError(err);
1477 }
1478 return tstate;
1479
Nick Coghland6009512014-11-20 21:39:37 +10001480}
1481
1482/* Delete an interpreter and its last thread. This requires that the
1483 given thread state is current, that the thread has no remaining
1484 frames, and that it is its interpreter's only remaining thread.
1485 It is a fatal error to violate these constraints.
1486
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001487 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001488 everything, regardless.)
1489
1490 Locking: as above.
1491
1492*/
1493
1494void
1495Py_EndInterpreter(PyThreadState *tstate)
1496{
1497 PyInterpreterState *interp = tstate->interp;
1498
Victor Stinner50b48572018-11-01 01:51:40 +01001499 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001500 Py_FatalError("Py_EndInterpreter: thread is not current");
1501 if (tstate->frame != NULL)
1502 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1503
1504 wait_for_thread_shutdown();
1505
Marcel Plch776407f2017-12-20 11:17:58 +01001506 call_py_exitfuncs(interp);
1507
Nick Coghland6009512014-11-20 21:39:37 +10001508 if (tstate != interp->tstate_head || tstate->next != NULL)
1509 Py_FatalError("Py_EndInterpreter: not the last thread");
1510
1511 PyImport_Cleanup();
1512 PyInterpreterState_Clear(interp);
1513 PyThreadState_Swap(NULL);
1514 PyInterpreterState_Delete(interp);
1515}
1516
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001518
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001519static _PyInitError
1520add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001521{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001522 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001523 m = PyImport_AddModule("__main__");
1524 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525 return _Py_INIT_ERR("can't create __main__ module");
1526
Nick Coghland6009512014-11-20 21:39:37 +10001527 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001528 ann_dict = PyDict_New();
1529 if ((ann_dict == NULL) ||
1530 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001532 }
1533 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001534
Nick Coghland6009512014-11-20 21:39:37 +10001535 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1536 PyObject *bimod = PyImport_ImportModule("builtins");
1537 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001538 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001539 }
1540 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001541 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001542 }
1543 Py_DECREF(bimod);
1544 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001545
Nick Coghland6009512014-11-20 21:39:37 +10001546 /* Main is a little special - imp.is_builtin("__main__") will return
1547 * False, but BuiltinImporter is still the most appropriate initial
1548 * setting for its __loader__ attribute. A more suitable value will
1549 * be set if __main__ gets further initialized later in the startup
1550 * process.
1551 */
1552 loader = PyDict_GetItemString(d, "__loader__");
1553 if (loader == NULL || loader == Py_None) {
1554 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1555 "BuiltinImporter");
1556 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001557 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001558 }
1559 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001560 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001561 }
1562 Py_DECREF(loader);
1563 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001564 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001565}
1566
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001568initfsencoding(PyInterpreterState *interp)
1569{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001570 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001571
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001572 char *encoding = get_codec_name(config->filesystem_encoding);
1573 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001574 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001575 memory, import a module of the standard library failed, etc. */
1576 return _Py_INIT_ERR("failed to get the Python codec "
1577 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001578 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001579
1580 /* Update the filesystem encoding to the normalized Python codec name.
1581 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1582 (Python codec name). */
1583 PyMem_RawFree(config->filesystem_encoding);
1584 config->filesystem_encoding = encoding;
1585
1586 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1587 global configuration variables. */
1588 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1589 config->filesystem_errors) < 0) {
1590 return _Py_INIT_NO_MEMORY();
1591 }
1592
1593 /* PyUnicode can now use the Python codec rather than C implementation
1594 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001595 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001596 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001597}
1598
1599/* Import the site module (not into __main__ though) */
1600
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001601static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001602initsite(void)
1603{
1604 PyObject *m;
1605 m = PyImport_ImportModule("site");
1606 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001607 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001608 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001609 Py_DECREF(m);
1610 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001611}
1612
Victor Stinner874dbe82015-09-04 17:29:57 +02001613/* Check if a file descriptor is valid or not.
1614 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1615static int
1616is_valid_fd(int fd)
1617{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001618#ifdef __APPLE__
1619 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1620 and the other side of the pipe is closed, dup(1) succeed, whereas
1621 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1622 such error. */
1623 struct stat st;
1624 return (fstat(fd, &st) == 0);
1625#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001626 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001627 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001628 return 0;
1629 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001630 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1631 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1632 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001633 fd2 = dup(fd);
1634 if (fd2 >= 0)
1635 close(fd2);
1636 _Py_END_SUPPRESS_IPH
1637 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001638#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001639}
1640
1641/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001642static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001643create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001644 int fd, int write_mode, const char* name,
1645 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001646{
1647 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1648 const char* mode;
1649 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001650 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001651 int buffering, isatty;
1652 _Py_IDENTIFIER(open);
1653 _Py_IDENTIFIER(isatty);
1654 _Py_IDENTIFIER(TextIOWrapper);
1655 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001656 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001657
Victor Stinner874dbe82015-09-04 17:29:57 +02001658 if (!is_valid_fd(fd))
1659 Py_RETURN_NONE;
1660
Nick Coghland6009512014-11-20 21:39:37 +10001661 /* stdin is always opened in buffered mode, first because it shouldn't
1662 make a difference in common use cases, second because TextIOWrapper
1663 depends on the presence of a read1() method which only exists on
1664 buffered streams.
1665 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001666 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001667 buffering = 0;
1668 else
1669 buffering = -1;
1670 if (write_mode)
1671 mode = "wb";
1672 else
1673 mode = "rb";
1674 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1675 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001676 Py_None, Py_None, /* encoding, errors */
1677 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001678 if (buf == NULL)
1679 goto error;
1680
1681 if (buffering) {
1682 _Py_IDENTIFIER(raw);
1683 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1684 if (raw == NULL)
1685 goto error;
1686 }
1687 else {
1688 raw = buf;
1689 Py_INCREF(raw);
1690 }
1691
Steve Dower39294992016-08-30 21:22:36 -07001692#ifdef MS_WINDOWS
1693 /* Windows console IO is always UTF-8 encoded */
1694 if (PyWindowsConsoleIO_Check(raw))
1695 encoding = "utf-8";
1696#endif
1697
Nick Coghland6009512014-11-20 21:39:37 +10001698 text = PyUnicode_FromString(name);
1699 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1700 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001701 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001702 if (res == NULL)
1703 goto error;
1704 isatty = PyObject_IsTrue(res);
1705 Py_DECREF(res);
1706 if (isatty == -1)
1707 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001708 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001709 write_through = Py_True;
1710 else
1711 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001712 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001713 line_buffering = Py_True;
1714 else
1715 line_buffering = Py_False;
1716
1717 Py_CLEAR(raw);
1718 Py_CLEAR(text);
1719
1720#ifdef MS_WINDOWS
1721 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1722 newlines to "\n".
1723 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1724 newline = NULL;
1725#else
1726 /* sys.stdin: split lines at "\n".
1727 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1728 newline = "\n";
1729#endif
1730
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001731 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001732 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001733 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001734 Py_CLEAR(buf);
1735 if (stream == NULL)
1736 goto error;
1737
1738 if (write_mode)
1739 mode = "w";
1740 else
1741 mode = "r";
1742 text = PyUnicode_FromString(mode);
1743 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1744 goto error;
1745 Py_CLEAR(text);
1746 return stream;
1747
1748error:
1749 Py_XDECREF(buf);
1750 Py_XDECREF(stream);
1751 Py_XDECREF(text);
1752 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001753
Victor Stinner874dbe82015-09-04 17:29:57 +02001754 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1755 /* Issue #24891: the file descriptor was closed after the first
1756 is_valid_fd() check was called. Ignore the OSError and set the
1757 stream to None. */
1758 PyErr_Clear();
1759 Py_RETURN_NONE;
1760 }
1761 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001762}
1763
1764/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001765static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001766init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001767{
1768 PyObject *iomod = NULL, *wrapper;
1769 PyObject *bimod = NULL;
1770 PyObject *m;
1771 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001772 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001773 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001774 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001775 _PyCoreConfig *config = &interp->core_config;
1776
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001777 /* Check that stdin is not a directory
1778 Using shell redirection, you can redirect stdin to a directory,
1779 crashing the Python interpreter. Catch this common mistake here
1780 and output a useful error message. Note that under MS Windows,
1781 the shell already prevents that. */
1782#ifndef MS_WINDOWS
1783 struct _Py_stat_struct sb;
1784 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1785 S_ISDIR(sb.st_mode)) {
1786 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1787 "cannot continue");
1788 }
1789#endif
1790
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001791 char *codec_name = get_codec_name(config->stdio_encoding);
1792 if (codec_name == NULL) {
1793 return _Py_INIT_ERR("failed to get the Python codec name "
1794 "of the stdio encoding");
1795 }
1796 PyMem_RawFree(config->stdio_encoding);
1797 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001798
1799 /* Hack to avoid a nasty recursion issue when Python is invoked
1800 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1801 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1802 goto error;
1803 }
1804 Py_DECREF(m);
1805
1806 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1807 goto error;
1808 }
1809 Py_DECREF(m);
1810
1811 if (!(bimod = PyImport_ImportModule("builtins"))) {
1812 goto error;
1813 }
1814
1815 if (!(iomod = PyImport_ImportModule("io"))) {
1816 goto error;
1817 }
1818 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1819 goto error;
1820 }
1821
1822 /* Set builtins.open */
1823 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1824 Py_DECREF(wrapper);
1825 goto error;
1826 }
1827 Py_DECREF(wrapper);
1828
Nick Coghland6009512014-11-20 21:39:37 +10001829 /* Set sys.stdin */
1830 fd = fileno(stdin);
1831 /* Under some conditions stdin, stdout and stderr may not be connected
1832 * and fileno() may point to an invalid file descriptor. For example
1833 * GUI apps don't have valid standard streams by default.
1834 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001835 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001836 config->stdio_encoding,
1837 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001838 if (std == NULL)
1839 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001840 PySys_SetObject("__stdin__", std);
1841 _PySys_SetObjectId(&PyId_stdin, std);
1842 Py_DECREF(std);
1843
1844 /* Set sys.stdout */
1845 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001846 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001847 config->stdio_encoding,
1848 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001849 if (std == NULL)
1850 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001851 PySys_SetObject("__stdout__", std);
1852 _PySys_SetObjectId(&PyId_stdout, std);
1853 Py_DECREF(std);
1854
1855#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1856 /* Set sys.stderr, replaces the preliminary stderr */
1857 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001858 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001859 config->stdio_encoding,
1860 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001861 if (std == NULL)
1862 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001863
1864 /* Same as hack above, pre-import stderr's codec to avoid recursion
1865 when import.c tries to write to stderr in verbose mode. */
1866 encoding_attr = PyObject_GetAttrString(std, "encoding");
1867 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001868 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001869 if (std_encoding != NULL) {
1870 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1871 Py_XDECREF(codec_info);
1872 }
1873 Py_DECREF(encoding_attr);
1874 }
1875 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1876
1877 if (PySys_SetObject("__stderr__", std) < 0) {
1878 Py_DECREF(std);
1879 goto error;
1880 }
1881 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1882 Py_DECREF(std);
1883 goto error;
1884 }
1885 Py_DECREF(std);
1886#endif
1887
Victor Stinnera7368ac2017-11-15 18:11:45 -08001888 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001889
Victor Stinnera7368ac2017-11-15 18:11:45 -08001890error:
1891 res = _Py_INIT_ERR("can't initialize sys standard streams");
1892
1893done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001894 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001895
Nick Coghland6009512014-11-20 21:39:37 +10001896 Py_XDECREF(bimod);
1897 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001898 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001899}
1900
1901
Victor Stinner10dc4842015-03-24 12:01:30 +01001902static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001903_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001904{
Victor Stinner10dc4842015-03-24 12:01:30 +01001905 fputc('\n', stderr);
1906 fflush(stderr);
1907
1908 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001909 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001910}
Victor Stinner791da1c2016-03-14 16:53:12 +01001911
1912/* Print the current exception (if an exception is set) with its traceback,
1913 or display the current Python stack.
1914
1915 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1916 called on catastrophic cases.
1917
1918 Return 1 if the traceback was displayed, 0 otherwise. */
1919
1920static int
1921_Py_FatalError_PrintExc(int fd)
1922{
1923 PyObject *ferr, *res;
1924 PyObject *exception, *v, *tb;
1925 int has_tb;
1926
Victor Stinner791da1c2016-03-14 16:53:12 +01001927 PyErr_Fetch(&exception, &v, &tb);
1928 if (exception == NULL) {
1929 /* No current exception */
1930 return 0;
1931 }
1932
1933 ferr = _PySys_GetObjectId(&PyId_stderr);
1934 if (ferr == NULL || ferr == Py_None) {
1935 /* sys.stderr is not set yet or set to None,
1936 no need to try to display the exception */
1937 return 0;
1938 }
1939
1940 PyErr_NormalizeException(&exception, &v, &tb);
1941 if (tb == NULL) {
1942 tb = Py_None;
1943 Py_INCREF(tb);
1944 }
1945 PyException_SetTraceback(v, tb);
1946 if (exception == NULL) {
1947 /* PyErr_NormalizeException() failed */
1948 return 0;
1949 }
1950
1951 has_tb = (tb != Py_None);
1952 PyErr_Display(exception, v, tb);
1953 Py_XDECREF(exception);
1954 Py_XDECREF(v);
1955 Py_XDECREF(tb);
1956
1957 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001958 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001959 if (res == NULL)
1960 PyErr_Clear();
1961 else
1962 Py_DECREF(res);
1963
1964 return has_tb;
1965}
1966
Nick Coghland6009512014-11-20 21:39:37 +10001967/* Print fatal error message and abort */
1968
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001969#ifdef MS_WINDOWS
1970static void
1971fatal_output_debug(const char *msg)
1972{
1973 /* buffer of 256 bytes allocated on the stack */
1974 WCHAR buffer[256 / sizeof(WCHAR)];
1975 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1976 size_t msglen;
1977
1978 OutputDebugStringW(L"Fatal Python error: ");
1979
1980 msglen = strlen(msg);
1981 while (msglen) {
1982 size_t i;
1983
1984 if (buflen > msglen) {
1985 buflen = msglen;
1986 }
1987
1988 /* Convert the message to wchar_t. This uses a simple one-to-one
1989 conversion, assuming that the this error message actually uses
1990 ASCII only. If this ceases to be true, we will have to convert. */
1991 for (i=0; i < buflen; ++i) {
1992 buffer[i] = msg[i];
1993 }
1994 buffer[i] = L'\0';
1995 OutputDebugStringW(buffer);
1996
1997 msg += buflen;
1998 msglen -= buflen;
1999 }
2000 OutputDebugStringW(L"\n");
2001}
2002#endif
2003
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002004static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002005fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002006{
2007 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002008 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002009
2010 if (reentrant) {
2011 /* Py_FatalError() caused a second fatal error.
2012 Example: flush_std_files() raises a recursion error. */
2013 goto exit;
2014 }
2015 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002016
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002017 fprintf(stderr, "Fatal Python error: ");
2018 if (prefix) {
2019 fputs(prefix, stderr);
2020 fputs(": ", stderr);
2021 }
2022 if (msg) {
2023 fputs(msg, stderr);
2024 }
2025 else {
2026 fprintf(stderr, "<message not set>");
2027 }
2028 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002029 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002030
Victor Stinner3a228ab2018-11-01 00:26:41 +01002031 /* Check if the current thread has a Python thread state
2032 and holds the GIL */
2033 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2034 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002035 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002036 if (tss_tstate != tstate) {
2037 /* The Python thread does not hold the GIL */
2038 tss_tstate = NULL;
2039 }
2040 }
2041 else {
2042 /* Py_FatalError() has been called from a C thread
2043 which has no Python thread state. */
2044 }
2045 int has_tstate_and_gil = (tss_tstate != NULL);
2046
2047 if (has_tstate_and_gil) {
2048 /* If an exception is set, print the exception with its traceback */
2049 if (!_Py_FatalError_PrintExc(fd)) {
2050 /* No exception is set, or an exception is set without traceback */
2051 _Py_FatalError_DumpTracebacks(fd);
2052 }
2053 }
2054 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002055 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002056 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002057
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002058 /* The main purpose of faulthandler is to display the traceback.
2059 This function already did its best to display a traceback.
2060 Disable faulthandler to prevent writing a second traceback
2061 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002062 _PyFaulthandler_Fini();
2063
Victor Stinner791da1c2016-03-14 16:53:12 +01002064 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002065 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002066 /* Flush sys.stdout and sys.stderr */
2067 flush_std_files();
2068 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002069
Nick Coghland6009512014-11-20 21:39:37 +10002070#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002071 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002072#endif /* MS_WINDOWS */
2073
2074exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002075 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002076#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002077 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002078#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002079 abort();
2080 }
2081 else {
2082 exit(status);
2083 }
2084}
2085
Victor Stinner19760862017-12-20 01:41:59 +01002086void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002087Py_FatalError(const char *msg)
2088{
2089 fatal_error(NULL, msg, -1);
2090}
2091
Victor Stinner19760862017-12-20 01:41:59 +01002092void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002093_Py_FatalInitError(_PyInitError err)
2094{
2095 /* On "user" error: exit with status 1.
2096 For all other errors, call abort(). */
2097 int status = err.user_err ? 1 : -1;
2098 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002099}
2100
2101/* Clean up and exit */
2102
Victor Stinnerd7292b52016-06-17 12:29:00 +02002103# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002104
Nick Coghland6009512014-11-20 21:39:37 +10002105/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002106void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002107{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002108 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002109
Antoine Pitroufc5db952017-12-13 02:29:07 +01002110 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002111 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2112
2113 is->pyexitfunc = func;
2114 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002115}
2116
2117static void
Marcel Plch776407f2017-12-20 11:17:58 +01002118call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002119{
Marcel Plch776407f2017-12-20 11:17:58 +01002120 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002121 return;
2122
Marcel Plch776407f2017-12-20 11:17:58 +01002123 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002124 PyErr_Clear();
2125}
2126
2127/* Wait until threading._shutdown completes, provided
2128 the threading module was imported in the first place.
2129 The shutdown routine will wait until all non-daemon
2130 "threading" threads have completed. */
2131static void
2132wait_for_thread_shutdown(void)
2133{
Nick Coghland6009512014-11-20 21:39:37 +10002134 _Py_IDENTIFIER(_shutdown);
2135 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002136 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002137 if (threading == NULL) {
2138 /* threading not imported */
2139 PyErr_Clear();
2140 return;
2141 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002142 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002143 if (result == NULL) {
2144 PyErr_WriteUnraisable(threading);
2145 }
2146 else {
2147 Py_DECREF(result);
2148 }
2149 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002150}
2151
2152#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002153int Py_AtExit(void (*func)(void))
2154{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002155 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002156 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002157 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002158 return 0;
2159}
2160
2161static void
2162call_ll_exitfuncs(void)
2163{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002164 while (_PyRuntime.nexitfuncs > 0)
2165 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002166
2167 fflush(stdout);
2168 fflush(stderr);
2169}
2170
Victor Stinnercfc88312018-08-01 16:41:25 +02002171void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002172Py_Exit(int sts)
2173{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002174 if (Py_FinalizeEx() < 0) {
2175 sts = 120;
2176 }
Nick Coghland6009512014-11-20 21:39:37 +10002177
2178 exit(sts);
2179}
2180
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002181static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002182initsigs(void)
2183{
2184#ifdef SIGPIPE
2185 PyOS_setsig(SIGPIPE, SIG_IGN);
2186#endif
2187#ifdef SIGXFZ
2188 PyOS_setsig(SIGXFZ, SIG_IGN);
2189#endif
2190#ifdef SIGXFSZ
2191 PyOS_setsig(SIGXFSZ, SIG_IGN);
2192#endif
2193 PyOS_InitInterrupts(); /* May imply initsignal() */
2194 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002195 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002196 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002197 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002198}
2199
2200
2201/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2202 *
2203 * All of the code in this function must only use async-signal-safe functions,
2204 * listed at `man 7 signal` or
2205 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2206 */
2207void
2208_Py_RestoreSignals(void)
2209{
2210#ifdef SIGPIPE
2211 PyOS_setsig(SIGPIPE, SIG_DFL);
2212#endif
2213#ifdef SIGXFZ
2214 PyOS_setsig(SIGXFZ, SIG_DFL);
2215#endif
2216#ifdef SIGXFSZ
2217 PyOS_setsig(SIGXFSZ, SIG_DFL);
2218#endif
2219}
2220
2221
2222/*
2223 * The file descriptor fd is considered ``interactive'' if either
2224 * a) isatty(fd) is TRUE, or
2225 * b) the -i flag was given, and the filename associated with
2226 * the descriptor is NULL or "<stdin>" or "???".
2227 */
2228int
2229Py_FdIsInteractive(FILE *fp, const char *filename)
2230{
2231 if (isatty((int)fileno(fp)))
2232 return 1;
2233 if (!Py_InteractiveFlag)
2234 return 0;
2235 return (filename == NULL) ||
2236 (strcmp(filename, "<stdin>") == 0) ||
2237 (strcmp(filename, "???") == 0);
2238}
2239
2240
Nick Coghland6009512014-11-20 21:39:37 +10002241/* Wrappers around sigaction() or signal(). */
2242
2243PyOS_sighandler_t
2244PyOS_getsig(int sig)
2245{
2246#ifdef HAVE_SIGACTION
2247 struct sigaction context;
2248 if (sigaction(sig, NULL, &context) == -1)
2249 return SIG_ERR;
2250 return context.sa_handler;
2251#else
2252 PyOS_sighandler_t handler;
2253/* Special signal handling for the secure CRT in Visual Studio 2005 */
2254#if defined(_MSC_VER) && _MSC_VER >= 1400
2255 switch (sig) {
2256 /* Only these signals are valid */
2257 case SIGINT:
2258 case SIGILL:
2259 case SIGFPE:
2260 case SIGSEGV:
2261 case SIGTERM:
2262 case SIGBREAK:
2263 case SIGABRT:
2264 break;
2265 /* Don't call signal() with other values or it will assert */
2266 default:
2267 return SIG_ERR;
2268 }
2269#endif /* _MSC_VER && _MSC_VER >= 1400 */
2270 handler = signal(sig, SIG_IGN);
2271 if (handler != SIG_ERR)
2272 signal(sig, handler);
2273 return handler;
2274#endif
2275}
2276
2277/*
2278 * All of the code in this function must only use async-signal-safe functions,
2279 * listed at `man 7 signal` or
2280 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2281 */
2282PyOS_sighandler_t
2283PyOS_setsig(int sig, PyOS_sighandler_t handler)
2284{
2285#ifdef HAVE_SIGACTION
2286 /* Some code in Modules/signalmodule.c depends on sigaction() being
2287 * used here if HAVE_SIGACTION is defined. Fix that if this code
2288 * changes to invalidate that assumption.
2289 */
2290 struct sigaction context, ocontext;
2291 context.sa_handler = handler;
2292 sigemptyset(&context.sa_mask);
2293 context.sa_flags = 0;
2294 if (sigaction(sig, &context, &ocontext) == -1)
2295 return SIG_ERR;
2296 return ocontext.sa_handler;
2297#else
2298 PyOS_sighandler_t oldhandler;
2299 oldhandler = signal(sig, handler);
2300#ifdef HAVE_SIGINTERRUPT
2301 siginterrupt(sig, 1);
2302#endif
2303 return oldhandler;
2304#endif
2305}
2306
2307#ifdef __cplusplus
2308}
2309#endif