blob: 2dbebe45fd4b0be16b6cd6b4be83bb8457a804cb [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
Victor Stinner4f98f462020-04-15 04:01:58 +02005#include "pycore_ceval.h" // _PyEval_FiniGIL()
6#include "pycore_context.h" // _PyContext_Init()
7#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner62230712020-11-18 23:18:29 +01008#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner4f98f462020-04-15 04:01:58 +02009#include "pycore_initconfig.h" // _PyStatus_OK()
10#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
11#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
12#include "pycore_pyerrors.h" // _PyErr_Occurred()
13#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020014#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020015#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
16#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
17
Victor Stinner4f98f462020-04-15 04:01:58 +020018#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100019
20#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020021# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100022#endif
23
24#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020025# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100026#endif
27
28#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020029# undef BYTE
30# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070031
Victor Stinner4f98f462020-04-15 04:01:58 +020032 extern PyTypeObject PyWindowsConsoleIO_Type;
33# define PyWindowsConsoleIO_Check(op) \
34 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100035#endif
36
Victor Stinner4f98f462020-04-15 04:01:58 +020037
Victor Stinner314b8782021-01-18 18:34:56 +010038#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
39
40
Nick Coghland6009512014-11-20 21:39:37 +100041_Py_IDENTIFIER(flush);
42_Py_IDENTIFIER(name);
43_Py_IDENTIFIER(stdin);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060046_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100047
48#ifdef __cplusplus
49extern "C" {
50#endif
51
Nick Coghland6009512014-11-20 21:39:37 +100052
Victor Stinnerb45d2592019-06-20 00:05:23 +020053/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020054static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020055static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050056static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020057static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020058static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020059static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100060
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080061int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010063static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060064
Victor Stinner331a6a52019-05-27 16:39:22 +020065PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066_PyRuntime_Initialize(void)
67{
68 /* XXX We only initialize once in the process, which aligns with
69 the static initialization of the former globals now found in
70 _PyRuntime. However, _PyRuntime *should* be initialized with
71 every Py_Initialize() call, but doing so breaks the runtime.
72 This is because the runtime state is not properly finalized
73 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010074 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020075 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010077 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078
79 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080}
81
82void
83_PyRuntime_Finalize(void)
84{
85 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
88
89int
90_Py_IsFinalizing(void)
91{
Victor Stinner7b3c2522020-03-07 00:24:23 +010092 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060093}
94
Nick Coghland6009512014-11-20 21:39:37 +100095/* Hack to force loading of object files */
96int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
97 PyOS_mystrnicmp; /* Python/pystrcmp.o */
98
Eric Snowc7ec9982017-05-23 23:00:52 -070099
Eric Snow1abcf672017-05-23 21:46:51 -0700100/* APIs to access the initialization flags
101 *
102 * Can be called prior to Py_Initialize.
103 */
Nick Coghland6009512014-11-20 21:39:37 +1000104
Eric Snow1abcf672017-05-23 21:46:51 -0700105int
106_Py_IsCoreInitialized(void)
107{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600108 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700109}
Nick Coghland6009512014-11-20 21:39:37 +1000110
111int
112Py_IsInitialized(void)
113{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000115}
116
Nick Coghlan6ea41862017-06-11 13:16:15 +1000117
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000118/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
119 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000120 initializations fail, a fatal error is issued and the function does
121 not return. On return, the first thread and interpreter state have
122 been created.
123
124 Locking: you must hold the interpreter lock while calling this.
125 (If the lock has not yet been initialized, that's equivalent to
126 having the lock, but you cannot use multiple threads.)
127
128*/
Victor Stinneref75a622020-11-12 15:14:13 +0100129static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200130init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000131{
Victor Stinneref75a622020-11-12 15:14:13 +0100132 assert(!_PyErr_Occurred(tstate));
133
Victor Stinnerb45d2592019-06-20 00:05:23 +0200134 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200135 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000136
Victor Stinneref75a622020-11-12 15:14:13 +0100137 // Import _importlib through its frozen version, _frozen_importlib.
138 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000139 PySys_FormatStderr("import _frozen_importlib # frozen\n");
140 }
Victor Stinneref75a622020-11-12 15:14:13 +0100141 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
142 return -1;
143 }
144 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000145 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100146 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000147 }
Victor Stinneref75a622020-11-12 15:14:13 +0100148 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000149
Victor Stinneref75a622020-11-12 15:14:13 +0100150 // Import the _imp module
151 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200152 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000153 }
Victor Stinner62230712020-11-18 23:18:29 +0100154 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100155 if (imp_mod == NULL) {
156 return -1;
157 }
158 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
159 Py_DECREF(imp_mod);
160 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000161 }
162
Victor Stinneref75a622020-11-12 15:14:13 +0100163 // Install importlib as the implementation of import
164 PyObject *value = PyObject_CallMethod(importlib, "_install",
165 "OO", sysmod, imp_mod);
166 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000167 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100168 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000169 }
170 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000171
Victor Stinneref75a622020-11-12 15:14:13 +0100172 assert(!_PyErr_Occurred(tstate));
173 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000174}
175
Victor Stinneref75a622020-11-12 15:14:13 +0100176
Victor Stinner331a6a52019-05-27 16:39:22 +0200177static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200178init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700179{
180 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200181 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700182 "_install_external_importers", "");
183 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200184 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200185 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700186 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200187 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200188 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700189}
Nick Coghland6009512014-11-20 21:39:37 +1000190
Nick Coghlan6ea41862017-06-11 13:16:15 +1000191/* Helper functions to better handle the legacy C locale
192 *
193 * The legacy C locale assumes ASCII as the default text encoding, which
194 * causes problems not only for the CPython runtime, but also other
195 * components like GNU readline.
196 *
197 * Accordingly, when the CLI detects it, it attempts to coerce it to a
198 * more capable UTF-8 based alternative as follows:
199 *
200 * if (_Py_LegacyLocaleDetected()) {
201 * _Py_CoerceLegacyLocale();
202 * }
203 *
204 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
205 *
206 * Locale coercion also impacts the default error handler for the standard
207 * streams: while the usual default is "strict", the default for the legacy
208 * C locale and for any of the coercion target locales is "surrogateescape".
209 */
210
211int
Victor Stinner0f721472019-05-20 17:16:38 +0200212_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000213{
214#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200215 if (!warn) {
216 const char *locale_override = getenv("LC_ALL");
217 if (locale_override != NULL && *locale_override != '\0') {
218 /* Don't coerce C locale if the LC_ALL environment variable
219 is set */
220 return 0;
221 }
222 }
223
Nick Coghlan6ea41862017-06-11 13:16:15 +1000224 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000225 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
226 * the POSIX locale as a simple alias for the C locale, so
227 * we may also want to check for that explicitly.
228 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000229 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
230 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
231#else
232 /* Windows uses code pages instead of locales, so no locale is legacy */
233 return 0;
234#endif
235}
236
Victor Stinnerb0051362019-11-22 17:52:42 +0100237#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000238static const char *_C_LOCALE_WARNING =
239 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
240 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
241 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
242 "locales is recommended.\n";
243
Nick Coghlaneb817952017-06-18 12:29:42 +1000244static void
Victor Stinner43125222019-04-24 18:23:53 +0200245emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000246{
Victor Stinner331a6a52019-05-27 16:39:22 +0200247 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200248 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200249 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000250 }
251}
Victor Stinnerb0051362019-11-22 17:52:42 +0100252#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000253
Nick Coghlan6ea41862017-06-11 13:16:15 +1000254typedef struct _CandidateLocale {
255 const char *locale_name; /* The locale to try as a coercion target */
256} _LocaleCoercionTarget;
257
258static _LocaleCoercionTarget _TARGET_LOCALES[] = {
259 {"C.UTF-8"},
260 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000261 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000262 {NULL}
263};
264
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200265
266int
267_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000268{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200269 const _LocaleCoercionTarget *target = NULL;
270 for (target = _TARGET_LOCALES; target->locale_name; target++) {
271 if (strcmp(ctype_loc, target->locale_name) == 0) {
272 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000273 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200274 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200275 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276}
277
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200278
Nick Coghlan6ea41862017-06-11 13:16:15 +1000279#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100280static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000281 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
282 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
283
Victor Stinner0f721472019-05-20 17:16:38 +0200284static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200285_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000286{
287 const char *newloc = target->locale_name;
288
289 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100290 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291
292 /* Set the relevant locale environment variable */
293 if (setenv("LC_CTYPE", newloc, 1)) {
294 fprintf(stderr,
295 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200296 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200298 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100299 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000300 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301
302 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100303 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200304 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305}
306#endif
307
Victor Stinner0f721472019-05-20 17:16:38 +0200308int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200309_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310{
Victor Stinner0f721472019-05-20 17:16:38 +0200311 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200313 char *oldloc = NULL;
314
315 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
316 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200317 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200318 }
319
Victor Stinner94540602017-12-16 04:54:22 +0100320 const char *locale_override = getenv("LC_ALL");
321 if (locale_override == NULL || *locale_override == '\0') {
322 /* LC_ALL is also not set (or is set to an empty string) */
323 const _LocaleCoercionTarget *target = NULL;
324 for (target = _TARGET_LOCALES; target->locale_name; target++) {
325 const char *new_locale = setlocale(LC_CTYPE,
326 target->locale_name);
327 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400328#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100329 /* Also ensure that nl_langinfo works in this locale */
330 char *codeset = nl_langinfo(CODESET);
331 if (!codeset || *codeset == '\0') {
332 /* CODESET is not set or empty, so skip coercion */
333 new_locale = NULL;
334 _Py_SetLocaleFromEnv(LC_CTYPE);
335 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000336 }
Victor Stinner94540602017-12-16 04:54:22 +0100337#endif
338 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200339 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200340 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000341 }
342 }
343 }
344 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200345
346 setlocale(LC_CTYPE, oldloc);
347
348done:
349 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200351 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000352}
353
xdegaye1588be62017-11-12 12:45:59 +0100354/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
355 * isolate the idiosyncrasies of different libc implementations. It reads the
356 * appropriate environment variable and uses its value to select the locale for
357 * 'category'. */
358char *
359_Py_SetLocaleFromEnv(int category)
360{
Victor Stinner353933e2018-11-23 13:08:26 +0100361 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100362#ifdef __ANDROID__
363 const char *locale;
364 const char **pvar;
365#ifdef PY_COERCE_C_LOCALE
366 const char *coerce_c_locale;
367#endif
368 const char *utf8_locale = "C.UTF-8";
369 const char *env_var_set[] = {
370 "LC_ALL",
371 "LC_CTYPE",
372 "LANG",
373 NULL,
374 };
375
376 /* Android setlocale(category, "") doesn't check the environment variables
377 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
378 * check the environment variables listed in env_var_set. */
379 for (pvar=env_var_set; *pvar; pvar++) {
380 locale = getenv(*pvar);
381 if (locale != NULL && *locale != '\0') {
382 if (strcmp(locale, utf8_locale) == 0 ||
383 strcmp(locale, "en_US.UTF-8") == 0) {
384 return setlocale(category, utf8_locale);
385 }
386 return setlocale(category, "C");
387 }
388 }
389
390 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
391 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
392 * Quote from POSIX section "8.2 Internationalization Variables":
393 * "4. If the LANG environment variable is not set or is set to the empty
394 * string, the implementation-defined default locale shall be used." */
395
396#ifdef PY_COERCE_C_LOCALE
397 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
398 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
399 /* Some other ported code may check the environment variables (e.g. in
400 * extension modules), so we make sure that they match the locale
401 * configuration */
402 if (setenv("LC_CTYPE", utf8_locale, 1)) {
403 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
404 "environment variable to %s\n", utf8_locale);
405 }
406 }
407#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100408 res = setlocale(category, utf8_locale);
409#else /* !defined(__ANDROID__) */
410 res = setlocale(category, "");
411#endif
412 _Py_ResetForceASCII();
413 return res;
xdegaye1588be62017-11-12 12:45:59 +0100414}
415
Nick Coghlan6ea41862017-06-11 13:16:15 +1000416
Victor Stinner048a3562020-11-05 00:45:56 +0100417static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100418interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100419{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100420 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100421
Victor Stinner9e1b8282020-11-10 13:21:52 +0100422 if (!only_update_path_config) {
423 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
424 if (_PyStatus_EXCEPTION(status)) {
425 _PyErr_SetFromPyStatus(status);
426 return -1;
427 }
Victor Stinner048a3562020-11-05 00:45:56 +0100428 }
429
Victor Stinner101bf692021-02-19 13:33:31 +0100430 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner9e1b8282020-11-10 13:21:52 +0100431 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100432 if (_PyStatus_EXCEPTION(status)) {
433 _PyErr_SetFromPyStatus(status);
434 return -1;
435 }
436 }
437
438 // Update the sys module for the new configuration
439 if (_PySys_UpdateConfig(tstate) < 0) {
440 return -1;
441 }
442 return 0;
443}
444
445
446int
447_PyInterpreterState_SetConfig(const PyConfig *src_config)
448{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100449 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100450 int res = -1;
451
452 PyConfig config;
453 PyConfig_InitPythonConfig(&config);
454 PyStatus status = _PyConfig_Copy(&config, src_config);
455 if (_PyStatus_EXCEPTION(status)) {
456 _PyErr_SetFromPyStatus(status);
457 goto done;
458 }
459
460 status = PyConfig_Read(&config);
461 if (_PyStatus_EXCEPTION(status)) {
462 _PyErr_SetFromPyStatus(status);
463 goto done;
464 }
465
Victor Stinner9e1b8282020-11-10 13:21:52 +0100466 status = _PyConfig_Copy(&tstate->interp->config, &config);
467 if (_PyStatus_EXCEPTION(status)) {
468 _PyErr_SetFromPyStatus(status);
469 goto done;
470 }
471
472 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100473
474done:
475 PyConfig_Clear(&config);
476 return res;
477}
478
479
Eric Snow1abcf672017-05-23 21:46:51 -0700480/* Global initializations. Can be undone by Py_Finalize(). Don't
481 call this twice without an intervening Py_Finalize() call.
482
Victor Stinner331a6a52019-05-27 16:39:22 +0200483 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700484 must have a corresponding call to Py_Finalize.
485
486 Locking: you must hold the interpreter lock while calling these APIs.
487 (If the lock has not yet been initialized, that's equivalent to
488 having the lock, but you cannot use multiple threads.)
489
490*/
491
Victor Stinner331a6a52019-05-27 16:39:22 +0200492static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200493pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200494 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200495 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200496{
Victor Stinner331a6a52019-05-27 16:39:22 +0200497 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100498 PyThreadState *tstate = _PyThreadState_GET();
499 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200500 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100501 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200502 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100503
504 PyInterpreterState *interp = tstate->interp;
505 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200506 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100507 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100508
Victor Stinnere81f6e62020-06-08 18:12:59 +0200509 status = _PyConfig_Write(config, runtime);
510 if (_PyStatus_EXCEPTION(status)) {
511 return status;
512 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200513
Victor Stinner048a3562020-11-05 00:45:56 +0100514 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200515 if (_PyStatus_EXCEPTION(status)) {
516 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200517 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200518 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200519
Victor Stinner331a6a52019-05-27 16:39:22 +0200520 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200521 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200522 if (_PyStatus_EXCEPTION(status)) {
523 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200524 }
525 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200526 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527}
528
529
Victor Stinner331a6a52019-05-27 16:39:22 +0200530static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200531pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200532 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000533{
Victor Stinner43125222019-04-24 18:23:53 +0200534 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200536 }
Victor Stinnerda273412017-12-15 01:46:02 +0100537
Victor Stinnere81f6e62020-06-08 18:12:59 +0200538 PyStatus status = _PyConfig_Write(config, runtime);
539 if (_PyStatus_EXCEPTION(status)) {
540 return status;
541 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600542
Eric Snow1abcf672017-05-23 21:46:51 -0700543 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
544 * threads behave a little more gracefully at interpreter shutdown.
545 * We clobber it here so the new interpreter can start with a clean
546 * slate.
547 *
548 * However, this may still lead to misbehaviour if there are daemon
549 * threads still hanging around from a previous Py_Initialize/Finalize
550 * pair :(
551 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100552 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600553
Victor Stinnere81f6e62020-06-08 18:12:59 +0200554 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200555 if (_PyStatus_EXCEPTION(status)) {
556 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800557 }
558
Victor Stinner331a6a52019-05-27 16:39:22 +0200559 status = _PyInterpreterState_Enable(runtime);
560 if (_PyStatus_EXCEPTION(status)) {
561 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800562 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200563 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100564}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800565
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100566
Victor Stinner331a6a52019-05-27 16:39:22 +0200567static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200568init_interp_create_gil(PyThreadState *tstate)
569{
570 PyStatus status;
571
572 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
573 only called here. */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100574 _PyEval_FiniGIL(tstate->interp);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200575
576 /* Auto-thread-state API */
Victor Stinner87f649a2021-03-10 20:00:46 +0100577 status = _PyGILState_SetTstate(tstate);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200578 if (_PyStatus_EXCEPTION(status)) {
579 return status;
580 }
581
582 /* Create the GIL and take it */
583 status = _PyEval_InitGIL(tstate);
584 if (_PyStatus_EXCEPTION(status)) {
585 return status;
586 }
587
588 return _PyStatus_OK();
589}
590
591
592static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200593pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200594 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200595 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596{
Victor Stinner87f649a2021-03-10 20:00:46 +0100597 /* Auto-thread-state API */
598 PyStatus status = _PyGILState_Init(runtime);
599 if (_PyStatus_EXCEPTION(status)) {
600 return status;
601 }
602
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100603 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100604 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200605 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100606 }
Victor Stinner87f649a2021-03-10 20:00:46 +0100607 assert(_Py_IsMainInterpreter(interp));
Victor Stinnerda273412017-12-15 01:46:02 +0100608
Victor Stinner87f649a2021-03-10 20:00:46 +0100609 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200610 if (_PyStatus_EXCEPTION(status)) {
611 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100612 }
Nick Coghland6009512014-11-20 21:39:37 +1000613
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200614 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200615 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200616 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200617 }
Nick Coghland6009512014-11-20 21:39:37 +1000618 (void) PyThreadState_Swap(tstate);
619
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200620 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100621 if (_PyStatus_EXCEPTION(status)) {
622 return status;
623 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100624
Victor Stinnerb45d2592019-06-20 00:05:23 +0200625 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200626 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100627}
Nick Coghland6009512014-11-20 21:39:37 +1000628
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100629
Victor Stinner331a6a52019-05-27 16:39:22 +0200630static PyStatus
Victor Stinner442ad742021-04-02 15:28:13 +0200631pycore_init_singletons(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100632{
Victor Stinner444b39b2019-11-20 01:18:11 +0100633 PyStatus status;
634
Victor Stinner442ad742021-04-02 15:28:13 +0200635 if (_PyLong_Init(interp) < 0) {
Victor Stinner630c8df2019-12-17 13:02:18 +0100636 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100637 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100638
Victor Stinner442ad742021-04-02 15:28:13 +0200639 if (_Py_IsMainInterpreter(interp)) {
640 _PyFloat_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641 }
642
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100643 status = _PyBytes_Init(interp);
Victor Stinner91698d82020-06-25 14:07:40 +0200644 if (_PyStatus_EXCEPTION(status)) {
645 return status;
646 }
647
Victor Stinner442ad742021-04-02 15:28:13 +0200648 status = _PyUnicode_Init(interp);
649 if (_PyStatus_EXCEPTION(status)) {
650 return status;
651 }
652
653 status = _PyTuple_Init(interp);
654 if (_PyStatus_EXCEPTION(status)) {
655 return status;
656 }
657
658 return _PyStatus_OK();
659}
660
661
662static PyStatus
663pycore_init_types(PyInterpreterState *interp)
664{
665 PyStatus status;
666 int is_main_interp = _Py_IsMainInterpreter(interp);
667
668 if (is_main_interp) {
669 if (_PyStructSequence_Init() < 0) {
670 return _PyStatus_ERR("can't initialize structseq");
671 }
672
673 status = _PyTypes_Init();
674 if (_PyStatus_EXCEPTION(status)) {
675 return status;
676 }
677
678 if (_PyLong_InitTypes() < 0) {
679 return _PyStatus_ERR("can't init int type");
680 }
681
682 status = _PyUnicode_InitTypes();
683 if (_PyStatus_EXCEPTION(status)) {
684 return status;
685 }
686 }
687
688 if (is_main_interp) {
689 if (_PyFloat_InitTypes() < 0) {
690 return _PyStatus_ERR("can't init float");
691 }
692 }
693
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100694 status = _PyExc_Init(interp);
Victor Stinner331a6a52019-05-27 16:39:22 +0200695 if (_PyStatus_EXCEPTION(status)) {
696 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100697 }
698
Victor Stinner442ad742021-04-02 15:28:13 +0200699 status = _PyErr_InitTypes();
Victor Stinner331a6a52019-05-27 16:39:22 +0200700 if (_PyStatus_EXCEPTION(status)) {
701 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200702 }
703
Victor Stinnere7e699e2019-11-20 12:08:13 +0100704 if (is_main_interp) {
705 if (!_PyContext_Init()) {
706 return _PyStatus_ERR("can't init context");
707 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100708 }
709
Victor Stinner331a6a52019-05-27 16:39:22 +0200710 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711}
712
713
Victor Stinner331a6a52019-05-27 16:39:22 +0200714static PyStatus
Victor Stinner442ad742021-04-02 15:28:13 +0200715pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100716{
Victor Stinner442ad742021-04-02 15:28:13 +0200717 PyInterpreterState *interp = tstate->interp;
718
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100719 PyObject *bimod = _PyBuiltin_Init(interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100720 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100721 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100722 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100723
Victor Stinner2582d462019-11-22 19:24:49 +0100724 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
725 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100726 }
Victor Stinner2582d462019-11-22 19:24:49 +0100727
728 PyObject *builtins_dict = PyModule_GetDict(bimod);
729 if (builtins_dict == NULL) {
730 goto error;
731 }
732 Py_INCREF(builtins_dict);
733 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100734
Victor Stinner331a6a52019-05-27 16:39:22 +0200735 PyStatus status = _PyBuiltins_AddExceptions(bimod);
736 if (_PyStatus_EXCEPTION(status)) {
737 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100738 }
Victor Stinner2582d462019-11-22 19:24:49 +0100739
740 interp->builtins_copy = PyDict_Copy(interp->builtins);
741 if (interp->builtins_copy == NULL) {
742 goto error;
743 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000744 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100745
Victor Stinner62230712020-11-18 23:18:29 +0100746 // Get the __import__ function
747 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
748 "__import__");
749 if (import_func == NULL) {
750 goto error;
751 }
752 interp->import_func = Py_NewRef(import_func);
753
Victor Stinner442ad742021-04-02 15:28:13 +0200754 assert(!_PyErr_Occurred(tstate));
Victor Stinner331a6a52019-05-27 16:39:22 +0200755 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100756
757error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000758 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100759 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100760}
761
762
Victor Stinner331a6a52019-05-27 16:39:22 +0200763static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100764pycore_interp_init(PyThreadState *tstate)
765{
Victor Stinner442ad742021-04-02 15:28:13 +0200766 PyInterpreterState *interp = tstate->interp;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100767 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100768 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100769
Victor Stinner442ad742021-04-02 15:28:13 +0200770 // Create singletons before the first PyType_Ready() call, since
771 // PyType_Ready() uses singletons like the Unicode empty string (tp_doc)
772 // and the empty tuple singletons (tp_bases).
773 status = pycore_init_singletons(interp);
774 if (_PyStatus_EXCEPTION(status)) {
775 return status;
776 }
777
778 // The GC must be initialized before the first GC collection.
779 status = _PyGC_Init(interp);
780 if (_PyStatus_EXCEPTION(status)) {
781 return status;
782 }
783
784 status = pycore_init_types(interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100785 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100786 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100787 }
788
Victor Stinner442ad742021-04-02 15:28:13 +0200789 if (_PyWarnings_InitState(interp) < 0) {
790 return _PyStatus_ERR("can't initialize warnings");
791 }
792
793 status = _PyAtExit_Init(interp);
794 if (_PyStatus_EXCEPTION(status)) {
795 return status;
796 }
797
Victor Stinnerd863ade2019-12-06 03:37:07 +0100798 status = _PySys_Create(tstate, &sysmod);
799 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100800 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100801 }
802
Victor Stinner442ad742021-04-02 15:28:13 +0200803 status = pycore_init_builtins(tstate);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100804 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100805 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100806 }
807
Victor Stinner442ad742021-04-02 15:28:13 +0200808 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinneref75a622020-11-12 15:14:13 +0100809 if (config->_install_importlib) {
810 /* This call sets up builtin and frozen import support */
811 if (init_importlib(tstate, sysmod) < 0) {
812 return _PyStatus_ERR("failed to initialize importlib");
813 }
814 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100815
816done:
817 /* sys.modules['sys'] contains a strong reference to the module */
818 Py_XDECREF(sysmod);
819 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100820}
821
822
823static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200824pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200825 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100827{
Victor Stinner331a6a52019-05-27 16:39:22 +0200828 PyStatus status = pycore_init_runtime(runtime, config);
829 if (_PyStatus_EXCEPTION(status)) {
830 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100831 }
832
Victor Stinnerb45d2592019-06-20 00:05:23 +0200833 PyThreadState *tstate;
834 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200835 if (_PyStatus_EXCEPTION(status)) {
836 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100837 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200838 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100839
Victor Stinnerd863ade2019-12-06 03:37:07 +0100840 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200841 if (_PyStatus_EXCEPTION(status)) {
842 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100843 }
Eric Snow1abcf672017-05-23 21:46:51 -0700844
845 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200846 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200847 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700848}
849
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100850
Victor Stinner331a6a52019-05-27 16:39:22 +0200851PyStatus
852_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100853{
Victor Stinner331a6a52019-05-27 16:39:22 +0200854 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100855
Victor Stinner6d1c4672019-05-20 11:02:00 +0200856 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200858 }
859
Victor Stinner331a6a52019-05-27 16:39:22 +0200860 status = _PyRuntime_Initialize();
861 if (_PyStatus_EXCEPTION(status)) {
862 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100863 }
Victor Stinner43125222019-04-24 18:23:53 +0200864 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100865
Victor Stinnerd3b90412019-09-17 23:59:51 +0200866 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100867 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200868 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100869 }
870
Victor Stinnerd3b90412019-09-17 23:59:51 +0200871 /* Note: preinitialized remains 1 on error, it is only set to 0
872 at exit on success. */
873 runtime->preinitializing = 1;
874
Victor Stinner331a6a52019-05-27 16:39:22 +0200875 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200876
877 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
878 if (_PyStatus_EXCEPTION(status)) {
879 return status;
880 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100881
Victor Stinner331a6a52019-05-27 16:39:22 +0200882 status = _PyPreConfig_Read(&config, args);
883 if (_PyStatus_EXCEPTION(status)) {
884 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100885 }
886
Victor Stinner331a6a52019-05-27 16:39:22 +0200887 status = _PyPreConfig_Write(&config);
888 if (_PyStatus_EXCEPTION(status)) {
889 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100890 }
891
Victor Stinnerd3b90412019-09-17 23:59:51 +0200892 runtime->preinitializing = 0;
893 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200894 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100895}
896
Victor Stinner70005ac2019-05-02 15:25:34 -0400897
Victor Stinner331a6a52019-05-27 16:39:22 +0200898PyStatus
899Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100900{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100901 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400902 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100903}
904
905
Victor Stinner331a6a52019-05-27 16:39:22 +0200906PyStatus
907Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100908{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100909 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400910 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100911}
912
913
Victor Stinner331a6a52019-05-27 16:39:22 +0200914PyStatus
915Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100916{
Victor Stinner70005ac2019-05-02 15:25:34 -0400917 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100918}
919
920
Victor Stinner331a6a52019-05-27 16:39:22 +0200921PyStatus
922_Py_PreInitializeFromConfig(const PyConfig *config,
923 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100924{
Victor Stinner331a6a52019-05-27 16:39:22 +0200925 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200926
Victor Stinner331a6a52019-05-27 16:39:22 +0200927 PyStatus status = _PyRuntime_Initialize();
928 if (_PyStatus_EXCEPTION(status)) {
929 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200930 }
931 _PyRuntimeState *runtime = &_PyRuntime;
932
Victor Stinnerd3b90412019-09-17 23:59:51 +0200933 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200934 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200935 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400936 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200937
Victor Stinner331a6a52019-05-27 16:39:22 +0200938 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200939
Victor Stinner3c30a762019-10-01 10:56:37 +0200940 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200941
Victor Stinner331a6a52019-05-27 16:39:22 +0200942 if (!config->parse_argv) {
943 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200944 }
945 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200946 _PyArgv config_args = {
947 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200948 .argc = config->argv.length,
949 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200950 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200951 }
952 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200953 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200954 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100955}
956
957
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100958/* Begin interpreter initialization
959 *
960 * On return, the first thread and interpreter state have been created,
961 * but the compiler, signal handling, multithreading and
962 * multiple interpreter support, and codec infrastructure are not yet
963 * available.
964 *
965 * The import system will support builtin and frozen modules only.
966 * The only supported io is writing to sys.stderr
967 *
968 * If any operation invoked by this function fails, a fatal error is
969 * issued and the function does not return.
970 *
971 * Any code invoked from this function should *not* assume it has access
972 * to the Python C API (unless the API is explicitly listed as being
973 * safe to call without calling Py_Initialize first)
974 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200975static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200976pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200977 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200978 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200979{
Victor Stinner331a6a52019-05-27 16:39:22 +0200980 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200981
Victor Stinner331a6a52019-05-27 16:39:22 +0200982 status = _Py_PreInitializeFromConfig(src_config, NULL);
983 if (_PyStatus_EXCEPTION(status)) {
984 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200985 }
986
Victor Stinner331a6a52019-05-27 16:39:22 +0200987 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100988 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200989
Victor Stinner331a6a52019-05-27 16:39:22 +0200990 status = _PyConfig_Copy(&config, src_config);
991 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200992 goto done;
993 }
994
Victor Stinner9e1b8282020-11-10 13:21:52 +0100995 // Read the configuration, but don't compute the path configuration
996 // (it is computed in the main init).
997 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200998 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200999 goto done;
1000 }
1001
1002 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02001003 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +02001004 }
1005 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +02001006 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +02001007 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001008 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +02001009 goto done;
1010 }
1011
1012done:
Victor Stinner331a6a52019-05-27 16:39:22 +02001013 PyConfig_Clear(&config);
1014 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +02001015}
1016
Victor Stinner5ac27a52019-03-27 13:40:14 +01001017
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001018/* Py_Initialize() has already been called: update the main interpreter
1019 configuration. Example of bpo-34008: Py_Main() called after
1020 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +02001021static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001022pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001023{
Victor Stinner9e1b8282020-11-10 13:21:52 +01001024 if (interpreter_update_config(tstate, 0) < 0) {
1025 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001026 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001027 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001028}
1029
Victor Stinnerb0051362019-11-22 17:52:42 +01001030
1031static PyStatus
1032init_interp_main(PyThreadState *tstate)
1033{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001034 assert(!_PyErr_Occurred(tstate));
1035
Victor Stinnerb0051362019-11-22 17:52:42 +01001036 PyStatus status;
Victor Stinner101bf692021-02-19 13:33:31 +01001037 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001038 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001039 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001040
1041 if (!config->_install_importlib) {
1042 /* Special mode for freeze_importlib: run with no import system
1043 *
1044 * This means anything which needs support from extension modules
1045 * or pure Python code in the standard library won't work.
1046 */
1047 if (is_main_interp) {
1048 interp->runtime->initialized = 1;
1049 }
1050 return _PyStatus_OK();
1051 }
1052
Victor Stinner9e1b8282020-11-10 13:21:52 +01001053 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001054 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001055 if (_PyStatus_EXCEPTION(status)) {
1056 return status;
1057 }
1058
Victor Stinner9e1b8282020-11-10 13:21:52 +01001059 if (interpreter_update_config(tstate, 1) < 0) {
1060 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001061 }
1062
1063 status = init_importlib_external(tstate);
1064 if (_PyStatus_EXCEPTION(status)) {
1065 return status;
1066 }
1067
1068 if (is_main_interp) {
1069 /* initialize the faulthandler module */
1070 status = _PyFaulthandler_Init(config->faulthandler);
1071 if (_PyStatus_EXCEPTION(status)) {
1072 return status;
1073 }
1074 }
1075
1076 status = _PyUnicode_InitEncodings(tstate);
1077 if (_PyStatus_EXCEPTION(status)) {
1078 return status;
1079 }
1080
1081 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001082 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1083 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001084 }
1085
1086 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1087 return _PyStatus_ERR("can't initialize tracemalloc");
1088 }
1089 }
1090
1091 status = init_sys_streams(tstate);
1092 if (_PyStatus_EXCEPTION(status)) {
1093 return status;
1094 }
1095
Andy Lester75cd5bf2020-03-12 02:49:05 -05001096 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001097 if (_PyStatus_EXCEPTION(status)) {
1098 return status;
1099 }
1100
1101 status = add_main_module(interp);
1102 if (_PyStatus_EXCEPTION(status)) {
1103 return status;
1104 }
1105
1106 if (is_main_interp) {
1107 /* Initialize warnings. */
1108 PyObject *warnoptions = PySys_GetObject("warnoptions");
1109 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1110 {
1111 PyObject *warnings_module = PyImport_ImportModule("warnings");
1112 if (warnings_module == NULL) {
1113 fprintf(stderr, "'import warnings' failed; traceback:\n");
1114 _PyErr_Print(tstate);
1115 }
1116 Py_XDECREF(warnings_module);
1117 }
1118
1119 interp->runtime->initialized = 1;
1120 }
1121
1122 if (config->site_import) {
1123 status = init_import_site();
1124 if (_PyStatus_EXCEPTION(status)) {
1125 return status;
1126 }
1127 }
1128
1129 if (is_main_interp) {
1130#ifndef MS_WINDOWS
1131 emit_stderr_warning_for_legacy_locale(interp->runtime);
1132#endif
1133 }
1134
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001135 assert(!_PyErr_Occurred(tstate));
1136
Victor Stinnerb0051362019-11-22 17:52:42 +01001137 return _PyStatus_OK();
1138}
1139
1140
Eric Snowc7ec9982017-05-23 23:00:52 -07001141/* Update interpreter state based on supplied configuration settings
1142 *
1143 * After calling this function, most of the restrictions on the interpreter
1144 * are lifted. The only remaining incomplete settings are those related
1145 * to the main module (sys.argv[0], __main__ metadata)
1146 *
1147 * Calling this when the interpreter is not initializing, is already
1148 * initialized or without a valid current thread state is a fatal error.
1149 * Other errors should be reported as normal Python exceptions with a
1150 * non-zero return code.
1151 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001152static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001153pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001154{
Victor Stinnerb0051362019-11-22 17:52:42 +01001155 PyInterpreterState *interp = tstate->interp;
1156 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001157 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001158 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001159
Victor Stinnerb0051362019-11-22 17:52:42 +01001160 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001161 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001162 }
1163
Victor Stinnerb0051362019-11-22 17:52:42 +01001164 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001165 if (_PyStatus_EXCEPTION(status)) {
1166 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001167 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001168 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001169}
1170
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001171
Victor Stinner331a6a52019-05-27 16:39:22 +02001172PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001173Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001174{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001175 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001177 }
1178
Victor Stinner331a6a52019-05-27 16:39:22 +02001179 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001180
Victor Stinner331a6a52019-05-27 16:39:22 +02001181 status = _PyRuntime_Initialize();
1182 if (_PyStatus_EXCEPTION(status)) {
1183 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001184 }
1185 _PyRuntimeState *runtime = &_PyRuntime;
1186
Victor Stinnerb45d2592019-06-20 00:05:23 +02001187 PyThreadState *tstate = NULL;
1188 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001189 if (_PyStatus_EXCEPTION(status)) {
1190 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001191 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001192 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001193
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001194 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001195 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001196 if (_PyStatus_EXCEPTION(status)) {
1197 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001198 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001199 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001200
Victor Stinner331a6a52019-05-27 16:39:22 +02001201 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001202}
1203
1204
Eric Snow1abcf672017-05-23 21:46:51 -07001205void
Nick Coghland6009512014-11-20 21:39:37 +10001206Py_InitializeEx(int install_sigs)
1207{
Victor Stinner331a6a52019-05-27 16:39:22 +02001208 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001209
Victor Stinner331a6a52019-05-27 16:39:22 +02001210 status = _PyRuntime_Initialize();
1211 if (_PyStatus_EXCEPTION(status)) {
1212 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001213 }
1214 _PyRuntimeState *runtime = &_PyRuntime;
1215
1216 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001217 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1218 return;
1219 }
1220
Victor Stinner331a6a52019-05-27 16:39:22 +02001221 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001222 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001223
Victor Stinner1dc6e392018-07-25 02:49:17 +02001224 config.install_signal_handlers = install_sigs;
1225
Victor Stinner331a6a52019-05-27 16:39:22 +02001226 status = Py_InitializeFromConfig(&config);
1227 if (_PyStatus_EXCEPTION(status)) {
1228 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001229 }
Nick Coghland6009512014-11-20 21:39:37 +10001230}
1231
1232void
1233Py_Initialize(void)
1234{
1235 Py_InitializeEx(1);
1236}
1237
1238
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001239PyStatus
1240_Py_InitializeMain(void)
1241{
1242 PyStatus status = _PyRuntime_Initialize();
1243 if (_PyStatus_EXCEPTION(status)) {
1244 return status;
1245 }
1246 _PyRuntimeState *runtime = &_PyRuntime;
1247 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1248 return pyinit_main(tstate);
1249}
1250
1251
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001252static void
1253finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1254{
1255 // List of names to clear in sys
1256 static const char * const sys_deletes[] = {
1257 "path", "argv", "ps1", "ps2",
1258 "last_type", "last_value", "last_traceback",
1259 "path_hooks", "path_importer_cache", "meta_path",
1260 "__interactivehook__",
1261 NULL
1262 };
1263
1264 static const char * const sys_files[] = {
1265 "stdin", "__stdin__",
1266 "stdout", "__stdout__",
1267 "stderr", "__stderr__",
1268 NULL
1269 };
1270
1271 PyInterpreterState *interp = tstate->interp;
1272 if (verbose) {
1273 PySys_WriteStderr("# clear builtins._\n");
1274 }
1275 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1276 PyErr_WriteUnraisable(NULL);
1277 }
1278
1279 const char * const *p;
1280 for (p = sys_deletes; *p != NULL; p++) {
1281 if (verbose) {
1282 PySys_WriteStderr("# clear sys.%s\n", *p);
1283 }
1284 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1285 PyErr_WriteUnraisable(NULL);
1286 }
1287 }
1288 for (p = sys_files; *p != NULL; p+=2) {
1289 const char *name = p[0];
1290 const char *orig_name = p[1];
1291 if (verbose) {
1292 PySys_WriteStderr("# restore sys.%s\n", name);
1293 }
1294 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1295 orig_name);
1296 if (value == NULL) {
1297 if (_PyErr_Occurred(tstate)) {
1298 PyErr_WriteUnraisable(NULL);
1299 }
1300 value = Py_None;
1301 }
1302 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1303 PyErr_WriteUnraisable(NULL);
1304 }
1305 }
1306}
1307
1308
1309static PyObject*
1310finalize_remove_modules(PyObject *modules, int verbose)
1311{
1312 PyObject *weaklist = PyList_New(0);
1313 if (weaklist == NULL) {
1314 PyErr_WriteUnraisable(NULL);
1315 }
1316
1317#define STORE_MODULE_WEAKREF(name, mod) \
1318 if (weaklist != NULL) { \
1319 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1320 if (wr) { \
1321 PyObject *tup = PyTuple_Pack(2, name, wr); \
1322 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1323 PyErr_WriteUnraisable(NULL); \
1324 } \
1325 Py_XDECREF(tup); \
1326 Py_DECREF(wr); \
1327 } \
1328 else { \
1329 PyErr_WriteUnraisable(NULL); \
1330 } \
1331 }
1332
1333#define CLEAR_MODULE(name, mod) \
1334 if (PyModule_Check(mod)) { \
1335 if (verbose && PyUnicode_Check(name)) { \
1336 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1337 } \
1338 STORE_MODULE_WEAKREF(name, mod); \
1339 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1340 PyErr_WriteUnraisable(NULL); \
1341 } \
1342 }
1343
1344 if (PyDict_CheckExact(modules)) {
1345 Py_ssize_t pos = 0;
1346 PyObject *key, *value;
1347 while (PyDict_Next(modules, &pos, &key, &value)) {
1348 CLEAR_MODULE(key, value);
1349 }
1350 }
1351 else {
1352 PyObject *iterator = PyObject_GetIter(modules);
1353 if (iterator == NULL) {
1354 PyErr_WriteUnraisable(NULL);
1355 }
1356 else {
1357 PyObject *key;
1358 while ((key = PyIter_Next(iterator))) {
1359 PyObject *value = PyObject_GetItem(modules, key);
1360 if (value == NULL) {
1361 PyErr_WriteUnraisable(NULL);
1362 continue;
1363 }
1364 CLEAR_MODULE(key, value);
1365 Py_DECREF(value);
1366 Py_DECREF(key);
1367 }
1368 if (PyErr_Occurred()) {
1369 PyErr_WriteUnraisable(NULL);
1370 }
1371 Py_DECREF(iterator);
1372 }
1373 }
1374#undef CLEAR_MODULE
1375#undef STORE_MODULE_WEAKREF
1376
1377 return weaklist;
1378}
1379
1380
1381static void
1382finalize_clear_modules_dict(PyObject *modules)
1383{
1384 if (PyDict_CheckExact(modules)) {
1385 PyDict_Clear(modules);
1386 }
1387 else {
1388 _Py_IDENTIFIER(clear);
1389 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1390 PyErr_WriteUnraisable(NULL);
1391 }
1392 }
1393}
1394
1395
1396static void
1397finalize_restore_builtins(PyThreadState *tstate)
1398{
1399 PyInterpreterState *interp = tstate->interp;
1400 PyObject *dict = PyDict_Copy(interp->builtins);
1401 if (dict == NULL) {
1402 PyErr_WriteUnraisable(NULL);
1403 }
1404 PyDict_Clear(interp->builtins);
1405 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1406 _PyErr_Clear(tstate);
1407 }
1408 Py_XDECREF(dict);
1409}
1410
1411
1412static void
1413finalize_modules_clear_weaklist(PyInterpreterState *interp,
1414 PyObject *weaklist, int verbose)
1415{
1416 // First clear modules imported later
1417 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1418 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1419 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1420 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1421 if (mod == Py_None) {
1422 continue;
1423 }
1424 assert(PyModule_Check(mod));
1425 PyObject *dict = PyModule_GetDict(mod);
1426 if (dict == interp->builtins || dict == interp->sysdict) {
1427 continue;
1428 }
1429 Py_INCREF(mod);
1430 if (verbose && PyUnicode_Check(name)) {
1431 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1432 }
1433 _PyModule_Clear(mod);
1434 Py_DECREF(mod);
1435 }
1436}
1437
1438
1439static void
1440finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1441{
1442 // Clear sys dict
1443 if (verbose) {
1444 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1445 }
1446 _PyModule_ClearDict(interp->sysdict);
1447
1448 // Clear builtins dict
1449 if (verbose) {
1450 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1451 }
1452 _PyModule_ClearDict(interp->builtins);
1453}
1454
1455
1456/* Clear modules, as good as we can */
1457static void
1458finalize_modules(PyThreadState *tstate)
1459{
1460 PyInterpreterState *interp = tstate->interp;
1461 PyObject *modules = interp->modules;
1462 if (modules == NULL) {
1463 // Already done
1464 return;
1465 }
1466 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1467
1468 // Delete some special builtins._ and sys attributes first. These are
1469 // common places where user values hide and people complain when their
1470 // destructors fail. Since the modules containing them are
1471 // deleted *last* of all, they would come too late in the normal
1472 // destruction order. Sigh.
1473 //
1474 // XXX Perhaps these precautions are obsolete. Who knows?
1475 finalize_modules_delete_special(tstate, verbose);
1476
1477 // Remove all modules from sys.modules, hoping that garbage collection
1478 // can reclaim most of them: set all sys.modules values to None.
1479 //
1480 // We prepare a list which will receive (name, weakref) tuples of
1481 // modules when they are removed from sys.modules. The name is used
1482 // for diagnosis messages (in verbose mode), while the weakref helps
1483 // detect those modules which have been held alive.
1484 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1485
1486 // Clear the modules dict
1487 finalize_clear_modules_dict(modules);
1488
1489 // Restore the original builtins dict, to ensure that any
1490 // user data gets cleared.
1491 finalize_restore_builtins(tstate);
1492
1493 // Collect garbage
1494 _PyGC_CollectNoFail(tstate);
1495
1496 // Dump GC stats before it's too late, since it uses the warnings
1497 // machinery.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001498 _PyGC_DumpShutdownStats(interp);
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001499
1500 if (weaklist != NULL) {
1501 // Now, if there are any modules left alive, clear their globals to
1502 // minimize potential leaks. All C extension modules actually end
1503 // up here, since they are kept alive in the interpreter state.
1504 //
1505 // The special treatment of "builtins" here is because even
1506 // when it's not referenced as a module, its dictionary is
1507 // referenced by almost every module's __builtins__. Since
1508 // deleting a module clears its dictionary (even if there are
1509 // references left to it), we need to delete the "builtins"
1510 // module last. Likewise, we don't delete sys until the very
1511 // end because it is implicitly referenced (e.g. by print).
1512 //
1513 // Since dict is ordered in CPython 3.6+, modules are saved in
1514 // importing order. First clear modules imported later.
1515 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1516 Py_DECREF(weaklist);
1517 }
1518
1519 // Clear sys and builtins modules dict
1520 finalize_clear_sys_builtins_dict(interp, verbose);
1521
1522 // Clear module dict copies stored in the interpreter state:
1523 // clear PyInterpreterState.modules_by_index and
1524 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1525 // initialization API)
1526 _PyInterpreterState_ClearModules(interp);
1527
1528 // Clear and delete the modules directory. Actual modules will
1529 // still be there only if imported during the execution of some
1530 // destructor.
1531 Py_SETREF(interp->modules, NULL);
1532
1533 // Collect garbage once more
1534 _PyGC_CollectNoFail(tstate);
1535}
1536
1537
Nick Coghland6009512014-11-20 21:39:37 +10001538/* Flush stdout and stderr */
1539
1540static int
1541file_is_closed(PyObject *fobj)
1542{
1543 int r;
1544 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1545 if (tmp == NULL) {
1546 PyErr_Clear();
1547 return 0;
1548 }
1549 r = PyObject_IsTrue(tmp);
1550 Py_DECREF(tmp);
1551 if (r < 0)
1552 PyErr_Clear();
1553 return r > 0;
1554}
1555
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001556
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001557static int
Nick Coghland6009512014-11-20 21:39:37 +10001558flush_std_files(void)
1559{
1560 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1561 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1562 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001563 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001564
1565 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001566 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001567 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001568 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001569 status = -1;
1570 }
Nick Coghland6009512014-11-20 21:39:37 +10001571 else
1572 Py_DECREF(tmp);
1573 }
1574
1575 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001576 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001577 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001578 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001579 status = -1;
1580 }
Nick Coghland6009512014-11-20 21:39:37 +10001581 else
1582 Py_DECREF(tmp);
1583 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001584
1585 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001586}
1587
1588/* Undo the effect of Py_Initialize().
1589
1590 Beware: if multiple interpreter and/or thread states exist, these
1591 are not wiped out; only the current thread and interpreter state
1592 are deleted. But since everything else is deleted, those other
1593 interpreter and thread states should no longer be used.
1594
1595 (XXX We should do better, e.g. wipe out all interpreters and
1596 threads.)
1597
1598 Locking: as above.
1599
1600*/
1601
Victor Stinner7eee5be2019-11-20 10:38:34 +01001602
1603static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001604finalize_interp_types(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001605{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001606 _PyExc_Fini(interp);
1607 _PyFrame_Fini(interp);
1608 _PyAsyncGen_Fini(interp);
1609 _PyContext_Fini(interp);
1610 _PyType_Fini(interp);
Victor Stinnerea251802020-12-26 02:58:33 +01001611 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1612 // a dict internally.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001613 _PyUnicode_ClearInterned(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001614
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001615 _PyDict_Fini(interp);
1616 _PyList_Fini(interp);
1617 _PyTuple_Fini(interp);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001618
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001619 _PySlice_Fini(interp);
Victor Stinner3d483342019-11-22 12:27:50 +01001620
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001621 _PyBytes_Fini(interp);
1622 _PyUnicode_Fini(interp);
1623 _PyFloat_Fini(interp);
1624 _PyLong_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001625}
1626
1627
1628static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001629finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001630{
Victor Stinner101bf692021-02-19 13:33:31 +01001631 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001632
Victor Stinner7eee5be2019-11-20 10:38:34 +01001633 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001634 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001635
Kongedaa0fe02020-07-04 05:06:46 +08001636 /* Clear all loghooks */
1637 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1638 Call _PySys_ClearAuditHooks when PyObject available. */
1639 if (is_main_interp) {
1640 _PySys_ClearAuditHooks(tstate);
1641 }
1642
Victor Stinner7907f8c2020-06-08 01:22:36 +02001643 if (is_main_interp) {
1644 _Py_HashRandomization_Fini();
1645 _PyArg_Fini();
1646 _Py_ClearFileSystemEncoding();
1647 }
1648
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001649 finalize_interp_types(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001650}
1651
1652
1653static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001654finalize_interp_delete(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001655{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001656 if (_Py_IsMainInterpreter(interp)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001657 /* Cleanup auto-thread-state */
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001658 _PyGILState_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001659 }
1660
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001661 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1662 fail when it is being awaited by another running daemon thread (see
1663 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1664 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1665 called multiple times. */
1666
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001667 PyInterpreterState_Delete(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001668}
1669
1670
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001671int
1672Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001673{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001674 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001675
Victor Stinner8e91c242019-04-24 17:24:01 +02001676 _PyRuntimeState *runtime = &_PyRuntime;
1677 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001678 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001679 }
Nick Coghland6009512014-11-20 21:39:37 +10001680
Victor Stinnere225beb2019-06-03 18:14:24 +02001681 /* Get current thread state and interpreter pointer */
1682 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001683
Victor Stinnerb45d2592019-06-20 00:05:23 +02001684 // Wrap up existing "threading"-module-created, non-daemon threads.
1685 wait_for_thread_shutdown(tstate);
1686
1687 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001688 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001689
Nick Coghland6009512014-11-20 21:39:37 +10001690 /* The interpreter is still entirely intact at this point, and the
1691 * exit funcs may be relying on that. In particular, if some thread
1692 * or exit func is still waiting to do an import, the import machinery
1693 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001694 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001695 * Note that Threading.py uses an exit func to do a join on all the
1696 * threads created thru it, so this also protects pending imports in
1697 * the threads created via Threading.
1698 */
Nick Coghland6009512014-11-20 21:39:37 +10001699
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001700 _PyAtExit_Call(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001701
Victor Stinnerda273412017-12-15 01:46:02 +01001702 /* Copy the core config, PyInterpreterState_Delete() free
1703 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001704#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001705 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001706#endif
1707#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001708 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001709#endif
1710#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001711 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001712#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001713
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001714 /* Remaining daemon threads will automatically exit
1715 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001716 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001717 runtime->initialized = 0;
1718 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001719
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001720 /* Destroy the state of all threads of the interpreter, except of the
1721 current thread. In practice, only daemon threads should still be alive,
1722 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1723 Clear frames of other threads to call objects destructors. Destructors
1724 will be called in the current Python thread. Since
1725 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1726 can take the GIL at this point: if they try, they will exit
1727 immediately. */
1728 _PyThreadState_DeleteExcept(runtime, tstate);
1729
Victor Stinnere0deff32015-03-24 13:46:18 +01001730 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001731 if (flush_std_files() < 0) {
1732 status = -1;
1733 }
Nick Coghland6009512014-11-20 21:39:37 +10001734
1735 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001736 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001737
1738 /* Collect garbage. This may call finalizers; it's nice to call these
1739 * before all modules are destroyed.
1740 * XXX If a __del__ or weakref callback is triggered here, and tries to
1741 * XXX import a module, bad things can happen, because Python no
1742 * XXX longer believes it's initialized.
1743 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1744 * XXX is easy to provoke that way. I've also seen, e.g.,
1745 * XXX Exception exceptions.ImportError: 'No module named sha'
1746 * XXX in <function callback at 0x008F5718> ignored
1747 * XXX but I'm unclear on exactly how that one happens. In any case,
1748 * XXX I haven't seen a real-life report of either of these.
1749 */
Victor Stinner8b341482020-10-30 17:00:00 +01001750 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001751
Nick Coghland6009512014-11-20 21:39:37 +10001752 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001753 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001754
Inada Naoki91234a12019-06-03 21:30:58 +09001755 /* Print debug stats if any */
1756 _PyEval_Fini();
1757
Victor Stinnere0deff32015-03-24 13:46:18 +01001758 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001759 if (flush_std_files() < 0) {
1760 status = -1;
1761 }
Nick Coghland6009512014-11-20 21:39:37 +10001762
1763 /* Collect final garbage. This disposes of cycles created by
1764 * class definitions, for example.
1765 * XXX This is disabled because it caused too many problems. If
1766 * XXX a __del__ or weakref callback triggers here, Python code has
1767 * XXX a hard time running, because even the sys module has been
1768 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1769 * XXX One symptom is a sequence of information-free messages
1770 * XXX coming from threads (if a __del__ or callback is invoked,
1771 * XXX other threads can execute too, and any exception they encounter
1772 * XXX triggers a comedy of errors as subsystem after subsystem
1773 * XXX fails to find what it *expects* to find in sys to help report
1774 * XXX the exception and consequent unexpected failures). I've also
1775 * XXX seen segfaults then, after adding print statements to the
1776 * XXX Python code getting called.
1777 */
1778#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001779 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001780#endif
1781
1782 /* Disable tracemalloc after all Python objects have been destroyed,
1783 so it is possible to use tracemalloc in objects destructor. */
1784 _PyTraceMalloc_Fini();
1785
1786 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1787 _PyImport_Fini();
1788
Nick Coghland6009512014-11-20 21:39:37 +10001789 /* unload faulthandler module */
1790 _PyFaulthandler_Fini();
1791
Nick Coghland6009512014-11-20 21:39:37 +10001792 /* dump hash stats */
1793 _PyHash_Fini();
1794
Eric Snowdae02762017-09-14 00:35:58 -07001795#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001796 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001797 _PyDebug_PrintTotalRefs();
1798 }
Eric Snowdae02762017-09-14 00:35:58 -07001799#endif
Nick Coghland6009512014-11-20 21:39:37 +10001800
1801#ifdef Py_TRACE_REFS
1802 /* Display all objects still alive -- this can invoke arbitrary
1803 * __repr__ overrides, so requires a mostly-intact interpreter.
1804 * Alas, a lot of stuff may still be alive now that will be cleaned
1805 * up later.
1806 */
Victor Stinnerda273412017-12-15 01:46:02 +01001807 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001808 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001809 }
Nick Coghland6009512014-11-20 21:39:37 +10001810#endif /* Py_TRACE_REFS */
1811
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001812 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001813 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001814
1815#ifdef Py_TRACE_REFS
1816 /* Display addresses (& refcnts) of all objects still alive.
1817 * An address can be used to find the repr of the object, printed
1818 * above by _Py_PrintReferences.
1819 */
Victor Stinnerda273412017-12-15 01:46:02 +01001820 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001821 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001822 }
Nick Coghland6009512014-11-20 21:39:37 +10001823#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001824#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001825 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001826 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001827 }
Nick Coghland6009512014-11-20 21:39:37 +10001828#endif
1829
Victor Stinner8e91c242019-04-24 17:24:01 +02001830 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001831
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001832 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001833 return status;
1834}
1835
1836void
1837Py_Finalize(void)
1838{
1839 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001840}
1841
Victor Stinnerb0051362019-11-22 17:52:42 +01001842
Nick Coghland6009512014-11-20 21:39:37 +10001843/* Create and initialize a new interpreter and thread, and return the
1844 new thread. This requires that Py_Initialize() has been called
1845 first.
1846
1847 Unsuccessful initialization yields a NULL pointer. Note that *no*
1848 exception information is available even in this case -- the
1849 exception information is held in the thread, and there is no
1850 thread.
1851
1852 Locking: as above.
1853
1854*/
1855
Victor Stinner331a6a52019-05-27 16:39:22 +02001856static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001857new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001858{
Victor Stinner331a6a52019-05-27 16:39:22 +02001859 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001860
Victor Stinner331a6a52019-05-27 16:39:22 +02001861 status = _PyRuntime_Initialize();
1862 if (_PyStatus_EXCEPTION(status)) {
1863 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001864 }
1865 _PyRuntimeState *runtime = &_PyRuntime;
1866
1867 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001868 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001869 }
Nick Coghland6009512014-11-20 21:39:37 +10001870
Victor Stinner8a1be612016-03-14 22:07:55 +01001871 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1872 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001873 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001874
Victor Stinner43125222019-04-24 18:23:53 +02001875 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001876 if (interp == NULL) {
1877 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001878 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001879 }
Nick Coghland6009512014-11-20 21:39:37 +10001880
Victor Stinner43125222019-04-24 18:23:53 +02001881 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001882 if (tstate == NULL) {
1883 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001884 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001885 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001886 }
1887
Victor Stinner43125222019-04-24 18:23:53 +02001888 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001889
Eric Snow1abcf672017-05-23 21:46:51 -07001890 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001891 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001892#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001893 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001894 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001895 }
1896 else
1897#endif
1898 {
Eric Snow1abcf672017-05-23 21:46:51 -07001899 /* No current thread state, copy from the main interpreter */
1900 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001901 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001902 }
1903
Victor Stinner048a3562020-11-05 00:45:56 +01001904
1905 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001906 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001907 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001908 }
Victor Stinner252346a2020-05-01 11:33:44 +02001909 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001910
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001911 status = init_interp_create_gil(tstate);
1912 if (_PyStatus_EXCEPTION(status)) {
1913 goto error;
1914 }
1915
Victor Stinnerd863ade2019-12-06 03:37:07 +01001916 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001917 if (_PyStatus_EXCEPTION(status)) {
1918 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001919 }
1920
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001921 status = init_interp_main(tstate);
1922 if (_PyStatus_EXCEPTION(status)) {
1923 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001924 }
Nick Coghland6009512014-11-20 21:39:37 +10001925
Victor Stinnera7368ac2017-11-15 18:11:45 -08001926 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001927 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001928
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001929error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001930 *tstate_p = NULL;
1931
1932 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001933 PyErr_PrintEx(0);
1934 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001935 PyThreadState_Delete(tstate);
1936 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001937 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001938
Victor Stinnerb0051362019-11-22 17:52:42 +01001939 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001940}
1941
1942PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001943_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001944{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001945 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001946 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001947 if (_PyStatus_EXCEPTION(status)) {
1948 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001949 }
1950 return tstate;
1951
Nick Coghland6009512014-11-20 21:39:37 +10001952}
1953
Victor Stinner252346a2020-05-01 11:33:44 +02001954PyThreadState *
1955Py_NewInterpreter(void)
1956{
1957 return _Py_NewInterpreter(0);
1958}
1959
Nick Coghland6009512014-11-20 21:39:37 +10001960/* Delete an interpreter and its last thread. This requires that the
1961 given thread state is current, that the thread has no remaining
1962 frames, and that it is its interpreter's only remaining thread.
1963 It is a fatal error to violate these constraints.
1964
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001965 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001966 everything, regardless.)
1967
1968 Locking: as above.
1969
1970*/
1971
1972void
1973Py_EndInterpreter(PyThreadState *tstate)
1974{
1975 PyInterpreterState *interp = tstate->interp;
1976
Victor Stinnerb45d2592019-06-20 00:05:23 +02001977 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001978 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001979 }
1980 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001981 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001982 }
Eric Snow5be45a62019-03-08 22:47:07 -07001983 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001984
Eric Snow842a2f02019-03-15 15:47:51 -06001985 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001986 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001987
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001988 _PyAtExit_Call(tstate->interp);
Marcel Plch776407f2017-12-20 11:17:58 +01001989
Victor Stinnerb45d2592019-06-20 00:05:23 +02001990 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001991 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001992 }
Nick Coghland6009512014-11-20 21:39:37 +10001993
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001994 finalize_modules(tstate);
1995
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001996 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001997 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001998}
1999
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002000/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10002001
Victor Stinner331a6a52019-05-27 16:39:22 +02002002static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002003add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10002004{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002005 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10002006 m = PyImport_AddModule("__main__");
2007 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02002008 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002009
Nick Coghland6009512014-11-20 21:39:37 +10002010 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002011 ann_dict = PyDict_New();
2012 if ((ann_dict == NULL) ||
2013 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002014 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002015 }
2016 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002017
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002018 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
2019 if (PyErr_Occurred()) {
2020 return _PyStatus_ERR("Failed to test __main__.__builtins__");
2021 }
Nick Coghland6009512014-11-20 21:39:37 +10002022 PyObject *bimod = PyImport_ImportModule("builtins");
2023 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002024 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10002025 }
2026 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002027 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002028 }
2029 Py_DECREF(bimod);
2030 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002031
Nick Coghland6009512014-11-20 21:39:37 +10002032 /* Main is a little special - imp.is_builtin("__main__") will return
2033 * False, but BuiltinImporter is still the most appropriate initial
2034 * setting for its __loader__ attribute. A more suitable value will
2035 * be set if __main__ gets further initialized later in the startup
2036 * process.
2037 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002038 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002039 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002040 if (PyErr_Occurred()) {
2041 return _PyStatus_ERR("Failed to test __main__.__loader__");
2042 }
Nick Coghland6009512014-11-20 21:39:37 +10002043 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2044 "BuiltinImporter");
2045 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002046 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002047 }
2048 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002049 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002050 }
2051 Py_DECREF(loader);
2052 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002053 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002054}
2055
Nick Coghland6009512014-11-20 21:39:37 +10002056/* Import the site module (not into __main__ though) */
2057
Victor Stinner331a6a52019-05-27 16:39:22 +02002058static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002059init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002060{
2061 PyObject *m;
2062 m = PyImport_ImportModule("site");
2063 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002064 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002065 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002066 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002067 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002068}
2069
Victor Stinner874dbe82015-09-04 17:29:57 +02002070/* Check if a file descriptor is valid or not.
2071 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2072static int
2073is_valid_fd(int fd)
2074{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002075/* dup() is faster than fstat(): fstat() can require input/output operations,
2076 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2077 startup. Problem: dup() doesn't check if the file descriptor is valid on
2078 some platforms.
2079
2080 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2081 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2082 EBADF. FreeBSD has similar issue (bpo-32849).
2083
2084 Only use dup() on platforms where dup() is enough to detect invalid FD in
2085 corner cases: on Linux and Windows (bpo-32849). */
2086#if defined(__linux__) || defined(MS_WINDOWS)
2087 if (fd < 0) {
2088 return 0;
2089 }
2090 int fd2;
2091
2092 _Py_BEGIN_SUPPRESS_IPH
2093 fd2 = dup(fd);
2094 if (fd2 >= 0) {
2095 close(fd2);
2096 }
2097 _Py_END_SUPPRESS_IPH
2098
2099 return (fd2 >= 0);
2100#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002101 struct stat st;
2102 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002103#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002104}
2105
2106/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002107static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002108create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002109 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002110 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002111{
2112 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2113 const char* mode;
2114 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002115 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002116 int buffering, isatty;
2117 _Py_IDENTIFIER(open);
2118 _Py_IDENTIFIER(isatty);
2119 _Py_IDENTIFIER(TextIOWrapper);
2120 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002121 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002122
Victor Stinner874dbe82015-09-04 17:29:57 +02002123 if (!is_valid_fd(fd))
2124 Py_RETURN_NONE;
2125
Nick Coghland6009512014-11-20 21:39:37 +10002126 /* stdin is always opened in buffered mode, first because it shouldn't
2127 make a difference in common use cases, second because TextIOWrapper
2128 depends on the presence of a read1() method which only exists on
2129 buffered streams.
2130 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002131 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002132 buffering = 0;
2133 else
2134 buffering = -1;
2135 if (write_mode)
2136 mode = "wb";
2137 else
2138 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002139 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002140 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002141 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002142 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002143 if (buf == NULL)
2144 goto error;
2145
2146 if (buffering) {
2147 _Py_IDENTIFIER(raw);
2148 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2149 if (raw == NULL)
2150 goto error;
2151 }
2152 else {
2153 raw = buf;
2154 Py_INCREF(raw);
2155 }
2156
Steve Dower39294992016-08-30 21:22:36 -07002157#ifdef MS_WINDOWS
2158 /* Windows console IO is always UTF-8 encoded */
2159 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002160 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002161#endif
2162
Nick Coghland6009512014-11-20 21:39:37 +10002163 text = PyUnicode_FromString(name);
2164 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2165 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002166 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002167 if (res == NULL)
2168 goto error;
2169 isatty = PyObject_IsTrue(res);
2170 Py_DECREF(res);
2171 if (isatty == -1)
2172 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002173 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002174 write_through = Py_True;
2175 else
2176 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002177 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002178 line_buffering = Py_True;
2179 else
2180 line_buffering = Py_False;
2181
2182 Py_CLEAR(raw);
2183 Py_CLEAR(text);
2184
2185#ifdef MS_WINDOWS
2186 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2187 newlines to "\n".
2188 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2189 newline = NULL;
2190#else
2191 /* sys.stdin: split lines at "\n".
2192 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2193 newline = "\n";
2194#endif
2195
Victor Stinner709d23d2019-05-02 14:56:30 -04002196 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2197 if (encoding_str == NULL) {
2198 Py_CLEAR(buf);
2199 goto error;
2200 }
2201
2202 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2203 if (errors_str == NULL) {
2204 Py_CLEAR(buf);
2205 Py_CLEAR(encoding_str);
2206 goto error;
2207 }
2208
2209 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2210 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002211 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002212 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002213 Py_CLEAR(encoding_str);
2214 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002215 if (stream == NULL)
2216 goto error;
2217
2218 if (write_mode)
2219 mode = "w";
2220 else
2221 mode = "r";
2222 text = PyUnicode_FromString(mode);
2223 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2224 goto error;
2225 Py_CLEAR(text);
2226 return stream;
2227
2228error:
2229 Py_XDECREF(buf);
2230 Py_XDECREF(stream);
2231 Py_XDECREF(text);
2232 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002233
Victor Stinner874dbe82015-09-04 17:29:57 +02002234 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2235 /* Issue #24891: the file descriptor was closed after the first
2236 is_valid_fd() check was called. Ignore the OSError and set the
2237 stream to None. */
2238 PyErr_Clear();
2239 Py_RETURN_NONE;
2240 }
2241 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002242}
2243
Victor Stinner77d668b2021-04-12 10:44:53 +02002244/* Set builtins.open to io.open */
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002245static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002246init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002247{
2248 PyObject *iomod = NULL, *wrapper;
2249 PyObject *bimod = NULL;
2250 PyStatus res = _PyStatus_OK();
2251
2252 if (!(iomod = PyImport_ImportModule("io"))) {
2253 goto error;
2254 }
2255
2256 if (!(bimod = PyImport_ImportModule("builtins"))) {
2257 goto error;
2258 }
2259
Victor Stinner77d668b2021-04-12 10:44:53 +02002260 if (!(wrapper = PyObject_GetAttrString(iomod, "open"))) {
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002261 goto error;
2262 }
2263
2264 /* Set builtins.open */
2265 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2266 Py_DECREF(wrapper);
2267 goto error;
2268 }
2269 Py_DECREF(wrapper);
2270 goto done;
2271
2272error:
2273 res = _PyStatus_ERR("can't initialize io.open");
2274
2275done:
2276 Py_XDECREF(bimod);
2277 Py_XDECREF(iomod);
2278 return res;
2279}
2280
2281
Victor Stinner77d668b2021-04-12 10:44:53 +02002282/* Create sys.stdin, sys.stdout and sys.stderr */
Victor Stinner331a6a52019-05-27 16:39:22 +02002283static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002284init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002285{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002286 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002287 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002288 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002289 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002290 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002291 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002292
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002293 /* Check that stdin is not a directory
2294 Using shell redirection, you can redirect stdin to a directory,
2295 crashing the Python interpreter. Catch this common mistake here
2296 and output a useful error message. Note that under MS Windows,
2297 the shell already prevents that. */
2298#ifndef MS_WINDOWS
2299 struct _Py_stat_struct sb;
2300 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2301 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002302 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002303 }
2304#endif
2305
Nick Coghland6009512014-11-20 21:39:37 +10002306 if (!(iomod = PyImport_ImportModule("io"))) {
2307 goto error;
2308 }
Nick Coghland6009512014-11-20 21:39:37 +10002309
Nick Coghland6009512014-11-20 21:39:37 +10002310 /* Set sys.stdin */
2311 fd = fileno(stdin);
2312 /* Under some conditions stdin, stdout and stderr may not be connected
2313 * and fileno() may point to an invalid file descriptor. For example
2314 * GUI apps don't have valid standard streams by default.
2315 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002316 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002317 config->stdio_encoding,
2318 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002319 if (std == NULL)
2320 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002321 PySys_SetObject("__stdin__", std);
2322 _PySys_SetObjectId(&PyId_stdin, std);
2323 Py_DECREF(std);
2324
2325 /* Set sys.stdout */
2326 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002327 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002328 config->stdio_encoding,
2329 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002330 if (std == NULL)
2331 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002332 PySys_SetObject("__stdout__", std);
2333 _PySys_SetObjectId(&PyId_stdout, std);
2334 Py_DECREF(std);
2335
2336#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2337 /* Set sys.stderr, replaces the preliminary stderr */
2338 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002339 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002340 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002341 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002342 if (std == NULL)
2343 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002344
2345 /* Same as hack above, pre-import stderr's codec to avoid recursion
2346 when import.c tries to write to stderr in verbose mode. */
2347 encoding_attr = PyObject_GetAttrString(std, "encoding");
2348 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002349 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002350 if (std_encoding != NULL) {
2351 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2352 Py_XDECREF(codec_info);
2353 }
2354 Py_DECREF(encoding_attr);
2355 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002356 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002357
2358 if (PySys_SetObject("__stderr__", std) < 0) {
2359 Py_DECREF(std);
2360 goto error;
2361 }
2362 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2363 Py_DECREF(std);
2364 goto error;
2365 }
2366 Py_DECREF(std);
2367#endif
2368
Victor Stinnera7368ac2017-11-15 18:11:45 -08002369 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002370
Victor Stinnera7368ac2017-11-15 18:11:45 -08002371error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002372 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002373
2374done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002375 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002376 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002377 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002378}
2379
2380
Victor Stinner10dc4842015-03-24 12:01:30 +01002381static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002382_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2383 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002384{
Victor Stinner314b8782021-01-18 18:34:56 +01002385 PUTS(fd, "\n");
Victor Stinner10dc4842015-03-24 12:01:30 +01002386
2387 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002388 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002389}
Victor Stinner791da1c2016-03-14 16:53:12 +01002390
2391/* Print the current exception (if an exception is set) with its traceback,
2392 or display the current Python stack.
2393
2394 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2395 called on catastrophic cases.
2396
2397 Return 1 if the traceback was displayed, 0 otherwise. */
2398
2399static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002400_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002401{
2402 PyObject *ferr, *res;
2403 PyObject *exception, *v, *tb;
2404 int has_tb;
2405
Victor Stinnerb45d2592019-06-20 00:05:23 +02002406 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002407 if (exception == NULL) {
2408 /* No current exception */
2409 return 0;
2410 }
2411
2412 ferr = _PySys_GetObjectId(&PyId_stderr);
2413 if (ferr == NULL || ferr == Py_None) {
2414 /* sys.stderr is not set yet or set to None,
2415 no need to try to display the exception */
2416 return 0;
2417 }
2418
Victor Stinnerb45d2592019-06-20 00:05:23 +02002419 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002420 if (tb == NULL) {
2421 tb = Py_None;
2422 Py_INCREF(tb);
2423 }
2424 PyException_SetTraceback(v, tb);
2425 if (exception == NULL) {
2426 /* PyErr_NormalizeException() failed */
2427 return 0;
2428 }
2429
2430 has_tb = (tb != Py_None);
2431 PyErr_Display(exception, v, tb);
2432 Py_XDECREF(exception);
2433 Py_XDECREF(v);
2434 Py_XDECREF(tb);
2435
2436 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002437 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002438 if (res == NULL) {
2439 _PyErr_Clear(tstate);
2440 }
2441 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002442 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002443 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002444
2445 return has_tb;
2446}
2447
Nick Coghland6009512014-11-20 21:39:37 +10002448/* Print fatal error message and abort */
2449
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002450#ifdef MS_WINDOWS
2451static void
2452fatal_output_debug(const char *msg)
2453{
2454 /* buffer of 256 bytes allocated on the stack */
2455 WCHAR buffer[256 / sizeof(WCHAR)];
2456 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2457 size_t msglen;
2458
2459 OutputDebugStringW(L"Fatal Python error: ");
2460
2461 msglen = strlen(msg);
2462 while (msglen) {
2463 size_t i;
2464
2465 if (buflen > msglen) {
2466 buflen = msglen;
2467 }
2468
2469 /* Convert the message to wchar_t. This uses a simple one-to-one
2470 conversion, assuming that the this error message actually uses
2471 ASCII only. If this ceases to be true, we will have to convert. */
2472 for (i=0; i < buflen; ++i) {
2473 buffer[i] = msg[i];
2474 }
2475 buffer[i] = L'\0';
2476 OutputDebugStringW(buffer);
2477
2478 msg += buflen;
2479 msglen -= buflen;
2480 }
2481 OutputDebugStringW(L"\n");
2482}
2483#endif
2484
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002485
2486static void
Victor Stinner314b8782021-01-18 18:34:56 +01002487fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002488{
Victor Stinner314b8782021-01-18 18:34:56 +01002489 PUTS(fd, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002490 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2491 if (finalizing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002492 PUTS(fd, "finalizing (tstate=0x");
2493 _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
2494 PUTS(fd, ")");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002495 }
2496 else if (runtime->initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002497 PUTS(fd, "initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002498 }
2499 else if (runtime->core_initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002500 PUTS(fd, "core initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002501 }
2502 else if (runtime->preinitialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002503 PUTS(fd, "preinitialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002504 }
2505 else if (runtime->preinitializing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002506 PUTS(fd, "preinitializing");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002507 }
2508 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002509 PUTS(fd, "unknown");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002510 }
Victor Stinner314b8782021-01-18 18:34:56 +01002511 PUTS(fd, "\n");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002512}
2513
2514
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002515static inline void _Py_NO_RETURN
2516fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002517{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002518 if (status < 0) {
2519#if defined(MS_WINDOWS) && defined(_DEBUG)
2520 DebugBreak();
2521#endif
2522 abort();
2523 }
2524 else {
2525 exit(status);
2526 }
2527}
2528
2529
Victor Stinner66f77ca2021-01-19 23:35:27 +01002530// Dump the list of extension modules of sys.modules, excluding stdlib modules
Victor Stinner9852cb32021-01-25 23:12:50 +01002531// (sys.stdlib_module_names), into fd file descriptor.
Victor Stinner66f77ca2021-01-19 23:35:27 +01002532//
Victor Stinner250035d2021-01-18 20:47:13 +01002533// This function is called by a signal handler in faulthandler: avoid memory
Victor Stinner66f77ca2021-01-19 23:35:27 +01002534// allocations and keep the implementation simple. For example, the list is not
2535// sorted on purpose.
Victor Stinner250035d2021-01-18 20:47:13 +01002536void
2537_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
2538{
2539 if (interp == NULL) {
2540 return;
2541 }
2542 PyObject *modules = interp->modules;
Victor Stinner66f77ca2021-01-19 23:35:27 +01002543 if (modules == NULL || !PyDict_Check(modules)) {
Victor Stinner250035d2021-01-18 20:47:13 +01002544 return;
2545 }
2546
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002547 Py_ssize_t pos;
2548 PyObject *key, *value;
2549
2550 // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
2551 // memory cannot be allocated on the heap in a signal handler.
2552 // Iterate on the dict instead.
Victor Stinner9852cb32021-01-25 23:12:50 +01002553 PyObject *stdlib_module_names = NULL;
Victor Stinner3d55aa92021-04-07 23:12:45 +02002554 if (interp->sysdict != NULL) {
2555 pos = 0;
2556 while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
2557 if (PyUnicode_Check(key)
2558 && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
2559 stdlib_module_names = value;
2560 break;
2561 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002562 }
2563 }
Victor Stinner9852cb32021-01-25 23:12:50 +01002564 // If we failed to get sys.stdlib_module_names or it's not a frozenset,
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002565 // don't exclude stdlib modules.
Victor Stinner9852cb32021-01-25 23:12:50 +01002566 if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
2567 stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002568 }
2569
2570 // List extensions
Victor Stinner66f77ca2021-01-19 23:35:27 +01002571 int header = 1;
2572 Py_ssize_t count = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002573 pos = 0;
Victor Stinner250035d2021-01-18 20:47:13 +01002574 while (PyDict_Next(modules, &pos, &key, &value)) {
2575 if (!PyUnicode_Check(key)) {
2576 continue;
2577 }
2578 if (!_PyModule_IsExtension(value)) {
2579 continue;
2580 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002581 // Use the module name from the sys.modules key,
2582 // don't attempt to get the module object name.
Victor Stinner9852cb32021-01-25 23:12:50 +01002583 if (stdlib_module_names != NULL) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002584 int is_stdlib_ext = 0;
2585
Victor Stinner9852cb32021-01-25 23:12:50 +01002586 Py_ssize_t i = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002587 PyObject *item;
2588 Py_hash_t hash;
Victor Stinner9852cb32021-01-25 23:12:50 +01002589 while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002590 if (PyUnicode_Check(item)
2591 && PyUnicode_Compare(key, item) == 0)
2592 {
2593 is_stdlib_ext = 1;
2594 break;
2595 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002596 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002597 if (is_stdlib_ext) {
2598 // Ignore stdlib extension
2599 continue;
2600 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002601 }
2602
2603 if (header) {
2604 PUTS(fd, "\nExtension modules: ");
2605 header = 0;
2606 }
2607 else {
Victor Stinner250035d2021-01-18 20:47:13 +01002608 PUTS(fd, ", ");
2609 }
Victor Stinner250035d2021-01-18 20:47:13 +01002610
2611 _Py_DumpASCII(fd, key);
Victor Stinner66f77ca2021-01-19 23:35:27 +01002612 count++;
Victor Stinner250035d2021-01-18 20:47:13 +01002613 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002614
2615 if (count) {
2616 PUTS(fd, " (total: ");
2617 _Py_DumpDecimal(fd, count);
2618 PUTS(fd, ")");
2619 PUTS(fd, "\n");
2620 }
Victor Stinner250035d2021-01-18 20:47:13 +01002621}
2622
2623
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002624static void _Py_NO_RETURN
Victor Stinner314b8782021-01-18 18:34:56 +01002625fatal_error(int fd, int header, const char *prefix, const char *msg,
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002626 int status)
2627{
Victor Stinner53345a42015-03-25 01:55:14 +01002628 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002629
2630 if (reentrant) {
2631 /* Py_FatalError() caused a second fatal error.
2632 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002633 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002634 }
2635 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002636
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002637 if (header) {
Victor Stinner314b8782021-01-18 18:34:56 +01002638 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002639 if (prefix) {
Victor Stinner314b8782021-01-18 18:34:56 +01002640 PUTS(fd, prefix);
2641 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002642 }
2643 if (msg) {
Victor Stinner314b8782021-01-18 18:34:56 +01002644 PUTS(fd, msg);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002645 }
2646 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002647 PUTS(fd, "<message not set>");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002648 }
Victor Stinner314b8782021-01-18 18:34:56 +01002649 PUTS(fd, "\n");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002650 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002651
2652 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner314b8782021-01-18 18:34:56 +01002653 fatal_error_dump_runtime(fd, runtime);
Victor Stinner10dc4842015-03-24 12:01:30 +01002654
Victor Stinner3a228ab2018-11-01 00:26:41 +01002655 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002656 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002657
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002658 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2659 has no Python thread state.
2660
2661 tss_tstate != tstate if the current Python thread does not hold the GIL.
2662 */
Victor Stinner314b8782021-01-18 18:34:56 +01002663 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2664 PyInterpreterState *interp = NULL;
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002665 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
Victor Stinner314b8782021-01-18 18:34:56 +01002666 if (tstate != NULL) {
2667 interp = tstate->interp;
2668 }
2669 else if (tss_tstate != NULL) {
2670 interp = tss_tstate->interp;
2671 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002672 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner314b8782021-01-18 18:34:56 +01002673
Victor Stinner3a228ab2018-11-01 00:26:41 +01002674 if (has_tstate_and_gil) {
2675 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002676 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002677 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002678 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002679 }
2680 }
2681 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002682 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002683 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002684
Victor Stinner250035d2021-01-18 20:47:13 +01002685 _Py_DumpExtensionModules(fd, interp);
2686
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002687 /* The main purpose of faulthandler is to display the traceback.
2688 This function already did its best to display a traceback.
2689 Disable faulthandler to prevent writing a second traceback
2690 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002691 _PyFaulthandler_Fini();
2692
Victor Stinner791da1c2016-03-14 16:53:12 +01002693 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002694 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002695 /* Flush sys.stdout and sys.stderr */
2696 flush_std_files();
2697 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002698
Nick Coghland6009512014-11-20 21:39:37 +10002699#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002700 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002701#endif /* MS_WINDOWS */
2702
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002703 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002704}
2705
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002706
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002707#undef Py_FatalError
2708
Victor Stinner19760862017-12-20 01:41:59 +01002709void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002710Py_FatalError(const char *msg)
2711{
Victor Stinner314b8782021-01-18 18:34:56 +01002712 fatal_error(fileno(stderr), 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002713}
2714
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002715
Victor Stinner19760862017-12-20 01:41:59 +01002716void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002717_Py_FatalErrorFunc(const char *func, const char *msg)
2718{
Victor Stinner314b8782021-01-18 18:34:56 +01002719 fatal_error(fileno(stderr), 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002720}
2721
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002722
2723void _Py_NO_RETURN
2724_Py_FatalErrorFormat(const char *func, const char *format, ...)
2725{
2726 static int reentrant = 0;
2727 if (reentrant) {
2728 /* _Py_FatalErrorFormat() caused a second fatal error */
2729 fatal_error_exit(-1);
2730 }
2731 reentrant = 1;
2732
2733 FILE *stream = stderr;
Victor Stinner314b8782021-01-18 18:34:56 +01002734 const int fd = fileno(stream);
2735 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002736 if (func) {
Victor Stinner314b8782021-01-18 18:34:56 +01002737 PUTS(fd, func);
2738 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002739 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002740
2741 va_list vargs;
2742#ifdef HAVE_STDARG_PROTOTYPES
2743 va_start(vargs, format);
2744#else
2745 va_start(vargs);
2746#endif
2747 vfprintf(stream, format, vargs);
2748 va_end(vargs);
2749
2750 fputs("\n", stream);
2751 fflush(stream);
2752
Victor Stinner314b8782021-01-18 18:34:56 +01002753 fatal_error(fd, 0, NULL, NULL, -1);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002754}
2755
2756
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002757void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002758Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002759{
Victor Stinner331a6a52019-05-27 16:39:22 +02002760 if (_PyStatus_IS_EXIT(status)) {
2761 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002762 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002763 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner314b8782021-01-18 18:34:56 +01002764 fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002765 }
2766 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002767 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002768 }
Nick Coghland6009512014-11-20 21:39:37 +10002769}
2770
Victor Stinner357704c2020-12-14 23:07:54 +01002771
Nick Coghland6009512014-11-20 21:39:37 +10002772/* Wait until threading._shutdown completes, provided
2773 the threading module was imported in the first place.
2774 The shutdown routine will wait until all non-daemon
2775 "threading" threads have completed. */
2776static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002777wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002778{
Nick Coghland6009512014-11-20 21:39:37 +10002779 _Py_IDENTIFIER(_shutdown);
2780 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002781 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002782 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002783 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002784 PyErr_WriteUnraisable(NULL);
2785 }
2786 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002787 return;
2788 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002789 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002790 if (result == NULL) {
2791 PyErr_WriteUnraisable(threading);
2792 }
2793 else {
2794 Py_DECREF(result);
2795 }
2796 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002797}
2798
2799#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002800int Py_AtExit(void (*func)(void))
2801{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002802 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002803 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002804 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002805 return 0;
2806}
2807
2808static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002809call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002810{
Victor Stinner8e91c242019-04-24 17:24:01 +02002811 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002812 /* pop last function from the list */
2813 runtime->nexitfuncs--;
2814 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2815 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2816
2817 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002818 }
Nick Coghland6009512014-11-20 21:39:37 +10002819
2820 fflush(stdout);
2821 fflush(stderr);
2822}
2823
Victor Stinnercfc88312018-08-01 16:41:25 +02002824void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002825Py_Exit(int sts)
2826{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002827 if (Py_FinalizeEx() < 0) {
2828 sts = 120;
2829 }
Nick Coghland6009512014-11-20 21:39:37 +10002830
2831 exit(sts);
2832}
2833
Nick Coghland6009512014-11-20 21:39:37 +10002834
Nick Coghland6009512014-11-20 21:39:37 +10002835/*
2836 * The file descriptor fd is considered ``interactive'' if either
2837 * a) isatty(fd) is TRUE, or
2838 * b) the -i flag was given, and the filename associated with
2839 * the descriptor is NULL or "<stdin>" or "???".
2840 */
2841int
2842Py_FdIsInteractive(FILE *fp, const char *filename)
2843{
2844 if (isatty((int)fileno(fp)))
2845 return 1;
2846 if (!Py_InteractiveFlag)
2847 return 0;
2848 return (filename == NULL) ||
2849 (strcmp(filename, "<stdin>") == 0) ||
2850 (strcmp(filename, "???") == 0);
2851}
2852
2853
Victor Stinnera82f63f2020-12-09 22:37:27 +01002854int
2855_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2856{
2857 if (isatty((int)fileno(fp))) {
2858 return 1;
2859 }
2860 if (!Py_InteractiveFlag) {
2861 return 0;
2862 }
2863 return (filename == NULL) ||
2864 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2865 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2866}
2867
2868
Nick Coghland6009512014-11-20 21:39:37 +10002869/* Wrappers around sigaction() or signal(). */
2870
2871PyOS_sighandler_t
2872PyOS_getsig(int sig)
2873{
2874#ifdef HAVE_SIGACTION
2875 struct sigaction context;
2876 if (sigaction(sig, NULL, &context) == -1)
2877 return SIG_ERR;
2878 return context.sa_handler;
2879#else
2880 PyOS_sighandler_t handler;
2881/* Special signal handling for the secure CRT in Visual Studio 2005 */
2882#if defined(_MSC_VER) && _MSC_VER >= 1400
2883 switch (sig) {
2884 /* Only these signals are valid */
2885 case SIGINT:
2886 case SIGILL:
2887 case SIGFPE:
2888 case SIGSEGV:
2889 case SIGTERM:
2890 case SIGBREAK:
2891 case SIGABRT:
2892 break;
2893 /* Don't call signal() with other values or it will assert */
2894 default:
2895 return SIG_ERR;
2896 }
2897#endif /* _MSC_VER && _MSC_VER >= 1400 */
2898 handler = signal(sig, SIG_IGN);
2899 if (handler != SIG_ERR)
2900 signal(sig, handler);
2901 return handler;
2902#endif
2903}
2904
2905/*
2906 * All of the code in this function must only use async-signal-safe functions,
2907 * listed at `man 7 signal` or
2908 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2909 */
2910PyOS_sighandler_t
2911PyOS_setsig(int sig, PyOS_sighandler_t handler)
2912{
2913#ifdef HAVE_SIGACTION
2914 /* Some code in Modules/signalmodule.c depends on sigaction() being
2915 * used here if HAVE_SIGACTION is defined. Fix that if this code
2916 * changes to invalidate that assumption.
2917 */
2918 struct sigaction context, ocontext;
2919 context.sa_handler = handler;
2920 sigemptyset(&context.sa_mask);
Gregory P. Smith02ac6f42021-03-04 21:49:30 -08002921 /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
2922 * extension module or embedding code may use where tiny thread stacks
2923 * are used. https://bugs.python.org/issue43390 */
2924 context.sa_flags = SA_ONSTACK;
Nick Coghland6009512014-11-20 21:39:37 +10002925 if (sigaction(sig, &context, &ocontext) == -1)
2926 return SIG_ERR;
2927 return ocontext.sa_handler;
2928#else
2929 PyOS_sighandler_t oldhandler;
2930 oldhandler = signal(sig, handler);
2931#ifdef HAVE_SIGINTERRUPT
2932 siginterrupt(sig, 1);
2933#endif
2934 return oldhandler;
2935#endif
2936}
2937
2938#ifdef __cplusplus
2939}
2940#endif