blob: 93bce49b63d277e2e044b51a8fbd3bce7cdc5fcb [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 Stinner4f98f462020-04-15 04:01:58 +02007
8#include "pycore_ceval.h" // _PyEval_FiniGIL()
9#include "pycore_context.h" // _PyContext_Init()
10#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner4f98f462020-04-15 04:01:58 +020011#include "pycore_initconfig.h" // _PyStatus_OK()
12#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
13#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
14#include "pycore_pyerrors.h" // _PyErr_Occurred()
15#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020016#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020017#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
18#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
19
Victor Stinner4f98f462020-04-15 04:01:58 +020020#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100021
22#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020023# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100024#endif
25
26#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020027# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100028#endif
29
30#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020031# undef BYTE
32# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070033
Victor Stinner4f98f462020-04-15 04:01:58 +020034 extern PyTypeObject PyWindowsConsoleIO_Type;
35# define PyWindowsConsoleIO_Check(op) \
36 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
Victor Stinner4f98f462020-04-15 04:01:58 +020039
Nick Coghland6009512014-11-20 21:39:37 +100040_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
Nick Coghland6009512014-11-20 21:39:37 +100051
Victor Stinnerb45d2592019-06-20 00:05:23 +020052/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020053static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020054static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050055static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020056static PyStatus init_sys_streams(PyThreadState *tstate);
57static PyStatus init_signals(PyThreadState *tstate);
58static void call_py_exitfuncs(PyThreadState *tstate);
59static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020060static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100061
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080062int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010064static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065
Victor Stinner331a6a52019-05-27 16:39:22 +020066PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067_PyRuntime_Initialize(void)
68{
69 /* XXX We only initialize once in the process, which aligns with
70 the static initialization of the former globals now found in
71 _PyRuntime. However, _PyRuntime *should* be initialized with
72 every Py_Initialize() call, but doing so breaks the runtime.
73 This is because the runtime state is not properly finalized
74 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010075 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020076 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010078 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079
80 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081}
82
83void
84_PyRuntime_Finalize(void)
85{
86 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010087 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
89
90int
91_Py_IsFinalizing(void)
92{
Victor Stinner7b3c2522020-03-07 00:24:23 +010093 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
Nick Coghland6009512014-11-20 21:39:37 +100096/* Hack to force loading of object files */
97int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
98 PyOS_mystrnicmp; /* Python/pystrcmp.o */
99
100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
104{
105 return PyImport_ImportModule("warnings");
106}
107
Eric Snowc7ec9982017-05-23 23:00:52 -0700108
Eric Snow1abcf672017-05-23 21:46:51 -0700109/* APIs to access the initialization flags
110 *
111 * Can be called prior to Py_Initialize.
112 */
Nick Coghland6009512014-11-20 21:39:37 +1000113
Eric Snow1abcf672017-05-23 21:46:51 -0700114int
115_Py_IsCoreInitialized(void)
116{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700118}
Nick Coghland6009512014-11-20 21:39:37 +1000119
120int
121Py_IsInitialized(void)
122{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600123 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000124}
125
Nick Coghlan6ea41862017-06-11 13:16:15 +1000126
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000127/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
128 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000129 initializations fail, a fatal error is issued and the function does
130 not return. On return, the first thread and interpreter state have
131 been created.
132
133 Locking: you must hold the interpreter lock while calling this.
134 (If the lock has not yet been initialized, that's equivalent to
135 having the lock, but you cannot use multiple threads.)
136
137*/
138
Victor Stinner331a6a52019-05-27 16:39:22 +0200139static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200140init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000141{
142 PyObject *importlib;
143 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000144 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200145 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200146 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000147
148 /* Import _importlib through its frozen version, _frozen_importlib. */
149 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200150 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000151 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200152 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000153 PySys_FormatStderr("import _frozen_importlib # frozen\n");
154 }
155 importlib = PyImport_AddModule("_frozen_importlib");
156 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200157 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000158 }
159 interp->importlib = importlib;
160 Py_INCREF(interp->importlib);
161
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200162 interp->import_func = _PyDict_GetItemStringWithError(interp->builtins, "__import__");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300163 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200164 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300165 Py_INCREF(interp->import_func);
166
Victor Stinnercd6e6942015-09-18 09:11:57 +0200167 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800168 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000169 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200170 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000171 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200172 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200173 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000174 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600175 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200176 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000177 }
178
Victor Stinnercd6e6942015-09-18 09:11:57 +0200179 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000180 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
181 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200182 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200183 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000184 }
185 Py_DECREF(value);
186 Py_DECREF(impmod);
187
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000189}
190
Victor Stinner331a6a52019-05-27 16:39:22 +0200191static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200192init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700193{
194 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200195 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700196 "_install_external_importers", "");
197 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200198 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200199 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700200 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200201 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200202 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700203}
Nick Coghland6009512014-11-20 21:39:37 +1000204
Nick Coghlan6ea41862017-06-11 13:16:15 +1000205/* Helper functions to better handle the legacy C locale
206 *
207 * The legacy C locale assumes ASCII as the default text encoding, which
208 * causes problems not only for the CPython runtime, but also other
209 * components like GNU readline.
210 *
211 * Accordingly, when the CLI detects it, it attempts to coerce it to a
212 * more capable UTF-8 based alternative as follows:
213 *
214 * if (_Py_LegacyLocaleDetected()) {
215 * _Py_CoerceLegacyLocale();
216 * }
217 *
218 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
219 *
220 * Locale coercion also impacts the default error handler for the standard
221 * streams: while the usual default is "strict", the default for the legacy
222 * C locale and for any of the coercion target locales is "surrogateescape".
223 */
224
225int
Victor Stinner0f721472019-05-20 17:16:38 +0200226_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000227{
228#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200229 if (!warn) {
230 const char *locale_override = getenv("LC_ALL");
231 if (locale_override != NULL && *locale_override != '\0') {
232 /* Don't coerce C locale if the LC_ALL environment variable
233 is set */
234 return 0;
235 }
236 }
237
Nick Coghlan6ea41862017-06-11 13:16:15 +1000238 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000239 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
240 * the POSIX locale as a simple alias for the C locale, so
241 * we may also want to check for that explicitly.
242 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000243 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
244 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
245#else
246 /* Windows uses code pages instead of locales, so no locale is legacy */
247 return 0;
248#endif
249}
250
Victor Stinnerb0051362019-11-22 17:52:42 +0100251#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000252static const char *_C_LOCALE_WARNING =
253 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
254 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
255 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
256 "locales is recommended.\n";
257
Nick Coghlaneb817952017-06-18 12:29:42 +1000258static void
Victor Stinner43125222019-04-24 18:23:53 +0200259emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000260{
Victor Stinner331a6a52019-05-27 16:39:22 +0200261 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200262 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200263 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000264 }
265}
Victor Stinnerb0051362019-11-22 17:52:42 +0100266#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000267
Nick Coghlan6ea41862017-06-11 13:16:15 +1000268typedef struct _CandidateLocale {
269 const char *locale_name; /* The locale to try as a coercion target */
270} _LocaleCoercionTarget;
271
272static _LocaleCoercionTarget _TARGET_LOCALES[] = {
273 {"C.UTF-8"},
274 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000275 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276 {NULL}
277};
278
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200279
280int
281_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200283 const _LocaleCoercionTarget *target = NULL;
284 for (target = _TARGET_LOCALES; target->locale_name; target++) {
285 if (strcmp(ctype_loc, target->locale_name) == 0) {
286 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000287 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200288 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200289 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000290}
291
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200292
Nick Coghlan6ea41862017-06-11 13:16:15 +1000293#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100294static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
296 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
297
Victor Stinner0f721472019-05-20 17:16:38 +0200298static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200299_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300{
301 const char *newloc = target->locale_name;
302
303 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100304 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305
306 /* Set the relevant locale environment variable */
307 if (setenv("LC_CTYPE", newloc, 1)) {
308 fprintf(stderr,
309 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200310 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200312 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100313 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000314 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315
316 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100317 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200318 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319}
320#endif
321
Victor Stinner0f721472019-05-20 17:16:38 +0200322int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200323_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000324{
Victor Stinner0f721472019-05-20 17:16:38 +0200325 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200327 char *oldloc = NULL;
328
329 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
330 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200331 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200332 }
333
Victor Stinner94540602017-12-16 04:54:22 +0100334 const char *locale_override = getenv("LC_ALL");
335 if (locale_override == NULL || *locale_override == '\0') {
336 /* LC_ALL is also not set (or is set to an empty string) */
337 const _LocaleCoercionTarget *target = NULL;
338 for (target = _TARGET_LOCALES; target->locale_name; target++) {
339 const char *new_locale = setlocale(LC_CTYPE,
340 target->locale_name);
341 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400342#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100343 /* Also ensure that nl_langinfo works in this locale */
344 char *codeset = nl_langinfo(CODESET);
345 if (!codeset || *codeset == '\0') {
346 /* CODESET is not set or empty, so skip coercion */
347 new_locale = NULL;
348 _Py_SetLocaleFromEnv(LC_CTYPE);
349 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350 }
Victor Stinner94540602017-12-16 04:54:22 +0100351#endif
352 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200353 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200354 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000355 }
356 }
357 }
358 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200359
360 setlocale(LC_CTYPE, oldloc);
361
362done:
363 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000364#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200365 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000366}
367
xdegaye1588be62017-11-12 12:45:59 +0100368/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
369 * isolate the idiosyncrasies of different libc implementations. It reads the
370 * appropriate environment variable and uses its value to select the locale for
371 * 'category'. */
372char *
373_Py_SetLocaleFromEnv(int category)
374{
Victor Stinner353933e2018-11-23 13:08:26 +0100375 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100376#ifdef __ANDROID__
377 const char *locale;
378 const char **pvar;
379#ifdef PY_COERCE_C_LOCALE
380 const char *coerce_c_locale;
381#endif
382 const char *utf8_locale = "C.UTF-8";
383 const char *env_var_set[] = {
384 "LC_ALL",
385 "LC_CTYPE",
386 "LANG",
387 NULL,
388 };
389
390 /* Android setlocale(category, "") doesn't check the environment variables
391 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
392 * check the environment variables listed in env_var_set. */
393 for (pvar=env_var_set; *pvar; pvar++) {
394 locale = getenv(*pvar);
395 if (locale != NULL && *locale != '\0') {
396 if (strcmp(locale, utf8_locale) == 0 ||
397 strcmp(locale, "en_US.UTF-8") == 0) {
398 return setlocale(category, utf8_locale);
399 }
400 return setlocale(category, "C");
401 }
402 }
403
404 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
405 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
406 * Quote from POSIX section "8.2 Internationalization Variables":
407 * "4. If the LANG environment variable is not set or is set to the empty
408 * string, the implementation-defined default locale shall be used." */
409
410#ifdef PY_COERCE_C_LOCALE
411 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
412 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
413 /* Some other ported code may check the environment variables (e.g. in
414 * extension modules), so we make sure that they match the locale
415 * configuration */
416 if (setenv("LC_CTYPE", utf8_locale, 1)) {
417 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
418 "environment variable to %s\n", utf8_locale);
419 }
420 }
421#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100422 res = setlocale(category, utf8_locale);
423#else /* !defined(__ANDROID__) */
424 res = setlocale(category, "");
425#endif
426 _Py_ResetForceASCII();
427 return res;
xdegaye1588be62017-11-12 12:45:59 +0100428}
429
Nick Coghlan6ea41862017-06-11 13:16:15 +1000430
Victor Stinner048a3562020-11-05 00:45:56 +0100431static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100432interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100433{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100434 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100435
Victor Stinner9e1b8282020-11-10 13:21:52 +0100436 if (!only_update_path_config) {
437 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
438 if (_PyStatus_EXCEPTION(status)) {
439 _PyErr_SetFromPyStatus(status);
440 return -1;
441 }
Victor Stinner048a3562020-11-05 00:45:56 +0100442 }
443
Victor Stinner9e1b8282020-11-10 13:21:52 +0100444 if (_Py_IsMainInterpreter(tstate)) {
445 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100446 if (_PyStatus_EXCEPTION(status)) {
447 _PyErr_SetFromPyStatus(status);
448 return -1;
449 }
450 }
451
452 // Update the sys module for the new configuration
453 if (_PySys_UpdateConfig(tstate) < 0) {
454 return -1;
455 }
456 return 0;
457}
458
459
460int
461_PyInterpreterState_SetConfig(const PyConfig *src_config)
462{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100463 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100464 int res = -1;
465
466 PyConfig config;
467 PyConfig_InitPythonConfig(&config);
468 PyStatus status = _PyConfig_Copy(&config, src_config);
469 if (_PyStatus_EXCEPTION(status)) {
470 _PyErr_SetFromPyStatus(status);
471 goto done;
472 }
473
474 status = PyConfig_Read(&config);
475 if (_PyStatus_EXCEPTION(status)) {
476 _PyErr_SetFromPyStatus(status);
477 goto done;
478 }
479
Victor Stinner9e1b8282020-11-10 13:21:52 +0100480 status = _PyConfig_Copy(&tstate->interp->config, &config);
481 if (_PyStatus_EXCEPTION(status)) {
482 _PyErr_SetFromPyStatus(status);
483 goto done;
484 }
485
486 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100487
488done:
489 PyConfig_Clear(&config);
490 return res;
491}
492
493
Eric Snow1abcf672017-05-23 21:46:51 -0700494/* Global initializations. Can be undone by Py_Finalize(). Don't
495 call this twice without an intervening Py_Finalize() call.
496
Victor Stinner331a6a52019-05-27 16:39:22 +0200497 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700498 must have a corresponding call to Py_Finalize.
499
500 Locking: you must hold the interpreter lock while calling these APIs.
501 (If the lock has not yet been initialized, that's equivalent to
502 having the lock, but you cannot use multiple threads.)
503
504*/
505
Victor Stinner331a6a52019-05-27 16:39:22 +0200506static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200507pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200508 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200509 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200510{
Victor Stinner331a6a52019-05-27 16:39:22 +0200511 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100512 PyThreadState *tstate = _PyThreadState_GET();
513 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200514 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100515 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200516 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517
518 PyInterpreterState *interp = tstate->interp;
519 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200520 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100521 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100522
Victor Stinnere81f6e62020-06-08 18:12:59 +0200523 status = _PyConfig_Write(config, runtime);
524 if (_PyStatus_EXCEPTION(status)) {
525 return status;
526 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527
Victor Stinner048a3562020-11-05 00:45:56 +0100528 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200529 if (_PyStatus_EXCEPTION(status)) {
530 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200531 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200532 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200533
Victor Stinner331a6a52019-05-27 16:39:22 +0200534 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200535 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200536 if (_PyStatus_EXCEPTION(status)) {
537 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200538 }
539 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200540 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200541}
542
543
Victor Stinner331a6a52019-05-27 16:39:22 +0200544static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200545pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200546 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000547{
Victor Stinner43125222019-04-24 18:23:53 +0200548 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200549 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200550 }
Victor Stinnerda273412017-12-15 01:46:02 +0100551
Victor Stinnere81f6e62020-06-08 18:12:59 +0200552 PyStatus status = _PyConfig_Write(config, runtime);
553 if (_PyStatus_EXCEPTION(status)) {
554 return status;
555 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600556
Eric Snow1abcf672017-05-23 21:46:51 -0700557 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
558 * threads behave a little more gracefully at interpreter shutdown.
559 * We clobber it here so the new interpreter can start with a clean
560 * slate.
561 *
562 * However, this may still lead to misbehaviour if there are daemon
563 * threads still hanging around from a previous Py_Initialize/Finalize
564 * pair :(
565 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100566 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600567
Victor Stinnere81f6e62020-06-08 18:12:59 +0200568 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200569 if (_PyStatus_EXCEPTION(status)) {
570 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800571 }
572
Victor Stinner331a6a52019-05-27 16:39:22 +0200573 status = _PyInterpreterState_Enable(runtime);
574 if (_PyStatus_EXCEPTION(status)) {
575 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800576 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200577 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100578}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800579
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100580
Victor Stinner331a6a52019-05-27 16:39:22 +0200581static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200582init_interp_create_gil(PyThreadState *tstate)
583{
584 PyStatus status;
585
586 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
587 only called here. */
588 _PyEval_FiniGIL(tstate);
589
590 /* Auto-thread-state API */
591 status = _PyGILState_Init(tstate);
592 if (_PyStatus_EXCEPTION(status)) {
593 return status;
594 }
595
596 /* Create the GIL and take it */
597 status = _PyEval_InitGIL(tstate);
598 if (_PyStatus_EXCEPTION(status)) {
599 return status;
600 }
601
602 return _PyStatus_OK();
603}
604
605
606static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200607pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200608 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200609 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100610{
611 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100612 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200613 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100614 }
615
Victor Stinner048a3562020-11-05 00:45:56 +0100616 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200617 if (_PyStatus_EXCEPTION(status)) {
618 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100619 }
Nick Coghland6009512014-11-20 21:39:37 +1000620
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200621 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200622 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200623 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200624 }
Nick Coghland6009512014-11-20 21:39:37 +1000625 (void) PyThreadState_Swap(tstate);
626
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200627 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100628 if (_PyStatus_EXCEPTION(status)) {
629 return status;
630 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100631
Victor Stinnerb45d2592019-06-20 00:05:23 +0200632 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200633 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100634}
Nick Coghland6009512014-11-20 21:39:37 +1000635
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100636
Victor Stinner331a6a52019-05-27 16:39:22 +0200637static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100638pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100639{
Victor Stinner444b39b2019-11-20 01:18:11 +0100640 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100641 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100642
Victor Stinner01b1cc12019-11-20 02:27:56 +0100643 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100644 if (_PyStatus_EXCEPTION(status)) {
645 return status;
646 }
647
Victor Stinner0430dfa2020-06-24 15:21:54 +0200648 // Create the empty tuple singleton. It must be created before the first
649 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
650 // for example.
651 status = _PyTuple_Init(tstate);
652 if (_PyStatus_EXCEPTION(status)) {
653 return status;
654 }
655
Victor Stinnere7e699e2019-11-20 12:08:13 +0100656 if (is_main_interp) {
657 status = _PyTypes_Init();
658 if (_PyStatus_EXCEPTION(status)) {
659 return status;
660 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100661 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100662
Victor Stinner630c8df2019-12-17 13:02:18 +0100663 if (!_PyLong_Init(tstate)) {
664 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100665 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100666
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200667 status = _PyUnicode_Init(tstate);
668 if (_PyStatus_EXCEPTION(status)) {
669 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100670 }
671
Victor Stinner91698d82020-06-25 14:07:40 +0200672 status = _PyBytes_Init(tstate);
673 if (_PyStatus_EXCEPTION(status)) {
674 return status;
675 }
676
Victor Stinner281cce12020-06-23 22:55:46 +0200677 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200678 if (_PyStatus_EXCEPTION(status)) {
679 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100680 }
681
Victor Stinnere7e699e2019-11-20 12:08:13 +0100682 if (is_main_interp) {
683 if (!_PyFloat_Init()) {
684 return _PyStatus_ERR("can't init float");
685 }
Nick Coghland6009512014-11-20 21:39:37 +1000686
Victor Stinnere7e699e2019-11-20 12:08:13 +0100687 if (_PyStructSequence_Init() < 0) {
688 return _PyStatus_ERR("can't initialize structseq");
689 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100690 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200691
Victor Stinner331a6a52019-05-27 16:39:22 +0200692 status = _PyErr_Init();
693 if (_PyStatus_EXCEPTION(status)) {
694 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200695 }
696
Victor Stinnere7e699e2019-11-20 12:08:13 +0100697 if (is_main_interp) {
698 if (!_PyContext_Init()) {
699 return _PyStatus_ERR("can't init context");
700 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100701 }
702
Victor Stinner331a6a52019-05-27 16:39:22 +0200703 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100704}
705
706
Victor Stinner331a6a52019-05-27 16:39:22 +0200707static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200708pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100709{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100710 assert(!_PyErr_Occurred(tstate));
711
Victor Stinnerb45d2592019-06-20 00:05:23 +0200712 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100713 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100714 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100715 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100716
Victor Stinner2582d462019-11-22 19:24:49 +0100717 PyInterpreterState *interp = tstate->interp;
718 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
719 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100720 }
Victor Stinner2582d462019-11-22 19:24:49 +0100721
722 PyObject *builtins_dict = PyModule_GetDict(bimod);
723 if (builtins_dict == NULL) {
724 goto error;
725 }
726 Py_INCREF(builtins_dict);
727 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100728
Victor Stinner331a6a52019-05-27 16:39:22 +0200729 PyStatus status = _PyBuiltins_AddExceptions(bimod);
730 if (_PyStatus_EXCEPTION(status)) {
731 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100732 }
Victor Stinner2582d462019-11-22 19:24:49 +0100733
734 interp->builtins_copy = PyDict_Copy(interp->builtins);
735 if (interp->builtins_copy == NULL) {
736 goto error;
737 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000738 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100739
740 assert(!_PyErr_Occurred(tstate));
741
Victor Stinner331a6a52019-05-27 16:39:22 +0200742 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100743
744error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000745 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100746 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100747}
748
749
Victor Stinner331a6a52019-05-27 16:39:22 +0200750static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200751pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100752{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100753 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200754
Victor Stinner2582d462019-11-22 19:24:49 +0100755 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200756 if (_PyStatus_EXCEPTION(status)) {
757 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800758 }
Nick Coghland6009512014-11-20 21:39:37 +1000759
Victor Stinner30a89332020-06-23 15:55:45 +0200760 /* Initialize _warnings. */
761 status = _PyWarnings_InitState(tstate);
762 if (_PyStatus_EXCEPTION(status)) {
763 return status;
764 }
Nick Coghland6009512014-11-20 21:39:37 +1000765
Victor Stinner30a89332020-06-23 15:55:45 +0200766 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
767 if (config->_install_importlib) {
Victor Stinner30a89332020-06-23 15:55:45 +0200768 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200769 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200770 if (_PyStatus_EXCEPTION(status)) {
771 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800772 }
Eric Snow1abcf672017-05-23 21:46:51 -0700773 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100774
775 assert(!_PyErr_Occurred(tstate));
776
Victor Stinner331a6a52019-05-27 16:39:22 +0200777 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100778}
779
780
Victor Stinner331a6a52019-05-27 16:39:22 +0200781static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100782pycore_interp_init(PyThreadState *tstate)
783{
784 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100785 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100786
787 status = pycore_init_types(tstate);
788 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100789 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100790 }
791
Victor Stinnerd863ade2019-12-06 03:37:07 +0100792 status = _PySys_Create(tstate, &sysmod);
793 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100794 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100795 }
796
797 status = pycore_init_builtins(tstate);
798 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100799 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100800 }
801
Victor Stinner080ee5a2019-12-08 21:55:58 +0100802 status = pycore_init_import_warnings(tstate, sysmod);
803
804done:
805 /* sys.modules['sys'] contains a strong reference to the module */
806 Py_XDECREF(sysmod);
807 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100808}
809
810
811static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200812pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200813 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200814 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100815{
Victor Stinner331a6a52019-05-27 16:39:22 +0200816 PyStatus status = pycore_init_runtime(runtime, config);
817 if (_PyStatus_EXCEPTION(status)) {
818 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100819 }
820
Victor Stinnerb45d2592019-06-20 00:05:23 +0200821 PyThreadState *tstate;
822 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200823 if (_PyStatus_EXCEPTION(status)) {
824 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100825 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200826 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100827
Victor Stinnerd863ade2019-12-06 03:37:07 +0100828 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200829 if (_PyStatus_EXCEPTION(status)) {
830 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100831 }
Eric Snow1abcf672017-05-23 21:46:51 -0700832
833 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200834 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200835 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700836}
837
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100838
Victor Stinner331a6a52019-05-27 16:39:22 +0200839PyStatus
840_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100841{
Victor Stinner331a6a52019-05-27 16:39:22 +0200842 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100843
Victor Stinner6d1c4672019-05-20 11:02:00 +0200844 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200845 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200846 }
847
Victor Stinner331a6a52019-05-27 16:39:22 +0200848 status = _PyRuntime_Initialize();
849 if (_PyStatus_EXCEPTION(status)) {
850 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100851 }
Victor Stinner43125222019-04-24 18:23:53 +0200852 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100853
Victor Stinnerd3b90412019-09-17 23:59:51 +0200854 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100855 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200856 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100857 }
858
Victor Stinnerd3b90412019-09-17 23:59:51 +0200859 /* Note: preinitialized remains 1 on error, it is only set to 0
860 at exit on success. */
861 runtime->preinitializing = 1;
862
Victor Stinner331a6a52019-05-27 16:39:22 +0200863 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200864
865 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
866 if (_PyStatus_EXCEPTION(status)) {
867 return status;
868 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100869
Victor Stinner331a6a52019-05-27 16:39:22 +0200870 status = _PyPreConfig_Read(&config, args);
871 if (_PyStatus_EXCEPTION(status)) {
872 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100873 }
874
Victor Stinner331a6a52019-05-27 16:39:22 +0200875 status = _PyPreConfig_Write(&config);
876 if (_PyStatus_EXCEPTION(status)) {
877 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100878 }
879
Victor Stinnerd3b90412019-09-17 23:59:51 +0200880 runtime->preinitializing = 0;
881 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200882 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100883}
884
Victor Stinner70005ac2019-05-02 15:25:34 -0400885
Victor Stinner331a6a52019-05-27 16:39:22 +0200886PyStatus
887Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100888{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100889 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400890 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100891}
892
893
Victor Stinner331a6a52019-05-27 16:39:22 +0200894PyStatus
895Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100896{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100897 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400898 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100899}
900
901
Victor Stinner331a6a52019-05-27 16:39:22 +0200902PyStatus
903Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100904{
Victor Stinner70005ac2019-05-02 15:25:34 -0400905 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100906}
907
908
Victor Stinner331a6a52019-05-27 16:39:22 +0200909PyStatus
910_Py_PreInitializeFromConfig(const PyConfig *config,
911 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100912{
Victor Stinner331a6a52019-05-27 16:39:22 +0200913 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200914
Victor Stinner331a6a52019-05-27 16:39:22 +0200915 PyStatus status = _PyRuntime_Initialize();
916 if (_PyStatus_EXCEPTION(status)) {
917 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200918 }
919 _PyRuntimeState *runtime = &_PyRuntime;
920
Victor Stinnerd3b90412019-09-17 23:59:51 +0200921 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200922 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200923 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400924 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200925
Victor Stinner331a6a52019-05-27 16:39:22 +0200926 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200927
Victor Stinner3c30a762019-10-01 10:56:37 +0200928 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200929
Victor Stinner331a6a52019-05-27 16:39:22 +0200930 if (!config->parse_argv) {
931 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200932 }
933 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200934 _PyArgv config_args = {
935 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200936 .argc = config->argv.length,
937 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200938 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200939 }
940 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200941 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200942 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100943}
944
945
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100946/* Begin interpreter initialization
947 *
948 * On return, the first thread and interpreter state have been created,
949 * but the compiler, signal handling, multithreading and
950 * multiple interpreter support, and codec infrastructure are not yet
951 * available.
952 *
953 * The import system will support builtin and frozen modules only.
954 * The only supported io is writing to sys.stderr
955 *
956 * If any operation invoked by this function fails, a fatal error is
957 * issued and the function does not return.
958 *
959 * Any code invoked from this function should *not* assume it has access
960 * to the Python C API (unless the API is explicitly listed as being
961 * safe to call without calling Py_Initialize first)
962 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200963static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200964pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200965 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200966 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200967{
Victor Stinner331a6a52019-05-27 16:39:22 +0200968 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200969
Victor Stinner331a6a52019-05-27 16:39:22 +0200970 status = _Py_PreInitializeFromConfig(src_config, NULL);
971 if (_PyStatus_EXCEPTION(status)) {
972 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200973 }
974
Victor Stinner331a6a52019-05-27 16:39:22 +0200975 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100976 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200977
Victor Stinner331a6a52019-05-27 16:39:22 +0200978 status = _PyConfig_Copy(&config, src_config);
979 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200980 goto done;
981 }
982
Victor Stinner9e1b8282020-11-10 13:21:52 +0100983 // Read the configuration, but don't compute the path configuration
984 // (it is computed in the main init).
985 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200986 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200987 goto done;
988 }
989
990 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200991 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200992 }
993 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200994 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200995 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200996 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200997 goto done;
998 }
999
1000done:
Victor Stinner331a6a52019-05-27 16:39:22 +02001001 PyConfig_Clear(&config);
1002 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +02001003}
1004
Victor Stinner5ac27a52019-03-27 13:40:14 +01001005
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001006/* Py_Initialize() has already been called: update the main interpreter
1007 configuration. Example of bpo-34008: Py_Main() called after
1008 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +02001009static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001010pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001011{
Victor Stinner9e1b8282020-11-10 13:21:52 +01001012 if (interpreter_update_config(tstate, 0) < 0) {
1013 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001014 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001015 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001016}
1017
Victor Stinnerb0051362019-11-22 17:52:42 +01001018
1019static PyStatus
1020init_interp_main(PyThreadState *tstate)
1021{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001022 assert(!_PyErr_Occurred(tstate));
1023
Victor Stinnerb0051362019-11-22 17:52:42 +01001024 PyStatus status;
1025 int is_main_interp = _Py_IsMainInterpreter(tstate);
1026 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001027 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001028
1029 if (!config->_install_importlib) {
1030 /* Special mode for freeze_importlib: run with no import system
1031 *
1032 * This means anything which needs support from extension modules
1033 * or pure Python code in the standard library won't work.
1034 */
1035 if (is_main_interp) {
1036 interp->runtime->initialized = 1;
1037 }
1038 return _PyStatus_OK();
1039 }
1040
Victor Stinner9e1b8282020-11-10 13:21:52 +01001041 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001042 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001043 if (_PyStatus_EXCEPTION(status)) {
1044 return status;
1045 }
1046
Victor Stinnerb0051362019-11-22 17:52:42 +01001047 if (is_main_interp) {
1048 if (_PyTime_Init() < 0) {
1049 return _PyStatus_ERR("can't initialize time");
1050 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001051 }
Victor Stinnerb0051362019-11-22 17:52:42 +01001052
Victor Stinner9e1b8282020-11-10 13:21:52 +01001053 if (interpreter_update_config(tstate, 1) < 0) {
1054 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001055 }
1056
1057 status = init_importlib_external(tstate);
1058 if (_PyStatus_EXCEPTION(status)) {
1059 return status;
1060 }
1061
1062 if (is_main_interp) {
1063 /* initialize the faulthandler module */
1064 status = _PyFaulthandler_Init(config->faulthandler);
1065 if (_PyStatus_EXCEPTION(status)) {
1066 return status;
1067 }
1068 }
1069
1070 status = _PyUnicode_InitEncodings(tstate);
1071 if (_PyStatus_EXCEPTION(status)) {
1072 return status;
1073 }
1074
1075 if (is_main_interp) {
1076 if (config->install_signal_handlers) {
1077 status = init_signals(tstate);
1078 if (_PyStatus_EXCEPTION(status)) {
1079 return status;
1080 }
1081 }
1082
1083 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1084 return _PyStatus_ERR("can't initialize tracemalloc");
1085 }
1086 }
1087
1088 status = init_sys_streams(tstate);
1089 if (_PyStatus_EXCEPTION(status)) {
1090 return status;
1091 }
1092
Andy Lester75cd5bf2020-03-12 02:49:05 -05001093 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001094 if (_PyStatus_EXCEPTION(status)) {
1095 return status;
1096 }
1097
1098 status = add_main_module(interp);
1099 if (_PyStatus_EXCEPTION(status)) {
1100 return status;
1101 }
1102
1103 if (is_main_interp) {
1104 /* Initialize warnings. */
1105 PyObject *warnoptions = PySys_GetObject("warnoptions");
1106 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1107 {
1108 PyObject *warnings_module = PyImport_ImportModule("warnings");
1109 if (warnings_module == NULL) {
1110 fprintf(stderr, "'import warnings' failed; traceback:\n");
1111 _PyErr_Print(tstate);
1112 }
1113 Py_XDECREF(warnings_module);
1114 }
1115
1116 interp->runtime->initialized = 1;
1117 }
1118
1119 if (config->site_import) {
1120 status = init_import_site();
1121 if (_PyStatus_EXCEPTION(status)) {
1122 return status;
1123 }
1124 }
1125
1126 if (is_main_interp) {
1127#ifndef MS_WINDOWS
1128 emit_stderr_warning_for_legacy_locale(interp->runtime);
1129#endif
1130 }
1131
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001132 assert(!_PyErr_Occurred(tstate));
1133
Victor Stinnerb0051362019-11-22 17:52:42 +01001134 return _PyStatus_OK();
1135}
1136
1137
Eric Snowc7ec9982017-05-23 23:00:52 -07001138/* Update interpreter state based on supplied configuration settings
1139 *
1140 * After calling this function, most of the restrictions on the interpreter
1141 * are lifted. The only remaining incomplete settings are those related
1142 * to the main module (sys.argv[0], __main__ metadata)
1143 *
1144 * Calling this when the interpreter is not initializing, is already
1145 * initialized or without a valid current thread state is a fatal error.
1146 * Other errors should be reported as normal Python exceptions with a
1147 * non-zero return code.
1148 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001149static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001150pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001151{
Victor Stinnerb0051362019-11-22 17:52:42 +01001152 PyInterpreterState *interp = tstate->interp;
1153 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001154 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001155 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001156
Victor Stinnerb0051362019-11-22 17:52:42 +01001157 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001158 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001159 }
1160
Victor Stinnerb0051362019-11-22 17:52:42 +01001161 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001162 if (_PyStatus_EXCEPTION(status)) {
1163 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001164 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001165 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001166}
1167
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001168
Victor Stinner331a6a52019-05-27 16:39:22 +02001169PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001170Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001171{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001172 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001173 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001174 }
1175
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001177
Victor Stinner331a6a52019-05-27 16:39:22 +02001178 status = _PyRuntime_Initialize();
1179 if (_PyStatus_EXCEPTION(status)) {
1180 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001181 }
1182 _PyRuntimeState *runtime = &_PyRuntime;
1183
Victor Stinnerb45d2592019-06-20 00:05:23 +02001184 PyThreadState *tstate = NULL;
1185 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001186 if (_PyStatus_EXCEPTION(status)) {
1187 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001188 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001189 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001190
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001191 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001192 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001193 if (_PyStatus_EXCEPTION(status)) {
1194 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001195 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001196 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001197
Victor Stinner331a6a52019-05-27 16:39:22 +02001198 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001199}
1200
1201
Eric Snow1abcf672017-05-23 21:46:51 -07001202void
Nick Coghland6009512014-11-20 21:39:37 +10001203Py_InitializeEx(int install_sigs)
1204{
Victor Stinner331a6a52019-05-27 16:39:22 +02001205 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001206
Victor Stinner331a6a52019-05-27 16:39:22 +02001207 status = _PyRuntime_Initialize();
1208 if (_PyStatus_EXCEPTION(status)) {
1209 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001210 }
1211 _PyRuntimeState *runtime = &_PyRuntime;
1212
1213 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001214 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1215 return;
1216 }
1217
Victor Stinner331a6a52019-05-27 16:39:22 +02001218 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001219 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001220
Victor Stinner1dc6e392018-07-25 02:49:17 +02001221 config.install_signal_handlers = install_sigs;
1222
Victor Stinner331a6a52019-05-27 16:39:22 +02001223 status = Py_InitializeFromConfig(&config);
1224 if (_PyStatus_EXCEPTION(status)) {
1225 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001226 }
Nick Coghland6009512014-11-20 21:39:37 +10001227}
1228
1229void
1230Py_Initialize(void)
1231{
1232 Py_InitializeEx(1);
1233}
1234
1235
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001236PyStatus
1237_Py_InitializeMain(void)
1238{
1239 PyStatus status = _PyRuntime_Initialize();
1240 if (_PyStatus_EXCEPTION(status)) {
1241 return status;
1242 }
1243 _PyRuntimeState *runtime = &_PyRuntime;
1244 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1245 return pyinit_main(tstate);
1246}
1247
1248
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001249static void
1250finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1251{
1252 // List of names to clear in sys
1253 static const char * const sys_deletes[] = {
1254 "path", "argv", "ps1", "ps2",
1255 "last_type", "last_value", "last_traceback",
1256 "path_hooks", "path_importer_cache", "meta_path",
1257 "__interactivehook__",
1258 NULL
1259 };
1260
1261 static const char * const sys_files[] = {
1262 "stdin", "__stdin__",
1263 "stdout", "__stdout__",
1264 "stderr", "__stderr__",
1265 NULL
1266 };
1267
1268 PyInterpreterState *interp = tstate->interp;
1269 if (verbose) {
1270 PySys_WriteStderr("# clear builtins._\n");
1271 }
1272 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1273 PyErr_WriteUnraisable(NULL);
1274 }
1275
1276 const char * const *p;
1277 for (p = sys_deletes; *p != NULL; p++) {
1278 if (verbose) {
1279 PySys_WriteStderr("# clear sys.%s\n", *p);
1280 }
1281 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1282 PyErr_WriteUnraisable(NULL);
1283 }
1284 }
1285 for (p = sys_files; *p != NULL; p+=2) {
1286 const char *name = p[0];
1287 const char *orig_name = p[1];
1288 if (verbose) {
1289 PySys_WriteStderr("# restore sys.%s\n", name);
1290 }
1291 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1292 orig_name);
1293 if (value == NULL) {
1294 if (_PyErr_Occurred(tstate)) {
1295 PyErr_WriteUnraisable(NULL);
1296 }
1297 value = Py_None;
1298 }
1299 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1300 PyErr_WriteUnraisable(NULL);
1301 }
1302 }
1303}
1304
1305
1306static PyObject*
1307finalize_remove_modules(PyObject *modules, int verbose)
1308{
1309 PyObject *weaklist = PyList_New(0);
1310 if (weaklist == NULL) {
1311 PyErr_WriteUnraisable(NULL);
1312 }
1313
1314#define STORE_MODULE_WEAKREF(name, mod) \
1315 if (weaklist != NULL) { \
1316 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1317 if (wr) { \
1318 PyObject *tup = PyTuple_Pack(2, name, wr); \
1319 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1320 PyErr_WriteUnraisable(NULL); \
1321 } \
1322 Py_XDECREF(tup); \
1323 Py_DECREF(wr); \
1324 } \
1325 else { \
1326 PyErr_WriteUnraisable(NULL); \
1327 } \
1328 }
1329
1330#define CLEAR_MODULE(name, mod) \
1331 if (PyModule_Check(mod)) { \
1332 if (verbose && PyUnicode_Check(name)) { \
1333 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1334 } \
1335 STORE_MODULE_WEAKREF(name, mod); \
1336 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1337 PyErr_WriteUnraisable(NULL); \
1338 } \
1339 }
1340
1341 if (PyDict_CheckExact(modules)) {
1342 Py_ssize_t pos = 0;
1343 PyObject *key, *value;
1344 while (PyDict_Next(modules, &pos, &key, &value)) {
1345 CLEAR_MODULE(key, value);
1346 }
1347 }
1348 else {
1349 PyObject *iterator = PyObject_GetIter(modules);
1350 if (iterator == NULL) {
1351 PyErr_WriteUnraisable(NULL);
1352 }
1353 else {
1354 PyObject *key;
1355 while ((key = PyIter_Next(iterator))) {
1356 PyObject *value = PyObject_GetItem(modules, key);
1357 if (value == NULL) {
1358 PyErr_WriteUnraisable(NULL);
1359 continue;
1360 }
1361 CLEAR_MODULE(key, value);
1362 Py_DECREF(value);
1363 Py_DECREF(key);
1364 }
1365 if (PyErr_Occurred()) {
1366 PyErr_WriteUnraisable(NULL);
1367 }
1368 Py_DECREF(iterator);
1369 }
1370 }
1371#undef CLEAR_MODULE
1372#undef STORE_MODULE_WEAKREF
1373
1374 return weaklist;
1375}
1376
1377
1378static void
1379finalize_clear_modules_dict(PyObject *modules)
1380{
1381 if (PyDict_CheckExact(modules)) {
1382 PyDict_Clear(modules);
1383 }
1384 else {
1385 _Py_IDENTIFIER(clear);
1386 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1387 PyErr_WriteUnraisable(NULL);
1388 }
1389 }
1390}
1391
1392
1393static void
1394finalize_restore_builtins(PyThreadState *tstate)
1395{
1396 PyInterpreterState *interp = tstate->interp;
1397 PyObject *dict = PyDict_Copy(interp->builtins);
1398 if (dict == NULL) {
1399 PyErr_WriteUnraisable(NULL);
1400 }
1401 PyDict_Clear(interp->builtins);
1402 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1403 _PyErr_Clear(tstate);
1404 }
1405 Py_XDECREF(dict);
1406}
1407
1408
1409static void
1410finalize_modules_clear_weaklist(PyInterpreterState *interp,
1411 PyObject *weaklist, int verbose)
1412{
1413 // First clear modules imported later
1414 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1415 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1416 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1417 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1418 if (mod == Py_None) {
1419 continue;
1420 }
1421 assert(PyModule_Check(mod));
1422 PyObject *dict = PyModule_GetDict(mod);
1423 if (dict == interp->builtins || dict == interp->sysdict) {
1424 continue;
1425 }
1426 Py_INCREF(mod);
1427 if (verbose && PyUnicode_Check(name)) {
1428 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1429 }
1430 _PyModule_Clear(mod);
1431 Py_DECREF(mod);
1432 }
1433}
1434
1435
1436static void
1437finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1438{
1439 // Clear sys dict
1440 if (verbose) {
1441 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1442 }
1443 _PyModule_ClearDict(interp->sysdict);
1444
1445 // Clear builtins dict
1446 if (verbose) {
1447 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1448 }
1449 _PyModule_ClearDict(interp->builtins);
1450}
1451
1452
1453/* Clear modules, as good as we can */
1454static void
1455finalize_modules(PyThreadState *tstate)
1456{
1457 PyInterpreterState *interp = tstate->interp;
1458 PyObject *modules = interp->modules;
1459 if (modules == NULL) {
1460 // Already done
1461 return;
1462 }
1463 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1464
1465 // Delete some special builtins._ and sys attributes first. These are
1466 // common places where user values hide and people complain when their
1467 // destructors fail. Since the modules containing them are
1468 // deleted *last* of all, they would come too late in the normal
1469 // destruction order. Sigh.
1470 //
1471 // XXX Perhaps these precautions are obsolete. Who knows?
1472 finalize_modules_delete_special(tstate, verbose);
1473
1474 // Remove all modules from sys.modules, hoping that garbage collection
1475 // can reclaim most of them: set all sys.modules values to None.
1476 //
1477 // We prepare a list which will receive (name, weakref) tuples of
1478 // modules when they are removed from sys.modules. The name is used
1479 // for diagnosis messages (in verbose mode), while the weakref helps
1480 // detect those modules which have been held alive.
1481 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1482
1483 // Clear the modules dict
1484 finalize_clear_modules_dict(modules);
1485
1486 // Restore the original builtins dict, to ensure that any
1487 // user data gets cleared.
1488 finalize_restore_builtins(tstate);
1489
1490 // Collect garbage
1491 _PyGC_CollectNoFail(tstate);
1492
1493 // Dump GC stats before it's too late, since it uses the warnings
1494 // machinery.
1495 _PyGC_DumpShutdownStats(tstate);
1496
1497 if (weaklist != NULL) {
1498 // Now, if there are any modules left alive, clear their globals to
1499 // minimize potential leaks. All C extension modules actually end
1500 // up here, since they are kept alive in the interpreter state.
1501 //
1502 // The special treatment of "builtins" here is because even
1503 // when it's not referenced as a module, its dictionary is
1504 // referenced by almost every module's __builtins__. Since
1505 // deleting a module clears its dictionary (even if there are
1506 // references left to it), we need to delete the "builtins"
1507 // module last. Likewise, we don't delete sys until the very
1508 // end because it is implicitly referenced (e.g. by print).
1509 //
1510 // Since dict is ordered in CPython 3.6+, modules are saved in
1511 // importing order. First clear modules imported later.
1512 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1513 Py_DECREF(weaklist);
1514 }
1515
1516 // Clear sys and builtins modules dict
1517 finalize_clear_sys_builtins_dict(interp, verbose);
1518
1519 // Clear module dict copies stored in the interpreter state:
1520 // clear PyInterpreterState.modules_by_index and
1521 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1522 // initialization API)
1523 _PyInterpreterState_ClearModules(interp);
1524
1525 // Clear and delete the modules directory. Actual modules will
1526 // still be there only if imported during the execution of some
1527 // destructor.
1528 Py_SETREF(interp->modules, NULL);
1529
1530 // Collect garbage once more
1531 _PyGC_CollectNoFail(tstate);
1532}
1533
1534
Nick Coghland6009512014-11-20 21:39:37 +10001535/* Flush stdout and stderr */
1536
1537static int
1538file_is_closed(PyObject *fobj)
1539{
1540 int r;
1541 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1542 if (tmp == NULL) {
1543 PyErr_Clear();
1544 return 0;
1545 }
1546 r = PyObject_IsTrue(tmp);
1547 Py_DECREF(tmp);
1548 if (r < 0)
1549 PyErr_Clear();
1550 return r > 0;
1551}
1552
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001553
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001554static int
Nick Coghland6009512014-11-20 21:39:37 +10001555flush_std_files(void)
1556{
1557 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1558 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1559 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001560 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001561
1562 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001563 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001564 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001565 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001566 status = -1;
1567 }
Nick Coghland6009512014-11-20 21:39:37 +10001568 else
1569 Py_DECREF(tmp);
1570 }
1571
1572 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001573 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001574 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001575 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001576 status = -1;
1577 }
Nick Coghland6009512014-11-20 21:39:37 +10001578 else
1579 Py_DECREF(tmp);
1580 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001581
1582 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001583}
1584
1585/* Undo the effect of Py_Initialize().
1586
1587 Beware: if multiple interpreter and/or thread states exist, these
1588 are not wiped out; only the current thread and interpreter state
1589 are deleted. But since everything else is deleted, those other
1590 interpreter and thread states should no longer be used.
1591
1592 (XXX We should do better, e.g. wipe out all interpreters and
1593 threads.)
1594
1595 Locking: as above.
1596
1597*/
1598
Victor Stinner7eee5be2019-11-20 10:38:34 +01001599
1600static void
Victor Stinner90db4652020-07-01 23:21:36 +02001601finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001602{
Victor Stinner281cce12020-06-23 22:55:46 +02001603 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001604 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001605 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001606 _PyContext_Fini(tstate);
Victor Stinner666ecfb2020-07-02 01:19:57 +02001607 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001608
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001609 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001610 _PyList_Fini(tstate);
1611 _PyTuple_Fini(tstate);
1612
1613 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001614
Victor Stinnerc41eed12020-06-23 15:54:35 +02001615 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001616 _PyUnicode_Fini(tstate);
1617 _PyFloat_Fini(tstate);
1618 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001619}
1620
1621
1622static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001623finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001624{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001625 int is_main_interp = _Py_IsMainInterpreter(tstate);
1626
Victor Stinner7eee5be2019-11-20 10:38:34 +01001627 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001628 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001629
Kongedaa0fe02020-07-04 05:06:46 +08001630 /* Clear all loghooks */
1631 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1632 Call _PySys_ClearAuditHooks when PyObject available. */
1633 if (is_main_interp) {
1634 _PySys_ClearAuditHooks(tstate);
1635 }
1636
Victor Stinner7907f8c2020-06-08 01:22:36 +02001637 if (is_main_interp) {
1638 _Py_HashRandomization_Fini();
1639 _PyArg_Fini();
1640 _Py_ClearFileSystemEncoding();
1641 }
1642
Victor Stinner90db4652020-07-01 23:21:36 +02001643 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001644}
1645
1646
1647static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001648finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001649{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001650 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001651 /* Cleanup auto-thread-state */
1652 _PyGILState_Fini(tstate);
1653 }
1654
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001655 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1656 fail when it is being awaited by another running daemon thread (see
1657 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1658 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1659 called multiple times. */
1660
Victor Stinner7eee5be2019-11-20 10:38:34 +01001661 PyInterpreterState_Delete(tstate->interp);
1662}
1663
1664
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001665int
1666Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001667{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001668 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001669
Victor Stinner8e91c242019-04-24 17:24:01 +02001670 _PyRuntimeState *runtime = &_PyRuntime;
1671 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001672 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001673 }
Nick Coghland6009512014-11-20 21:39:37 +10001674
Victor Stinnere225beb2019-06-03 18:14:24 +02001675 /* Get current thread state and interpreter pointer */
1676 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1677 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001678
Victor Stinnerb45d2592019-06-20 00:05:23 +02001679 // Wrap up existing "threading"-module-created, non-daemon threads.
1680 wait_for_thread_shutdown(tstate);
1681
1682 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001683 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001684
Nick Coghland6009512014-11-20 21:39:37 +10001685 /* The interpreter is still entirely intact at this point, and the
1686 * exit funcs may be relying on that. In particular, if some thread
1687 * or exit func is still waiting to do an import, the import machinery
1688 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001689 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001690 * Note that Threading.py uses an exit func to do a join on all the
1691 * threads created thru it, so this also protects pending imports in
1692 * the threads created via Threading.
1693 */
Nick Coghland6009512014-11-20 21:39:37 +10001694
Victor Stinnerb45d2592019-06-20 00:05:23 +02001695 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001696
Victor Stinnerda273412017-12-15 01:46:02 +01001697 /* Copy the core config, PyInterpreterState_Delete() free
1698 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001699#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001700 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001701#endif
1702#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001703 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001704#endif
1705#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001706 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001707#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001708
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001709 /* Remaining daemon threads will automatically exit
1710 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001711 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001712 runtime->initialized = 0;
1713 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001714
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001715 /* Destroy the state of all threads of the interpreter, except of the
1716 current thread. In practice, only daemon threads should still be alive,
1717 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1718 Clear frames of other threads to call objects destructors. Destructors
1719 will be called in the current Python thread. Since
1720 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1721 can take the GIL at this point: if they try, they will exit
1722 immediately. */
1723 _PyThreadState_DeleteExcept(runtime, tstate);
1724
Victor Stinnere0deff32015-03-24 13:46:18 +01001725 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001726 if (flush_std_files() < 0) {
1727 status = -1;
1728 }
Nick Coghland6009512014-11-20 21:39:37 +10001729
1730 /* Disable signal handling */
1731 PyOS_FiniInterrupts();
1732
1733 /* Collect garbage. This may call finalizers; it's nice to call these
1734 * before all modules are destroyed.
1735 * XXX If a __del__ or weakref callback is triggered here, and tries to
1736 * XXX import a module, bad things can happen, because Python no
1737 * XXX longer believes it's initialized.
1738 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1739 * XXX is easy to provoke that way. I've also seen, e.g.,
1740 * XXX Exception exceptions.ImportError: 'No module named sha'
1741 * XXX in <function callback at 0x008F5718> ignored
1742 * XXX but I'm unclear on exactly how that one happens. In any case,
1743 * XXX I haven't seen a real-life report of either of these.
1744 */
Victor Stinner8b341482020-10-30 17:00:00 +01001745 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001746
Nick Coghland6009512014-11-20 21:39:37 +10001747 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001748 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001749
Inada Naoki91234a12019-06-03 21:30:58 +09001750 /* Print debug stats if any */
1751 _PyEval_Fini();
1752
Victor Stinnere0deff32015-03-24 13:46:18 +01001753 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001754 if (flush_std_files() < 0) {
1755 status = -1;
1756 }
Nick Coghland6009512014-11-20 21:39:37 +10001757
1758 /* Collect final garbage. This disposes of cycles created by
1759 * class definitions, for example.
1760 * XXX This is disabled because it caused too many problems. If
1761 * XXX a __del__ or weakref callback triggers here, Python code has
1762 * XXX a hard time running, because even the sys module has been
1763 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1764 * XXX One symptom is a sequence of information-free messages
1765 * XXX coming from threads (if a __del__ or callback is invoked,
1766 * XXX other threads can execute too, and any exception they encounter
1767 * XXX triggers a comedy of errors as subsystem after subsystem
1768 * XXX fails to find what it *expects* to find in sys to help report
1769 * XXX the exception and consequent unexpected failures). I've also
1770 * XXX seen segfaults then, after adding print statements to the
1771 * XXX Python code getting called.
1772 */
1773#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001774 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001775#endif
1776
1777 /* Disable tracemalloc after all Python objects have been destroyed,
1778 so it is possible to use tracemalloc in objects destructor. */
1779 _PyTraceMalloc_Fini();
1780
1781 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1782 _PyImport_Fini();
1783
1784 /* Cleanup typeobject.c's internal caches. */
1785 _PyType_Fini();
1786
1787 /* unload faulthandler module */
1788 _PyFaulthandler_Fini();
1789
Nick Coghland6009512014-11-20 21:39:37 +10001790 /* dump hash stats */
1791 _PyHash_Fini();
1792
Eric Snowdae02762017-09-14 00:35:58 -07001793#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001794 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001795 _PyDebug_PrintTotalRefs();
1796 }
Eric Snowdae02762017-09-14 00:35:58 -07001797#endif
Nick Coghland6009512014-11-20 21:39:37 +10001798
1799#ifdef Py_TRACE_REFS
1800 /* Display all objects still alive -- this can invoke arbitrary
1801 * __repr__ overrides, so requires a mostly-intact interpreter.
1802 * Alas, a lot of stuff may still be alive now that will be cleaned
1803 * up later.
1804 */
Victor Stinnerda273412017-12-15 01:46:02 +01001805 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001806 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001807 }
Nick Coghland6009512014-11-20 21:39:37 +10001808#endif /* Py_TRACE_REFS */
1809
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001810 finalize_interp_clear(tstate);
1811 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001812
1813#ifdef Py_TRACE_REFS
1814 /* Display addresses (& refcnts) of all objects still alive.
1815 * An address can be used to find the repr of the object, printed
1816 * above by _Py_PrintReferences.
1817 */
Victor Stinnerda273412017-12-15 01:46:02 +01001818 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001819 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001820 }
Nick Coghland6009512014-11-20 21:39:37 +10001821#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001822#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001823 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001824 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001825 }
Nick Coghland6009512014-11-20 21:39:37 +10001826#endif
1827
Victor Stinner8e91c242019-04-24 17:24:01 +02001828 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001829
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001830 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001831 return status;
1832}
1833
1834void
1835Py_Finalize(void)
1836{
1837 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001838}
1839
Victor Stinnerb0051362019-11-22 17:52:42 +01001840
Nick Coghland6009512014-11-20 21:39:37 +10001841/* Create and initialize a new interpreter and thread, and return the
1842 new thread. This requires that Py_Initialize() has been called
1843 first.
1844
1845 Unsuccessful initialization yields a NULL pointer. Note that *no*
1846 exception information is available even in this case -- the
1847 exception information is held in the thread, and there is no
1848 thread.
1849
1850 Locking: as above.
1851
1852*/
1853
Victor Stinner331a6a52019-05-27 16:39:22 +02001854static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001855new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001856{
Victor Stinner331a6a52019-05-27 16:39:22 +02001857 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001858
Victor Stinner331a6a52019-05-27 16:39:22 +02001859 status = _PyRuntime_Initialize();
1860 if (_PyStatus_EXCEPTION(status)) {
1861 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001862 }
1863 _PyRuntimeState *runtime = &_PyRuntime;
1864
1865 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001866 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001867 }
Nick Coghland6009512014-11-20 21:39:37 +10001868
Victor Stinner8a1be612016-03-14 22:07:55 +01001869 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1870 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001871 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001872
Victor Stinner43125222019-04-24 18:23:53 +02001873 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001874 if (interp == NULL) {
1875 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001876 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001877 }
Nick Coghland6009512014-11-20 21:39:37 +10001878
Victor Stinner43125222019-04-24 18:23:53 +02001879 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001880 if (tstate == NULL) {
1881 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001882 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001883 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001884 }
1885
Victor Stinner43125222019-04-24 18:23:53 +02001886 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001887
Eric Snow1abcf672017-05-23 21:46:51 -07001888 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001889 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001890#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001891 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001892 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001893 }
1894 else
1895#endif
1896 {
Eric Snow1abcf672017-05-23 21:46:51 -07001897 /* No current thread state, copy from the main interpreter */
1898 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001899 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001900 }
1901
Victor Stinner048a3562020-11-05 00:45:56 +01001902
1903 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001904 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001905 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001906 }
Victor Stinner252346a2020-05-01 11:33:44 +02001907 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001908
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001909 status = init_interp_create_gil(tstate);
1910 if (_PyStatus_EXCEPTION(status)) {
1911 goto error;
1912 }
1913
Victor Stinnerd863ade2019-12-06 03:37:07 +01001914 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001915 if (_PyStatus_EXCEPTION(status)) {
1916 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001917 }
1918
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001919 status = init_interp_main(tstate);
1920 if (_PyStatus_EXCEPTION(status)) {
1921 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001922 }
Nick Coghland6009512014-11-20 21:39:37 +10001923
Victor Stinnera7368ac2017-11-15 18:11:45 -08001924 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001925 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001926
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001927error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001928 *tstate_p = NULL;
1929
1930 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001931 PyErr_PrintEx(0);
1932 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001933 PyThreadState_Delete(tstate);
1934 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001935 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001936
Victor Stinnerb0051362019-11-22 17:52:42 +01001937 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001938}
1939
1940PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001941_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001942{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001943 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001944 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001945 if (_PyStatus_EXCEPTION(status)) {
1946 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001947 }
1948 return tstate;
1949
Nick Coghland6009512014-11-20 21:39:37 +10001950}
1951
Victor Stinner252346a2020-05-01 11:33:44 +02001952PyThreadState *
1953Py_NewInterpreter(void)
1954{
1955 return _Py_NewInterpreter(0);
1956}
1957
Nick Coghland6009512014-11-20 21:39:37 +10001958/* Delete an interpreter and its last thread. This requires that the
1959 given thread state is current, that the thread has no remaining
1960 frames, and that it is its interpreter's only remaining thread.
1961 It is a fatal error to violate these constraints.
1962
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001963 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001964 everything, regardless.)
1965
1966 Locking: as above.
1967
1968*/
1969
1970void
1971Py_EndInterpreter(PyThreadState *tstate)
1972{
1973 PyInterpreterState *interp = tstate->interp;
1974
Victor Stinnerb45d2592019-06-20 00:05:23 +02001975 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001976 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001977 }
1978 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001979 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001980 }
Eric Snow5be45a62019-03-08 22:47:07 -07001981 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001982
Eric Snow842a2f02019-03-15 15:47:51 -06001983 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001984 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001985
Victor Stinnerb45d2592019-06-20 00:05:23 +02001986 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001987
Victor Stinnerb45d2592019-06-20 00:05:23 +02001988 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001989 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001990 }
Nick Coghland6009512014-11-20 21:39:37 +10001991
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001992 finalize_modules(tstate);
1993
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001994 finalize_interp_clear(tstate);
1995 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001996}
1997
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001998/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001999
Victor Stinner331a6a52019-05-27 16:39:22 +02002000static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002001add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10002002{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002003 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10002004 m = PyImport_AddModule("__main__");
2005 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02002006 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002007
Nick Coghland6009512014-11-20 21:39:37 +10002008 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002009 ann_dict = PyDict_New();
2010 if ((ann_dict == NULL) ||
2011 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002012 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002013 }
2014 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002015
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002016 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
2017 if (PyErr_Occurred()) {
2018 return _PyStatus_ERR("Failed to test __main__.__builtins__");
2019 }
Nick Coghland6009512014-11-20 21:39:37 +10002020 PyObject *bimod = PyImport_ImportModule("builtins");
2021 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002022 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10002023 }
2024 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002025 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002026 }
2027 Py_DECREF(bimod);
2028 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002029
Nick Coghland6009512014-11-20 21:39:37 +10002030 /* Main is a little special - imp.is_builtin("__main__") will return
2031 * False, but BuiltinImporter is still the most appropriate initial
2032 * setting for its __loader__ attribute. A more suitable value will
2033 * be set if __main__ gets further initialized later in the startup
2034 * process.
2035 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002036 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002037 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002038 if (PyErr_Occurred()) {
2039 return _PyStatus_ERR("Failed to test __main__.__loader__");
2040 }
Nick Coghland6009512014-11-20 21:39:37 +10002041 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2042 "BuiltinImporter");
2043 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002044 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002045 }
2046 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002047 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002048 }
2049 Py_DECREF(loader);
2050 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002051 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002052}
2053
Nick Coghland6009512014-11-20 21:39:37 +10002054/* Import the site module (not into __main__ though) */
2055
Victor Stinner331a6a52019-05-27 16:39:22 +02002056static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002057init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002058{
2059 PyObject *m;
2060 m = PyImport_ImportModule("site");
2061 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002062 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002063 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002064 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002065 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002066}
2067
Victor Stinner874dbe82015-09-04 17:29:57 +02002068/* Check if a file descriptor is valid or not.
2069 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2070static int
2071is_valid_fd(int fd)
2072{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002073/* dup() is faster than fstat(): fstat() can require input/output operations,
2074 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2075 startup. Problem: dup() doesn't check if the file descriptor is valid on
2076 some platforms.
2077
2078 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2079 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2080 EBADF. FreeBSD has similar issue (bpo-32849).
2081
2082 Only use dup() on platforms where dup() is enough to detect invalid FD in
2083 corner cases: on Linux and Windows (bpo-32849). */
2084#if defined(__linux__) || defined(MS_WINDOWS)
2085 if (fd < 0) {
2086 return 0;
2087 }
2088 int fd2;
2089
2090 _Py_BEGIN_SUPPRESS_IPH
2091 fd2 = dup(fd);
2092 if (fd2 >= 0) {
2093 close(fd2);
2094 }
2095 _Py_END_SUPPRESS_IPH
2096
2097 return (fd2 >= 0);
2098#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002099 struct stat st;
2100 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002101#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002102}
2103
2104/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002105static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002106create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002107 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002108 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002109{
2110 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2111 const char* mode;
2112 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002113 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002114 int buffering, isatty;
2115 _Py_IDENTIFIER(open);
2116 _Py_IDENTIFIER(isatty);
2117 _Py_IDENTIFIER(TextIOWrapper);
2118 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002119 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002120
Victor Stinner874dbe82015-09-04 17:29:57 +02002121 if (!is_valid_fd(fd))
2122 Py_RETURN_NONE;
2123
Nick Coghland6009512014-11-20 21:39:37 +10002124 /* stdin is always opened in buffered mode, first because it shouldn't
2125 make a difference in common use cases, second because TextIOWrapper
2126 depends on the presence of a read1() method which only exists on
2127 buffered streams.
2128 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002129 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002130 buffering = 0;
2131 else
2132 buffering = -1;
2133 if (write_mode)
2134 mode = "wb";
2135 else
2136 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002137 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002138 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002139 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002140 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002141 if (buf == NULL)
2142 goto error;
2143
2144 if (buffering) {
2145 _Py_IDENTIFIER(raw);
2146 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2147 if (raw == NULL)
2148 goto error;
2149 }
2150 else {
2151 raw = buf;
2152 Py_INCREF(raw);
2153 }
2154
Steve Dower39294992016-08-30 21:22:36 -07002155#ifdef MS_WINDOWS
2156 /* Windows console IO is always UTF-8 encoded */
2157 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002158 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002159#endif
2160
Nick Coghland6009512014-11-20 21:39:37 +10002161 text = PyUnicode_FromString(name);
2162 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2163 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002164 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002165 if (res == NULL)
2166 goto error;
2167 isatty = PyObject_IsTrue(res);
2168 Py_DECREF(res);
2169 if (isatty == -1)
2170 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002171 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002172 write_through = Py_True;
2173 else
2174 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002175 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002176 line_buffering = Py_True;
2177 else
2178 line_buffering = Py_False;
2179
2180 Py_CLEAR(raw);
2181 Py_CLEAR(text);
2182
2183#ifdef MS_WINDOWS
2184 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2185 newlines to "\n".
2186 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2187 newline = NULL;
2188#else
2189 /* sys.stdin: split lines at "\n".
2190 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2191 newline = "\n";
2192#endif
2193
Victor Stinner709d23d2019-05-02 14:56:30 -04002194 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2195 if (encoding_str == NULL) {
2196 Py_CLEAR(buf);
2197 goto error;
2198 }
2199
2200 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2201 if (errors_str == NULL) {
2202 Py_CLEAR(buf);
2203 Py_CLEAR(encoding_str);
2204 goto error;
2205 }
2206
2207 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2208 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002209 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002210 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002211 Py_CLEAR(encoding_str);
2212 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002213 if (stream == NULL)
2214 goto error;
2215
2216 if (write_mode)
2217 mode = "w";
2218 else
2219 mode = "r";
2220 text = PyUnicode_FromString(mode);
2221 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2222 goto error;
2223 Py_CLEAR(text);
2224 return stream;
2225
2226error:
2227 Py_XDECREF(buf);
2228 Py_XDECREF(stream);
2229 Py_XDECREF(text);
2230 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002231
Victor Stinner874dbe82015-09-04 17:29:57 +02002232 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2233 /* Issue #24891: the file descriptor was closed after the first
2234 is_valid_fd() check was called. Ignore the OSError and set the
2235 stream to None. */
2236 PyErr_Clear();
2237 Py_RETURN_NONE;
2238 }
2239 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002240}
2241
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002242/* Set builtins.open to io.OpenWrapper */
2243static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002244init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002245{
2246 PyObject *iomod = NULL, *wrapper;
2247 PyObject *bimod = NULL;
2248 PyStatus res = _PyStatus_OK();
2249
2250 if (!(iomod = PyImport_ImportModule("io"))) {
2251 goto error;
2252 }
2253
2254 if (!(bimod = PyImport_ImportModule("builtins"))) {
2255 goto error;
2256 }
2257
2258 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2259 goto error;
2260 }
2261
2262 /* Set builtins.open */
2263 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2264 Py_DECREF(wrapper);
2265 goto error;
2266 }
2267 Py_DECREF(wrapper);
2268 goto done;
2269
2270error:
2271 res = _PyStatus_ERR("can't initialize io.open");
2272
2273done:
2274 Py_XDECREF(bimod);
2275 Py_XDECREF(iomod);
2276 return res;
2277}
2278
2279
Nick Coghland6009512014-11-20 21:39:37 +10002280/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002281static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002282init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002283{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002284 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002285 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002286 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002287 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002288 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002289 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002290
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002291 /* Check that stdin is not a directory
2292 Using shell redirection, you can redirect stdin to a directory,
2293 crashing the Python interpreter. Catch this common mistake here
2294 and output a useful error message. Note that under MS Windows,
2295 the shell already prevents that. */
2296#ifndef MS_WINDOWS
2297 struct _Py_stat_struct sb;
2298 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2299 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002300 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002301 }
2302#endif
2303
Nick Coghland6009512014-11-20 21:39:37 +10002304 if (!(iomod = PyImport_ImportModule("io"))) {
2305 goto error;
2306 }
Nick Coghland6009512014-11-20 21:39:37 +10002307
Nick Coghland6009512014-11-20 21:39:37 +10002308 /* Set sys.stdin */
2309 fd = fileno(stdin);
2310 /* Under some conditions stdin, stdout and stderr may not be connected
2311 * and fileno() may point to an invalid file descriptor. For example
2312 * GUI apps don't have valid standard streams by default.
2313 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002314 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002315 config->stdio_encoding,
2316 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002317 if (std == NULL)
2318 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002319 PySys_SetObject("__stdin__", std);
2320 _PySys_SetObjectId(&PyId_stdin, std);
2321 Py_DECREF(std);
2322
2323 /* Set sys.stdout */
2324 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002325 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002326 config->stdio_encoding,
2327 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002328 if (std == NULL)
2329 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002330 PySys_SetObject("__stdout__", std);
2331 _PySys_SetObjectId(&PyId_stdout, std);
2332 Py_DECREF(std);
2333
2334#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2335 /* Set sys.stderr, replaces the preliminary stderr */
2336 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002337 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002338 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002339 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002340 if (std == NULL)
2341 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002342
2343 /* Same as hack above, pre-import stderr's codec to avoid recursion
2344 when import.c tries to write to stderr in verbose mode. */
2345 encoding_attr = PyObject_GetAttrString(std, "encoding");
2346 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002347 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002348 if (std_encoding != NULL) {
2349 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2350 Py_XDECREF(codec_info);
2351 }
2352 Py_DECREF(encoding_attr);
2353 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002354 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002355
2356 if (PySys_SetObject("__stderr__", std) < 0) {
2357 Py_DECREF(std);
2358 goto error;
2359 }
2360 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2361 Py_DECREF(std);
2362 goto error;
2363 }
2364 Py_DECREF(std);
2365#endif
2366
Victor Stinnera7368ac2017-11-15 18:11:45 -08002367 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002368
Victor Stinnera7368ac2017-11-15 18:11:45 -08002369error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002370 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002371
2372done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002373 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002374 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002375 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002376}
2377
2378
Victor Stinner10dc4842015-03-24 12:01:30 +01002379static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002380_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2381 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002382{
Victor Stinner10dc4842015-03-24 12:01:30 +01002383 fputc('\n', stderr);
2384 fflush(stderr);
2385
2386 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002387 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002388}
Victor Stinner791da1c2016-03-14 16:53:12 +01002389
2390/* Print the current exception (if an exception is set) with its traceback,
2391 or display the current Python stack.
2392
2393 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2394 called on catastrophic cases.
2395
2396 Return 1 if the traceback was displayed, 0 otherwise. */
2397
2398static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002399_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002400{
2401 PyObject *ferr, *res;
2402 PyObject *exception, *v, *tb;
2403 int has_tb;
2404
Victor Stinnerb45d2592019-06-20 00:05:23 +02002405 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002406 if (exception == NULL) {
2407 /* No current exception */
2408 return 0;
2409 }
2410
2411 ferr = _PySys_GetObjectId(&PyId_stderr);
2412 if (ferr == NULL || ferr == Py_None) {
2413 /* sys.stderr is not set yet or set to None,
2414 no need to try to display the exception */
2415 return 0;
2416 }
2417
Victor Stinnerb45d2592019-06-20 00:05:23 +02002418 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002419 if (tb == NULL) {
2420 tb = Py_None;
2421 Py_INCREF(tb);
2422 }
2423 PyException_SetTraceback(v, tb);
2424 if (exception == NULL) {
2425 /* PyErr_NormalizeException() failed */
2426 return 0;
2427 }
2428
2429 has_tb = (tb != Py_None);
2430 PyErr_Display(exception, v, tb);
2431 Py_XDECREF(exception);
2432 Py_XDECREF(v);
2433 Py_XDECREF(tb);
2434
2435 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002436 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002437 if (res == NULL) {
2438 _PyErr_Clear(tstate);
2439 }
2440 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002441 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002442 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002443
2444 return has_tb;
2445}
2446
Nick Coghland6009512014-11-20 21:39:37 +10002447/* Print fatal error message and abort */
2448
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002449#ifdef MS_WINDOWS
2450static void
2451fatal_output_debug(const char *msg)
2452{
2453 /* buffer of 256 bytes allocated on the stack */
2454 WCHAR buffer[256 / sizeof(WCHAR)];
2455 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2456 size_t msglen;
2457
2458 OutputDebugStringW(L"Fatal Python error: ");
2459
2460 msglen = strlen(msg);
2461 while (msglen) {
2462 size_t i;
2463
2464 if (buflen > msglen) {
2465 buflen = msglen;
2466 }
2467
2468 /* Convert the message to wchar_t. This uses a simple one-to-one
2469 conversion, assuming that the this error message actually uses
2470 ASCII only. If this ceases to be true, we will have to convert. */
2471 for (i=0; i < buflen; ++i) {
2472 buffer[i] = msg[i];
2473 }
2474 buffer[i] = L'\0';
2475 OutputDebugStringW(buffer);
2476
2477 msg += buflen;
2478 msglen -= buflen;
2479 }
2480 OutputDebugStringW(L"\n");
2481}
2482#endif
2483
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002484
2485static void
2486fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2487{
2488 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002489 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2490 if (finalizing) {
2491 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002492 }
2493 else if (runtime->initialized) {
2494 fprintf(stream, "initialized");
2495 }
2496 else if (runtime->core_initialized) {
2497 fprintf(stream, "core initialized");
2498 }
2499 else if (runtime->preinitialized) {
2500 fprintf(stream, "preinitialized");
2501 }
2502 else if (runtime->preinitializing) {
2503 fprintf(stream, "preinitializing");
2504 }
2505 else {
2506 fprintf(stream, "unknown");
2507 }
2508 fprintf(stream, "\n");
2509 fflush(stream);
2510}
2511
2512
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002513static inline void _Py_NO_RETURN
2514fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002515{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002516 if (status < 0) {
2517#if defined(MS_WINDOWS) && defined(_DEBUG)
2518 DebugBreak();
2519#endif
2520 abort();
2521 }
2522 else {
2523 exit(status);
2524 }
2525}
2526
2527
2528static void _Py_NO_RETURN
2529fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2530 int status)
2531{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002532 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002533 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002534
2535 if (reentrant) {
2536 /* Py_FatalError() caused a second fatal error.
2537 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002538 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002539 }
2540 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002541
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002542 if (header) {
2543 fprintf(stream, "Fatal Python error: ");
2544 if (prefix) {
2545 fputs(prefix, stream);
2546 fputs(": ", stream);
2547 }
2548 if (msg) {
2549 fputs(msg, stream);
2550 }
2551 else {
2552 fprintf(stream, "<message not set>");
2553 }
2554 fputs("\n", stream);
2555 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002556 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002557
2558 _PyRuntimeState *runtime = &_PyRuntime;
2559 fatal_error_dump_runtime(stream, runtime);
2560
2561 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2562 PyInterpreterState *interp = NULL;
2563 if (tstate != NULL) {
2564 interp = tstate->interp;
2565 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002566
Victor Stinner3a228ab2018-11-01 00:26:41 +01002567 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002568 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002569
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002570 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2571 has no Python thread state.
2572
2573 tss_tstate != tstate if the current Python thread does not hold the GIL.
2574 */
2575 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2576 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002577 if (has_tstate_and_gil) {
2578 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002579 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002580 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002581 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002582 }
2583 }
2584 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002585 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002586 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002587
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002588 /* The main purpose of faulthandler is to display the traceback.
2589 This function already did its best to display a traceback.
2590 Disable faulthandler to prevent writing a second traceback
2591 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002592 _PyFaulthandler_Fini();
2593
Victor Stinner791da1c2016-03-14 16:53:12 +01002594 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002595 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002596 /* Flush sys.stdout and sys.stderr */
2597 flush_std_files();
2598 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002599
Nick Coghland6009512014-11-20 21:39:37 +10002600#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002601 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002602#endif /* MS_WINDOWS */
2603
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002604 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002605}
2606
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002607
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002608#undef Py_FatalError
2609
Victor Stinner19760862017-12-20 01:41:59 +01002610void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002611Py_FatalError(const char *msg)
2612{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002613 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002614}
2615
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002616
Victor Stinner19760862017-12-20 01:41:59 +01002617void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002618_Py_FatalErrorFunc(const char *func, const char *msg)
2619{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002620 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002621}
2622
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002623
2624void _Py_NO_RETURN
2625_Py_FatalErrorFormat(const char *func, const char *format, ...)
2626{
2627 static int reentrant = 0;
2628 if (reentrant) {
2629 /* _Py_FatalErrorFormat() caused a second fatal error */
2630 fatal_error_exit(-1);
2631 }
2632 reentrant = 1;
2633
2634 FILE *stream = stderr;
2635 fprintf(stream, "Fatal Python error: ");
2636 if (func) {
2637 fputs(func, stream);
2638 fputs(": ", stream);
2639 }
2640 fflush(stream);
2641
2642 va_list vargs;
2643#ifdef HAVE_STDARG_PROTOTYPES
2644 va_start(vargs, format);
2645#else
2646 va_start(vargs);
2647#endif
2648 vfprintf(stream, format, vargs);
2649 va_end(vargs);
2650
2651 fputs("\n", stream);
2652 fflush(stream);
2653
2654 fatal_error(stream, 0, NULL, NULL, -1);
2655}
2656
2657
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002658void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002659Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002660{
Victor Stinner331a6a52019-05-27 16:39:22 +02002661 if (_PyStatus_IS_EXIT(status)) {
2662 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002663 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002664 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002665 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002666 }
2667 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002668 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002669 }
Nick Coghland6009512014-11-20 21:39:37 +10002670}
2671
2672/* Clean up and exit */
2673
Nick Coghland6009512014-11-20 21:39:37 +10002674/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002675void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002676{
Victor Stinner81a7be32020-04-14 15:14:01 +02002677 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002678
Antoine Pitroufc5db952017-12-13 02:29:07 +01002679 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002680 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2681
2682 is->pyexitfunc = func;
2683 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002684}
2685
2686static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002687call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002688{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002689 PyInterpreterState *interp = tstate->interp;
2690 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002691 return;
2692
Victor Stinnerb45d2592019-06-20 00:05:23 +02002693 (*interp->pyexitfunc)(interp->pyexitmodule);
2694 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002695}
2696
2697/* Wait until threading._shutdown completes, provided
2698 the threading module was imported in the first place.
2699 The shutdown routine will wait until all non-daemon
2700 "threading" threads have completed. */
2701static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002702wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002703{
Nick Coghland6009512014-11-20 21:39:37 +10002704 _Py_IDENTIFIER(_shutdown);
2705 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002706 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002707 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002708 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002709 PyErr_WriteUnraisable(NULL);
2710 }
2711 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002712 return;
2713 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002714 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002715 if (result == NULL) {
2716 PyErr_WriteUnraisable(threading);
2717 }
2718 else {
2719 Py_DECREF(result);
2720 }
2721 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002722}
2723
2724#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002725int Py_AtExit(void (*func)(void))
2726{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002727 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002728 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002729 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002730 return 0;
2731}
2732
2733static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002734call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002735{
Victor Stinner8e91c242019-04-24 17:24:01 +02002736 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002737 /* pop last function from the list */
2738 runtime->nexitfuncs--;
2739 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2740 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2741
2742 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002743 }
Nick Coghland6009512014-11-20 21:39:37 +10002744
2745 fflush(stdout);
2746 fflush(stderr);
2747}
2748
Victor Stinnercfc88312018-08-01 16:41:25 +02002749void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002750Py_Exit(int sts)
2751{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002752 if (Py_FinalizeEx() < 0) {
2753 sts = 120;
2754 }
Nick Coghland6009512014-11-20 21:39:37 +10002755
2756 exit(sts);
2757}
2758
Victor Stinner331a6a52019-05-27 16:39:22 +02002759static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002760init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002761{
2762#ifdef SIGPIPE
2763 PyOS_setsig(SIGPIPE, SIG_IGN);
2764#endif
2765#ifdef SIGXFZ
2766 PyOS_setsig(SIGXFZ, SIG_IGN);
2767#endif
2768#ifdef SIGXFSZ
2769 PyOS_setsig(SIGXFSZ, SIG_IGN);
2770#endif
Victor Stinner400e1db2020-03-31 19:13:10 +02002771 PyOS_InitInterrupts(); /* May imply init_signals() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002772 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002773 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002774 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002775 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002776}
2777
2778
2779/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2780 *
2781 * All of the code in this function must only use async-signal-safe functions,
2782 * listed at `man 7 signal` or
2783 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002784 *
2785 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002786 */
2787void
2788_Py_RestoreSignals(void)
2789{
2790#ifdef SIGPIPE
2791 PyOS_setsig(SIGPIPE, SIG_DFL);
2792#endif
2793#ifdef SIGXFZ
2794 PyOS_setsig(SIGXFZ, SIG_DFL);
2795#endif
2796#ifdef SIGXFSZ
2797 PyOS_setsig(SIGXFSZ, SIG_DFL);
2798#endif
2799}
2800
2801
2802/*
2803 * The file descriptor fd is considered ``interactive'' if either
2804 * a) isatty(fd) is TRUE, or
2805 * b) the -i flag was given, and the filename associated with
2806 * the descriptor is NULL or "<stdin>" or "???".
2807 */
2808int
2809Py_FdIsInteractive(FILE *fp, const char *filename)
2810{
2811 if (isatty((int)fileno(fp)))
2812 return 1;
2813 if (!Py_InteractiveFlag)
2814 return 0;
2815 return (filename == NULL) ||
2816 (strcmp(filename, "<stdin>") == 0) ||
2817 (strcmp(filename, "???") == 0);
2818}
2819
2820
Nick Coghland6009512014-11-20 21:39:37 +10002821/* Wrappers around sigaction() or signal(). */
2822
2823PyOS_sighandler_t
2824PyOS_getsig(int sig)
2825{
2826#ifdef HAVE_SIGACTION
2827 struct sigaction context;
2828 if (sigaction(sig, NULL, &context) == -1)
2829 return SIG_ERR;
2830 return context.sa_handler;
2831#else
2832 PyOS_sighandler_t handler;
2833/* Special signal handling for the secure CRT in Visual Studio 2005 */
2834#if defined(_MSC_VER) && _MSC_VER >= 1400
2835 switch (sig) {
2836 /* Only these signals are valid */
2837 case SIGINT:
2838 case SIGILL:
2839 case SIGFPE:
2840 case SIGSEGV:
2841 case SIGTERM:
2842 case SIGBREAK:
2843 case SIGABRT:
2844 break;
2845 /* Don't call signal() with other values or it will assert */
2846 default:
2847 return SIG_ERR;
2848 }
2849#endif /* _MSC_VER && _MSC_VER >= 1400 */
2850 handler = signal(sig, SIG_IGN);
2851 if (handler != SIG_ERR)
2852 signal(sig, handler);
2853 return handler;
2854#endif
2855}
2856
2857/*
2858 * All of the code in this function must only use async-signal-safe functions,
2859 * listed at `man 7 signal` or
2860 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2861 */
2862PyOS_sighandler_t
2863PyOS_setsig(int sig, PyOS_sighandler_t handler)
2864{
2865#ifdef HAVE_SIGACTION
2866 /* Some code in Modules/signalmodule.c depends on sigaction() being
2867 * used here if HAVE_SIGACTION is defined. Fix that if this code
2868 * changes to invalidate that assumption.
2869 */
2870 struct sigaction context, ocontext;
2871 context.sa_handler = handler;
2872 sigemptyset(&context.sa_mask);
2873 context.sa_flags = 0;
2874 if (sigaction(sig, &context, &ocontext) == -1)
2875 return SIG_ERR;
2876 return ocontext.sa_handler;
2877#else
2878 PyOS_sighandler_t oldhandler;
2879 oldhandler = signal(sig, handler);
2880#ifdef HAVE_SIGINTERRUPT
2881 siginterrupt(sig, 1);
2882#endif
2883 return oldhandler;
2884#endif
2885}
2886
2887#ifdef __cplusplus
2888}
2889#endif