blob: d31a9c15fd1ec57ff59f9bc5df73099f798cf87b [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
Miss Islington (bot)ebba2862021-07-29 08:20:58 -070020#if defined(__APPLE__)
21#include <mach-o/loader.h>
22#endif
23
Nick Coghland6009512014-11-20 21:39:37 +100024#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020025# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100026#endif
27
28#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020029# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100030#endif
31
32#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020033# undef BYTE
34# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
Victor Stinner4f98f462020-04-15 04:01:58 +020036 extern PyTypeObject PyWindowsConsoleIO_Type;
37# define PyWindowsConsoleIO_Check(op) \
38 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100039#endif
40
Victor Stinner314b8782021-01-18 18:34:56 +010041#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
42
43
Nick Coghland6009512014-11-20 21:39:37 +100044_Py_IDENTIFIER(flush);
45_Py_IDENTIFIER(name);
46_Py_IDENTIFIER(stdin);
47_Py_IDENTIFIER(stdout);
48_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060049_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100050
51#ifdef __cplusplus
52extern "C" {
53#endif
54
Nick Coghland6009512014-11-20 21:39:37 +100055
Victor Stinnerb45d2592019-06-20 00:05:23 +020056/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020057static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020058static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050059static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020060static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020061static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020062static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100063
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080064int _Py_UnhandledKeyboardInterrupt = 0;
Miss Islington (bot)ebba2862021-07-29 08:20:58 -070065
66/* The following places the `_PyRuntime` structure in a location that can be
67 * found without any external information. This is meant to ease access to the
68 * interpreter state for various runtime debugging tools, but is *not* an
69 * officially supported feature */
70
71#if defined(MS_WINDOWS)
72
73#pragma section("PyRuntime", read, write)
74__declspec(allocate("PyRuntime"))
75
76#elif defined(__APPLE__)
77
78__attribute__((
79 section(SEG_DATA ",PyRuntime")
80))
81
82#endif
83
84_PyRuntimeState _PyRuntime
85#if defined(__linux__) && (defined(__GNUC__) || defined(__clang__))
86__attribute__ ((section (".PyRuntime")))
87#endif
88= _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010089static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090
Victor Stinner331a6a52019-05-27 16:39:22 +020091PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092_PyRuntime_Initialize(void)
93{
94 /* XXX We only initialize once in the process, which aligns with
95 the static initialization of the former globals now found in
96 _PyRuntime. However, _PyRuntime *should* be initialized with
97 every Py_Initialize() call, but doing so breaks the runtime.
98 This is because the runtime state is not properly finalized
99 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +0100100 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200101 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800102 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +0100103 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800104
105 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600106}
107
108void
109_PyRuntime_Finalize(void)
110{
111 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +0100112 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600113}
114
115int
116_Py_IsFinalizing(void)
117{
Victor Stinner7b3c2522020-03-07 00:24:23 +0100118 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600119}
120
Nick Coghland6009512014-11-20 21:39:37 +1000121/* Hack to force loading of object files */
122int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
123 PyOS_mystrnicmp; /* Python/pystrcmp.o */
124
Eric Snowc7ec9982017-05-23 23:00:52 -0700125
Eric Snow1abcf672017-05-23 21:46:51 -0700126/* APIs to access the initialization flags
127 *
128 * Can be called prior to Py_Initialize.
129 */
Nick Coghland6009512014-11-20 21:39:37 +1000130
Eric Snow1abcf672017-05-23 21:46:51 -0700131int
132_Py_IsCoreInitialized(void)
133{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600134 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700135}
Nick Coghland6009512014-11-20 21:39:37 +1000136
137int
138Py_IsInitialized(void)
139{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600140 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000141}
142
Nick Coghlan6ea41862017-06-11 13:16:15 +1000143
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000144/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
145 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000146 initializations fail, a fatal error is issued and the function does
147 not return. On return, the first thread and interpreter state have
148 been created.
149
150 Locking: you must hold the interpreter lock while calling this.
151 (If the lock has not yet been initialized, that's equivalent to
152 having the lock, but you cannot use multiple threads.)
153
154*/
Victor Stinneref75a622020-11-12 15:14:13 +0100155static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200156init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000157{
Victor Stinneref75a622020-11-12 15:14:13 +0100158 assert(!_PyErr_Occurred(tstate));
159
Victor Stinnerb45d2592019-06-20 00:05:23 +0200160 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200161 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000162
Victor Stinneref75a622020-11-12 15:14:13 +0100163 // Import _importlib through its frozen version, _frozen_importlib.
164 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000165 PySys_FormatStderr("import _frozen_importlib # frozen\n");
166 }
Victor Stinneref75a622020-11-12 15:14:13 +0100167 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
168 return -1;
169 }
170 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000171 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100172 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000173 }
Victor Stinneref75a622020-11-12 15:14:13 +0100174 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000175
Victor Stinneref75a622020-11-12 15:14:13 +0100176 // Import the _imp module
177 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200178 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000179 }
Victor Stinner62230712020-11-18 23:18:29 +0100180 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100181 if (imp_mod == NULL) {
182 return -1;
183 }
184 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
185 Py_DECREF(imp_mod);
186 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000187 }
188
Victor Stinneref75a622020-11-12 15:14:13 +0100189 // Install importlib as the implementation of import
190 PyObject *value = PyObject_CallMethod(importlib, "_install",
191 "OO", sysmod, imp_mod);
192 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000193 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100194 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000195 }
196 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000197
Victor Stinneref75a622020-11-12 15:14:13 +0100198 assert(!_PyErr_Occurred(tstate));
199 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000200}
201
Victor Stinneref75a622020-11-12 15:14:13 +0100202
Victor Stinner331a6a52019-05-27 16:39:22 +0200203static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200204init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700205{
206 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200207 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700208 "_install_external_importers", "");
209 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200210 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200211 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700212 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200213 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200214 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700215}
Nick Coghland6009512014-11-20 21:39:37 +1000216
Nick Coghlan6ea41862017-06-11 13:16:15 +1000217/* Helper functions to better handle the legacy C locale
218 *
219 * The legacy C locale assumes ASCII as the default text encoding, which
220 * causes problems not only for the CPython runtime, but also other
221 * components like GNU readline.
222 *
223 * Accordingly, when the CLI detects it, it attempts to coerce it to a
224 * more capable UTF-8 based alternative as follows:
225 *
226 * if (_Py_LegacyLocaleDetected()) {
227 * _Py_CoerceLegacyLocale();
228 * }
229 *
230 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
231 *
232 * Locale coercion also impacts the default error handler for the standard
233 * streams: while the usual default is "strict", the default for the legacy
234 * C locale and for any of the coercion target locales is "surrogateescape".
235 */
236
237int
Victor Stinner0f721472019-05-20 17:16:38 +0200238_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000239{
240#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200241 if (!warn) {
242 const char *locale_override = getenv("LC_ALL");
243 if (locale_override != NULL && *locale_override != '\0') {
244 /* Don't coerce C locale if the LC_ALL environment variable
245 is set */
246 return 0;
247 }
248 }
249
Nick Coghlan6ea41862017-06-11 13:16:15 +1000250 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000251 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
252 * the POSIX locale as a simple alias for the C locale, so
253 * we may also want to check for that explicitly.
254 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000255 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
256 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
257#else
258 /* Windows uses code pages instead of locales, so no locale is legacy */
259 return 0;
260#endif
261}
262
Victor Stinnerb0051362019-11-22 17:52:42 +0100263#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000264static const char *_C_LOCALE_WARNING =
265 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
266 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
267 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
268 "locales is recommended.\n";
269
Nick Coghlaneb817952017-06-18 12:29:42 +1000270static void
Victor Stinner43125222019-04-24 18:23:53 +0200271emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000272{
Victor Stinner331a6a52019-05-27 16:39:22 +0200273 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200274 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200275 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000276 }
277}
Victor Stinnerb0051362019-11-22 17:52:42 +0100278#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000279
Nick Coghlan6ea41862017-06-11 13:16:15 +1000280typedef struct _CandidateLocale {
281 const char *locale_name; /* The locale to try as a coercion target */
282} _LocaleCoercionTarget;
283
284static _LocaleCoercionTarget _TARGET_LOCALES[] = {
285 {"C.UTF-8"},
286 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000287 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000288 {NULL}
289};
290
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200291
292int
293_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200295 const _LocaleCoercionTarget *target = NULL;
296 for (target = _TARGET_LOCALES; target->locale_name; target++) {
297 if (strcmp(ctype_loc, target->locale_name) == 0) {
298 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000299 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200300 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200301 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302}
303
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200304
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100306static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
308 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
309
Victor Stinner0f721472019-05-20 17:16:38 +0200310static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200311_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312{
313 const char *newloc = target->locale_name;
314
315 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100316 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317
318 /* Set the relevant locale environment variable */
319 if (setenv("LC_CTYPE", newloc, 1)) {
320 fprintf(stderr,
321 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200322 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000323 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200324 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100325 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000326 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000327
328 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100329 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200330 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000331}
332#endif
333
Victor Stinner0f721472019-05-20 17:16:38 +0200334int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200335_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000336{
Victor Stinner0f721472019-05-20 17:16:38 +0200337 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000338#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200339 char *oldloc = NULL;
340
341 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
342 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200343 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200344 }
345
Victor Stinner94540602017-12-16 04:54:22 +0100346 const char *locale_override = getenv("LC_ALL");
347 if (locale_override == NULL || *locale_override == '\0') {
348 /* LC_ALL is also not set (or is set to an empty string) */
349 const _LocaleCoercionTarget *target = NULL;
350 for (target = _TARGET_LOCALES; target->locale_name; target++) {
351 const char *new_locale = setlocale(LC_CTYPE,
352 target->locale_name);
353 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400354#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100355 /* Also ensure that nl_langinfo works in this locale */
356 char *codeset = nl_langinfo(CODESET);
357 if (!codeset || *codeset == '\0') {
358 /* CODESET is not set or empty, so skip coercion */
359 new_locale = NULL;
360 _Py_SetLocaleFromEnv(LC_CTYPE);
361 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000362 }
Victor Stinner94540602017-12-16 04:54:22 +0100363#endif
364 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200365 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200366 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000367 }
368 }
369 }
370 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200371
372 setlocale(LC_CTYPE, oldloc);
373
374done:
375 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000376#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200377 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000378}
379
xdegaye1588be62017-11-12 12:45:59 +0100380/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
381 * isolate the idiosyncrasies of different libc implementations. It reads the
382 * appropriate environment variable and uses its value to select the locale for
383 * 'category'. */
384char *
385_Py_SetLocaleFromEnv(int category)
386{
Victor Stinner353933e2018-11-23 13:08:26 +0100387 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100388#ifdef __ANDROID__
389 const char *locale;
390 const char **pvar;
391#ifdef PY_COERCE_C_LOCALE
392 const char *coerce_c_locale;
393#endif
394 const char *utf8_locale = "C.UTF-8";
395 const char *env_var_set[] = {
396 "LC_ALL",
397 "LC_CTYPE",
398 "LANG",
399 NULL,
400 };
401
402 /* Android setlocale(category, "") doesn't check the environment variables
403 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
404 * check the environment variables listed in env_var_set. */
405 for (pvar=env_var_set; *pvar; pvar++) {
406 locale = getenv(*pvar);
407 if (locale != NULL && *locale != '\0') {
408 if (strcmp(locale, utf8_locale) == 0 ||
409 strcmp(locale, "en_US.UTF-8") == 0) {
410 return setlocale(category, utf8_locale);
411 }
412 return setlocale(category, "C");
413 }
414 }
415
416 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
417 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
418 * Quote from POSIX section "8.2 Internationalization Variables":
419 * "4. If the LANG environment variable is not set or is set to the empty
420 * string, the implementation-defined default locale shall be used." */
421
422#ifdef PY_COERCE_C_LOCALE
423 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
424 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
425 /* Some other ported code may check the environment variables (e.g. in
426 * extension modules), so we make sure that they match the locale
427 * configuration */
428 if (setenv("LC_CTYPE", utf8_locale, 1)) {
429 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
430 "environment variable to %s\n", utf8_locale);
431 }
432 }
433#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100434 res = setlocale(category, utf8_locale);
435#else /* !defined(__ANDROID__) */
436 res = setlocale(category, "");
437#endif
438 _Py_ResetForceASCII();
439 return res;
xdegaye1588be62017-11-12 12:45:59 +0100440}
441
Nick Coghlan6ea41862017-06-11 13:16:15 +1000442
Victor Stinner048a3562020-11-05 00:45:56 +0100443static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100444interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100445{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100446 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100447
Victor Stinner9e1b8282020-11-10 13:21:52 +0100448 if (!only_update_path_config) {
449 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
450 if (_PyStatus_EXCEPTION(status)) {
451 _PyErr_SetFromPyStatus(status);
452 return -1;
453 }
Victor Stinner048a3562020-11-05 00:45:56 +0100454 }
455
Victor Stinner101bf692021-02-19 13:33:31 +0100456 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner9e1b8282020-11-10 13:21:52 +0100457 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100458 if (_PyStatus_EXCEPTION(status)) {
459 _PyErr_SetFromPyStatus(status);
460 return -1;
461 }
462 }
463
464 // Update the sys module for the new configuration
465 if (_PySys_UpdateConfig(tstate) < 0) {
466 return -1;
467 }
468 return 0;
469}
470
471
472int
473_PyInterpreterState_SetConfig(const PyConfig *src_config)
474{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100475 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100476 int res = -1;
477
478 PyConfig config;
479 PyConfig_InitPythonConfig(&config);
480 PyStatus status = _PyConfig_Copy(&config, src_config);
481 if (_PyStatus_EXCEPTION(status)) {
482 _PyErr_SetFromPyStatus(status);
483 goto done;
484 }
485
486 status = PyConfig_Read(&config);
487 if (_PyStatus_EXCEPTION(status)) {
488 _PyErr_SetFromPyStatus(status);
489 goto done;
490 }
491
Victor Stinner9e1b8282020-11-10 13:21:52 +0100492 status = _PyConfig_Copy(&tstate->interp->config, &config);
493 if (_PyStatus_EXCEPTION(status)) {
494 _PyErr_SetFromPyStatus(status);
495 goto done;
496 }
497
498 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100499
500done:
501 PyConfig_Clear(&config);
502 return res;
503}
504
505
Eric Snow1abcf672017-05-23 21:46:51 -0700506/* Global initializations. Can be undone by Py_Finalize(). Don't
507 call this twice without an intervening Py_Finalize() call.
508
Victor Stinner331a6a52019-05-27 16:39:22 +0200509 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700510 must have a corresponding call to Py_Finalize.
511
512 Locking: you must hold the interpreter lock while calling these APIs.
513 (If the lock has not yet been initialized, that's equivalent to
514 having the lock, but you cannot use multiple threads.)
515
516*/
517
Victor Stinner331a6a52019-05-27 16:39:22 +0200518static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200519pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200520 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200521 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200522{
Victor Stinner331a6a52019-05-27 16:39:22 +0200523 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100524 PyThreadState *tstate = _PyThreadState_GET();
525 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200526 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100527 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200528 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100529
530 PyInterpreterState *interp = tstate->interp;
531 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200532 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100533 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100534
Victor Stinnere81f6e62020-06-08 18:12:59 +0200535 status = _PyConfig_Write(config, runtime);
536 if (_PyStatus_EXCEPTION(status)) {
537 return status;
538 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200539
Victor Stinner048a3562020-11-05 00:45:56 +0100540 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200541 if (_PyStatus_EXCEPTION(status)) {
542 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200543 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200544 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200545
Victor Stinner331a6a52019-05-27 16:39:22 +0200546 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200547 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200548 if (_PyStatus_EXCEPTION(status)) {
549 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200550 }
551 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200552 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200553}
554
555
Victor Stinner331a6a52019-05-27 16:39:22 +0200556static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200557pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200558 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000559{
Victor Stinner43125222019-04-24 18:23:53 +0200560 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200561 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200562 }
Victor Stinnerda273412017-12-15 01:46:02 +0100563
Victor Stinnere81f6e62020-06-08 18:12:59 +0200564 PyStatus status = _PyConfig_Write(config, runtime);
565 if (_PyStatus_EXCEPTION(status)) {
566 return status;
567 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600568
Eric Snow1abcf672017-05-23 21:46:51 -0700569 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
570 * threads behave a little more gracefully at interpreter shutdown.
571 * We clobber it here so the new interpreter can start with a clean
572 * slate.
573 *
574 * However, this may still lead to misbehaviour if there are daemon
575 * threads still hanging around from a previous Py_Initialize/Finalize
576 * pair :(
577 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100578 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600579
Victor Stinnere81f6e62020-06-08 18:12:59 +0200580 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200581 if (_PyStatus_EXCEPTION(status)) {
582 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800583 }
584
Victor Stinner331a6a52019-05-27 16:39:22 +0200585 status = _PyInterpreterState_Enable(runtime);
586 if (_PyStatus_EXCEPTION(status)) {
587 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800588 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200589 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100590}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800591
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100592
Victor Stinner331a6a52019-05-27 16:39:22 +0200593static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200594init_interp_create_gil(PyThreadState *tstate)
595{
596 PyStatus status;
597
598 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
599 only called here. */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100600 _PyEval_FiniGIL(tstate->interp);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200601
602 /* Auto-thread-state API */
Victor Stinner87f649a2021-03-10 20:00:46 +0100603 status = _PyGILState_SetTstate(tstate);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200604 if (_PyStatus_EXCEPTION(status)) {
605 return status;
606 }
607
608 /* Create the GIL and take it */
609 status = _PyEval_InitGIL(tstate);
610 if (_PyStatus_EXCEPTION(status)) {
611 return status;
612 }
613
614 return _PyStatus_OK();
615}
616
617
618static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200619pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200620 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200621 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100622{
Victor Stinner87f649a2021-03-10 20:00:46 +0100623 /* Auto-thread-state API */
624 PyStatus status = _PyGILState_Init(runtime);
625 if (_PyStatus_EXCEPTION(status)) {
626 return status;
627 }
628
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100629 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100630 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200631 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100632 }
Victor Stinner87f649a2021-03-10 20:00:46 +0100633 assert(_Py_IsMainInterpreter(interp));
Victor Stinnerda273412017-12-15 01:46:02 +0100634
Victor Stinner87f649a2021-03-10 20:00:46 +0100635 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200636 if (_PyStatus_EXCEPTION(status)) {
637 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100638 }
Nick Coghland6009512014-11-20 21:39:37 +1000639
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200640 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200641 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200642 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200643 }
Nick Coghland6009512014-11-20 21:39:37 +1000644 (void) PyThreadState_Swap(tstate);
645
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200646 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100647 if (_PyStatus_EXCEPTION(status)) {
648 return status;
649 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100650
Victor Stinnerb45d2592019-06-20 00:05:23 +0200651 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200652 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100653}
Nick Coghland6009512014-11-20 21:39:37 +1000654
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655
Victor Stinner331a6a52019-05-27 16:39:22 +0200656static PyStatus
Victor Stinner442ad742021-04-02 15:28:13 +0200657pycore_init_singletons(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100658{
Victor Stinner444b39b2019-11-20 01:18:11 +0100659 PyStatus status;
660
Victor Stinner442ad742021-04-02 15:28:13 +0200661 if (_PyLong_Init(interp) < 0) {
Victor Stinner630c8df2019-12-17 13:02:18 +0100662 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100663 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100664
Victor Stinner442ad742021-04-02 15:28:13 +0200665 if (_Py_IsMainInterpreter(interp)) {
666 _PyFloat_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100667 }
668
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100669 status = _PyBytes_Init(interp);
Victor Stinner91698d82020-06-25 14:07:40 +0200670 if (_PyStatus_EXCEPTION(status)) {
671 return status;
672 }
673
Victor Stinner442ad742021-04-02 15:28:13 +0200674 status = _PyUnicode_Init(interp);
675 if (_PyStatus_EXCEPTION(status)) {
676 return status;
677 }
678
679 status = _PyTuple_Init(interp);
680 if (_PyStatus_EXCEPTION(status)) {
681 return status;
682 }
683
684 return _PyStatus_OK();
685}
686
687
688static PyStatus
689pycore_init_types(PyInterpreterState *interp)
690{
691 PyStatus status;
692 int is_main_interp = _Py_IsMainInterpreter(interp);
693
694 if (is_main_interp) {
695 if (_PyStructSequence_Init() < 0) {
696 return _PyStatus_ERR("can't initialize structseq");
697 }
698
699 status = _PyTypes_Init();
700 if (_PyStatus_EXCEPTION(status)) {
701 return status;
702 }
703
704 if (_PyLong_InitTypes() < 0) {
705 return _PyStatus_ERR("can't init int type");
706 }
707
708 status = _PyUnicode_InitTypes();
709 if (_PyStatus_EXCEPTION(status)) {
710 return status;
711 }
712 }
713
714 if (is_main_interp) {
715 if (_PyFloat_InitTypes() < 0) {
716 return _PyStatus_ERR("can't init float");
717 }
718 }
719
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100720 status = _PyExc_Init(interp);
Victor Stinner331a6a52019-05-27 16:39:22 +0200721 if (_PyStatus_EXCEPTION(status)) {
722 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100723 }
724
Victor Stinner442ad742021-04-02 15:28:13 +0200725 status = _PyErr_InitTypes();
Victor Stinner331a6a52019-05-27 16:39:22 +0200726 if (_PyStatus_EXCEPTION(status)) {
727 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200728 }
729
Victor Stinnere7e699e2019-11-20 12:08:13 +0100730 if (is_main_interp) {
731 if (!_PyContext_Init()) {
732 return _PyStatus_ERR("can't init context");
733 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100734 }
735
Victor Stinner331a6a52019-05-27 16:39:22 +0200736 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100737}
738
739
Victor Stinner331a6a52019-05-27 16:39:22 +0200740static PyStatus
Victor Stinner442ad742021-04-02 15:28:13 +0200741pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100742{
Victor Stinner442ad742021-04-02 15:28:13 +0200743 PyInterpreterState *interp = tstate->interp;
744
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100745 PyObject *bimod = _PyBuiltin_Init(interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100746 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100747 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100748 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100749
Victor Stinner2582d462019-11-22 19:24:49 +0100750 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
751 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100752 }
Victor Stinner2582d462019-11-22 19:24:49 +0100753
754 PyObject *builtins_dict = PyModule_GetDict(bimod);
755 if (builtins_dict == NULL) {
756 goto error;
757 }
758 Py_INCREF(builtins_dict);
759 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100760
Victor Stinner331a6a52019-05-27 16:39:22 +0200761 PyStatus status = _PyBuiltins_AddExceptions(bimod);
762 if (_PyStatus_EXCEPTION(status)) {
763 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100764 }
Victor Stinner2582d462019-11-22 19:24:49 +0100765
766 interp->builtins_copy = PyDict_Copy(interp->builtins);
767 if (interp->builtins_copy == NULL) {
768 goto error;
769 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000770 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100771
Victor Stinner62230712020-11-18 23:18:29 +0100772 // Get the __import__ function
773 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
774 "__import__");
775 if (import_func == NULL) {
776 goto error;
777 }
778 interp->import_func = Py_NewRef(import_func);
779
Victor Stinner442ad742021-04-02 15:28:13 +0200780 assert(!_PyErr_Occurred(tstate));
Victor Stinner331a6a52019-05-27 16:39:22 +0200781 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100782
783error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000784 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100785 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100786}
787
788
Victor Stinner331a6a52019-05-27 16:39:22 +0200789static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100790pycore_interp_init(PyThreadState *tstate)
791{
Victor Stinner442ad742021-04-02 15:28:13 +0200792 PyInterpreterState *interp = tstate->interp;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100793 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100794 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100795
Victor Stinner442ad742021-04-02 15:28:13 +0200796 // Create singletons before the first PyType_Ready() call, since
797 // PyType_Ready() uses singletons like the Unicode empty string (tp_doc)
798 // and the empty tuple singletons (tp_bases).
799 status = pycore_init_singletons(interp);
800 if (_PyStatus_EXCEPTION(status)) {
801 return status;
802 }
803
804 // The GC must be initialized before the first GC collection.
805 status = _PyGC_Init(interp);
806 if (_PyStatus_EXCEPTION(status)) {
807 return status;
808 }
809
810 status = pycore_init_types(interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100811 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100812 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100813 }
814
Victor Stinner442ad742021-04-02 15:28:13 +0200815 if (_PyWarnings_InitState(interp) < 0) {
816 return _PyStatus_ERR("can't initialize warnings");
817 }
818
819 status = _PyAtExit_Init(interp);
820 if (_PyStatus_EXCEPTION(status)) {
821 return status;
822 }
823
Victor Stinnerd863ade2019-12-06 03:37:07 +0100824 status = _PySys_Create(tstate, &sysmod);
825 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100826 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100827 }
828
Victor Stinner442ad742021-04-02 15:28:13 +0200829 status = pycore_init_builtins(tstate);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100830 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100831 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100832 }
833
Victor Stinner442ad742021-04-02 15:28:13 +0200834 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinneref75a622020-11-12 15:14:13 +0100835 if (config->_install_importlib) {
836 /* This call sets up builtin and frozen import support */
837 if (init_importlib(tstate, sysmod) < 0) {
838 return _PyStatus_ERR("failed to initialize importlib");
839 }
840 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100841
842done:
843 /* sys.modules['sys'] contains a strong reference to the module */
844 Py_XDECREF(sysmod);
845 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100846}
847
848
849static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200850pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200851 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200852 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100853{
Victor Stinner331a6a52019-05-27 16:39:22 +0200854 PyStatus status = pycore_init_runtime(runtime, config);
855 if (_PyStatus_EXCEPTION(status)) {
856 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100857 }
858
Victor Stinnerb45d2592019-06-20 00:05:23 +0200859 PyThreadState *tstate;
860 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200861 if (_PyStatus_EXCEPTION(status)) {
862 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100863 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200864 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100865
Victor Stinnerd863ade2019-12-06 03:37:07 +0100866 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200867 if (_PyStatus_EXCEPTION(status)) {
868 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100869 }
Eric Snow1abcf672017-05-23 21:46:51 -0700870
871 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200872 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200873 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700874}
875
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100876
Victor Stinner331a6a52019-05-27 16:39:22 +0200877PyStatus
878_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100879{
Victor Stinner331a6a52019-05-27 16:39:22 +0200880 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100881
Victor Stinner6d1c4672019-05-20 11:02:00 +0200882 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200883 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200884 }
885
Victor Stinner331a6a52019-05-27 16:39:22 +0200886 status = _PyRuntime_Initialize();
887 if (_PyStatus_EXCEPTION(status)) {
888 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100889 }
Victor Stinner43125222019-04-24 18:23:53 +0200890 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100891
Victor Stinnerd3b90412019-09-17 23:59:51 +0200892 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100893 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200894 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100895 }
896
Victor Stinnerd3b90412019-09-17 23:59:51 +0200897 /* Note: preinitialized remains 1 on error, it is only set to 0
898 at exit on success. */
899 runtime->preinitializing = 1;
900
Victor Stinner331a6a52019-05-27 16:39:22 +0200901 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200902
903 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
904 if (_PyStatus_EXCEPTION(status)) {
905 return status;
906 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100907
Victor Stinner331a6a52019-05-27 16:39:22 +0200908 status = _PyPreConfig_Read(&config, args);
909 if (_PyStatus_EXCEPTION(status)) {
910 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100911 }
912
Victor Stinner331a6a52019-05-27 16:39:22 +0200913 status = _PyPreConfig_Write(&config);
914 if (_PyStatus_EXCEPTION(status)) {
915 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100916 }
917
Victor Stinnerd3b90412019-09-17 23:59:51 +0200918 runtime->preinitializing = 0;
919 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200920 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100921}
922
Victor Stinner70005ac2019-05-02 15:25:34 -0400923
Victor Stinner331a6a52019-05-27 16:39:22 +0200924PyStatus
925Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100926{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100927 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400928 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100929}
930
931
Victor Stinner331a6a52019-05-27 16:39:22 +0200932PyStatus
933Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100934{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100935 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400936 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100937}
938
939
Victor Stinner331a6a52019-05-27 16:39:22 +0200940PyStatus
941Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100942{
Victor Stinner70005ac2019-05-02 15:25:34 -0400943 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100944}
945
946
Victor Stinner331a6a52019-05-27 16:39:22 +0200947PyStatus
948_Py_PreInitializeFromConfig(const PyConfig *config,
949 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100950{
Victor Stinner331a6a52019-05-27 16:39:22 +0200951 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200952
Victor Stinner331a6a52019-05-27 16:39:22 +0200953 PyStatus status = _PyRuntime_Initialize();
954 if (_PyStatus_EXCEPTION(status)) {
955 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200956 }
957 _PyRuntimeState *runtime = &_PyRuntime;
958
Victor Stinnerd3b90412019-09-17 23:59:51 +0200959 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200960 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200961 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400962 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200963
Victor Stinner331a6a52019-05-27 16:39:22 +0200964 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200965
Victor Stinner3c30a762019-10-01 10:56:37 +0200966 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200967
Victor Stinner331a6a52019-05-27 16:39:22 +0200968 if (!config->parse_argv) {
969 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200970 }
971 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200972 _PyArgv config_args = {
973 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200974 .argc = config->argv.length,
975 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200976 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200977 }
978 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200979 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200980 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100981}
982
983
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100984/* Begin interpreter initialization
985 *
986 * On return, the first thread and interpreter state have been created,
987 * but the compiler, signal handling, multithreading and
988 * multiple interpreter support, and codec infrastructure are not yet
989 * available.
990 *
991 * The import system will support builtin and frozen modules only.
992 * The only supported io is writing to sys.stderr
993 *
994 * If any operation invoked by this function fails, a fatal error is
995 * issued and the function does not return.
996 *
997 * Any code invoked from this function should *not* assume it has access
998 * to the Python C API (unless the API is explicitly listed as being
999 * safe to call without calling Py_Initialize first)
1000 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001001static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +02001002pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +02001003 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +02001004 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +02001005{
Victor Stinner331a6a52019-05-27 16:39:22 +02001006 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +02001007
Victor Stinner331a6a52019-05-27 16:39:22 +02001008 status = _Py_PreInitializeFromConfig(src_config, NULL);
1009 if (_PyStatus_EXCEPTION(status)) {
1010 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +02001011 }
1012
Victor Stinner331a6a52019-05-27 16:39:22 +02001013 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +01001014 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +02001015
Victor Stinner331a6a52019-05-27 16:39:22 +02001016 status = _PyConfig_Copy(&config, src_config);
1017 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +02001018 goto done;
1019 }
1020
Victor Stinner9e1b8282020-11-10 13:21:52 +01001021 // Read the configuration, but don't compute the path configuration
1022 // (it is computed in the main init).
1023 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +02001024 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +02001025 goto done;
1026 }
1027
1028 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02001029 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +02001030 }
1031 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +02001032 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +02001033 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001034 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +02001035 goto done;
1036 }
1037
1038done:
Victor Stinner331a6a52019-05-27 16:39:22 +02001039 PyConfig_Clear(&config);
1040 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +02001041}
1042
Victor Stinner5ac27a52019-03-27 13:40:14 +01001043
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001044/* Py_Initialize() has already been called: update the main interpreter
1045 configuration. Example of bpo-34008: Py_Main() called after
1046 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +02001047static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001048pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001049{
Victor Stinner9e1b8282020-11-10 13:21:52 +01001050 if (interpreter_update_config(tstate, 0) < 0) {
1051 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001052 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001053 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001054}
1055
Victor Stinnerb0051362019-11-22 17:52:42 +01001056
1057static PyStatus
1058init_interp_main(PyThreadState *tstate)
1059{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001060 assert(!_PyErr_Occurred(tstate));
1061
Victor Stinnerb0051362019-11-22 17:52:42 +01001062 PyStatus status;
Victor Stinner101bf692021-02-19 13:33:31 +01001063 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001064 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001065 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001066
1067 if (!config->_install_importlib) {
1068 /* Special mode for freeze_importlib: run with no import system
1069 *
1070 * This means anything which needs support from extension modules
1071 * or pure Python code in the standard library won't work.
1072 */
1073 if (is_main_interp) {
1074 interp->runtime->initialized = 1;
1075 }
1076 return _PyStatus_OK();
1077 }
1078
Victor Stinner9e1b8282020-11-10 13:21:52 +01001079 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001080 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001081 if (_PyStatus_EXCEPTION(status)) {
1082 return status;
1083 }
1084
Victor Stinner9e1b8282020-11-10 13:21:52 +01001085 if (interpreter_update_config(tstate, 1) < 0) {
1086 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001087 }
1088
1089 status = init_importlib_external(tstate);
1090 if (_PyStatus_EXCEPTION(status)) {
1091 return status;
1092 }
1093
1094 if (is_main_interp) {
1095 /* initialize the faulthandler module */
1096 status = _PyFaulthandler_Init(config->faulthandler);
1097 if (_PyStatus_EXCEPTION(status)) {
1098 return status;
1099 }
1100 }
1101
1102 status = _PyUnicode_InitEncodings(tstate);
1103 if (_PyStatus_EXCEPTION(status)) {
1104 return status;
1105 }
1106
1107 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001108 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1109 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001110 }
1111
1112 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1113 return _PyStatus_ERR("can't initialize tracemalloc");
1114 }
1115 }
1116
1117 status = init_sys_streams(tstate);
1118 if (_PyStatus_EXCEPTION(status)) {
1119 return status;
1120 }
1121
Andy Lester75cd5bf2020-03-12 02:49:05 -05001122 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001123 if (_PyStatus_EXCEPTION(status)) {
1124 return status;
1125 }
1126
1127 status = add_main_module(interp);
1128 if (_PyStatus_EXCEPTION(status)) {
1129 return status;
1130 }
1131
1132 if (is_main_interp) {
1133 /* Initialize warnings. */
1134 PyObject *warnoptions = PySys_GetObject("warnoptions");
1135 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1136 {
1137 PyObject *warnings_module = PyImport_ImportModule("warnings");
1138 if (warnings_module == NULL) {
1139 fprintf(stderr, "'import warnings' failed; traceback:\n");
1140 _PyErr_Print(tstate);
1141 }
1142 Py_XDECREF(warnings_module);
1143 }
1144
1145 interp->runtime->initialized = 1;
1146 }
1147
1148 if (config->site_import) {
1149 status = init_import_site();
1150 if (_PyStatus_EXCEPTION(status)) {
1151 return status;
1152 }
1153 }
1154
1155 if (is_main_interp) {
1156#ifndef MS_WINDOWS
1157 emit_stderr_warning_for_legacy_locale(interp->runtime);
1158#endif
1159 }
1160
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001161 assert(!_PyErr_Occurred(tstate));
1162
Victor Stinnerb0051362019-11-22 17:52:42 +01001163 return _PyStatus_OK();
1164}
1165
1166
Eric Snowc7ec9982017-05-23 23:00:52 -07001167/* Update interpreter state based on supplied configuration settings
1168 *
1169 * After calling this function, most of the restrictions on the interpreter
1170 * are lifted. The only remaining incomplete settings are those related
1171 * to the main module (sys.argv[0], __main__ metadata)
1172 *
1173 * Calling this when the interpreter is not initializing, is already
1174 * initialized or without a valid current thread state is a fatal error.
1175 * Other errors should be reported as normal Python exceptions with a
1176 * non-zero return code.
1177 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001178static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001179pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001180{
Victor Stinnerb0051362019-11-22 17:52:42 +01001181 PyInterpreterState *interp = tstate->interp;
1182 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001183 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001184 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001185
Victor Stinnerb0051362019-11-22 17:52:42 +01001186 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001187 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001188 }
1189
Victor Stinnerb0051362019-11-22 17:52:42 +01001190 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001191 if (_PyStatus_EXCEPTION(status)) {
1192 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001193 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001194 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001195}
1196
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001197
Victor Stinner331a6a52019-05-27 16:39:22 +02001198PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001199Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001200{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001201 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001202 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001203 }
1204
Victor Stinner331a6a52019-05-27 16:39:22 +02001205 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001206
Victor Stinner331a6a52019-05-27 16:39:22 +02001207 status = _PyRuntime_Initialize();
1208 if (_PyStatus_EXCEPTION(status)) {
1209 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001210 }
1211 _PyRuntimeState *runtime = &_PyRuntime;
1212
Victor Stinnerb45d2592019-06-20 00:05:23 +02001213 PyThreadState *tstate = NULL;
1214 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001215 if (_PyStatus_EXCEPTION(status)) {
1216 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001217 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001218 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001219
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001220 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001221 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001222 if (_PyStatus_EXCEPTION(status)) {
1223 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001224 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001225 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001226
Victor Stinner331a6a52019-05-27 16:39:22 +02001227 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001228}
1229
1230
Eric Snow1abcf672017-05-23 21:46:51 -07001231void
Nick Coghland6009512014-11-20 21:39:37 +10001232Py_InitializeEx(int install_sigs)
1233{
Victor Stinner331a6a52019-05-27 16:39:22 +02001234 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001235
Victor Stinner331a6a52019-05-27 16:39:22 +02001236 status = _PyRuntime_Initialize();
1237 if (_PyStatus_EXCEPTION(status)) {
1238 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001239 }
1240 _PyRuntimeState *runtime = &_PyRuntime;
1241
1242 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001243 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1244 return;
1245 }
1246
Victor Stinner331a6a52019-05-27 16:39:22 +02001247 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001248 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001249
Victor Stinner1dc6e392018-07-25 02:49:17 +02001250 config.install_signal_handlers = install_sigs;
1251
Victor Stinner331a6a52019-05-27 16:39:22 +02001252 status = Py_InitializeFromConfig(&config);
1253 if (_PyStatus_EXCEPTION(status)) {
1254 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001255 }
Nick Coghland6009512014-11-20 21:39:37 +10001256}
1257
1258void
1259Py_Initialize(void)
1260{
1261 Py_InitializeEx(1);
1262}
1263
1264
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001265PyStatus
1266_Py_InitializeMain(void)
1267{
1268 PyStatus status = _PyRuntime_Initialize();
1269 if (_PyStatus_EXCEPTION(status)) {
1270 return status;
1271 }
1272 _PyRuntimeState *runtime = &_PyRuntime;
1273 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1274 return pyinit_main(tstate);
1275}
1276
1277
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001278static void
1279finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1280{
1281 // List of names to clear in sys
1282 static const char * const sys_deletes[] = {
1283 "path", "argv", "ps1", "ps2",
1284 "last_type", "last_value", "last_traceback",
1285 "path_hooks", "path_importer_cache", "meta_path",
1286 "__interactivehook__",
1287 NULL
1288 };
1289
1290 static const char * const sys_files[] = {
1291 "stdin", "__stdin__",
1292 "stdout", "__stdout__",
1293 "stderr", "__stderr__",
1294 NULL
1295 };
1296
1297 PyInterpreterState *interp = tstate->interp;
1298 if (verbose) {
1299 PySys_WriteStderr("# clear builtins._\n");
1300 }
1301 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1302 PyErr_WriteUnraisable(NULL);
1303 }
1304
1305 const char * const *p;
1306 for (p = sys_deletes; *p != NULL; p++) {
1307 if (verbose) {
1308 PySys_WriteStderr("# clear sys.%s\n", *p);
1309 }
1310 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1311 PyErr_WriteUnraisable(NULL);
1312 }
1313 }
1314 for (p = sys_files; *p != NULL; p+=2) {
1315 const char *name = p[0];
1316 const char *orig_name = p[1];
1317 if (verbose) {
1318 PySys_WriteStderr("# restore sys.%s\n", name);
1319 }
1320 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1321 orig_name);
1322 if (value == NULL) {
1323 if (_PyErr_Occurred(tstate)) {
1324 PyErr_WriteUnraisable(NULL);
1325 }
1326 value = Py_None;
1327 }
1328 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1329 PyErr_WriteUnraisable(NULL);
1330 }
1331 }
1332}
1333
1334
1335static PyObject*
1336finalize_remove_modules(PyObject *modules, int verbose)
1337{
1338 PyObject *weaklist = PyList_New(0);
1339 if (weaklist == NULL) {
1340 PyErr_WriteUnraisable(NULL);
1341 }
1342
1343#define STORE_MODULE_WEAKREF(name, mod) \
1344 if (weaklist != NULL) { \
1345 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1346 if (wr) { \
1347 PyObject *tup = PyTuple_Pack(2, name, wr); \
1348 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1349 PyErr_WriteUnraisable(NULL); \
1350 } \
1351 Py_XDECREF(tup); \
1352 Py_DECREF(wr); \
1353 } \
1354 else { \
1355 PyErr_WriteUnraisable(NULL); \
1356 } \
1357 }
1358
1359#define CLEAR_MODULE(name, mod) \
1360 if (PyModule_Check(mod)) { \
1361 if (verbose && PyUnicode_Check(name)) { \
1362 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1363 } \
1364 STORE_MODULE_WEAKREF(name, mod); \
1365 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1366 PyErr_WriteUnraisable(NULL); \
1367 } \
1368 }
1369
1370 if (PyDict_CheckExact(modules)) {
1371 Py_ssize_t pos = 0;
1372 PyObject *key, *value;
1373 while (PyDict_Next(modules, &pos, &key, &value)) {
1374 CLEAR_MODULE(key, value);
1375 }
1376 }
1377 else {
1378 PyObject *iterator = PyObject_GetIter(modules);
1379 if (iterator == NULL) {
1380 PyErr_WriteUnraisable(NULL);
1381 }
1382 else {
1383 PyObject *key;
1384 while ((key = PyIter_Next(iterator))) {
1385 PyObject *value = PyObject_GetItem(modules, key);
1386 if (value == NULL) {
1387 PyErr_WriteUnraisable(NULL);
1388 continue;
1389 }
1390 CLEAR_MODULE(key, value);
1391 Py_DECREF(value);
1392 Py_DECREF(key);
1393 }
1394 if (PyErr_Occurred()) {
1395 PyErr_WriteUnraisable(NULL);
1396 }
1397 Py_DECREF(iterator);
1398 }
1399 }
1400#undef CLEAR_MODULE
1401#undef STORE_MODULE_WEAKREF
1402
1403 return weaklist;
1404}
1405
1406
1407static void
1408finalize_clear_modules_dict(PyObject *modules)
1409{
1410 if (PyDict_CheckExact(modules)) {
1411 PyDict_Clear(modules);
1412 }
1413 else {
1414 _Py_IDENTIFIER(clear);
1415 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1416 PyErr_WriteUnraisable(NULL);
1417 }
1418 }
1419}
1420
1421
1422static void
1423finalize_restore_builtins(PyThreadState *tstate)
1424{
1425 PyInterpreterState *interp = tstate->interp;
1426 PyObject *dict = PyDict_Copy(interp->builtins);
1427 if (dict == NULL) {
1428 PyErr_WriteUnraisable(NULL);
1429 }
1430 PyDict_Clear(interp->builtins);
1431 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1432 _PyErr_Clear(tstate);
1433 }
1434 Py_XDECREF(dict);
1435}
1436
1437
1438static void
1439finalize_modules_clear_weaklist(PyInterpreterState *interp,
1440 PyObject *weaklist, int verbose)
1441{
1442 // First clear modules imported later
1443 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1444 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1445 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1446 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1447 if (mod == Py_None) {
1448 continue;
1449 }
1450 assert(PyModule_Check(mod));
1451 PyObject *dict = PyModule_GetDict(mod);
1452 if (dict == interp->builtins || dict == interp->sysdict) {
1453 continue;
1454 }
1455 Py_INCREF(mod);
1456 if (verbose && PyUnicode_Check(name)) {
1457 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1458 }
1459 _PyModule_Clear(mod);
1460 Py_DECREF(mod);
1461 }
1462}
1463
1464
1465static void
1466finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1467{
1468 // Clear sys dict
1469 if (verbose) {
1470 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1471 }
1472 _PyModule_ClearDict(interp->sysdict);
1473
1474 // Clear builtins dict
1475 if (verbose) {
1476 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1477 }
1478 _PyModule_ClearDict(interp->builtins);
1479}
1480
1481
1482/* Clear modules, as good as we can */
1483static void
1484finalize_modules(PyThreadState *tstate)
1485{
1486 PyInterpreterState *interp = tstate->interp;
1487 PyObject *modules = interp->modules;
1488 if (modules == NULL) {
1489 // Already done
1490 return;
1491 }
1492 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1493
1494 // Delete some special builtins._ and sys attributes first. These are
1495 // common places where user values hide and people complain when their
1496 // destructors fail. Since the modules containing them are
1497 // deleted *last* of all, they would come too late in the normal
1498 // destruction order. Sigh.
1499 //
1500 // XXX Perhaps these precautions are obsolete. Who knows?
1501 finalize_modules_delete_special(tstate, verbose);
1502
1503 // Remove all modules from sys.modules, hoping that garbage collection
1504 // can reclaim most of them: set all sys.modules values to None.
1505 //
1506 // We prepare a list which will receive (name, weakref) tuples of
1507 // modules when they are removed from sys.modules. The name is used
1508 // for diagnosis messages (in verbose mode), while the weakref helps
1509 // detect those modules which have been held alive.
1510 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1511
1512 // Clear the modules dict
1513 finalize_clear_modules_dict(modules);
1514
1515 // Restore the original builtins dict, to ensure that any
1516 // user data gets cleared.
1517 finalize_restore_builtins(tstate);
1518
1519 // Collect garbage
1520 _PyGC_CollectNoFail(tstate);
1521
1522 // Dump GC stats before it's too late, since it uses the warnings
1523 // machinery.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001524 _PyGC_DumpShutdownStats(interp);
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001525
1526 if (weaklist != NULL) {
1527 // Now, if there are any modules left alive, clear their globals to
1528 // minimize potential leaks. All C extension modules actually end
1529 // up here, since they are kept alive in the interpreter state.
1530 //
1531 // The special treatment of "builtins" here is because even
1532 // when it's not referenced as a module, its dictionary is
1533 // referenced by almost every module's __builtins__. Since
1534 // deleting a module clears its dictionary (even if there are
1535 // references left to it), we need to delete the "builtins"
1536 // module last. Likewise, we don't delete sys until the very
1537 // end because it is implicitly referenced (e.g. by print).
1538 //
1539 // Since dict is ordered in CPython 3.6+, modules are saved in
1540 // importing order. First clear modules imported later.
1541 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1542 Py_DECREF(weaklist);
1543 }
1544
1545 // Clear sys and builtins modules dict
1546 finalize_clear_sys_builtins_dict(interp, verbose);
1547
1548 // Clear module dict copies stored in the interpreter state:
1549 // clear PyInterpreterState.modules_by_index and
1550 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1551 // initialization API)
1552 _PyInterpreterState_ClearModules(interp);
1553
1554 // Clear and delete the modules directory. Actual modules will
1555 // still be there only if imported during the execution of some
1556 // destructor.
1557 Py_SETREF(interp->modules, NULL);
1558
1559 // Collect garbage once more
1560 _PyGC_CollectNoFail(tstate);
1561}
1562
1563
Nick Coghland6009512014-11-20 21:39:37 +10001564/* Flush stdout and stderr */
1565
1566static int
1567file_is_closed(PyObject *fobj)
1568{
1569 int r;
1570 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1571 if (tmp == NULL) {
1572 PyErr_Clear();
1573 return 0;
1574 }
1575 r = PyObject_IsTrue(tmp);
1576 Py_DECREF(tmp);
1577 if (r < 0)
1578 PyErr_Clear();
1579 return r > 0;
1580}
1581
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001582
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001583static int
Nick Coghland6009512014-11-20 21:39:37 +10001584flush_std_files(void)
1585{
1586 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1587 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1588 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001589 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001590
1591 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001592 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001593 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001594 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001595 status = -1;
1596 }
Nick Coghland6009512014-11-20 21:39:37 +10001597 else
1598 Py_DECREF(tmp);
1599 }
1600
1601 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001602 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001603 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001604 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001605 status = -1;
1606 }
Nick Coghland6009512014-11-20 21:39:37 +10001607 else
1608 Py_DECREF(tmp);
1609 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001610
1611 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001612}
1613
1614/* Undo the effect of Py_Initialize().
1615
1616 Beware: if multiple interpreter and/or thread states exist, these
1617 are not wiped out; only the current thread and interpreter state
1618 are deleted. But since everything else is deleted, those other
1619 interpreter and thread states should no longer be used.
1620
1621 (XXX We should do better, e.g. wipe out all interpreters and
1622 threads.)
1623
1624 Locking: as above.
1625
1626*/
1627
Victor Stinner7eee5be2019-11-20 10:38:34 +01001628
1629static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001630finalize_interp_types(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001631{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001632 _PyExc_Fini(interp);
1633 _PyFrame_Fini(interp);
1634 _PyAsyncGen_Fini(interp);
1635 _PyContext_Fini(interp);
1636 _PyType_Fini(interp);
Victor Stinnerea251802020-12-26 02:58:33 +01001637 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1638 // a dict internally.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001639 _PyUnicode_ClearInterned(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001640
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001641 _PyDict_Fini(interp);
1642 _PyList_Fini(interp);
1643 _PyTuple_Fini(interp);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001644
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001645 _PySlice_Fini(interp);
Victor Stinner3d483342019-11-22 12:27:50 +01001646
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001647 _PyBytes_Fini(interp);
1648 _PyUnicode_Fini(interp);
1649 _PyFloat_Fini(interp);
1650 _PyLong_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001651}
1652
1653
1654static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001655finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001656{
Victor Stinner101bf692021-02-19 13:33:31 +01001657 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001658
Victor Stinner7eee5be2019-11-20 10:38:34 +01001659 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001660 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001661
Kongedaa0fe02020-07-04 05:06:46 +08001662 /* Clear all loghooks */
1663 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1664 Call _PySys_ClearAuditHooks when PyObject available. */
1665 if (is_main_interp) {
1666 _PySys_ClearAuditHooks(tstate);
1667 }
1668
Victor Stinner7907f8c2020-06-08 01:22:36 +02001669 if (is_main_interp) {
1670 _Py_HashRandomization_Fini();
1671 _PyArg_Fini();
1672 _Py_ClearFileSystemEncoding();
1673 }
1674
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001675 finalize_interp_types(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001676}
1677
1678
1679static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001680finalize_interp_delete(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001681{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001682 if (_Py_IsMainInterpreter(interp)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001683 /* Cleanup auto-thread-state */
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001684 _PyGILState_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001685 }
1686
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001687 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1688 fail when it is being awaited by another running daemon thread (see
1689 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1690 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1691 called multiple times. */
1692
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001693 PyInterpreterState_Delete(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001694}
1695
1696
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001697int
1698Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001699{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001700 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001701
Victor Stinner8e91c242019-04-24 17:24:01 +02001702 _PyRuntimeState *runtime = &_PyRuntime;
1703 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001704 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001705 }
Nick Coghland6009512014-11-20 21:39:37 +10001706
Victor Stinnere225beb2019-06-03 18:14:24 +02001707 /* Get current thread state and interpreter pointer */
1708 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001709
Victor Stinnerb45d2592019-06-20 00:05:23 +02001710 // Wrap up existing "threading"-module-created, non-daemon threads.
1711 wait_for_thread_shutdown(tstate);
1712
1713 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001714 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001715
Nick Coghland6009512014-11-20 21:39:37 +10001716 /* The interpreter is still entirely intact at this point, and the
1717 * exit funcs may be relying on that. In particular, if some thread
1718 * or exit func is still waiting to do an import, the import machinery
1719 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001720 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001721 * Note that Threading.py uses an exit func to do a join on all the
1722 * threads created thru it, so this also protects pending imports in
1723 * the threads created via Threading.
1724 */
Nick Coghland6009512014-11-20 21:39:37 +10001725
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001726 _PyAtExit_Call(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001727
Victor Stinnerda273412017-12-15 01:46:02 +01001728 /* Copy the core config, PyInterpreterState_Delete() free
1729 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001730#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001731 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001732#endif
1733#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001734 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001735#endif
1736#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001737 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001738#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001739
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001740 /* Remaining daemon threads will automatically exit
1741 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001742 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001743 runtime->initialized = 0;
1744 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001745
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001746 /* Destroy the state of all threads of the interpreter, except of the
1747 current thread. In practice, only daemon threads should still be alive,
1748 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1749 Clear frames of other threads to call objects destructors. Destructors
1750 will be called in the current Python thread. Since
1751 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1752 can take the GIL at this point: if they try, they will exit
1753 immediately. */
1754 _PyThreadState_DeleteExcept(runtime, tstate);
1755
Victor Stinnere0deff32015-03-24 13:46:18 +01001756 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001757 if (flush_std_files() < 0) {
1758 status = -1;
1759 }
Nick Coghland6009512014-11-20 21:39:37 +10001760
1761 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001762 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001763
1764 /* Collect garbage. This may call finalizers; it's nice to call these
1765 * before all modules are destroyed.
1766 * XXX If a __del__ or weakref callback is triggered here, and tries to
1767 * XXX import a module, bad things can happen, because Python no
1768 * XXX longer believes it's initialized.
1769 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1770 * XXX is easy to provoke that way. I've also seen, e.g.,
1771 * XXX Exception exceptions.ImportError: 'No module named sha'
1772 * XXX in <function callback at 0x008F5718> ignored
1773 * XXX but I'm unclear on exactly how that one happens. In any case,
1774 * XXX I haven't seen a real-life report of either of these.
1775 */
Victor Stinner8b341482020-10-30 17:00:00 +01001776 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001777
Nick Coghland6009512014-11-20 21:39:37 +10001778 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001779 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001780
Inada Naoki91234a12019-06-03 21:30:58 +09001781 /* Print debug stats if any */
1782 _PyEval_Fini();
1783
Victor Stinnere0deff32015-03-24 13:46:18 +01001784 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001785 if (flush_std_files() < 0) {
1786 status = -1;
1787 }
Nick Coghland6009512014-11-20 21:39:37 +10001788
1789 /* Collect final garbage. This disposes of cycles created by
1790 * class definitions, for example.
1791 * XXX This is disabled because it caused too many problems. If
1792 * XXX a __del__ or weakref callback triggers here, Python code has
1793 * XXX a hard time running, because even the sys module has been
1794 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1795 * XXX One symptom is a sequence of information-free messages
1796 * XXX coming from threads (if a __del__ or callback is invoked,
1797 * XXX other threads can execute too, and any exception they encounter
1798 * XXX triggers a comedy of errors as subsystem after subsystem
1799 * XXX fails to find what it *expects* to find in sys to help report
1800 * XXX the exception and consequent unexpected failures). I've also
1801 * XXX seen segfaults then, after adding print statements to the
1802 * XXX Python code getting called.
1803 */
1804#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001805 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001806#endif
1807
1808 /* Disable tracemalloc after all Python objects have been destroyed,
1809 so it is possible to use tracemalloc in objects destructor. */
1810 _PyTraceMalloc_Fini();
1811
1812 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1813 _PyImport_Fini();
1814
Nick Coghland6009512014-11-20 21:39:37 +10001815 /* unload faulthandler module */
1816 _PyFaulthandler_Fini();
1817
Nick Coghland6009512014-11-20 21:39:37 +10001818 /* dump hash stats */
1819 _PyHash_Fini();
1820
Eric Snowdae02762017-09-14 00:35:58 -07001821#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001822 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001823 _PyDebug_PrintTotalRefs();
1824 }
Eric Snowdae02762017-09-14 00:35:58 -07001825#endif
Nick Coghland6009512014-11-20 21:39:37 +10001826
1827#ifdef Py_TRACE_REFS
1828 /* Display all objects still alive -- this can invoke arbitrary
1829 * __repr__ overrides, so requires a mostly-intact interpreter.
1830 * Alas, a lot of stuff may still be alive now that will be cleaned
1831 * up later.
1832 */
Victor Stinnerda273412017-12-15 01:46:02 +01001833 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001834 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001835 }
Nick Coghland6009512014-11-20 21:39:37 +10001836#endif /* Py_TRACE_REFS */
1837
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001838 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001839 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001840
1841#ifdef Py_TRACE_REFS
1842 /* Display addresses (& refcnts) of all objects still alive.
1843 * An address can be used to find the repr of the object, printed
1844 * above by _Py_PrintReferences.
1845 */
Victor Stinnerda273412017-12-15 01:46:02 +01001846 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001847 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001848 }
Nick Coghland6009512014-11-20 21:39:37 +10001849#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001850#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001851 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001852 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001853 }
Nick Coghland6009512014-11-20 21:39:37 +10001854#endif
1855
Victor Stinner8e91c242019-04-24 17:24:01 +02001856 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001857
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001858 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001859 return status;
1860}
1861
1862void
1863Py_Finalize(void)
1864{
1865 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001866}
1867
Victor Stinnerb0051362019-11-22 17:52:42 +01001868
Nick Coghland6009512014-11-20 21:39:37 +10001869/* Create and initialize a new interpreter and thread, and return the
1870 new thread. This requires that Py_Initialize() has been called
1871 first.
1872
1873 Unsuccessful initialization yields a NULL pointer. Note that *no*
1874 exception information is available even in this case -- the
1875 exception information is held in the thread, and there is no
1876 thread.
1877
1878 Locking: as above.
1879
1880*/
1881
Victor Stinner331a6a52019-05-27 16:39:22 +02001882static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001883new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001884{
Victor Stinner331a6a52019-05-27 16:39:22 +02001885 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001886
Victor Stinner331a6a52019-05-27 16:39:22 +02001887 status = _PyRuntime_Initialize();
1888 if (_PyStatus_EXCEPTION(status)) {
1889 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001890 }
1891 _PyRuntimeState *runtime = &_PyRuntime;
1892
1893 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001894 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001895 }
Nick Coghland6009512014-11-20 21:39:37 +10001896
Victor Stinner8a1be612016-03-14 22:07:55 +01001897 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1898 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001899 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001900
Victor Stinner43125222019-04-24 18:23:53 +02001901 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001902 if (interp == NULL) {
1903 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001904 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001905 }
Nick Coghland6009512014-11-20 21:39:37 +10001906
Victor Stinner43125222019-04-24 18:23:53 +02001907 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001908 if (tstate == NULL) {
1909 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001910 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001911 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001912 }
1913
Victor Stinner43125222019-04-24 18:23:53 +02001914 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001915
Eric Snow1abcf672017-05-23 21:46:51 -07001916 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001917 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001918#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001919 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001920 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001921 }
1922 else
1923#endif
1924 {
Eric Snow1abcf672017-05-23 21:46:51 -07001925 /* No current thread state, copy from the main interpreter */
1926 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001927 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001928 }
1929
Victor Stinner048a3562020-11-05 00:45:56 +01001930
1931 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001932 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001933 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001934 }
Victor Stinner252346a2020-05-01 11:33:44 +02001935 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001936
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001937 status = init_interp_create_gil(tstate);
1938 if (_PyStatus_EXCEPTION(status)) {
1939 goto error;
1940 }
1941
Victor Stinnerd863ade2019-12-06 03:37:07 +01001942 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001943 if (_PyStatus_EXCEPTION(status)) {
1944 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001945 }
1946
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001947 status = init_interp_main(tstate);
1948 if (_PyStatus_EXCEPTION(status)) {
1949 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001950 }
Nick Coghland6009512014-11-20 21:39:37 +10001951
Victor Stinnera7368ac2017-11-15 18:11:45 -08001952 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001953 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001954
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001955error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001956 *tstate_p = NULL;
1957
1958 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001959 PyErr_PrintEx(0);
1960 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001961 PyThreadState_Delete(tstate);
1962 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001963 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001964
Victor Stinnerb0051362019-11-22 17:52:42 +01001965 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001966}
1967
1968PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001969_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001970{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001971 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001972 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001973 if (_PyStatus_EXCEPTION(status)) {
1974 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001975 }
1976 return tstate;
1977
Nick Coghland6009512014-11-20 21:39:37 +10001978}
1979
Victor Stinner252346a2020-05-01 11:33:44 +02001980PyThreadState *
1981Py_NewInterpreter(void)
1982{
1983 return _Py_NewInterpreter(0);
1984}
1985
Nick Coghland6009512014-11-20 21:39:37 +10001986/* Delete an interpreter and its last thread. This requires that the
1987 given thread state is current, that the thread has no remaining
1988 frames, and that it is its interpreter's only remaining thread.
1989 It is a fatal error to violate these constraints.
1990
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001991 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001992 everything, regardless.)
1993
1994 Locking: as above.
1995
1996*/
1997
1998void
1999Py_EndInterpreter(PyThreadState *tstate)
2000{
2001 PyInterpreterState *interp = tstate->interp;
2002
Victor Stinnerb45d2592019-06-20 00:05:23 +02002003 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002004 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02002005 }
2006 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002007 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02002008 }
Eric Snow5be45a62019-03-08 22:47:07 -07002009 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002010
Eric Snow842a2f02019-03-15 15:47:51 -06002011 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02002012 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002013
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002014 _PyAtExit_Call(tstate->interp);
Marcel Plch776407f2017-12-20 11:17:58 +01002015
Victor Stinnerb45d2592019-06-20 00:05:23 +02002016 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002017 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02002018 }
Nick Coghland6009512014-11-20 21:39:37 +10002019
Victor Stinnerdff1ad52020-10-30 18:03:28 +01002020 finalize_modules(tstate);
2021
Victor Stinnerb93f31f2019-11-20 18:39:12 +01002022 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002023 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10002024}
2025
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002026/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10002027
Victor Stinner331a6a52019-05-27 16:39:22 +02002028static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002029add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10002030{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002031 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10002032 m = PyImport_AddModule("__main__");
2033 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02002034 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002035
Nick Coghland6009512014-11-20 21:39:37 +10002036 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002037 ann_dict = PyDict_New();
2038 if ((ann_dict == NULL) ||
2039 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002040 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002041 }
2042 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002043
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002044 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
2045 if (PyErr_Occurred()) {
2046 return _PyStatus_ERR("Failed to test __main__.__builtins__");
2047 }
Nick Coghland6009512014-11-20 21:39:37 +10002048 PyObject *bimod = PyImport_ImportModule("builtins");
2049 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002050 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10002051 }
2052 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002053 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002054 }
2055 Py_DECREF(bimod);
2056 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002057
Nick Coghland6009512014-11-20 21:39:37 +10002058 /* Main is a little special - imp.is_builtin("__main__") will return
2059 * False, but BuiltinImporter is still the most appropriate initial
2060 * setting for its __loader__ attribute. A more suitable value will
2061 * be set if __main__ gets further initialized later in the startup
2062 * process.
2063 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002064 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002065 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002066 if (PyErr_Occurred()) {
2067 return _PyStatus_ERR("Failed to test __main__.__loader__");
2068 }
Nick Coghland6009512014-11-20 21:39:37 +10002069 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2070 "BuiltinImporter");
2071 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002072 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002073 }
2074 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002075 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002076 }
2077 Py_DECREF(loader);
2078 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002079 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002080}
2081
Nick Coghland6009512014-11-20 21:39:37 +10002082/* Import the site module (not into __main__ though) */
2083
Victor Stinner331a6a52019-05-27 16:39:22 +02002084static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002085init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002086{
2087 PyObject *m;
2088 m = PyImport_ImportModule("site");
2089 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002090 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002091 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002092 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002093 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002094}
2095
Victor Stinner874dbe82015-09-04 17:29:57 +02002096/* Check if a file descriptor is valid or not.
2097 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2098static int
2099is_valid_fd(int fd)
2100{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002101/* dup() is faster than fstat(): fstat() can require input/output operations,
2102 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2103 startup. Problem: dup() doesn't check if the file descriptor is valid on
2104 some platforms.
2105
2106 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2107 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2108 EBADF. FreeBSD has similar issue (bpo-32849).
2109
2110 Only use dup() on platforms where dup() is enough to detect invalid FD in
2111 corner cases: on Linux and Windows (bpo-32849). */
2112#if defined(__linux__) || defined(MS_WINDOWS)
2113 if (fd < 0) {
2114 return 0;
2115 }
2116 int fd2;
2117
2118 _Py_BEGIN_SUPPRESS_IPH
2119 fd2 = dup(fd);
2120 if (fd2 >= 0) {
2121 close(fd2);
2122 }
2123 _Py_END_SUPPRESS_IPH
2124
2125 return (fd2 >= 0);
2126#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002127 struct stat st;
2128 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002129#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002130}
2131
2132/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002133static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002134create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002135 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002136 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002137{
2138 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2139 const char* mode;
2140 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002141 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002142 int buffering, isatty;
2143 _Py_IDENTIFIER(open);
2144 _Py_IDENTIFIER(isatty);
2145 _Py_IDENTIFIER(TextIOWrapper);
2146 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002147 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002148
Victor Stinner874dbe82015-09-04 17:29:57 +02002149 if (!is_valid_fd(fd))
2150 Py_RETURN_NONE;
2151
Nick Coghland6009512014-11-20 21:39:37 +10002152 /* stdin is always opened in buffered mode, first because it shouldn't
2153 make a difference in common use cases, second because TextIOWrapper
2154 depends on the presence of a read1() method which only exists on
2155 buffered streams.
2156 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002157 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002158 buffering = 0;
2159 else
2160 buffering = -1;
2161 if (write_mode)
2162 mode = "wb";
2163 else
2164 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002165 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002166 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002167 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002168 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002169 if (buf == NULL)
2170 goto error;
2171
2172 if (buffering) {
2173 _Py_IDENTIFIER(raw);
2174 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2175 if (raw == NULL)
2176 goto error;
2177 }
2178 else {
2179 raw = buf;
2180 Py_INCREF(raw);
2181 }
2182
Steve Dower39294992016-08-30 21:22:36 -07002183#ifdef MS_WINDOWS
2184 /* Windows console IO is always UTF-8 encoded */
2185 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002186 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002187#endif
2188
Nick Coghland6009512014-11-20 21:39:37 +10002189 text = PyUnicode_FromString(name);
2190 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2191 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002192 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002193 if (res == NULL)
2194 goto error;
2195 isatty = PyObject_IsTrue(res);
2196 Py_DECREF(res);
2197 if (isatty == -1)
2198 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002199 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002200 write_through = Py_True;
2201 else
2202 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002203 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002204 line_buffering = Py_True;
2205 else
2206 line_buffering = Py_False;
2207
2208 Py_CLEAR(raw);
2209 Py_CLEAR(text);
2210
2211#ifdef MS_WINDOWS
2212 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2213 newlines to "\n".
2214 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2215 newline = NULL;
2216#else
2217 /* sys.stdin: split lines at "\n".
2218 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2219 newline = "\n";
2220#endif
2221
Victor Stinner709d23d2019-05-02 14:56:30 -04002222 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2223 if (encoding_str == NULL) {
2224 Py_CLEAR(buf);
2225 goto error;
2226 }
2227
2228 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2229 if (errors_str == NULL) {
2230 Py_CLEAR(buf);
2231 Py_CLEAR(encoding_str);
2232 goto error;
2233 }
2234
2235 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2236 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002237 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002238 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002239 Py_CLEAR(encoding_str);
2240 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002241 if (stream == NULL)
2242 goto error;
2243
2244 if (write_mode)
2245 mode = "w";
2246 else
2247 mode = "r";
2248 text = PyUnicode_FromString(mode);
2249 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2250 goto error;
2251 Py_CLEAR(text);
2252 return stream;
2253
2254error:
2255 Py_XDECREF(buf);
2256 Py_XDECREF(stream);
2257 Py_XDECREF(text);
2258 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002259
Victor Stinner874dbe82015-09-04 17:29:57 +02002260 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2261 /* Issue #24891: the file descriptor was closed after the first
2262 is_valid_fd() check was called. Ignore the OSError and set the
2263 stream to None. */
2264 PyErr_Clear();
2265 Py_RETURN_NONE;
2266 }
2267 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002268}
2269
Victor Stinner77d668b2021-04-12 10:44:53 +02002270/* Set builtins.open to io.open */
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002271static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002272init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002273{
2274 PyObject *iomod = NULL, *wrapper;
2275 PyObject *bimod = NULL;
2276 PyStatus res = _PyStatus_OK();
2277
2278 if (!(iomod = PyImport_ImportModule("io"))) {
2279 goto error;
2280 }
2281
2282 if (!(bimod = PyImport_ImportModule("builtins"))) {
2283 goto error;
2284 }
2285
Victor Stinner77d668b2021-04-12 10:44:53 +02002286 if (!(wrapper = PyObject_GetAttrString(iomod, "open"))) {
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002287 goto error;
2288 }
2289
2290 /* Set builtins.open */
2291 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2292 Py_DECREF(wrapper);
2293 goto error;
2294 }
2295 Py_DECREF(wrapper);
2296 goto done;
2297
2298error:
2299 res = _PyStatus_ERR("can't initialize io.open");
2300
2301done:
2302 Py_XDECREF(bimod);
2303 Py_XDECREF(iomod);
2304 return res;
2305}
2306
2307
Victor Stinner77d668b2021-04-12 10:44:53 +02002308/* Create sys.stdin, sys.stdout and sys.stderr */
Victor Stinner331a6a52019-05-27 16:39:22 +02002309static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002310init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002311{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002312 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002313 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002314 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002315 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002316 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002317 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002318
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002319 /* Check that stdin is not a directory
2320 Using shell redirection, you can redirect stdin to a directory,
2321 crashing the Python interpreter. Catch this common mistake here
2322 and output a useful error message. Note that under MS Windows,
2323 the shell already prevents that. */
2324#ifndef MS_WINDOWS
2325 struct _Py_stat_struct sb;
2326 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2327 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002328 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002329 }
2330#endif
2331
Nick Coghland6009512014-11-20 21:39:37 +10002332 if (!(iomod = PyImport_ImportModule("io"))) {
2333 goto error;
2334 }
Nick Coghland6009512014-11-20 21:39:37 +10002335
Nick Coghland6009512014-11-20 21:39:37 +10002336 /* Set sys.stdin */
2337 fd = fileno(stdin);
2338 /* Under some conditions stdin, stdout and stderr may not be connected
2339 * and fileno() may point to an invalid file descriptor. For example
2340 * GUI apps don't have valid standard streams by default.
2341 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002342 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002343 config->stdio_encoding,
2344 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002345 if (std == NULL)
2346 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002347 PySys_SetObject("__stdin__", std);
2348 _PySys_SetObjectId(&PyId_stdin, std);
2349 Py_DECREF(std);
2350
2351 /* Set sys.stdout */
2352 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002353 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002354 config->stdio_encoding,
2355 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002356 if (std == NULL)
2357 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002358 PySys_SetObject("__stdout__", std);
2359 _PySys_SetObjectId(&PyId_stdout, std);
2360 Py_DECREF(std);
2361
2362#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2363 /* Set sys.stderr, replaces the preliminary stderr */
2364 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002365 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002366 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002367 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002368 if (std == NULL)
2369 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002370
2371 /* Same as hack above, pre-import stderr's codec to avoid recursion
2372 when import.c tries to write to stderr in verbose mode. */
2373 encoding_attr = PyObject_GetAttrString(std, "encoding");
2374 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002375 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002376 if (std_encoding != NULL) {
2377 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2378 Py_XDECREF(codec_info);
2379 }
2380 Py_DECREF(encoding_attr);
2381 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002382 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002383
2384 if (PySys_SetObject("__stderr__", std) < 0) {
2385 Py_DECREF(std);
2386 goto error;
2387 }
2388 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2389 Py_DECREF(std);
2390 goto error;
2391 }
2392 Py_DECREF(std);
2393#endif
2394
Victor Stinnera7368ac2017-11-15 18:11:45 -08002395 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002396
Victor Stinnera7368ac2017-11-15 18:11:45 -08002397error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002398 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002399
2400done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002401 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002402 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002403 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002404}
2405
2406
Victor Stinner10dc4842015-03-24 12:01:30 +01002407static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002408_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2409 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002410{
Victor Stinner314b8782021-01-18 18:34:56 +01002411 PUTS(fd, "\n");
Victor Stinner10dc4842015-03-24 12:01:30 +01002412
2413 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002414 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002415}
Victor Stinner791da1c2016-03-14 16:53:12 +01002416
2417/* Print the current exception (if an exception is set) with its traceback,
2418 or display the current Python stack.
2419
2420 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2421 called on catastrophic cases.
2422
2423 Return 1 if the traceback was displayed, 0 otherwise. */
2424
2425static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002426_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002427{
2428 PyObject *ferr, *res;
2429 PyObject *exception, *v, *tb;
2430 int has_tb;
2431
Victor Stinnerb45d2592019-06-20 00:05:23 +02002432 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002433 if (exception == NULL) {
2434 /* No current exception */
2435 return 0;
2436 }
2437
2438 ferr = _PySys_GetObjectId(&PyId_stderr);
2439 if (ferr == NULL || ferr == Py_None) {
2440 /* sys.stderr is not set yet or set to None,
2441 no need to try to display the exception */
2442 return 0;
2443 }
2444
Victor Stinnerb45d2592019-06-20 00:05:23 +02002445 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002446 if (tb == NULL) {
2447 tb = Py_None;
2448 Py_INCREF(tb);
2449 }
2450 PyException_SetTraceback(v, tb);
2451 if (exception == NULL) {
2452 /* PyErr_NormalizeException() failed */
2453 return 0;
2454 }
2455
2456 has_tb = (tb != Py_None);
2457 PyErr_Display(exception, v, tb);
2458 Py_XDECREF(exception);
2459 Py_XDECREF(v);
2460 Py_XDECREF(tb);
2461
2462 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002463 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002464 if (res == NULL) {
2465 _PyErr_Clear(tstate);
2466 }
2467 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002468 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002469 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002470
2471 return has_tb;
2472}
2473
Nick Coghland6009512014-11-20 21:39:37 +10002474/* Print fatal error message and abort */
2475
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002476#ifdef MS_WINDOWS
2477static void
2478fatal_output_debug(const char *msg)
2479{
2480 /* buffer of 256 bytes allocated on the stack */
2481 WCHAR buffer[256 / sizeof(WCHAR)];
2482 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2483 size_t msglen;
2484
2485 OutputDebugStringW(L"Fatal Python error: ");
2486
2487 msglen = strlen(msg);
2488 while (msglen) {
2489 size_t i;
2490
2491 if (buflen > msglen) {
2492 buflen = msglen;
2493 }
2494
2495 /* Convert the message to wchar_t. This uses a simple one-to-one
2496 conversion, assuming that the this error message actually uses
2497 ASCII only. If this ceases to be true, we will have to convert. */
2498 for (i=0; i < buflen; ++i) {
2499 buffer[i] = msg[i];
2500 }
2501 buffer[i] = L'\0';
2502 OutputDebugStringW(buffer);
2503
2504 msg += buflen;
2505 msglen -= buflen;
2506 }
2507 OutputDebugStringW(L"\n");
2508}
2509#endif
2510
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002511
2512static void
Victor Stinner314b8782021-01-18 18:34:56 +01002513fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002514{
Victor Stinner314b8782021-01-18 18:34:56 +01002515 PUTS(fd, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002516 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2517 if (finalizing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002518 PUTS(fd, "finalizing (tstate=0x");
2519 _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
2520 PUTS(fd, ")");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002521 }
2522 else if (runtime->initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002523 PUTS(fd, "initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002524 }
2525 else if (runtime->core_initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002526 PUTS(fd, "core initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002527 }
2528 else if (runtime->preinitialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002529 PUTS(fd, "preinitialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002530 }
2531 else if (runtime->preinitializing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002532 PUTS(fd, "preinitializing");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002533 }
2534 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002535 PUTS(fd, "unknown");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002536 }
Victor Stinner314b8782021-01-18 18:34:56 +01002537 PUTS(fd, "\n");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002538}
2539
2540
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002541static inline void _Py_NO_RETURN
2542fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002543{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002544 if (status < 0) {
2545#if defined(MS_WINDOWS) && defined(_DEBUG)
2546 DebugBreak();
2547#endif
2548 abort();
2549 }
2550 else {
2551 exit(status);
2552 }
2553}
2554
2555
Victor Stinner66f77ca2021-01-19 23:35:27 +01002556// Dump the list of extension modules of sys.modules, excluding stdlib modules
Victor Stinner9852cb32021-01-25 23:12:50 +01002557// (sys.stdlib_module_names), into fd file descriptor.
Victor Stinner66f77ca2021-01-19 23:35:27 +01002558//
Victor Stinner250035d2021-01-18 20:47:13 +01002559// This function is called by a signal handler in faulthandler: avoid memory
Victor Stinner66f77ca2021-01-19 23:35:27 +01002560// allocations and keep the implementation simple. For example, the list is not
2561// sorted on purpose.
Victor Stinner250035d2021-01-18 20:47:13 +01002562void
2563_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
2564{
2565 if (interp == NULL) {
2566 return;
2567 }
2568 PyObject *modules = interp->modules;
Victor Stinner66f77ca2021-01-19 23:35:27 +01002569 if (modules == NULL || !PyDict_Check(modules)) {
Victor Stinner250035d2021-01-18 20:47:13 +01002570 return;
2571 }
2572
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002573 Py_ssize_t pos;
2574 PyObject *key, *value;
2575
2576 // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
2577 // memory cannot be allocated on the heap in a signal handler.
2578 // Iterate on the dict instead.
Victor Stinner9852cb32021-01-25 23:12:50 +01002579 PyObject *stdlib_module_names = NULL;
Victor Stinner3d55aa92021-04-07 23:12:45 +02002580 if (interp->sysdict != NULL) {
2581 pos = 0;
2582 while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
2583 if (PyUnicode_Check(key)
2584 && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
2585 stdlib_module_names = value;
2586 break;
2587 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002588 }
2589 }
Victor Stinner9852cb32021-01-25 23:12:50 +01002590 // If we failed to get sys.stdlib_module_names or it's not a frozenset,
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002591 // don't exclude stdlib modules.
Victor Stinner9852cb32021-01-25 23:12:50 +01002592 if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
2593 stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002594 }
2595
2596 // List extensions
Victor Stinner66f77ca2021-01-19 23:35:27 +01002597 int header = 1;
2598 Py_ssize_t count = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002599 pos = 0;
Victor Stinner250035d2021-01-18 20:47:13 +01002600 while (PyDict_Next(modules, &pos, &key, &value)) {
2601 if (!PyUnicode_Check(key)) {
2602 continue;
2603 }
2604 if (!_PyModule_IsExtension(value)) {
2605 continue;
2606 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002607 // Use the module name from the sys.modules key,
2608 // don't attempt to get the module object name.
Victor Stinner9852cb32021-01-25 23:12:50 +01002609 if (stdlib_module_names != NULL) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002610 int is_stdlib_ext = 0;
2611
Victor Stinner9852cb32021-01-25 23:12:50 +01002612 Py_ssize_t i = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002613 PyObject *item;
2614 Py_hash_t hash;
Victor Stinner9852cb32021-01-25 23:12:50 +01002615 while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002616 if (PyUnicode_Check(item)
2617 && PyUnicode_Compare(key, item) == 0)
2618 {
2619 is_stdlib_ext = 1;
2620 break;
2621 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002622 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002623 if (is_stdlib_ext) {
2624 // Ignore stdlib extension
2625 continue;
2626 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002627 }
2628
2629 if (header) {
2630 PUTS(fd, "\nExtension modules: ");
2631 header = 0;
2632 }
2633 else {
Victor Stinner250035d2021-01-18 20:47:13 +01002634 PUTS(fd, ", ");
2635 }
Victor Stinner250035d2021-01-18 20:47:13 +01002636
2637 _Py_DumpASCII(fd, key);
Victor Stinner66f77ca2021-01-19 23:35:27 +01002638 count++;
Victor Stinner250035d2021-01-18 20:47:13 +01002639 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002640
2641 if (count) {
2642 PUTS(fd, " (total: ");
2643 _Py_DumpDecimal(fd, count);
2644 PUTS(fd, ")");
2645 PUTS(fd, "\n");
2646 }
Victor Stinner250035d2021-01-18 20:47:13 +01002647}
2648
2649
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002650static void _Py_NO_RETURN
Victor Stinner314b8782021-01-18 18:34:56 +01002651fatal_error(int fd, int header, const char *prefix, const char *msg,
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002652 int status)
2653{
Victor Stinner53345a42015-03-25 01:55:14 +01002654 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002655
2656 if (reentrant) {
2657 /* Py_FatalError() caused a second fatal error.
2658 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002659 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002660 }
2661 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002662
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002663 if (header) {
Victor Stinner314b8782021-01-18 18:34:56 +01002664 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002665 if (prefix) {
Victor Stinner314b8782021-01-18 18:34:56 +01002666 PUTS(fd, prefix);
2667 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002668 }
2669 if (msg) {
Victor Stinner314b8782021-01-18 18:34:56 +01002670 PUTS(fd, msg);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002671 }
2672 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002673 PUTS(fd, "<message not set>");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002674 }
Victor Stinner314b8782021-01-18 18:34:56 +01002675 PUTS(fd, "\n");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002676 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002677
2678 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner314b8782021-01-18 18:34:56 +01002679 fatal_error_dump_runtime(fd, runtime);
Victor Stinner10dc4842015-03-24 12:01:30 +01002680
Victor Stinner3a228ab2018-11-01 00:26:41 +01002681 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002682 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002683
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002684 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2685 has no Python thread state.
2686
2687 tss_tstate != tstate if the current Python thread does not hold the GIL.
2688 */
Victor Stinner314b8782021-01-18 18:34:56 +01002689 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2690 PyInterpreterState *interp = NULL;
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002691 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
Victor Stinner314b8782021-01-18 18:34:56 +01002692 if (tstate != NULL) {
2693 interp = tstate->interp;
2694 }
2695 else if (tss_tstate != NULL) {
2696 interp = tss_tstate->interp;
2697 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002698 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner314b8782021-01-18 18:34:56 +01002699
Victor Stinner3a228ab2018-11-01 00:26:41 +01002700 if (has_tstate_and_gil) {
2701 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002702 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002703 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002704 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002705 }
2706 }
2707 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002708 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002709 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002710
Victor Stinner250035d2021-01-18 20:47:13 +01002711 _Py_DumpExtensionModules(fd, interp);
2712
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002713 /* The main purpose of faulthandler is to display the traceback.
2714 This function already did its best to display a traceback.
2715 Disable faulthandler to prevent writing a second traceback
2716 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002717 _PyFaulthandler_Fini();
2718
Victor Stinner791da1c2016-03-14 16:53:12 +01002719 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002720 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002721 /* Flush sys.stdout and sys.stderr */
2722 flush_std_files();
2723 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002724
Nick Coghland6009512014-11-20 21:39:37 +10002725#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002726 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002727#endif /* MS_WINDOWS */
2728
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002729 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002730}
2731
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002732
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002733#undef Py_FatalError
2734
Victor Stinner19760862017-12-20 01:41:59 +01002735void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002736Py_FatalError(const char *msg)
2737{
Victor Stinner314b8782021-01-18 18:34:56 +01002738 fatal_error(fileno(stderr), 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002739}
2740
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002741
Victor Stinner19760862017-12-20 01:41:59 +01002742void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002743_Py_FatalErrorFunc(const char *func, const char *msg)
2744{
Victor Stinner314b8782021-01-18 18:34:56 +01002745 fatal_error(fileno(stderr), 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002746}
2747
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002748
2749void _Py_NO_RETURN
2750_Py_FatalErrorFormat(const char *func, const char *format, ...)
2751{
2752 static int reentrant = 0;
2753 if (reentrant) {
2754 /* _Py_FatalErrorFormat() caused a second fatal error */
2755 fatal_error_exit(-1);
2756 }
2757 reentrant = 1;
2758
2759 FILE *stream = stderr;
Victor Stinner314b8782021-01-18 18:34:56 +01002760 const int fd = fileno(stream);
2761 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002762 if (func) {
Victor Stinner314b8782021-01-18 18:34:56 +01002763 PUTS(fd, func);
2764 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002765 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002766
2767 va_list vargs;
2768#ifdef HAVE_STDARG_PROTOTYPES
2769 va_start(vargs, format);
2770#else
2771 va_start(vargs);
2772#endif
2773 vfprintf(stream, format, vargs);
2774 va_end(vargs);
2775
2776 fputs("\n", stream);
2777 fflush(stream);
2778
Victor Stinner314b8782021-01-18 18:34:56 +01002779 fatal_error(fd, 0, NULL, NULL, -1);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002780}
2781
2782
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002783void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002784Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002785{
Victor Stinner331a6a52019-05-27 16:39:22 +02002786 if (_PyStatus_IS_EXIT(status)) {
2787 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002788 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002789 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner314b8782021-01-18 18:34:56 +01002790 fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002791 }
2792 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002793 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002794 }
Nick Coghland6009512014-11-20 21:39:37 +10002795}
2796
Victor Stinner357704c2020-12-14 23:07:54 +01002797
Nick Coghland6009512014-11-20 21:39:37 +10002798/* Wait until threading._shutdown completes, provided
2799 the threading module was imported in the first place.
2800 The shutdown routine will wait until all non-daemon
2801 "threading" threads have completed. */
2802static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002803wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002804{
Nick Coghland6009512014-11-20 21:39:37 +10002805 _Py_IDENTIFIER(_shutdown);
2806 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002807 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002808 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002809 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002810 PyErr_WriteUnraisable(NULL);
2811 }
2812 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002813 return;
2814 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002815 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002816 if (result == NULL) {
2817 PyErr_WriteUnraisable(threading);
2818 }
2819 else {
2820 Py_DECREF(result);
2821 }
2822 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002823}
2824
2825#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002826int Py_AtExit(void (*func)(void))
2827{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002828 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002829 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002830 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002831 return 0;
2832}
2833
2834static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002835call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002836{
Victor Stinner8e91c242019-04-24 17:24:01 +02002837 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002838 /* pop last function from the list */
2839 runtime->nexitfuncs--;
2840 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2841 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2842
2843 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002844 }
Nick Coghland6009512014-11-20 21:39:37 +10002845
2846 fflush(stdout);
2847 fflush(stderr);
2848}
2849
Victor Stinnercfc88312018-08-01 16:41:25 +02002850void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002851Py_Exit(int sts)
2852{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002853 if (Py_FinalizeEx() < 0) {
2854 sts = 120;
2855 }
Nick Coghland6009512014-11-20 21:39:37 +10002856
2857 exit(sts);
2858}
2859
Nick Coghland6009512014-11-20 21:39:37 +10002860
Nick Coghland6009512014-11-20 21:39:37 +10002861/*
2862 * The file descriptor fd is considered ``interactive'' if either
2863 * a) isatty(fd) is TRUE, or
2864 * b) the -i flag was given, and the filename associated with
2865 * the descriptor is NULL or "<stdin>" or "???".
2866 */
2867int
2868Py_FdIsInteractive(FILE *fp, const char *filename)
2869{
2870 if (isatty((int)fileno(fp)))
2871 return 1;
2872 if (!Py_InteractiveFlag)
2873 return 0;
2874 return (filename == NULL) ||
2875 (strcmp(filename, "<stdin>") == 0) ||
2876 (strcmp(filename, "???") == 0);
2877}
2878
2879
Victor Stinnera82f63f2020-12-09 22:37:27 +01002880int
2881_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2882{
2883 if (isatty((int)fileno(fp))) {
2884 return 1;
2885 }
2886 if (!Py_InteractiveFlag) {
2887 return 0;
2888 }
2889 return (filename == NULL) ||
2890 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2891 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2892}
2893
2894
Nick Coghland6009512014-11-20 21:39:37 +10002895/* Wrappers around sigaction() or signal(). */
2896
2897PyOS_sighandler_t
2898PyOS_getsig(int sig)
2899{
2900#ifdef HAVE_SIGACTION
2901 struct sigaction context;
2902 if (sigaction(sig, NULL, &context) == -1)
2903 return SIG_ERR;
2904 return context.sa_handler;
2905#else
2906 PyOS_sighandler_t handler;
2907/* Special signal handling for the secure CRT in Visual Studio 2005 */
2908#if defined(_MSC_VER) && _MSC_VER >= 1400
2909 switch (sig) {
2910 /* Only these signals are valid */
2911 case SIGINT:
2912 case SIGILL:
2913 case SIGFPE:
2914 case SIGSEGV:
2915 case SIGTERM:
2916 case SIGBREAK:
2917 case SIGABRT:
2918 break;
2919 /* Don't call signal() with other values or it will assert */
2920 default:
2921 return SIG_ERR;
2922 }
2923#endif /* _MSC_VER && _MSC_VER >= 1400 */
2924 handler = signal(sig, SIG_IGN);
2925 if (handler != SIG_ERR)
2926 signal(sig, handler);
2927 return handler;
2928#endif
2929}
2930
2931/*
2932 * All of the code in this function must only use async-signal-safe functions,
2933 * listed at `man 7 signal` or
2934 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2935 */
2936PyOS_sighandler_t
2937PyOS_setsig(int sig, PyOS_sighandler_t handler)
2938{
2939#ifdef HAVE_SIGACTION
2940 /* Some code in Modules/signalmodule.c depends on sigaction() being
2941 * used here if HAVE_SIGACTION is defined. Fix that if this code
2942 * changes to invalidate that assumption.
2943 */
2944 struct sigaction context, ocontext;
2945 context.sa_handler = handler;
2946 sigemptyset(&context.sa_mask);
Gregory P. Smith02ac6f42021-03-04 21:49:30 -08002947 /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
2948 * extension module or embedding code may use where tiny thread stacks
2949 * are used. https://bugs.python.org/issue43390 */
2950 context.sa_flags = SA_ONSTACK;
Nick Coghland6009512014-11-20 21:39:37 +10002951 if (sigaction(sig, &context, &ocontext) == -1)
2952 return SIG_ERR;
2953 return ocontext.sa_handler;
2954#else
2955 PyOS_sighandler_t oldhandler;
2956 oldhandler = signal(sig, handler);
2957#ifdef HAVE_SIGINTERRUPT
2958 siginterrupt(sig, 1);
2959#endif
2960 return oldhandler;
2961#endif
2962}
2963
2964#ifdef __cplusplus
2965}
2966#endif