blob: e34d6471e178e4b8922ecb6c88e138c63c07fdf0 [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
432interpreter_set_config(const PyConfig *config)
433{
434 PyThreadState *tstate = PyThreadState_Get();
435
436 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
437 if (_PyStatus_EXCEPTION(status)) {
438 _PyErr_SetFromPyStatus(status);
439 return -1;
440 }
441
442 status = _PyConfig_Copy(&tstate->interp->config, config);
443 if (_PyStatus_EXCEPTION(status)) {
444 _PyErr_SetFromPyStatus(status);
445 return -1;
446 }
447 config = &tstate->interp->config;
448
449 if (config->_install_importlib && _Py_IsMainInterpreter(tstate)) {
450 status = _PyConfig_WritePathConfig(config);
451 if (_PyStatus_EXCEPTION(status)) {
452 _PyErr_SetFromPyStatus(status);
453 return -1;
454 }
455 }
456
457 // Update the sys module for the new configuration
458 if (_PySys_UpdateConfig(tstate) < 0) {
459 return -1;
460 }
461 return 0;
462}
463
464
465int
466_PyInterpreterState_SetConfig(const PyConfig *src_config)
467{
468 int res = -1;
469
470 PyConfig config;
471 PyConfig_InitPythonConfig(&config);
472 PyStatus status = _PyConfig_Copy(&config, src_config);
473 if (_PyStatus_EXCEPTION(status)) {
474 _PyErr_SetFromPyStatus(status);
475 goto done;
476 }
477
478 status = PyConfig_Read(&config);
479 if (_PyStatus_EXCEPTION(status)) {
480 _PyErr_SetFromPyStatus(status);
481 goto done;
482 }
483
484 res = interpreter_set_config(&config);
485
486done:
487 PyConfig_Clear(&config);
488 return res;
489}
490
491
Eric Snow1abcf672017-05-23 21:46:51 -0700492/* Global initializations. Can be undone by Py_Finalize(). Don't
493 call this twice without an intervening Py_Finalize() call.
494
Victor Stinner331a6a52019-05-27 16:39:22 +0200495 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700496 must have a corresponding call to Py_Finalize.
497
498 Locking: you must hold the interpreter lock while calling these APIs.
499 (If the lock has not yet been initialized, that's equivalent to
500 having the lock, but you cannot use multiple threads.)
501
502*/
503
Victor Stinner331a6a52019-05-27 16:39:22 +0200504static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200505pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200506 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200507 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200508{
Victor Stinner331a6a52019-05-27 16:39:22 +0200509 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100510 PyThreadState *tstate = _PyThreadState_GET();
511 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200512 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100513 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200514 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100515
516 PyInterpreterState *interp = tstate->interp;
517 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200518 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100519 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100520
Victor Stinnere81f6e62020-06-08 18:12:59 +0200521 status = _PyConfig_Write(config, runtime);
522 if (_PyStatus_EXCEPTION(status)) {
523 return status;
524 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200525
Victor Stinner048a3562020-11-05 00:45:56 +0100526 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200527 if (_PyStatus_EXCEPTION(status)) {
528 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200529 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200530 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200531
Victor Stinner331a6a52019-05-27 16:39:22 +0200532 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200533 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200534 if (_PyStatus_EXCEPTION(status)) {
535 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200536 }
537 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200538 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200539}
540
541
Victor Stinner331a6a52019-05-27 16:39:22 +0200542static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200543pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200544 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000545{
Victor Stinner43125222019-04-24 18:23:53 +0200546 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200547 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200548 }
Victor Stinnerda273412017-12-15 01:46:02 +0100549
Victor Stinnere81f6e62020-06-08 18:12:59 +0200550 PyStatus status = _PyConfig_Write(config, runtime);
551 if (_PyStatus_EXCEPTION(status)) {
552 return status;
553 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600554
Eric Snow1abcf672017-05-23 21:46:51 -0700555 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
556 * threads behave a little more gracefully at interpreter shutdown.
557 * We clobber it here so the new interpreter can start with a clean
558 * slate.
559 *
560 * However, this may still lead to misbehaviour if there are daemon
561 * threads still hanging around from a previous Py_Initialize/Finalize
562 * pair :(
563 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100564 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600565
Victor Stinnere81f6e62020-06-08 18:12:59 +0200566 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200567 if (_PyStatus_EXCEPTION(status)) {
568 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800569 }
570
Victor Stinner331a6a52019-05-27 16:39:22 +0200571 status = _PyInterpreterState_Enable(runtime);
572 if (_PyStatus_EXCEPTION(status)) {
573 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800574 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200575 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100576}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800577
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100578
Victor Stinner331a6a52019-05-27 16:39:22 +0200579static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200580init_interp_create_gil(PyThreadState *tstate)
581{
582 PyStatus status;
583
584 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
585 only called here. */
586 _PyEval_FiniGIL(tstate);
587
588 /* Auto-thread-state API */
589 status = _PyGILState_Init(tstate);
590 if (_PyStatus_EXCEPTION(status)) {
591 return status;
592 }
593
594 /* Create the GIL and take it */
595 status = _PyEval_InitGIL(tstate);
596 if (_PyStatus_EXCEPTION(status)) {
597 return status;
598 }
599
600 return _PyStatus_OK();
601}
602
603
604static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200605pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200606 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200607 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100608{
609 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100610 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200611 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100612 }
613
Victor Stinner048a3562020-11-05 00:45:56 +0100614 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 if (_PyStatus_EXCEPTION(status)) {
616 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100617 }
Nick Coghland6009512014-11-20 21:39:37 +1000618
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200619 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200620 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200621 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200622 }
Nick Coghland6009512014-11-20 21:39:37 +1000623 (void) PyThreadState_Swap(tstate);
624
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200625 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100626 if (_PyStatus_EXCEPTION(status)) {
627 return status;
628 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100629
Victor Stinnerb45d2592019-06-20 00:05:23 +0200630 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200631 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100632}
Nick Coghland6009512014-11-20 21:39:37 +1000633
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100634
Victor Stinner331a6a52019-05-27 16:39:22 +0200635static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100636pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100637{
Victor Stinner444b39b2019-11-20 01:18:11 +0100638 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100639 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100640
Victor Stinner01b1cc12019-11-20 02:27:56 +0100641 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100642 if (_PyStatus_EXCEPTION(status)) {
643 return status;
644 }
645
Victor Stinner0430dfa2020-06-24 15:21:54 +0200646 // Create the empty tuple singleton. It must be created before the first
647 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
648 // for example.
649 status = _PyTuple_Init(tstate);
650 if (_PyStatus_EXCEPTION(status)) {
651 return status;
652 }
653
Victor Stinnere7e699e2019-11-20 12:08:13 +0100654 if (is_main_interp) {
655 status = _PyTypes_Init();
656 if (_PyStatus_EXCEPTION(status)) {
657 return status;
658 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100659 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100660
Victor Stinner630c8df2019-12-17 13:02:18 +0100661 if (!_PyLong_Init(tstate)) {
662 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100663 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100664
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200665 status = _PyUnicode_Init(tstate);
666 if (_PyStatus_EXCEPTION(status)) {
667 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100668 }
669
Victor Stinner91698d82020-06-25 14:07:40 +0200670 status = _PyBytes_Init(tstate);
671 if (_PyStatus_EXCEPTION(status)) {
672 return status;
673 }
674
Victor Stinner281cce12020-06-23 22:55:46 +0200675 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200676 if (_PyStatus_EXCEPTION(status)) {
677 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100678 }
679
Victor Stinnere7e699e2019-11-20 12:08:13 +0100680 if (is_main_interp) {
681 if (!_PyFloat_Init()) {
682 return _PyStatus_ERR("can't init float");
683 }
Nick Coghland6009512014-11-20 21:39:37 +1000684
Victor Stinnere7e699e2019-11-20 12:08:13 +0100685 if (_PyStructSequence_Init() < 0) {
686 return _PyStatus_ERR("can't initialize structseq");
687 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100688 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200689
Victor Stinner331a6a52019-05-27 16:39:22 +0200690 status = _PyErr_Init();
691 if (_PyStatus_EXCEPTION(status)) {
692 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200693 }
694
Victor Stinnere7e699e2019-11-20 12:08:13 +0100695 if (is_main_interp) {
696 if (!_PyContext_Init()) {
697 return _PyStatus_ERR("can't init context");
698 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100699 }
700
Victor Stinner331a6a52019-05-27 16:39:22 +0200701 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100702}
703
704
Victor Stinner331a6a52019-05-27 16:39:22 +0200705static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200706pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100707{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100708 assert(!_PyErr_Occurred(tstate));
709
Victor Stinnerb45d2592019-06-20 00:05:23 +0200710 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100712 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100713 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100714
Victor Stinner2582d462019-11-22 19:24:49 +0100715 PyInterpreterState *interp = tstate->interp;
716 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
717 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100718 }
Victor Stinner2582d462019-11-22 19:24:49 +0100719
720 PyObject *builtins_dict = PyModule_GetDict(bimod);
721 if (builtins_dict == NULL) {
722 goto error;
723 }
724 Py_INCREF(builtins_dict);
725 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100726
Victor Stinner331a6a52019-05-27 16:39:22 +0200727 PyStatus status = _PyBuiltins_AddExceptions(bimod);
728 if (_PyStatus_EXCEPTION(status)) {
729 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100730 }
Victor Stinner2582d462019-11-22 19:24:49 +0100731
732 interp->builtins_copy = PyDict_Copy(interp->builtins);
733 if (interp->builtins_copy == NULL) {
734 goto error;
735 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000736 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100737
738 assert(!_PyErr_Occurred(tstate));
739
Victor Stinner331a6a52019-05-27 16:39:22 +0200740 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100741
742error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000743 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100744 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100745}
746
747
Victor Stinner331a6a52019-05-27 16:39:22 +0200748static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200749pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100750{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100751 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200752
Victor Stinner2582d462019-11-22 19:24:49 +0100753 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200754 if (_PyStatus_EXCEPTION(status)) {
755 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800756 }
Nick Coghland6009512014-11-20 21:39:37 +1000757
Victor Stinner30a89332020-06-23 15:55:45 +0200758 /* Initialize _warnings. */
759 status = _PyWarnings_InitState(tstate);
760 if (_PyStatus_EXCEPTION(status)) {
761 return status;
762 }
Nick Coghland6009512014-11-20 21:39:37 +1000763
Victor Stinner30a89332020-06-23 15:55:45 +0200764 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
765 if (config->_install_importlib) {
766 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100767 status = _PyConfig_WritePathConfig(config);
768 if (_PyStatus_EXCEPTION(status)) {
769 return status;
770 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200771 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200772
Victor Stinner30a89332020-06-23 15:55:45 +0200773 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200774 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200775 if (_PyStatus_EXCEPTION(status)) {
776 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800777 }
Eric Snow1abcf672017-05-23 21:46:51 -0700778 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100779
780 assert(!_PyErr_Occurred(tstate));
781
Victor Stinner331a6a52019-05-27 16:39:22 +0200782 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100783}
784
785
Victor Stinner331a6a52019-05-27 16:39:22 +0200786static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100787pycore_interp_init(PyThreadState *tstate)
788{
789 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100790 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100791
792 status = pycore_init_types(tstate);
793 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100794 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100795 }
796
Victor Stinnerd863ade2019-12-06 03:37:07 +0100797 status = _PySys_Create(tstate, &sysmod);
798 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100799 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100800 }
801
802 status = pycore_init_builtins(tstate);
803 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100804 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100805 }
806
Victor Stinner080ee5a2019-12-08 21:55:58 +0100807 status = pycore_init_import_warnings(tstate, sysmod);
808
809done:
810 /* sys.modules['sys'] contains a strong reference to the module */
811 Py_XDECREF(sysmod);
812 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100813}
814
815
816static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200817pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200818 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200819 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100820{
Victor Stinner331a6a52019-05-27 16:39:22 +0200821 PyStatus status = pycore_init_runtime(runtime, config);
822 if (_PyStatus_EXCEPTION(status)) {
823 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100824 }
825
Victor Stinnerb45d2592019-06-20 00:05:23 +0200826 PyThreadState *tstate;
827 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200828 if (_PyStatus_EXCEPTION(status)) {
829 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100830 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200831 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100832
Victor Stinnerd863ade2019-12-06 03:37:07 +0100833 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200834 if (_PyStatus_EXCEPTION(status)) {
835 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100836 }
Eric Snow1abcf672017-05-23 21:46:51 -0700837
838 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200839 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200840 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700841}
842
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100843
Victor Stinner331a6a52019-05-27 16:39:22 +0200844PyStatus
845_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100846{
Victor Stinner331a6a52019-05-27 16:39:22 +0200847 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100848
Victor Stinner6d1c4672019-05-20 11:02:00 +0200849 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200851 }
852
Victor Stinner331a6a52019-05-27 16:39:22 +0200853 status = _PyRuntime_Initialize();
854 if (_PyStatus_EXCEPTION(status)) {
855 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100856 }
Victor Stinner43125222019-04-24 18:23:53 +0200857 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100858
Victor Stinnerd3b90412019-09-17 23:59:51 +0200859 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100860 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200861 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100862 }
863
Victor Stinnerd3b90412019-09-17 23:59:51 +0200864 /* Note: preinitialized remains 1 on error, it is only set to 0
865 at exit on success. */
866 runtime->preinitializing = 1;
867
Victor Stinner331a6a52019-05-27 16:39:22 +0200868 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200869
870 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
871 if (_PyStatus_EXCEPTION(status)) {
872 return status;
873 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100874
Victor Stinner331a6a52019-05-27 16:39:22 +0200875 status = _PyPreConfig_Read(&config, args);
876 if (_PyStatus_EXCEPTION(status)) {
877 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100878 }
879
Victor Stinner331a6a52019-05-27 16:39:22 +0200880 status = _PyPreConfig_Write(&config);
881 if (_PyStatus_EXCEPTION(status)) {
882 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100883 }
884
Victor Stinnerd3b90412019-09-17 23:59:51 +0200885 runtime->preinitializing = 0;
886 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200887 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100888}
889
Victor Stinner70005ac2019-05-02 15:25:34 -0400890
Victor Stinner331a6a52019-05-27 16:39:22 +0200891PyStatus
892Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100893{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100894 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400895 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100896}
897
898
Victor Stinner331a6a52019-05-27 16:39:22 +0200899PyStatus
900Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100901{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100902 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400903 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100904}
905
906
Victor Stinner331a6a52019-05-27 16:39:22 +0200907PyStatus
908Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100909{
Victor Stinner70005ac2019-05-02 15:25:34 -0400910 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100911}
912
913
Victor Stinner331a6a52019-05-27 16:39:22 +0200914PyStatus
915_Py_PreInitializeFromConfig(const PyConfig *config,
916 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100917{
Victor Stinner331a6a52019-05-27 16:39:22 +0200918 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200919
Victor Stinner331a6a52019-05-27 16:39:22 +0200920 PyStatus status = _PyRuntime_Initialize();
921 if (_PyStatus_EXCEPTION(status)) {
922 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200923 }
924 _PyRuntimeState *runtime = &_PyRuntime;
925
Victor Stinnerd3b90412019-09-17 23:59:51 +0200926 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200927 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200928 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400929 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200930
Victor Stinner331a6a52019-05-27 16:39:22 +0200931 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200932
Victor Stinner3c30a762019-10-01 10:56:37 +0200933 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200934
Victor Stinner331a6a52019-05-27 16:39:22 +0200935 if (!config->parse_argv) {
936 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200937 }
938 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200939 _PyArgv config_args = {
940 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200941 .argc = config->argv.length,
942 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200943 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200944 }
945 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200946 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200947 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100948}
949
950
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100951/* Begin interpreter initialization
952 *
953 * On return, the first thread and interpreter state have been created,
954 * but the compiler, signal handling, multithreading and
955 * multiple interpreter support, and codec infrastructure are not yet
956 * available.
957 *
958 * The import system will support builtin and frozen modules only.
959 * The only supported io is writing to sys.stderr
960 *
961 * If any operation invoked by this function fails, a fatal error is
962 * issued and the function does not return.
963 *
964 * Any code invoked from this function should *not* assume it has access
965 * to the Python C API (unless the API is explicitly listed as being
966 * safe to call without calling Py_Initialize first)
967 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200968static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200969pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200970 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200971 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200972{
Victor Stinner331a6a52019-05-27 16:39:22 +0200973 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200974
Victor Stinner331a6a52019-05-27 16:39:22 +0200975 status = _Py_PreInitializeFromConfig(src_config, NULL);
976 if (_PyStatus_EXCEPTION(status)) {
977 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200978 }
979
Victor Stinner331a6a52019-05-27 16:39:22 +0200980 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100981 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200982
Victor Stinner331a6a52019-05-27 16:39:22 +0200983 status = _PyConfig_Copy(&config, src_config);
984 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200985 goto done;
986 }
987
Victor Stinner331a6a52019-05-27 16:39:22 +0200988 status = PyConfig_Read(&config);
989 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200990 goto done;
991 }
992
993 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200994 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200995 }
996 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200997 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200998 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200999 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +02001000 goto done;
1001 }
1002
1003done:
Victor Stinner331a6a52019-05-27 16:39:22 +02001004 PyConfig_Clear(&config);
1005 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +02001006}
1007
Victor Stinner5ac27a52019-03-27 13:40:14 +01001008
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001009/* Py_Initialize() has already been called: update the main interpreter
1010 configuration. Example of bpo-34008: Py_Main() called after
1011 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +02001012static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001013pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001014{
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001015 if (_PySys_UpdateConfig(tstate) < 0) {
1016 return _PyStatus_ERR("fail to update sys for the new conf");
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001017 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001018 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001019}
1020
Victor Stinnerb0051362019-11-22 17:52:42 +01001021
1022static PyStatus
1023init_interp_main(PyThreadState *tstate)
1024{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001025 assert(!_PyErr_Occurred(tstate));
1026
Victor Stinnerb0051362019-11-22 17:52:42 +01001027 PyStatus status;
1028 int is_main_interp = _Py_IsMainInterpreter(tstate);
1029 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001030 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001031
1032 if (!config->_install_importlib) {
1033 /* Special mode for freeze_importlib: run with no import system
1034 *
1035 * This means anything which needs support from extension modules
1036 * or pure Python code in the standard library won't work.
1037 */
1038 if (is_main_interp) {
1039 interp->runtime->initialized = 1;
1040 }
1041 return _PyStatus_OK();
1042 }
1043
1044 if (is_main_interp) {
1045 if (_PyTime_Init() < 0) {
1046 return _PyStatus_ERR("can't initialize time");
1047 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001048 }
Victor Stinnerb0051362019-11-22 17:52:42 +01001049
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001050 if (_PySys_UpdateConfig(tstate) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001051 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +01001052 }
1053
1054 status = init_importlib_external(tstate);
1055 if (_PyStatus_EXCEPTION(status)) {
1056 return status;
1057 }
1058
1059 if (is_main_interp) {
1060 /* initialize the faulthandler module */
1061 status = _PyFaulthandler_Init(config->faulthandler);
1062 if (_PyStatus_EXCEPTION(status)) {
1063 return status;
1064 }
1065 }
1066
1067 status = _PyUnicode_InitEncodings(tstate);
1068 if (_PyStatus_EXCEPTION(status)) {
1069 return status;
1070 }
1071
1072 if (is_main_interp) {
1073 if (config->install_signal_handlers) {
1074 status = init_signals(tstate);
1075 if (_PyStatus_EXCEPTION(status)) {
1076 return status;
1077 }
1078 }
1079
1080 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1081 return _PyStatus_ERR("can't initialize tracemalloc");
1082 }
1083 }
1084
1085 status = init_sys_streams(tstate);
1086 if (_PyStatus_EXCEPTION(status)) {
1087 return status;
1088 }
1089
Andy Lester75cd5bf2020-03-12 02:49:05 -05001090 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001091 if (_PyStatus_EXCEPTION(status)) {
1092 return status;
1093 }
1094
1095 status = add_main_module(interp);
1096 if (_PyStatus_EXCEPTION(status)) {
1097 return status;
1098 }
1099
1100 if (is_main_interp) {
1101 /* Initialize warnings. */
1102 PyObject *warnoptions = PySys_GetObject("warnoptions");
1103 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1104 {
1105 PyObject *warnings_module = PyImport_ImportModule("warnings");
1106 if (warnings_module == NULL) {
1107 fprintf(stderr, "'import warnings' failed; traceback:\n");
1108 _PyErr_Print(tstate);
1109 }
1110 Py_XDECREF(warnings_module);
1111 }
1112
1113 interp->runtime->initialized = 1;
1114 }
1115
1116 if (config->site_import) {
1117 status = init_import_site();
1118 if (_PyStatus_EXCEPTION(status)) {
1119 return status;
1120 }
1121 }
1122
1123 if (is_main_interp) {
1124#ifndef MS_WINDOWS
1125 emit_stderr_warning_for_legacy_locale(interp->runtime);
1126#endif
1127 }
1128
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001129 assert(!_PyErr_Occurred(tstate));
1130
Victor Stinnerb0051362019-11-22 17:52:42 +01001131 return _PyStatus_OK();
1132}
1133
1134
Eric Snowc7ec9982017-05-23 23:00:52 -07001135/* Update interpreter state based on supplied configuration settings
1136 *
1137 * After calling this function, most of the restrictions on the interpreter
1138 * are lifted. The only remaining incomplete settings are those related
1139 * to the main module (sys.argv[0], __main__ metadata)
1140 *
1141 * Calling this when the interpreter is not initializing, is already
1142 * initialized or without a valid current thread state is a fatal error.
1143 * Other errors should be reported as normal Python exceptions with a
1144 * non-zero return code.
1145 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001146static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001147pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001148{
Victor Stinnerb0051362019-11-22 17:52:42 +01001149 PyInterpreterState *interp = tstate->interp;
1150 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001151 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001152 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001153
Victor Stinnerb0051362019-11-22 17:52:42 +01001154 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001155 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001156 }
1157
Victor Stinnerb0051362019-11-22 17:52:42 +01001158 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001159 if (_PyStatus_EXCEPTION(status)) {
1160 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001161 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001162 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001163}
1164
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001165
Victor Stinner331a6a52019-05-27 16:39:22 +02001166PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001167Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001168{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001169 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001170 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001171 }
1172
Victor Stinner331a6a52019-05-27 16:39:22 +02001173 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001174
Victor Stinner331a6a52019-05-27 16:39:22 +02001175 status = _PyRuntime_Initialize();
1176 if (_PyStatus_EXCEPTION(status)) {
1177 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001178 }
1179 _PyRuntimeState *runtime = &_PyRuntime;
1180
Victor Stinnerb45d2592019-06-20 00:05:23 +02001181 PyThreadState *tstate = NULL;
1182 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001183 if (_PyStatus_EXCEPTION(status)) {
1184 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001185 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001186 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001187
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001188 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001189 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001190 if (_PyStatus_EXCEPTION(status)) {
1191 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001192 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001193 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001194
Victor Stinner331a6a52019-05-27 16:39:22 +02001195 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001196}
1197
1198
Eric Snow1abcf672017-05-23 21:46:51 -07001199void
Nick Coghland6009512014-11-20 21:39:37 +10001200Py_InitializeEx(int install_sigs)
1201{
Victor Stinner331a6a52019-05-27 16:39:22 +02001202 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001203
Victor Stinner331a6a52019-05-27 16:39:22 +02001204 status = _PyRuntime_Initialize();
1205 if (_PyStatus_EXCEPTION(status)) {
1206 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001207 }
1208 _PyRuntimeState *runtime = &_PyRuntime;
1209
1210 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001211 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1212 return;
1213 }
1214
Victor Stinner331a6a52019-05-27 16:39:22 +02001215 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001216 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001217
Victor Stinner1dc6e392018-07-25 02:49:17 +02001218 config.install_signal_handlers = install_sigs;
1219
Victor Stinner331a6a52019-05-27 16:39:22 +02001220 status = Py_InitializeFromConfig(&config);
1221 if (_PyStatus_EXCEPTION(status)) {
1222 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001223 }
Nick Coghland6009512014-11-20 21:39:37 +10001224}
1225
1226void
1227Py_Initialize(void)
1228{
1229 Py_InitializeEx(1);
1230}
1231
1232
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001233PyStatus
1234_Py_InitializeMain(void)
1235{
1236 PyStatus status = _PyRuntime_Initialize();
1237 if (_PyStatus_EXCEPTION(status)) {
1238 return status;
1239 }
1240 _PyRuntimeState *runtime = &_PyRuntime;
1241 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1242 return pyinit_main(tstate);
1243}
1244
1245
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001246static void
1247finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1248{
1249 // List of names to clear in sys
1250 static const char * const sys_deletes[] = {
1251 "path", "argv", "ps1", "ps2",
1252 "last_type", "last_value", "last_traceback",
1253 "path_hooks", "path_importer_cache", "meta_path",
1254 "__interactivehook__",
1255 NULL
1256 };
1257
1258 static const char * const sys_files[] = {
1259 "stdin", "__stdin__",
1260 "stdout", "__stdout__",
1261 "stderr", "__stderr__",
1262 NULL
1263 };
1264
1265 PyInterpreterState *interp = tstate->interp;
1266 if (verbose) {
1267 PySys_WriteStderr("# clear builtins._\n");
1268 }
1269 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1270 PyErr_WriteUnraisable(NULL);
1271 }
1272
1273 const char * const *p;
1274 for (p = sys_deletes; *p != NULL; p++) {
1275 if (verbose) {
1276 PySys_WriteStderr("# clear sys.%s\n", *p);
1277 }
1278 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1279 PyErr_WriteUnraisable(NULL);
1280 }
1281 }
1282 for (p = sys_files; *p != NULL; p+=2) {
1283 const char *name = p[0];
1284 const char *orig_name = p[1];
1285 if (verbose) {
1286 PySys_WriteStderr("# restore sys.%s\n", name);
1287 }
1288 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1289 orig_name);
1290 if (value == NULL) {
1291 if (_PyErr_Occurred(tstate)) {
1292 PyErr_WriteUnraisable(NULL);
1293 }
1294 value = Py_None;
1295 }
1296 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1297 PyErr_WriteUnraisable(NULL);
1298 }
1299 }
1300}
1301
1302
1303static PyObject*
1304finalize_remove_modules(PyObject *modules, int verbose)
1305{
1306 PyObject *weaklist = PyList_New(0);
1307 if (weaklist == NULL) {
1308 PyErr_WriteUnraisable(NULL);
1309 }
1310
1311#define STORE_MODULE_WEAKREF(name, mod) \
1312 if (weaklist != NULL) { \
1313 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1314 if (wr) { \
1315 PyObject *tup = PyTuple_Pack(2, name, wr); \
1316 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1317 PyErr_WriteUnraisable(NULL); \
1318 } \
1319 Py_XDECREF(tup); \
1320 Py_DECREF(wr); \
1321 } \
1322 else { \
1323 PyErr_WriteUnraisable(NULL); \
1324 } \
1325 }
1326
1327#define CLEAR_MODULE(name, mod) \
1328 if (PyModule_Check(mod)) { \
1329 if (verbose && PyUnicode_Check(name)) { \
1330 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1331 } \
1332 STORE_MODULE_WEAKREF(name, mod); \
1333 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1334 PyErr_WriteUnraisable(NULL); \
1335 } \
1336 }
1337
1338 if (PyDict_CheckExact(modules)) {
1339 Py_ssize_t pos = 0;
1340 PyObject *key, *value;
1341 while (PyDict_Next(modules, &pos, &key, &value)) {
1342 CLEAR_MODULE(key, value);
1343 }
1344 }
1345 else {
1346 PyObject *iterator = PyObject_GetIter(modules);
1347 if (iterator == NULL) {
1348 PyErr_WriteUnraisable(NULL);
1349 }
1350 else {
1351 PyObject *key;
1352 while ((key = PyIter_Next(iterator))) {
1353 PyObject *value = PyObject_GetItem(modules, key);
1354 if (value == NULL) {
1355 PyErr_WriteUnraisable(NULL);
1356 continue;
1357 }
1358 CLEAR_MODULE(key, value);
1359 Py_DECREF(value);
1360 Py_DECREF(key);
1361 }
1362 if (PyErr_Occurred()) {
1363 PyErr_WriteUnraisable(NULL);
1364 }
1365 Py_DECREF(iterator);
1366 }
1367 }
1368#undef CLEAR_MODULE
1369#undef STORE_MODULE_WEAKREF
1370
1371 return weaklist;
1372}
1373
1374
1375static void
1376finalize_clear_modules_dict(PyObject *modules)
1377{
1378 if (PyDict_CheckExact(modules)) {
1379 PyDict_Clear(modules);
1380 }
1381 else {
1382 _Py_IDENTIFIER(clear);
1383 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1384 PyErr_WriteUnraisable(NULL);
1385 }
1386 }
1387}
1388
1389
1390static void
1391finalize_restore_builtins(PyThreadState *tstate)
1392{
1393 PyInterpreterState *interp = tstate->interp;
1394 PyObject *dict = PyDict_Copy(interp->builtins);
1395 if (dict == NULL) {
1396 PyErr_WriteUnraisable(NULL);
1397 }
1398 PyDict_Clear(interp->builtins);
1399 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1400 _PyErr_Clear(tstate);
1401 }
1402 Py_XDECREF(dict);
1403}
1404
1405
1406static void
1407finalize_modules_clear_weaklist(PyInterpreterState *interp,
1408 PyObject *weaklist, int verbose)
1409{
1410 // First clear modules imported later
1411 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1412 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1413 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1414 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1415 if (mod == Py_None) {
1416 continue;
1417 }
1418 assert(PyModule_Check(mod));
1419 PyObject *dict = PyModule_GetDict(mod);
1420 if (dict == interp->builtins || dict == interp->sysdict) {
1421 continue;
1422 }
1423 Py_INCREF(mod);
1424 if (verbose && PyUnicode_Check(name)) {
1425 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1426 }
1427 _PyModule_Clear(mod);
1428 Py_DECREF(mod);
1429 }
1430}
1431
1432
1433static void
1434finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1435{
1436 // Clear sys dict
1437 if (verbose) {
1438 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1439 }
1440 _PyModule_ClearDict(interp->sysdict);
1441
1442 // Clear builtins dict
1443 if (verbose) {
1444 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1445 }
1446 _PyModule_ClearDict(interp->builtins);
1447}
1448
1449
1450/* Clear modules, as good as we can */
1451static void
1452finalize_modules(PyThreadState *tstate)
1453{
1454 PyInterpreterState *interp = tstate->interp;
1455 PyObject *modules = interp->modules;
1456 if (modules == NULL) {
1457 // Already done
1458 return;
1459 }
1460 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1461
1462 // Delete some special builtins._ and sys attributes first. These are
1463 // common places where user values hide and people complain when their
1464 // destructors fail. Since the modules containing them are
1465 // deleted *last* of all, they would come too late in the normal
1466 // destruction order. Sigh.
1467 //
1468 // XXX Perhaps these precautions are obsolete. Who knows?
1469 finalize_modules_delete_special(tstate, verbose);
1470
1471 // Remove all modules from sys.modules, hoping that garbage collection
1472 // can reclaim most of them: set all sys.modules values to None.
1473 //
1474 // We prepare a list which will receive (name, weakref) tuples of
1475 // modules when they are removed from sys.modules. The name is used
1476 // for diagnosis messages (in verbose mode), while the weakref helps
1477 // detect those modules which have been held alive.
1478 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1479
1480 // Clear the modules dict
1481 finalize_clear_modules_dict(modules);
1482
1483 // Restore the original builtins dict, to ensure that any
1484 // user data gets cleared.
1485 finalize_restore_builtins(tstate);
1486
1487 // Collect garbage
1488 _PyGC_CollectNoFail(tstate);
1489
1490 // Dump GC stats before it's too late, since it uses the warnings
1491 // machinery.
1492 _PyGC_DumpShutdownStats(tstate);
1493
1494 if (weaklist != NULL) {
1495 // Now, if there are any modules left alive, clear their globals to
1496 // minimize potential leaks. All C extension modules actually end
1497 // up here, since they are kept alive in the interpreter state.
1498 //
1499 // The special treatment of "builtins" here is because even
1500 // when it's not referenced as a module, its dictionary is
1501 // referenced by almost every module's __builtins__. Since
1502 // deleting a module clears its dictionary (even if there are
1503 // references left to it), we need to delete the "builtins"
1504 // module last. Likewise, we don't delete sys until the very
1505 // end because it is implicitly referenced (e.g. by print).
1506 //
1507 // Since dict is ordered in CPython 3.6+, modules are saved in
1508 // importing order. First clear modules imported later.
1509 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1510 Py_DECREF(weaklist);
1511 }
1512
1513 // Clear sys and builtins modules dict
1514 finalize_clear_sys_builtins_dict(interp, verbose);
1515
1516 // Clear module dict copies stored in the interpreter state:
1517 // clear PyInterpreterState.modules_by_index and
1518 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1519 // initialization API)
1520 _PyInterpreterState_ClearModules(interp);
1521
1522 // Clear and delete the modules directory. Actual modules will
1523 // still be there only if imported during the execution of some
1524 // destructor.
1525 Py_SETREF(interp->modules, NULL);
1526
1527 // Collect garbage once more
1528 _PyGC_CollectNoFail(tstate);
1529}
1530
1531
Nick Coghland6009512014-11-20 21:39:37 +10001532/* Flush stdout and stderr */
1533
1534static int
1535file_is_closed(PyObject *fobj)
1536{
1537 int r;
1538 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1539 if (tmp == NULL) {
1540 PyErr_Clear();
1541 return 0;
1542 }
1543 r = PyObject_IsTrue(tmp);
1544 Py_DECREF(tmp);
1545 if (r < 0)
1546 PyErr_Clear();
1547 return r > 0;
1548}
1549
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001550
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001551static int
Nick Coghland6009512014-11-20 21:39:37 +10001552flush_std_files(void)
1553{
1554 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1555 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1556 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001557 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001558
1559 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001560 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001561 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001562 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001563 status = -1;
1564 }
Nick Coghland6009512014-11-20 21:39:37 +10001565 else
1566 Py_DECREF(tmp);
1567 }
1568
1569 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001570 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001571 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001572 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001573 status = -1;
1574 }
Nick Coghland6009512014-11-20 21:39:37 +10001575 else
1576 Py_DECREF(tmp);
1577 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001578
1579 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001580}
1581
1582/* Undo the effect of Py_Initialize().
1583
1584 Beware: if multiple interpreter and/or thread states exist, these
1585 are not wiped out; only the current thread and interpreter state
1586 are deleted. But since everything else is deleted, those other
1587 interpreter and thread states should no longer be used.
1588
1589 (XXX We should do better, e.g. wipe out all interpreters and
1590 threads.)
1591
1592 Locking: as above.
1593
1594*/
1595
Victor Stinner7eee5be2019-11-20 10:38:34 +01001596
1597static void
Victor Stinner90db4652020-07-01 23:21:36 +02001598finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001599{
Victor Stinner281cce12020-06-23 22:55:46 +02001600 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001601 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001602 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001603 _PyContext_Fini(tstate);
Victor Stinner666ecfb2020-07-02 01:19:57 +02001604 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001605
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001606 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001607 _PyList_Fini(tstate);
1608 _PyTuple_Fini(tstate);
1609
1610 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001611
Victor Stinnerc41eed12020-06-23 15:54:35 +02001612 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001613 _PyUnicode_Fini(tstate);
1614 _PyFloat_Fini(tstate);
1615 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001616}
1617
1618
1619static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001620finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001621{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001622 int is_main_interp = _Py_IsMainInterpreter(tstate);
1623
Victor Stinner7eee5be2019-11-20 10:38:34 +01001624 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001625 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001626
Kongedaa0fe02020-07-04 05:06:46 +08001627 /* Clear all loghooks */
1628 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1629 Call _PySys_ClearAuditHooks when PyObject available. */
1630 if (is_main_interp) {
1631 _PySys_ClearAuditHooks(tstate);
1632 }
1633
Victor Stinner7907f8c2020-06-08 01:22:36 +02001634 if (is_main_interp) {
1635 _Py_HashRandomization_Fini();
1636 _PyArg_Fini();
1637 _Py_ClearFileSystemEncoding();
1638 }
1639
Victor Stinner90db4652020-07-01 23:21:36 +02001640 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001641}
1642
1643
1644static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001645finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001646{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001647 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001648 /* Cleanup auto-thread-state */
1649 _PyGILState_Fini(tstate);
1650 }
1651
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001652 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1653 fail when it is being awaited by another running daemon thread (see
1654 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1655 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1656 called multiple times. */
1657
Victor Stinner7eee5be2019-11-20 10:38:34 +01001658 PyInterpreterState_Delete(tstate->interp);
1659}
1660
1661
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001662int
1663Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001664{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001665 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001666
Victor Stinner8e91c242019-04-24 17:24:01 +02001667 _PyRuntimeState *runtime = &_PyRuntime;
1668 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001669 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001670 }
Nick Coghland6009512014-11-20 21:39:37 +10001671
Victor Stinnere225beb2019-06-03 18:14:24 +02001672 /* Get current thread state and interpreter pointer */
1673 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1674 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001675
Victor Stinnerb45d2592019-06-20 00:05:23 +02001676 // Wrap up existing "threading"-module-created, non-daemon threads.
1677 wait_for_thread_shutdown(tstate);
1678
1679 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001680 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001681
Nick Coghland6009512014-11-20 21:39:37 +10001682 /* The interpreter is still entirely intact at this point, and the
1683 * exit funcs may be relying on that. In particular, if some thread
1684 * or exit func is still waiting to do an import, the import machinery
1685 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001686 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001687 * Note that Threading.py uses an exit func to do a join on all the
1688 * threads created thru it, so this also protects pending imports in
1689 * the threads created via Threading.
1690 */
Nick Coghland6009512014-11-20 21:39:37 +10001691
Victor Stinnerb45d2592019-06-20 00:05:23 +02001692 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001693
Victor Stinnerda273412017-12-15 01:46:02 +01001694 /* Copy the core config, PyInterpreterState_Delete() free
1695 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001696#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001697 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001698#endif
1699#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001700 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001701#endif
1702#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001703 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001704#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001705
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001706 /* Remaining daemon threads will automatically exit
1707 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001708 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001709 runtime->initialized = 0;
1710 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001711
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001712 /* Destroy the state of all threads of the interpreter, except of the
1713 current thread. In practice, only daemon threads should still be alive,
1714 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1715 Clear frames of other threads to call objects destructors. Destructors
1716 will be called in the current Python thread. Since
1717 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1718 can take the GIL at this point: if they try, they will exit
1719 immediately. */
1720 _PyThreadState_DeleteExcept(runtime, tstate);
1721
Victor Stinnere0deff32015-03-24 13:46:18 +01001722 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001723 if (flush_std_files() < 0) {
1724 status = -1;
1725 }
Nick Coghland6009512014-11-20 21:39:37 +10001726
1727 /* Disable signal handling */
1728 PyOS_FiniInterrupts();
1729
1730 /* Collect garbage. This may call finalizers; it's nice to call these
1731 * before all modules are destroyed.
1732 * XXX If a __del__ or weakref callback is triggered here, and tries to
1733 * XXX import a module, bad things can happen, because Python no
1734 * XXX longer believes it's initialized.
1735 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1736 * XXX is easy to provoke that way. I've also seen, e.g.,
1737 * XXX Exception exceptions.ImportError: 'No module named sha'
1738 * XXX in <function callback at 0x008F5718> ignored
1739 * XXX but I'm unclear on exactly how that one happens. In any case,
1740 * XXX I haven't seen a real-life report of either of these.
1741 */
Victor Stinner8b341482020-10-30 17:00:00 +01001742 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001743
Nick Coghland6009512014-11-20 21:39:37 +10001744 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001745 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001746
Inada Naoki91234a12019-06-03 21:30:58 +09001747 /* Print debug stats if any */
1748 _PyEval_Fini();
1749
Victor Stinnere0deff32015-03-24 13:46:18 +01001750 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001751 if (flush_std_files() < 0) {
1752 status = -1;
1753 }
Nick Coghland6009512014-11-20 21:39:37 +10001754
1755 /* Collect final garbage. This disposes of cycles created by
1756 * class definitions, for example.
1757 * XXX This is disabled because it caused too many problems. If
1758 * XXX a __del__ or weakref callback triggers here, Python code has
1759 * XXX a hard time running, because even the sys module has been
1760 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1761 * XXX One symptom is a sequence of information-free messages
1762 * XXX coming from threads (if a __del__ or callback is invoked,
1763 * XXX other threads can execute too, and any exception they encounter
1764 * XXX triggers a comedy of errors as subsystem after subsystem
1765 * XXX fails to find what it *expects* to find in sys to help report
1766 * XXX the exception and consequent unexpected failures). I've also
1767 * XXX seen segfaults then, after adding print statements to the
1768 * XXX Python code getting called.
1769 */
1770#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001771 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001772#endif
1773
1774 /* Disable tracemalloc after all Python objects have been destroyed,
1775 so it is possible to use tracemalloc in objects destructor. */
1776 _PyTraceMalloc_Fini();
1777
1778 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1779 _PyImport_Fini();
1780
1781 /* Cleanup typeobject.c's internal caches. */
1782 _PyType_Fini();
1783
1784 /* unload faulthandler module */
1785 _PyFaulthandler_Fini();
1786
Nick Coghland6009512014-11-20 21:39:37 +10001787 /* dump hash stats */
1788 _PyHash_Fini();
1789
Eric Snowdae02762017-09-14 00:35:58 -07001790#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001791 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001792 _PyDebug_PrintTotalRefs();
1793 }
Eric Snowdae02762017-09-14 00:35:58 -07001794#endif
Nick Coghland6009512014-11-20 21:39:37 +10001795
1796#ifdef Py_TRACE_REFS
1797 /* Display all objects still alive -- this can invoke arbitrary
1798 * __repr__ overrides, so requires a mostly-intact interpreter.
1799 * Alas, a lot of stuff may still be alive now that will be cleaned
1800 * up later.
1801 */
Victor Stinnerda273412017-12-15 01:46:02 +01001802 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001803 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001804 }
Nick Coghland6009512014-11-20 21:39:37 +10001805#endif /* Py_TRACE_REFS */
1806
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001807 finalize_interp_clear(tstate);
1808 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001809
1810#ifdef Py_TRACE_REFS
1811 /* Display addresses (& refcnts) of all objects still alive.
1812 * An address can be used to find the repr of the object, printed
1813 * above by _Py_PrintReferences.
1814 */
Victor Stinnerda273412017-12-15 01:46:02 +01001815 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001816 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001817 }
Nick Coghland6009512014-11-20 21:39:37 +10001818#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001819#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001820 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001821 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001822 }
Nick Coghland6009512014-11-20 21:39:37 +10001823#endif
1824
Victor Stinner8e91c242019-04-24 17:24:01 +02001825 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001826
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001827 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001828 return status;
1829}
1830
1831void
1832Py_Finalize(void)
1833{
1834 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001835}
1836
Victor Stinnerb0051362019-11-22 17:52:42 +01001837
Nick Coghland6009512014-11-20 21:39:37 +10001838/* Create and initialize a new interpreter and thread, and return the
1839 new thread. This requires that Py_Initialize() has been called
1840 first.
1841
1842 Unsuccessful initialization yields a NULL pointer. Note that *no*
1843 exception information is available even in this case -- the
1844 exception information is held in the thread, and there is no
1845 thread.
1846
1847 Locking: as above.
1848
1849*/
1850
Victor Stinner331a6a52019-05-27 16:39:22 +02001851static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001852new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001853{
Victor Stinner331a6a52019-05-27 16:39:22 +02001854 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001855
Victor Stinner331a6a52019-05-27 16:39:22 +02001856 status = _PyRuntime_Initialize();
1857 if (_PyStatus_EXCEPTION(status)) {
1858 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001859 }
1860 _PyRuntimeState *runtime = &_PyRuntime;
1861
1862 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001863 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001864 }
Nick Coghland6009512014-11-20 21:39:37 +10001865
Victor Stinner8a1be612016-03-14 22:07:55 +01001866 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1867 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001868 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001869
Victor Stinner43125222019-04-24 18:23:53 +02001870 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001871 if (interp == NULL) {
1872 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001873 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001874 }
Nick Coghland6009512014-11-20 21:39:37 +10001875
Victor Stinner43125222019-04-24 18:23:53 +02001876 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001877 if (tstate == NULL) {
1878 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001879 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001880 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001881 }
1882
Victor Stinner43125222019-04-24 18:23:53 +02001883 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001884
Eric Snow1abcf672017-05-23 21:46:51 -07001885 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001886 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001887#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001888 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001889 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001890 }
1891 else
1892#endif
1893 {
Eric Snow1abcf672017-05-23 21:46:51 -07001894 /* No current thread state, copy from the main interpreter */
1895 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001896 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001897 }
1898
Victor Stinner048a3562020-11-05 00:45:56 +01001899
1900 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001901 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001902 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001903 }
Victor Stinner252346a2020-05-01 11:33:44 +02001904 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001905
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001906 status = init_interp_create_gil(tstate);
1907 if (_PyStatus_EXCEPTION(status)) {
1908 goto error;
1909 }
1910
Victor Stinnerd863ade2019-12-06 03:37:07 +01001911 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001912 if (_PyStatus_EXCEPTION(status)) {
1913 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001914 }
1915
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001916 status = init_interp_main(tstate);
1917 if (_PyStatus_EXCEPTION(status)) {
1918 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001919 }
Nick Coghland6009512014-11-20 21:39:37 +10001920
Victor Stinnera7368ac2017-11-15 18:11:45 -08001921 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001922 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001923
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001924error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001925 *tstate_p = NULL;
1926
1927 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001928 PyErr_PrintEx(0);
1929 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001930 PyThreadState_Delete(tstate);
1931 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001932 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001933
Victor Stinnerb0051362019-11-22 17:52:42 +01001934 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001935}
1936
1937PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001938_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001939{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001940 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001941 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001942 if (_PyStatus_EXCEPTION(status)) {
1943 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001944 }
1945 return tstate;
1946
Nick Coghland6009512014-11-20 21:39:37 +10001947}
1948
Victor Stinner252346a2020-05-01 11:33:44 +02001949PyThreadState *
1950Py_NewInterpreter(void)
1951{
1952 return _Py_NewInterpreter(0);
1953}
1954
Nick Coghland6009512014-11-20 21:39:37 +10001955/* Delete an interpreter and its last thread. This requires that the
1956 given thread state is current, that the thread has no remaining
1957 frames, and that it is its interpreter's only remaining thread.
1958 It is a fatal error to violate these constraints.
1959
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001960 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001961 everything, regardless.)
1962
1963 Locking: as above.
1964
1965*/
1966
1967void
1968Py_EndInterpreter(PyThreadState *tstate)
1969{
1970 PyInterpreterState *interp = tstate->interp;
1971
Victor Stinnerb45d2592019-06-20 00:05:23 +02001972 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001973 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001974 }
1975 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001976 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001977 }
Eric Snow5be45a62019-03-08 22:47:07 -07001978 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001979
Eric Snow842a2f02019-03-15 15:47:51 -06001980 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001981 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001982
Victor Stinnerb45d2592019-06-20 00:05:23 +02001983 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001984
Victor Stinnerb45d2592019-06-20 00:05:23 +02001985 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001986 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001987 }
Nick Coghland6009512014-11-20 21:39:37 +10001988
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001989 finalize_modules(tstate);
1990
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001991 finalize_interp_clear(tstate);
1992 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001993}
1994
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001995/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001996
Victor Stinner331a6a52019-05-27 16:39:22 +02001997static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001998add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001999{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002000 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10002001 m = PyImport_AddModule("__main__");
2002 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02002003 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002004
Nick Coghland6009512014-11-20 21:39:37 +10002005 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002006 ann_dict = PyDict_New();
2007 if ((ann_dict == NULL) ||
2008 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002009 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002010 }
2011 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002012
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002013 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
2014 if (PyErr_Occurred()) {
2015 return _PyStatus_ERR("Failed to test __main__.__builtins__");
2016 }
Nick Coghland6009512014-11-20 21:39:37 +10002017 PyObject *bimod = PyImport_ImportModule("builtins");
2018 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002019 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10002020 }
2021 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002022 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002023 }
2024 Py_DECREF(bimod);
2025 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002026
Nick Coghland6009512014-11-20 21:39:37 +10002027 /* Main is a little special - imp.is_builtin("__main__") will return
2028 * False, but BuiltinImporter is still the most appropriate initial
2029 * setting for its __loader__ attribute. A more suitable value will
2030 * be set if __main__ gets further initialized later in the startup
2031 * process.
2032 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002033 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002034 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002035 if (PyErr_Occurred()) {
2036 return _PyStatus_ERR("Failed to test __main__.__loader__");
2037 }
Nick Coghland6009512014-11-20 21:39:37 +10002038 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2039 "BuiltinImporter");
2040 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002041 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002042 }
2043 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002044 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002045 }
2046 Py_DECREF(loader);
2047 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002048 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002049}
2050
Nick Coghland6009512014-11-20 21:39:37 +10002051/* Import the site module (not into __main__ though) */
2052
Victor Stinner331a6a52019-05-27 16:39:22 +02002053static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002054init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002055{
2056 PyObject *m;
2057 m = PyImport_ImportModule("site");
2058 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002059 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002060 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002061 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002062 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002063}
2064
Victor Stinner874dbe82015-09-04 17:29:57 +02002065/* Check if a file descriptor is valid or not.
2066 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2067static int
2068is_valid_fd(int fd)
2069{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002070/* dup() is faster than fstat(): fstat() can require input/output operations,
2071 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2072 startup. Problem: dup() doesn't check if the file descriptor is valid on
2073 some platforms.
2074
2075 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2076 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2077 EBADF. FreeBSD has similar issue (bpo-32849).
2078
2079 Only use dup() on platforms where dup() is enough to detect invalid FD in
2080 corner cases: on Linux and Windows (bpo-32849). */
2081#if defined(__linux__) || defined(MS_WINDOWS)
2082 if (fd < 0) {
2083 return 0;
2084 }
2085 int fd2;
2086
2087 _Py_BEGIN_SUPPRESS_IPH
2088 fd2 = dup(fd);
2089 if (fd2 >= 0) {
2090 close(fd2);
2091 }
2092 _Py_END_SUPPRESS_IPH
2093
2094 return (fd2 >= 0);
2095#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002096 struct stat st;
2097 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002098#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002099}
2100
2101/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002102static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002103create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002104 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002105 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002106{
2107 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2108 const char* mode;
2109 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002110 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002111 int buffering, isatty;
2112 _Py_IDENTIFIER(open);
2113 _Py_IDENTIFIER(isatty);
2114 _Py_IDENTIFIER(TextIOWrapper);
2115 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002116 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002117
Victor Stinner874dbe82015-09-04 17:29:57 +02002118 if (!is_valid_fd(fd))
2119 Py_RETURN_NONE;
2120
Nick Coghland6009512014-11-20 21:39:37 +10002121 /* stdin is always opened in buffered mode, first because it shouldn't
2122 make a difference in common use cases, second because TextIOWrapper
2123 depends on the presence of a read1() method which only exists on
2124 buffered streams.
2125 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002126 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002127 buffering = 0;
2128 else
2129 buffering = -1;
2130 if (write_mode)
2131 mode = "wb";
2132 else
2133 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002134 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002135 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002136 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002137 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002138 if (buf == NULL)
2139 goto error;
2140
2141 if (buffering) {
2142 _Py_IDENTIFIER(raw);
2143 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2144 if (raw == NULL)
2145 goto error;
2146 }
2147 else {
2148 raw = buf;
2149 Py_INCREF(raw);
2150 }
2151
Steve Dower39294992016-08-30 21:22:36 -07002152#ifdef MS_WINDOWS
2153 /* Windows console IO is always UTF-8 encoded */
2154 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002155 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002156#endif
2157
Nick Coghland6009512014-11-20 21:39:37 +10002158 text = PyUnicode_FromString(name);
2159 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2160 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002161 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002162 if (res == NULL)
2163 goto error;
2164 isatty = PyObject_IsTrue(res);
2165 Py_DECREF(res);
2166 if (isatty == -1)
2167 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002168 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002169 write_through = Py_True;
2170 else
2171 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002172 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002173 line_buffering = Py_True;
2174 else
2175 line_buffering = Py_False;
2176
2177 Py_CLEAR(raw);
2178 Py_CLEAR(text);
2179
2180#ifdef MS_WINDOWS
2181 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2182 newlines to "\n".
2183 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2184 newline = NULL;
2185#else
2186 /* sys.stdin: split lines at "\n".
2187 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2188 newline = "\n";
2189#endif
2190
Victor Stinner709d23d2019-05-02 14:56:30 -04002191 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2192 if (encoding_str == NULL) {
2193 Py_CLEAR(buf);
2194 goto error;
2195 }
2196
2197 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2198 if (errors_str == NULL) {
2199 Py_CLEAR(buf);
2200 Py_CLEAR(encoding_str);
2201 goto error;
2202 }
2203
2204 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2205 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002206 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002207 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002208 Py_CLEAR(encoding_str);
2209 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002210 if (stream == NULL)
2211 goto error;
2212
2213 if (write_mode)
2214 mode = "w";
2215 else
2216 mode = "r";
2217 text = PyUnicode_FromString(mode);
2218 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2219 goto error;
2220 Py_CLEAR(text);
2221 return stream;
2222
2223error:
2224 Py_XDECREF(buf);
2225 Py_XDECREF(stream);
2226 Py_XDECREF(text);
2227 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002228
Victor Stinner874dbe82015-09-04 17:29:57 +02002229 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2230 /* Issue #24891: the file descriptor was closed after the first
2231 is_valid_fd() check was called. Ignore the OSError and set the
2232 stream to None. */
2233 PyErr_Clear();
2234 Py_RETURN_NONE;
2235 }
2236 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002237}
2238
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002239/* Set builtins.open to io.OpenWrapper */
2240static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002241init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002242{
2243 PyObject *iomod = NULL, *wrapper;
2244 PyObject *bimod = NULL;
2245 PyStatus res = _PyStatus_OK();
2246
2247 if (!(iomod = PyImport_ImportModule("io"))) {
2248 goto error;
2249 }
2250
2251 if (!(bimod = PyImport_ImportModule("builtins"))) {
2252 goto error;
2253 }
2254
2255 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2256 goto error;
2257 }
2258
2259 /* Set builtins.open */
2260 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2261 Py_DECREF(wrapper);
2262 goto error;
2263 }
2264 Py_DECREF(wrapper);
2265 goto done;
2266
2267error:
2268 res = _PyStatus_ERR("can't initialize io.open");
2269
2270done:
2271 Py_XDECREF(bimod);
2272 Py_XDECREF(iomod);
2273 return res;
2274}
2275
2276
Nick Coghland6009512014-11-20 21:39:37 +10002277/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002278static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002279init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002280{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002281 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002282 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002283 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002284 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002285 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002286 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002287
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002288 /* Check that stdin is not a directory
2289 Using shell redirection, you can redirect stdin to a directory,
2290 crashing the Python interpreter. Catch this common mistake here
2291 and output a useful error message. Note that under MS Windows,
2292 the shell already prevents that. */
2293#ifndef MS_WINDOWS
2294 struct _Py_stat_struct sb;
2295 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2296 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002297 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002298 }
2299#endif
2300
Nick Coghland6009512014-11-20 21:39:37 +10002301 if (!(iomod = PyImport_ImportModule("io"))) {
2302 goto error;
2303 }
Nick Coghland6009512014-11-20 21:39:37 +10002304
Nick Coghland6009512014-11-20 21:39:37 +10002305 /* Set sys.stdin */
2306 fd = fileno(stdin);
2307 /* Under some conditions stdin, stdout and stderr may not be connected
2308 * and fileno() may point to an invalid file descriptor. For example
2309 * GUI apps don't have valid standard streams by default.
2310 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002311 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002312 config->stdio_encoding,
2313 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002314 if (std == NULL)
2315 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002316 PySys_SetObject("__stdin__", std);
2317 _PySys_SetObjectId(&PyId_stdin, std);
2318 Py_DECREF(std);
2319
2320 /* Set sys.stdout */
2321 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002322 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002323 config->stdio_encoding,
2324 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002325 if (std == NULL)
2326 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002327 PySys_SetObject("__stdout__", std);
2328 _PySys_SetObjectId(&PyId_stdout, std);
2329 Py_DECREF(std);
2330
2331#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2332 /* Set sys.stderr, replaces the preliminary stderr */
2333 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002334 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002335 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002336 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002337 if (std == NULL)
2338 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002339
2340 /* Same as hack above, pre-import stderr's codec to avoid recursion
2341 when import.c tries to write to stderr in verbose mode. */
2342 encoding_attr = PyObject_GetAttrString(std, "encoding");
2343 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002344 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002345 if (std_encoding != NULL) {
2346 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2347 Py_XDECREF(codec_info);
2348 }
2349 Py_DECREF(encoding_attr);
2350 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002351 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002352
2353 if (PySys_SetObject("__stderr__", std) < 0) {
2354 Py_DECREF(std);
2355 goto error;
2356 }
2357 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2358 Py_DECREF(std);
2359 goto error;
2360 }
2361 Py_DECREF(std);
2362#endif
2363
Victor Stinnera7368ac2017-11-15 18:11:45 -08002364 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002365
Victor Stinnera7368ac2017-11-15 18:11:45 -08002366error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002367 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002368
2369done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002370 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002371 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002372 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002373}
2374
2375
Victor Stinner10dc4842015-03-24 12:01:30 +01002376static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002377_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2378 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002379{
Victor Stinner10dc4842015-03-24 12:01:30 +01002380 fputc('\n', stderr);
2381 fflush(stderr);
2382
2383 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002384 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002385}
Victor Stinner791da1c2016-03-14 16:53:12 +01002386
2387/* Print the current exception (if an exception is set) with its traceback,
2388 or display the current Python stack.
2389
2390 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2391 called on catastrophic cases.
2392
2393 Return 1 if the traceback was displayed, 0 otherwise. */
2394
2395static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002396_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002397{
2398 PyObject *ferr, *res;
2399 PyObject *exception, *v, *tb;
2400 int has_tb;
2401
Victor Stinnerb45d2592019-06-20 00:05:23 +02002402 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002403 if (exception == NULL) {
2404 /* No current exception */
2405 return 0;
2406 }
2407
2408 ferr = _PySys_GetObjectId(&PyId_stderr);
2409 if (ferr == NULL || ferr == Py_None) {
2410 /* sys.stderr is not set yet or set to None,
2411 no need to try to display the exception */
2412 return 0;
2413 }
2414
Victor Stinnerb45d2592019-06-20 00:05:23 +02002415 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002416 if (tb == NULL) {
2417 tb = Py_None;
2418 Py_INCREF(tb);
2419 }
2420 PyException_SetTraceback(v, tb);
2421 if (exception == NULL) {
2422 /* PyErr_NormalizeException() failed */
2423 return 0;
2424 }
2425
2426 has_tb = (tb != Py_None);
2427 PyErr_Display(exception, v, tb);
2428 Py_XDECREF(exception);
2429 Py_XDECREF(v);
2430 Py_XDECREF(tb);
2431
2432 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002433 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002434 if (res == NULL) {
2435 _PyErr_Clear(tstate);
2436 }
2437 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002438 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002439 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002440
2441 return has_tb;
2442}
2443
Nick Coghland6009512014-11-20 21:39:37 +10002444/* Print fatal error message and abort */
2445
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002446#ifdef MS_WINDOWS
2447static void
2448fatal_output_debug(const char *msg)
2449{
2450 /* buffer of 256 bytes allocated on the stack */
2451 WCHAR buffer[256 / sizeof(WCHAR)];
2452 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2453 size_t msglen;
2454
2455 OutputDebugStringW(L"Fatal Python error: ");
2456
2457 msglen = strlen(msg);
2458 while (msglen) {
2459 size_t i;
2460
2461 if (buflen > msglen) {
2462 buflen = msglen;
2463 }
2464
2465 /* Convert the message to wchar_t. This uses a simple one-to-one
2466 conversion, assuming that the this error message actually uses
2467 ASCII only. If this ceases to be true, we will have to convert. */
2468 for (i=0; i < buflen; ++i) {
2469 buffer[i] = msg[i];
2470 }
2471 buffer[i] = L'\0';
2472 OutputDebugStringW(buffer);
2473
2474 msg += buflen;
2475 msglen -= buflen;
2476 }
2477 OutputDebugStringW(L"\n");
2478}
2479#endif
2480
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002481
2482static void
2483fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2484{
2485 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002486 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2487 if (finalizing) {
2488 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002489 }
2490 else if (runtime->initialized) {
2491 fprintf(stream, "initialized");
2492 }
2493 else if (runtime->core_initialized) {
2494 fprintf(stream, "core initialized");
2495 }
2496 else if (runtime->preinitialized) {
2497 fprintf(stream, "preinitialized");
2498 }
2499 else if (runtime->preinitializing) {
2500 fprintf(stream, "preinitializing");
2501 }
2502 else {
2503 fprintf(stream, "unknown");
2504 }
2505 fprintf(stream, "\n");
2506 fflush(stream);
2507}
2508
2509
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002510static inline void _Py_NO_RETURN
2511fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002512{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002513 if (status < 0) {
2514#if defined(MS_WINDOWS) && defined(_DEBUG)
2515 DebugBreak();
2516#endif
2517 abort();
2518 }
2519 else {
2520 exit(status);
2521 }
2522}
2523
2524
2525static void _Py_NO_RETURN
2526fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2527 int status)
2528{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002529 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002530 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002531
2532 if (reentrant) {
2533 /* Py_FatalError() caused a second fatal error.
2534 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002535 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002536 }
2537 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002538
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002539 if (header) {
2540 fprintf(stream, "Fatal Python error: ");
2541 if (prefix) {
2542 fputs(prefix, stream);
2543 fputs(": ", stream);
2544 }
2545 if (msg) {
2546 fputs(msg, stream);
2547 }
2548 else {
2549 fprintf(stream, "<message not set>");
2550 }
2551 fputs("\n", stream);
2552 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002553 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002554
2555 _PyRuntimeState *runtime = &_PyRuntime;
2556 fatal_error_dump_runtime(stream, runtime);
2557
2558 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2559 PyInterpreterState *interp = NULL;
2560 if (tstate != NULL) {
2561 interp = tstate->interp;
2562 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002563
Victor Stinner3a228ab2018-11-01 00:26:41 +01002564 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002565 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002566
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002567 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2568 has no Python thread state.
2569
2570 tss_tstate != tstate if the current Python thread does not hold the GIL.
2571 */
2572 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2573 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002574 if (has_tstate_and_gil) {
2575 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002576 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002577 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002578 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002579 }
2580 }
2581 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002582 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002583 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002584
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002585 /* The main purpose of faulthandler is to display the traceback.
2586 This function already did its best to display a traceback.
2587 Disable faulthandler to prevent writing a second traceback
2588 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002589 _PyFaulthandler_Fini();
2590
Victor Stinner791da1c2016-03-14 16:53:12 +01002591 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002592 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002593 /* Flush sys.stdout and sys.stderr */
2594 flush_std_files();
2595 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002596
Nick Coghland6009512014-11-20 21:39:37 +10002597#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002598 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002599#endif /* MS_WINDOWS */
2600
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002601 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002602}
2603
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002604
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002605#undef Py_FatalError
2606
Victor Stinner19760862017-12-20 01:41:59 +01002607void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002608Py_FatalError(const char *msg)
2609{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002610 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002611}
2612
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002613
Victor Stinner19760862017-12-20 01:41:59 +01002614void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002615_Py_FatalErrorFunc(const char *func, const char *msg)
2616{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002617 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002618}
2619
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002620
2621void _Py_NO_RETURN
2622_Py_FatalErrorFormat(const char *func, const char *format, ...)
2623{
2624 static int reentrant = 0;
2625 if (reentrant) {
2626 /* _Py_FatalErrorFormat() caused a second fatal error */
2627 fatal_error_exit(-1);
2628 }
2629 reentrant = 1;
2630
2631 FILE *stream = stderr;
2632 fprintf(stream, "Fatal Python error: ");
2633 if (func) {
2634 fputs(func, stream);
2635 fputs(": ", stream);
2636 }
2637 fflush(stream);
2638
2639 va_list vargs;
2640#ifdef HAVE_STDARG_PROTOTYPES
2641 va_start(vargs, format);
2642#else
2643 va_start(vargs);
2644#endif
2645 vfprintf(stream, format, vargs);
2646 va_end(vargs);
2647
2648 fputs("\n", stream);
2649 fflush(stream);
2650
2651 fatal_error(stream, 0, NULL, NULL, -1);
2652}
2653
2654
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002655void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002656Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002657{
Victor Stinner331a6a52019-05-27 16:39:22 +02002658 if (_PyStatus_IS_EXIT(status)) {
2659 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002660 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002661 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002662 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002663 }
2664 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002665 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002666 }
Nick Coghland6009512014-11-20 21:39:37 +10002667}
2668
2669/* Clean up and exit */
2670
Nick Coghland6009512014-11-20 21:39:37 +10002671/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002672void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002673{
Victor Stinner81a7be32020-04-14 15:14:01 +02002674 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002675
Antoine Pitroufc5db952017-12-13 02:29:07 +01002676 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002677 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2678
2679 is->pyexitfunc = func;
2680 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002681}
2682
2683static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002684call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002685{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002686 PyInterpreterState *interp = tstate->interp;
2687 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002688 return;
2689
Victor Stinnerb45d2592019-06-20 00:05:23 +02002690 (*interp->pyexitfunc)(interp->pyexitmodule);
2691 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002692}
2693
2694/* Wait until threading._shutdown completes, provided
2695 the threading module was imported in the first place.
2696 The shutdown routine will wait until all non-daemon
2697 "threading" threads have completed. */
2698static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002699wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002700{
Nick Coghland6009512014-11-20 21:39:37 +10002701 _Py_IDENTIFIER(_shutdown);
2702 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002703 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002704 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002705 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002706 PyErr_WriteUnraisable(NULL);
2707 }
2708 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002709 return;
2710 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002711 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002712 if (result == NULL) {
2713 PyErr_WriteUnraisable(threading);
2714 }
2715 else {
2716 Py_DECREF(result);
2717 }
2718 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002719}
2720
2721#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002722int Py_AtExit(void (*func)(void))
2723{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002724 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002725 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002726 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002727 return 0;
2728}
2729
2730static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002731call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002732{
Victor Stinner8e91c242019-04-24 17:24:01 +02002733 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002734 /* pop last function from the list */
2735 runtime->nexitfuncs--;
2736 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2737 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2738
2739 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002740 }
Nick Coghland6009512014-11-20 21:39:37 +10002741
2742 fflush(stdout);
2743 fflush(stderr);
2744}
2745
Victor Stinnercfc88312018-08-01 16:41:25 +02002746void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002747Py_Exit(int sts)
2748{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002749 if (Py_FinalizeEx() < 0) {
2750 sts = 120;
2751 }
Nick Coghland6009512014-11-20 21:39:37 +10002752
2753 exit(sts);
2754}
2755
Victor Stinner331a6a52019-05-27 16:39:22 +02002756static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002757init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002758{
2759#ifdef SIGPIPE
2760 PyOS_setsig(SIGPIPE, SIG_IGN);
2761#endif
2762#ifdef SIGXFZ
2763 PyOS_setsig(SIGXFZ, SIG_IGN);
2764#endif
2765#ifdef SIGXFSZ
2766 PyOS_setsig(SIGXFSZ, SIG_IGN);
2767#endif
Victor Stinner400e1db2020-03-31 19:13:10 +02002768 PyOS_InitInterrupts(); /* May imply init_signals() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002769 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002770 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002771 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002772 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002773}
2774
2775
2776/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2777 *
2778 * All of the code in this function must only use async-signal-safe functions,
2779 * listed at `man 7 signal` or
2780 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002781 *
2782 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002783 */
2784void
2785_Py_RestoreSignals(void)
2786{
2787#ifdef SIGPIPE
2788 PyOS_setsig(SIGPIPE, SIG_DFL);
2789#endif
2790#ifdef SIGXFZ
2791 PyOS_setsig(SIGXFZ, SIG_DFL);
2792#endif
2793#ifdef SIGXFSZ
2794 PyOS_setsig(SIGXFSZ, SIG_DFL);
2795#endif
2796}
2797
2798
2799/*
2800 * The file descriptor fd is considered ``interactive'' if either
2801 * a) isatty(fd) is TRUE, or
2802 * b) the -i flag was given, and the filename associated with
2803 * the descriptor is NULL or "<stdin>" or "???".
2804 */
2805int
2806Py_FdIsInteractive(FILE *fp, const char *filename)
2807{
2808 if (isatty((int)fileno(fp)))
2809 return 1;
2810 if (!Py_InteractiveFlag)
2811 return 0;
2812 return (filename == NULL) ||
2813 (strcmp(filename, "<stdin>") == 0) ||
2814 (strcmp(filename, "???") == 0);
2815}
2816
2817
Nick Coghland6009512014-11-20 21:39:37 +10002818/* Wrappers around sigaction() or signal(). */
2819
2820PyOS_sighandler_t
2821PyOS_getsig(int sig)
2822{
2823#ifdef HAVE_SIGACTION
2824 struct sigaction context;
2825 if (sigaction(sig, NULL, &context) == -1)
2826 return SIG_ERR;
2827 return context.sa_handler;
2828#else
2829 PyOS_sighandler_t handler;
2830/* Special signal handling for the secure CRT in Visual Studio 2005 */
2831#if defined(_MSC_VER) && _MSC_VER >= 1400
2832 switch (sig) {
2833 /* Only these signals are valid */
2834 case SIGINT:
2835 case SIGILL:
2836 case SIGFPE:
2837 case SIGSEGV:
2838 case SIGTERM:
2839 case SIGBREAK:
2840 case SIGABRT:
2841 break;
2842 /* Don't call signal() with other values or it will assert */
2843 default:
2844 return SIG_ERR;
2845 }
2846#endif /* _MSC_VER && _MSC_VER >= 1400 */
2847 handler = signal(sig, SIG_IGN);
2848 if (handler != SIG_ERR)
2849 signal(sig, handler);
2850 return handler;
2851#endif
2852}
2853
2854/*
2855 * All of the code in this function must only use async-signal-safe functions,
2856 * listed at `man 7 signal` or
2857 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2858 */
2859PyOS_sighandler_t
2860PyOS_setsig(int sig, PyOS_sighandler_t handler)
2861{
2862#ifdef HAVE_SIGACTION
2863 /* Some code in Modules/signalmodule.c depends on sigaction() being
2864 * used here if HAVE_SIGACTION is defined. Fix that if this code
2865 * changes to invalidate that assumption.
2866 */
2867 struct sigaction context, ocontext;
2868 context.sa_handler = handler;
2869 sigemptyset(&context.sa_mask);
2870 context.sa_flags = 0;
2871 if (sigaction(sig, &context, &ocontext) == -1)
2872 return SIG_ERR;
2873 return ocontext.sa_handler;
2874#else
2875 PyOS_sighandler_t oldhandler;
2876 oldhandler = signal(sig, handler);
2877#ifdef HAVE_SIGINTERRUPT
2878 siginterrupt(sig, 1);
2879#endif
2880 return oldhandler;
2881#endif
2882}
2883
2884#ifdef __cplusplus
2885}
2886#endif