blob: eeaf20b4617a2095bc6702199e509f5435870a4a [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{
Miss Islington (bot)a11158e2021-08-06 04:32:37 -07001060 extern void _PyThread_debug_deprecation(void);
1061
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001062 assert(!_PyErr_Occurred(tstate));
1063
Victor Stinnerb0051362019-11-22 17:52:42 +01001064 PyStatus status;
Victor Stinner101bf692021-02-19 13:33:31 +01001065 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001066 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001067 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001068
1069 if (!config->_install_importlib) {
1070 /* Special mode for freeze_importlib: run with no import system
1071 *
1072 * This means anything which needs support from extension modules
1073 * or pure Python code in the standard library won't work.
1074 */
1075 if (is_main_interp) {
1076 interp->runtime->initialized = 1;
1077 }
1078 return _PyStatus_OK();
1079 }
1080
Victor Stinner9e1b8282020-11-10 13:21:52 +01001081 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001082 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001083 if (_PyStatus_EXCEPTION(status)) {
1084 return status;
1085 }
1086
Victor Stinner9e1b8282020-11-10 13:21:52 +01001087 if (interpreter_update_config(tstate, 1) < 0) {
1088 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001089 }
1090
1091 status = init_importlib_external(tstate);
1092 if (_PyStatus_EXCEPTION(status)) {
1093 return status;
1094 }
1095
1096 if (is_main_interp) {
1097 /* initialize the faulthandler module */
1098 status = _PyFaulthandler_Init(config->faulthandler);
1099 if (_PyStatus_EXCEPTION(status)) {
1100 return status;
1101 }
1102 }
1103
1104 status = _PyUnicode_InitEncodings(tstate);
1105 if (_PyStatus_EXCEPTION(status)) {
1106 return status;
1107 }
1108
1109 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001110 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1111 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001112 }
1113
1114 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1115 return _PyStatus_ERR("can't initialize tracemalloc");
1116 }
1117 }
1118
1119 status = init_sys_streams(tstate);
1120 if (_PyStatus_EXCEPTION(status)) {
1121 return status;
1122 }
1123
Andy Lester75cd5bf2020-03-12 02:49:05 -05001124 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001125 if (_PyStatus_EXCEPTION(status)) {
1126 return status;
1127 }
1128
1129 status = add_main_module(interp);
1130 if (_PyStatus_EXCEPTION(status)) {
1131 return status;
1132 }
1133
1134 if (is_main_interp) {
1135 /* Initialize warnings. */
1136 PyObject *warnoptions = PySys_GetObject("warnoptions");
1137 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1138 {
1139 PyObject *warnings_module = PyImport_ImportModule("warnings");
1140 if (warnings_module == NULL) {
1141 fprintf(stderr, "'import warnings' failed; traceback:\n");
1142 _PyErr_Print(tstate);
1143 }
1144 Py_XDECREF(warnings_module);
1145 }
1146
1147 interp->runtime->initialized = 1;
1148 }
1149
1150 if (config->site_import) {
1151 status = init_import_site();
1152 if (_PyStatus_EXCEPTION(status)) {
1153 return status;
1154 }
1155 }
1156
1157 if (is_main_interp) {
1158#ifndef MS_WINDOWS
1159 emit_stderr_warning_for_legacy_locale(interp->runtime);
1160#endif
1161 }
1162
Miss Islington (bot)a11158e2021-08-06 04:32:37 -07001163 // Warn about PYTHONTHREADDEBUG deprecation
1164 _PyThread_debug_deprecation();
1165
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001166 assert(!_PyErr_Occurred(tstate));
1167
Victor Stinnerb0051362019-11-22 17:52:42 +01001168 return _PyStatus_OK();
1169}
1170
1171
Eric Snowc7ec9982017-05-23 23:00:52 -07001172/* Update interpreter state based on supplied configuration settings
1173 *
1174 * After calling this function, most of the restrictions on the interpreter
1175 * are lifted. The only remaining incomplete settings are those related
1176 * to the main module (sys.argv[0], __main__ metadata)
1177 *
1178 * Calling this when the interpreter is not initializing, is already
1179 * initialized or without a valid current thread state is a fatal error.
1180 * Other errors should be reported as normal Python exceptions with a
1181 * non-zero return code.
1182 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001183static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001184pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001185{
Victor Stinnerb0051362019-11-22 17:52:42 +01001186 PyInterpreterState *interp = tstate->interp;
1187 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001188 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001189 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001190
Victor Stinnerb0051362019-11-22 17:52:42 +01001191 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001192 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001193 }
1194
Victor Stinnerb0051362019-11-22 17:52:42 +01001195 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001196 if (_PyStatus_EXCEPTION(status)) {
1197 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001198 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001199 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001200}
1201
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001202
Victor Stinner331a6a52019-05-27 16:39:22 +02001203PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001204Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001205{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001206 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001207 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001208 }
1209
Victor Stinner331a6a52019-05-27 16:39:22 +02001210 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001211
Victor Stinner331a6a52019-05-27 16:39:22 +02001212 status = _PyRuntime_Initialize();
1213 if (_PyStatus_EXCEPTION(status)) {
1214 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001215 }
1216 _PyRuntimeState *runtime = &_PyRuntime;
1217
Victor Stinnerb45d2592019-06-20 00:05:23 +02001218 PyThreadState *tstate = NULL;
1219 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001220 if (_PyStatus_EXCEPTION(status)) {
1221 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001222 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001223 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001224
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001225 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001226 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001227 if (_PyStatus_EXCEPTION(status)) {
1228 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001229 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001230 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001231
Victor Stinner331a6a52019-05-27 16:39:22 +02001232 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001233}
1234
1235
Eric Snow1abcf672017-05-23 21:46:51 -07001236void
Nick Coghland6009512014-11-20 21:39:37 +10001237Py_InitializeEx(int install_sigs)
1238{
Victor Stinner331a6a52019-05-27 16:39:22 +02001239 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001240
Victor Stinner331a6a52019-05-27 16:39:22 +02001241 status = _PyRuntime_Initialize();
1242 if (_PyStatus_EXCEPTION(status)) {
1243 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001244 }
1245 _PyRuntimeState *runtime = &_PyRuntime;
1246
1247 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001248 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1249 return;
1250 }
1251
Victor Stinner331a6a52019-05-27 16:39:22 +02001252 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001253 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001254
Victor Stinner1dc6e392018-07-25 02:49:17 +02001255 config.install_signal_handlers = install_sigs;
1256
Victor Stinner331a6a52019-05-27 16:39:22 +02001257 status = Py_InitializeFromConfig(&config);
1258 if (_PyStatus_EXCEPTION(status)) {
1259 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001260 }
Nick Coghland6009512014-11-20 21:39:37 +10001261}
1262
1263void
1264Py_Initialize(void)
1265{
1266 Py_InitializeEx(1);
1267}
1268
1269
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001270PyStatus
1271_Py_InitializeMain(void)
1272{
1273 PyStatus status = _PyRuntime_Initialize();
1274 if (_PyStatus_EXCEPTION(status)) {
1275 return status;
1276 }
1277 _PyRuntimeState *runtime = &_PyRuntime;
1278 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1279 return pyinit_main(tstate);
1280}
1281
1282
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001283static void
1284finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1285{
1286 // List of names to clear in sys
1287 static const char * const sys_deletes[] = {
1288 "path", "argv", "ps1", "ps2",
1289 "last_type", "last_value", "last_traceback",
1290 "path_hooks", "path_importer_cache", "meta_path",
1291 "__interactivehook__",
1292 NULL
1293 };
1294
1295 static const char * const sys_files[] = {
1296 "stdin", "__stdin__",
1297 "stdout", "__stdout__",
1298 "stderr", "__stderr__",
1299 NULL
1300 };
1301
1302 PyInterpreterState *interp = tstate->interp;
1303 if (verbose) {
1304 PySys_WriteStderr("# clear builtins._\n");
1305 }
1306 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1307 PyErr_WriteUnraisable(NULL);
1308 }
1309
1310 const char * const *p;
1311 for (p = sys_deletes; *p != NULL; p++) {
1312 if (verbose) {
1313 PySys_WriteStderr("# clear sys.%s\n", *p);
1314 }
1315 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1316 PyErr_WriteUnraisable(NULL);
1317 }
1318 }
1319 for (p = sys_files; *p != NULL; p+=2) {
1320 const char *name = p[0];
1321 const char *orig_name = p[1];
1322 if (verbose) {
1323 PySys_WriteStderr("# restore sys.%s\n", name);
1324 }
1325 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1326 orig_name);
1327 if (value == NULL) {
1328 if (_PyErr_Occurred(tstate)) {
1329 PyErr_WriteUnraisable(NULL);
1330 }
1331 value = Py_None;
1332 }
1333 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1334 PyErr_WriteUnraisable(NULL);
1335 }
1336 }
1337}
1338
1339
1340static PyObject*
1341finalize_remove_modules(PyObject *modules, int verbose)
1342{
1343 PyObject *weaklist = PyList_New(0);
1344 if (weaklist == NULL) {
1345 PyErr_WriteUnraisable(NULL);
1346 }
1347
1348#define STORE_MODULE_WEAKREF(name, mod) \
1349 if (weaklist != NULL) { \
1350 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1351 if (wr) { \
1352 PyObject *tup = PyTuple_Pack(2, name, wr); \
1353 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1354 PyErr_WriteUnraisable(NULL); \
1355 } \
1356 Py_XDECREF(tup); \
1357 Py_DECREF(wr); \
1358 } \
1359 else { \
1360 PyErr_WriteUnraisable(NULL); \
1361 } \
1362 }
1363
1364#define CLEAR_MODULE(name, mod) \
1365 if (PyModule_Check(mod)) { \
1366 if (verbose && PyUnicode_Check(name)) { \
1367 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1368 } \
1369 STORE_MODULE_WEAKREF(name, mod); \
1370 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1371 PyErr_WriteUnraisable(NULL); \
1372 } \
1373 }
1374
1375 if (PyDict_CheckExact(modules)) {
1376 Py_ssize_t pos = 0;
1377 PyObject *key, *value;
1378 while (PyDict_Next(modules, &pos, &key, &value)) {
1379 CLEAR_MODULE(key, value);
1380 }
1381 }
1382 else {
1383 PyObject *iterator = PyObject_GetIter(modules);
1384 if (iterator == NULL) {
1385 PyErr_WriteUnraisable(NULL);
1386 }
1387 else {
1388 PyObject *key;
1389 while ((key = PyIter_Next(iterator))) {
1390 PyObject *value = PyObject_GetItem(modules, key);
1391 if (value == NULL) {
1392 PyErr_WriteUnraisable(NULL);
1393 continue;
1394 }
1395 CLEAR_MODULE(key, value);
1396 Py_DECREF(value);
1397 Py_DECREF(key);
1398 }
1399 if (PyErr_Occurred()) {
1400 PyErr_WriteUnraisable(NULL);
1401 }
1402 Py_DECREF(iterator);
1403 }
1404 }
1405#undef CLEAR_MODULE
1406#undef STORE_MODULE_WEAKREF
1407
1408 return weaklist;
1409}
1410
1411
1412static void
1413finalize_clear_modules_dict(PyObject *modules)
1414{
1415 if (PyDict_CheckExact(modules)) {
1416 PyDict_Clear(modules);
1417 }
1418 else {
1419 _Py_IDENTIFIER(clear);
1420 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1421 PyErr_WriteUnraisable(NULL);
1422 }
1423 }
1424}
1425
1426
1427static void
1428finalize_restore_builtins(PyThreadState *tstate)
1429{
1430 PyInterpreterState *interp = tstate->interp;
1431 PyObject *dict = PyDict_Copy(interp->builtins);
1432 if (dict == NULL) {
1433 PyErr_WriteUnraisable(NULL);
1434 }
1435 PyDict_Clear(interp->builtins);
1436 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1437 _PyErr_Clear(tstate);
1438 }
1439 Py_XDECREF(dict);
1440}
1441
1442
1443static void
1444finalize_modules_clear_weaklist(PyInterpreterState *interp,
1445 PyObject *weaklist, int verbose)
1446{
1447 // First clear modules imported later
1448 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1449 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1450 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1451 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1452 if (mod == Py_None) {
1453 continue;
1454 }
1455 assert(PyModule_Check(mod));
1456 PyObject *dict = PyModule_GetDict(mod);
1457 if (dict == interp->builtins || dict == interp->sysdict) {
1458 continue;
1459 }
1460 Py_INCREF(mod);
1461 if (verbose && PyUnicode_Check(name)) {
1462 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1463 }
1464 _PyModule_Clear(mod);
1465 Py_DECREF(mod);
1466 }
1467}
1468
1469
1470static void
1471finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1472{
1473 // Clear sys dict
1474 if (verbose) {
1475 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1476 }
1477 _PyModule_ClearDict(interp->sysdict);
1478
1479 // Clear builtins dict
1480 if (verbose) {
1481 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1482 }
1483 _PyModule_ClearDict(interp->builtins);
1484}
1485
1486
1487/* Clear modules, as good as we can */
1488static void
1489finalize_modules(PyThreadState *tstate)
1490{
1491 PyInterpreterState *interp = tstate->interp;
1492 PyObject *modules = interp->modules;
1493 if (modules == NULL) {
1494 // Already done
1495 return;
1496 }
1497 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1498
1499 // Delete some special builtins._ and sys attributes first. These are
1500 // common places where user values hide and people complain when their
1501 // destructors fail. Since the modules containing them are
1502 // deleted *last* of all, they would come too late in the normal
1503 // destruction order. Sigh.
1504 //
1505 // XXX Perhaps these precautions are obsolete. Who knows?
1506 finalize_modules_delete_special(tstate, verbose);
1507
1508 // Remove all modules from sys.modules, hoping that garbage collection
1509 // can reclaim most of them: set all sys.modules values to None.
1510 //
1511 // We prepare a list which will receive (name, weakref) tuples of
1512 // modules when they are removed from sys.modules. The name is used
1513 // for diagnosis messages (in verbose mode), while the weakref helps
1514 // detect those modules which have been held alive.
1515 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1516
1517 // Clear the modules dict
1518 finalize_clear_modules_dict(modules);
1519
1520 // Restore the original builtins dict, to ensure that any
1521 // user data gets cleared.
1522 finalize_restore_builtins(tstate);
1523
1524 // Collect garbage
1525 _PyGC_CollectNoFail(tstate);
1526
1527 // Dump GC stats before it's too late, since it uses the warnings
1528 // machinery.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001529 _PyGC_DumpShutdownStats(interp);
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001530
1531 if (weaklist != NULL) {
1532 // Now, if there are any modules left alive, clear their globals to
1533 // minimize potential leaks. All C extension modules actually end
1534 // up here, since they are kept alive in the interpreter state.
1535 //
1536 // The special treatment of "builtins" here is because even
1537 // when it's not referenced as a module, its dictionary is
1538 // referenced by almost every module's __builtins__. Since
1539 // deleting a module clears its dictionary (even if there are
1540 // references left to it), we need to delete the "builtins"
1541 // module last. Likewise, we don't delete sys until the very
1542 // end because it is implicitly referenced (e.g. by print).
1543 //
1544 // Since dict is ordered in CPython 3.6+, modules are saved in
1545 // importing order. First clear modules imported later.
1546 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1547 Py_DECREF(weaklist);
1548 }
1549
1550 // Clear sys and builtins modules dict
1551 finalize_clear_sys_builtins_dict(interp, verbose);
1552
1553 // Clear module dict copies stored in the interpreter state:
1554 // clear PyInterpreterState.modules_by_index and
1555 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1556 // initialization API)
1557 _PyInterpreterState_ClearModules(interp);
1558
1559 // Clear and delete the modules directory. Actual modules will
1560 // still be there only if imported during the execution of some
1561 // destructor.
1562 Py_SETREF(interp->modules, NULL);
1563
1564 // Collect garbage once more
1565 _PyGC_CollectNoFail(tstate);
1566}
1567
1568
Nick Coghland6009512014-11-20 21:39:37 +10001569/* Flush stdout and stderr */
1570
1571static int
1572file_is_closed(PyObject *fobj)
1573{
1574 int r;
1575 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1576 if (tmp == NULL) {
1577 PyErr_Clear();
1578 return 0;
1579 }
1580 r = PyObject_IsTrue(tmp);
1581 Py_DECREF(tmp);
1582 if (r < 0)
1583 PyErr_Clear();
1584 return r > 0;
1585}
1586
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001587
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001588static int
Nick Coghland6009512014-11-20 21:39:37 +10001589flush_std_files(void)
1590{
1591 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1592 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1593 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001594 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001595
1596 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001597 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001598 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001599 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001600 status = -1;
1601 }
Nick Coghland6009512014-11-20 21:39:37 +10001602 else
1603 Py_DECREF(tmp);
1604 }
1605
1606 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001607 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001608 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001609 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001610 status = -1;
1611 }
Nick Coghland6009512014-11-20 21:39:37 +10001612 else
1613 Py_DECREF(tmp);
1614 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001615
1616 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001617}
1618
1619/* Undo the effect of Py_Initialize().
1620
1621 Beware: if multiple interpreter and/or thread states exist, these
1622 are not wiped out; only the current thread and interpreter state
1623 are deleted. But since everything else is deleted, those other
1624 interpreter and thread states should no longer be used.
1625
1626 (XXX We should do better, e.g. wipe out all interpreters and
1627 threads.)
1628
1629 Locking: as above.
1630
1631*/
1632
Victor Stinner7eee5be2019-11-20 10:38:34 +01001633
1634static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001635finalize_interp_types(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001636{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001637 _PyExc_Fini(interp);
1638 _PyFrame_Fini(interp);
1639 _PyAsyncGen_Fini(interp);
1640 _PyContext_Fini(interp);
1641 _PyType_Fini(interp);
Victor Stinnerea251802020-12-26 02:58:33 +01001642 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1643 // a dict internally.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001644 _PyUnicode_ClearInterned(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001645
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001646 _PyDict_Fini(interp);
1647 _PyList_Fini(interp);
1648 _PyTuple_Fini(interp);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001649
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001650 _PySlice_Fini(interp);
Victor Stinner3d483342019-11-22 12:27:50 +01001651
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001652 _PyBytes_Fini(interp);
1653 _PyUnicode_Fini(interp);
1654 _PyFloat_Fini(interp);
1655 _PyLong_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001656}
1657
1658
1659static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001660finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001661{
Victor Stinner101bf692021-02-19 13:33:31 +01001662 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001663
Victor Stinner7eee5be2019-11-20 10:38:34 +01001664 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001665 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001666
Kongedaa0fe02020-07-04 05:06:46 +08001667 /* Clear all loghooks */
1668 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1669 Call _PySys_ClearAuditHooks when PyObject available. */
1670 if (is_main_interp) {
1671 _PySys_ClearAuditHooks(tstate);
1672 }
1673
Victor Stinner7907f8c2020-06-08 01:22:36 +02001674 if (is_main_interp) {
1675 _Py_HashRandomization_Fini();
1676 _PyArg_Fini();
1677 _Py_ClearFileSystemEncoding();
1678 }
1679
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001680 finalize_interp_types(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001681}
1682
1683
1684static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001685finalize_interp_delete(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001686{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001687 if (_Py_IsMainInterpreter(interp)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001688 /* Cleanup auto-thread-state */
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001689 _PyGILState_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001690 }
1691
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001692 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1693 fail when it is being awaited by another running daemon thread (see
1694 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1695 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1696 called multiple times. */
1697
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001698 PyInterpreterState_Delete(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001699}
1700
1701
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001702int
1703Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001704{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001705 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001706
Victor Stinner8e91c242019-04-24 17:24:01 +02001707 _PyRuntimeState *runtime = &_PyRuntime;
1708 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001709 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001710 }
Nick Coghland6009512014-11-20 21:39:37 +10001711
Victor Stinnere225beb2019-06-03 18:14:24 +02001712 /* Get current thread state and interpreter pointer */
1713 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001714
Victor Stinnerb45d2592019-06-20 00:05:23 +02001715 // Wrap up existing "threading"-module-created, non-daemon threads.
1716 wait_for_thread_shutdown(tstate);
1717
1718 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001719 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001720
Nick Coghland6009512014-11-20 21:39:37 +10001721 /* The interpreter is still entirely intact at this point, and the
1722 * exit funcs may be relying on that. In particular, if some thread
1723 * or exit func is still waiting to do an import, the import machinery
1724 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001725 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001726 * Note that Threading.py uses an exit func to do a join on all the
1727 * threads created thru it, so this also protects pending imports in
1728 * the threads created via Threading.
1729 */
Nick Coghland6009512014-11-20 21:39:37 +10001730
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001731 _PyAtExit_Call(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001732
Victor Stinnerda273412017-12-15 01:46:02 +01001733 /* Copy the core config, PyInterpreterState_Delete() free
1734 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001735#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001736 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001737#endif
1738#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001739 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001740#endif
1741#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001742 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001743#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001744
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001745 /* Remaining daemon threads will automatically exit
1746 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001747 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001748 runtime->initialized = 0;
1749 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001750
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001751 /* Destroy the state of all threads of the interpreter, except of the
1752 current thread. In practice, only daemon threads should still be alive,
1753 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1754 Clear frames of other threads to call objects destructors. Destructors
1755 will be called in the current Python thread. Since
1756 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1757 can take the GIL at this point: if they try, they will exit
1758 immediately. */
1759 _PyThreadState_DeleteExcept(runtime, tstate);
1760
Victor Stinnere0deff32015-03-24 13:46:18 +01001761 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001762 if (flush_std_files() < 0) {
1763 status = -1;
1764 }
Nick Coghland6009512014-11-20 21:39:37 +10001765
1766 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001767 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001768
1769 /* Collect garbage. This may call finalizers; it's nice to call these
1770 * before all modules are destroyed.
1771 * XXX If a __del__ or weakref callback is triggered here, and tries to
1772 * XXX import a module, bad things can happen, because Python no
1773 * XXX longer believes it's initialized.
1774 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1775 * XXX is easy to provoke that way. I've also seen, e.g.,
1776 * XXX Exception exceptions.ImportError: 'No module named sha'
1777 * XXX in <function callback at 0x008F5718> ignored
1778 * XXX but I'm unclear on exactly how that one happens. In any case,
1779 * XXX I haven't seen a real-life report of either of these.
1780 */
Victor Stinner8b341482020-10-30 17:00:00 +01001781 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001782
Nick Coghland6009512014-11-20 21:39:37 +10001783 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001784 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001785
Inada Naoki91234a12019-06-03 21:30:58 +09001786 /* Print debug stats if any */
1787 _PyEval_Fini();
1788
Victor Stinnere0deff32015-03-24 13:46:18 +01001789 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001790 if (flush_std_files() < 0) {
1791 status = -1;
1792 }
Nick Coghland6009512014-11-20 21:39:37 +10001793
1794 /* Collect final garbage. This disposes of cycles created by
1795 * class definitions, for example.
1796 * XXX This is disabled because it caused too many problems. If
1797 * XXX a __del__ or weakref callback triggers here, Python code has
1798 * XXX a hard time running, because even the sys module has been
1799 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1800 * XXX One symptom is a sequence of information-free messages
1801 * XXX coming from threads (if a __del__ or callback is invoked,
1802 * XXX other threads can execute too, and any exception they encounter
1803 * XXX triggers a comedy of errors as subsystem after subsystem
1804 * XXX fails to find what it *expects* to find in sys to help report
1805 * XXX the exception and consequent unexpected failures). I've also
1806 * XXX seen segfaults then, after adding print statements to the
1807 * XXX Python code getting called.
1808 */
1809#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001810 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001811#endif
1812
1813 /* Disable tracemalloc after all Python objects have been destroyed,
1814 so it is possible to use tracemalloc in objects destructor. */
1815 _PyTraceMalloc_Fini();
1816
1817 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1818 _PyImport_Fini();
1819
Nick Coghland6009512014-11-20 21:39:37 +10001820 /* unload faulthandler module */
1821 _PyFaulthandler_Fini();
1822
Nick Coghland6009512014-11-20 21:39:37 +10001823 /* dump hash stats */
1824 _PyHash_Fini();
1825
Eric Snowdae02762017-09-14 00:35:58 -07001826#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001827 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001828 _PyDebug_PrintTotalRefs();
1829 }
Eric Snowdae02762017-09-14 00:35:58 -07001830#endif
Nick Coghland6009512014-11-20 21:39:37 +10001831
1832#ifdef Py_TRACE_REFS
1833 /* Display all objects still alive -- this can invoke arbitrary
1834 * __repr__ overrides, so requires a mostly-intact interpreter.
1835 * Alas, a lot of stuff may still be alive now that will be cleaned
1836 * up later.
1837 */
Victor Stinnerda273412017-12-15 01:46:02 +01001838 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001839 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001840 }
Nick Coghland6009512014-11-20 21:39:37 +10001841#endif /* Py_TRACE_REFS */
1842
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001843 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001844 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001845
1846#ifdef Py_TRACE_REFS
1847 /* Display addresses (& refcnts) of all objects still alive.
1848 * An address can be used to find the repr of the object, printed
1849 * above by _Py_PrintReferences.
1850 */
Victor Stinnerda273412017-12-15 01:46:02 +01001851 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001852 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001853 }
Nick Coghland6009512014-11-20 21:39:37 +10001854#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001855#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001856 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001857 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001858 }
Nick Coghland6009512014-11-20 21:39:37 +10001859#endif
1860
Victor Stinner8e91c242019-04-24 17:24:01 +02001861 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001862
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001863 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001864 return status;
1865}
1866
1867void
1868Py_Finalize(void)
1869{
1870 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001871}
1872
Victor Stinnerb0051362019-11-22 17:52:42 +01001873
Nick Coghland6009512014-11-20 21:39:37 +10001874/* Create and initialize a new interpreter and thread, and return the
1875 new thread. This requires that Py_Initialize() has been called
1876 first.
1877
1878 Unsuccessful initialization yields a NULL pointer. Note that *no*
1879 exception information is available even in this case -- the
1880 exception information is held in the thread, and there is no
1881 thread.
1882
1883 Locking: as above.
1884
1885*/
1886
Victor Stinner331a6a52019-05-27 16:39:22 +02001887static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001888new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001889{
Victor Stinner331a6a52019-05-27 16:39:22 +02001890 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001891
Victor Stinner331a6a52019-05-27 16:39:22 +02001892 status = _PyRuntime_Initialize();
1893 if (_PyStatus_EXCEPTION(status)) {
1894 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001895 }
1896 _PyRuntimeState *runtime = &_PyRuntime;
1897
1898 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001899 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001900 }
Nick Coghland6009512014-11-20 21:39:37 +10001901
Victor Stinner8a1be612016-03-14 22:07:55 +01001902 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1903 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001904 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001905
Victor Stinner43125222019-04-24 18:23:53 +02001906 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001907 if (interp == NULL) {
1908 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001909 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001910 }
Nick Coghland6009512014-11-20 21:39:37 +10001911
Victor Stinner43125222019-04-24 18:23:53 +02001912 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001913 if (tstate == NULL) {
1914 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001915 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001916 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001917 }
1918
Victor Stinner43125222019-04-24 18:23:53 +02001919 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001920
Eric Snow1abcf672017-05-23 21:46:51 -07001921 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001922 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001923#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001924 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001925 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001926 }
1927 else
1928#endif
1929 {
Eric Snow1abcf672017-05-23 21:46:51 -07001930 /* No current thread state, copy from the main interpreter */
1931 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001932 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001933 }
1934
Victor Stinner048a3562020-11-05 00:45:56 +01001935
1936 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001937 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001938 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001939 }
Victor Stinner252346a2020-05-01 11:33:44 +02001940 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001941
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001942 status = init_interp_create_gil(tstate);
1943 if (_PyStatus_EXCEPTION(status)) {
1944 goto error;
1945 }
1946
Victor Stinnerd863ade2019-12-06 03:37:07 +01001947 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001948 if (_PyStatus_EXCEPTION(status)) {
1949 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001950 }
1951
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001952 status = init_interp_main(tstate);
1953 if (_PyStatus_EXCEPTION(status)) {
1954 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001955 }
Nick Coghland6009512014-11-20 21:39:37 +10001956
Victor Stinnera7368ac2017-11-15 18:11:45 -08001957 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001958 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001959
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001960error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001961 *tstate_p = NULL;
1962
1963 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001964 PyErr_PrintEx(0);
1965 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001966 PyThreadState_Delete(tstate);
1967 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001968 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001969
Victor Stinnerb0051362019-11-22 17:52:42 +01001970 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001971}
1972
1973PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001974_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001975{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001976 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001977 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001978 if (_PyStatus_EXCEPTION(status)) {
1979 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001980 }
1981 return tstate;
1982
Nick Coghland6009512014-11-20 21:39:37 +10001983}
1984
Victor Stinner252346a2020-05-01 11:33:44 +02001985PyThreadState *
1986Py_NewInterpreter(void)
1987{
1988 return _Py_NewInterpreter(0);
1989}
1990
Nick Coghland6009512014-11-20 21:39:37 +10001991/* Delete an interpreter and its last thread. This requires that the
1992 given thread state is current, that the thread has no remaining
1993 frames, and that it is its interpreter's only remaining thread.
1994 It is a fatal error to violate these constraints.
1995
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001996 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001997 everything, regardless.)
1998
1999 Locking: as above.
2000
2001*/
2002
2003void
2004Py_EndInterpreter(PyThreadState *tstate)
2005{
2006 PyInterpreterState *interp = tstate->interp;
2007
Victor Stinnerb45d2592019-06-20 00:05:23 +02002008 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002009 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02002010 }
2011 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002012 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02002013 }
Eric Snow5be45a62019-03-08 22:47:07 -07002014 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002015
Eric Snow842a2f02019-03-15 15:47:51 -06002016 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02002017 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002018
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002019 _PyAtExit_Call(tstate->interp);
Marcel Plch776407f2017-12-20 11:17:58 +01002020
Victor Stinnerb45d2592019-06-20 00:05:23 +02002021 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002022 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02002023 }
Nick Coghland6009512014-11-20 21:39:37 +10002024
Victor Stinnerdff1ad52020-10-30 18:03:28 +01002025 finalize_modules(tstate);
2026
Victor Stinnerb93f31f2019-11-20 18:39:12 +01002027 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002028 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10002029}
2030
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002031/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10002032
Victor Stinner331a6a52019-05-27 16:39:22 +02002033static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002034add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10002035{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002036 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10002037 m = PyImport_AddModule("__main__");
2038 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02002039 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002040
Nick Coghland6009512014-11-20 21:39:37 +10002041 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002042 ann_dict = PyDict_New();
2043 if ((ann_dict == NULL) ||
2044 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002045 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002046 }
2047 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002048
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002049 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
2050 if (PyErr_Occurred()) {
2051 return _PyStatus_ERR("Failed to test __main__.__builtins__");
2052 }
Nick Coghland6009512014-11-20 21:39:37 +10002053 PyObject *bimod = PyImport_ImportModule("builtins");
2054 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002055 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10002056 }
2057 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002058 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002059 }
2060 Py_DECREF(bimod);
2061 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002062
Nick Coghland6009512014-11-20 21:39:37 +10002063 /* Main is a little special - imp.is_builtin("__main__") will return
2064 * False, but BuiltinImporter is still the most appropriate initial
2065 * setting for its __loader__ attribute. A more suitable value will
2066 * be set if __main__ gets further initialized later in the startup
2067 * process.
2068 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002069 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002070 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002071 if (PyErr_Occurred()) {
2072 return _PyStatus_ERR("Failed to test __main__.__loader__");
2073 }
Nick Coghland6009512014-11-20 21:39:37 +10002074 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2075 "BuiltinImporter");
2076 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002077 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002078 }
2079 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002080 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002081 }
2082 Py_DECREF(loader);
2083 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002084 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002085}
2086
Nick Coghland6009512014-11-20 21:39:37 +10002087/* Import the site module (not into __main__ though) */
2088
Victor Stinner331a6a52019-05-27 16:39:22 +02002089static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002090init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002091{
2092 PyObject *m;
2093 m = PyImport_ImportModule("site");
2094 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002095 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002096 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002097 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002098 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002099}
2100
Victor Stinner874dbe82015-09-04 17:29:57 +02002101/* Check if a file descriptor is valid or not.
2102 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2103static int
2104is_valid_fd(int fd)
2105{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002106/* dup() is faster than fstat(): fstat() can require input/output operations,
2107 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2108 startup. Problem: dup() doesn't check if the file descriptor is valid on
2109 some platforms.
2110
2111 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2112 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2113 EBADF. FreeBSD has similar issue (bpo-32849).
2114
2115 Only use dup() on platforms where dup() is enough to detect invalid FD in
2116 corner cases: on Linux and Windows (bpo-32849). */
2117#if defined(__linux__) || defined(MS_WINDOWS)
2118 if (fd < 0) {
2119 return 0;
2120 }
2121 int fd2;
2122
2123 _Py_BEGIN_SUPPRESS_IPH
2124 fd2 = dup(fd);
2125 if (fd2 >= 0) {
2126 close(fd2);
2127 }
2128 _Py_END_SUPPRESS_IPH
2129
2130 return (fd2 >= 0);
2131#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002132 struct stat st;
2133 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002134#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002135}
2136
2137/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002138static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002139create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002140 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002141 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002142{
2143 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2144 const char* mode;
2145 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002146 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002147 int buffering, isatty;
2148 _Py_IDENTIFIER(open);
2149 _Py_IDENTIFIER(isatty);
2150 _Py_IDENTIFIER(TextIOWrapper);
2151 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002152 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002153
Victor Stinner874dbe82015-09-04 17:29:57 +02002154 if (!is_valid_fd(fd))
2155 Py_RETURN_NONE;
2156
Nick Coghland6009512014-11-20 21:39:37 +10002157 /* stdin is always opened in buffered mode, first because it shouldn't
2158 make a difference in common use cases, second because TextIOWrapper
2159 depends on the presence of a read1() method which only exists on
2160 buffered streams.
2161 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002162 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002163 buffering = 0;
2164 else
2165 buffering = -1;
2166 if (write_mode)
2167 mode = "wb";
2168 else
2169 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002170 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002171 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002172 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002173 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002174 if (buf == NULL)
2175 goto error;
2176
2177 if (buffering) {
2178 _Py_IDENTIFIER(raw);
2179 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2180 if (raw == NULL)
2181 goto error;
2182 }
2183 else {
2184 raw = buf;
2185 Py_INCREF(raw);
2186 }
2187
Steve Dower39294992016-08-30 21:22:36 -07002188#ifdef MS_WINDOWS
2189 /* Windows console IO is always UTF-8 encoded */
2190 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002191 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002192#endif
2193
Nick Coghland6009512014-11-20 21:39:37 +10002194 text = PyUnicode_FromString(name);
2195 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2196 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002197 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002198 if (res == NULL)
2199 goto error;
2200 isatty = PyObject_IsTrue(res);
2201 Py_DECREF(res);
2202 if (isatty == -1)
2203 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002204 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002205 write_through = Py_True;
2206 else
2207 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002208 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002209 line_buffering = Py_True;
2210 else
2211 line_buffering = Py_False;
2212
2213 Py_CLEAR(raw);
2214 Py_CLEAR(text);
2215
2216#ifdef MS_WINDOWS
2217 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2218 newlines to "\n".
2219 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2220 newline = NULL;
2221#else
2222 /* sys.stdin: split lines at "\n".
2223 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2224 newline = "\n";
2225#endif
2226
Victor Stinner709d23d2019-05-02 14:56:30 -04002227 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2228 if (encoding_str == NULL) {
2229 Py_CLEAR(buf);
2230 goto error;
2231 }
2232
2233 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2234 if (errors_str == NULL) {
2235 Py_CLEAR(buf);
2236 Py_CLEAR(encoding_str);
2237 goto error;
2238 }
2239
2240 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2241 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002242 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002243 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002244 Py_CLEAR(encoding_str);
2245 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002246 if (stream == NULL)
2247 goto error;
2248
2249 if (write_mode)
2250 mode = "w";
2251 else
2252 mode = "r";
2253 text = PyUnicode_FromString(mode);
2254 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2255 goto error;
2256 Py_CLEAR(text);
2257 return stream;
2258
2259error:
2260 Py_XDECREF(buf);
2261 Py_XDECREF(stream);
2262 Py_XDECREF(text);
2263 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002264
Victor Stinner874dbe82015-09-04 17:29:57 +02002265 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2266 /* Issue #24891: the file descriptor was closed after the first
2267 is_valid_fd() check was called. Ignore the OSError and set the
2268 stream to None. */
2269 PyErr_Clear();
2270 Py_RETURN_NONE;
2271 }
2272 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002273}
2274
Victor Stinner77d668b2021-04-12 10:44:53 +02002275/* Set builtins.open to io.open */
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002276static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002277init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002278{
2279 PyObject *iomod = NULL, *wrapper;
2280 PyObject *bimod = NULL;
2281 PyStatus res = _PyStatus_OK();
2282
2283 if (!(iomod = PyImport_ImportModule("io"))) {
2284 goto error;
2285 }
2286
2287 if (!(bimod = PyImport_ImportModule("builtins"))) {
2288 goto error;
2289 }
2290
Victor Stinner77d668b2021-04-12 10:44:53 +02002291 if (!(wrapper = PyObject_GetAttrString(iomod, "open"))) {
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002292 goto error;
2293 }
2294
2295 /* Set builtins.open */
2296 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2297 Py_DECREF(wrapper);
2298 goto error;
2299 }
2300 Py_DECREF(wrapper);
2301 goto done;
2302
2303error:
2304 res = _PyStatus_ERR("can't initialize io.open");
2305
2306done:
2307 Py_XDECREF(bimod);
2308 Py_XDECREF(iomod);
2309 return res;
2310}
2311
2312
Victor Stinner77d668b2021-04-12 10:44:53 +02002313/* Create sys.stdin, sys.stdout and sys.stderr */
Victor Stinner331a6a52019-05-27 16:39:22 +02002314static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002315init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002316{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002317 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002318 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002319 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002320 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002321 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002322 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002323
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002324 /* Check that stdin is not a directory
2325 Using shell redirection, you can redirect stdin to a directory,
2326 crashing the Python interpreter. Catch this common mistake here
2327 and output a useful error message. Note that under MS Windows,
2328 the shell already prevents that. */
2329#ifndef MS_WINDOWS
2330 struct _Py_stat_struct sb;
2331 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2332 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002333 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002334 }
2335#endif
2336
Nick Coghland6009512014-11-20 21:39:37 +10002337 if (!(iomod = PyImport_ImportModule("io"))) {
2338 goto error;
2339 }
Nick Coghland6009512014-11-20 21:39:37 +10002340
Nick Coghland6009512014-11-20 21:39:37 +10002341 /* Set sys.stdin */
2342 fd = fileno(stdin);
2343 /* Under some conditions stdin, stdout and stderr may not be connected
2344 * and fileno() may point to an invalid file descriptor. For example
2345 * GUI apps don't have valid standard streams by default.
2346 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002347 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002348 config->stdio_encoding,
2349 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002350 if (std == NULL)
2351 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002352 PySys_SetObject("__stdin__", std);
2353 _PySys_SetObjectId(&PyId_stdin, std);
2354 Py_DECREF(std);
2355
2356 /* Set sys.stdout */
2357 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002358 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002359 config->stdio_encoding,
2360 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002361 if (std == NULL)
2362 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002363 PySys_SetObject("__stdout__", std);
2364 _PySys_SetObjectId(&PyId_stdout, std);
2365 Py_DECREF(std);
2366
2367#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2368 /* Set sys.stderr, replaces the preliminary stderr */
2369 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002370 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002371 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002372 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002373 if (std == NULL)
2374 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002375
2376 /* Same as hack above, pre-import stderr's codec to avoid recursion
2377 when import.c tries to write to stderr in verbose mode. */
2378 encoding_attr = PyObject_GetAttrString(std, "encoding");
2379 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002380 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002381 if (std_encoding != NULL) {
2382 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2383 Py_XDECREF(codec_info);
2384 }
2385 Py_DECREF(encoding_attr);
2386 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002387 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002388
2389 if (PySys_SetObject("__stderr__", std) < 0) {
2390 Py_DECREF(std);
2391 goto error;
2392 }
2393 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2394 Py_DECREF(std);
2395 goto error;
2396 }
2397 Py_DECREF(std);
2398#endif
2399
Victor Stinnera7368ac2017-11-15 18:11:45 -08002400 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002401
Victor Stinnera7368ac2017-11-15 18:11:45 -08002402error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002403 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002404
2405done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002406 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002407 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002408 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002409}
2410
2411
Victor Stinner10dc4842015-03-24 12:01:30 +01002412static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002413_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2414 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002415{
Victor Stinner314b8782021-01-18 18:34:56 +01002416 PUTS(fd, "\n");
Victor Stinner10dc4842015-03-24 12:01:30 +01002417
2418 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002419 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002420}
Victor Stinner791da1c2016-03-14 16:53:12 +01002421
2422/* Print the current exception (if an exception is set) with its traceback,
2423 or display the current Python stack.
2424
2425 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2426 called on catastrophic cases.
2427
2428 Return 1 if the traceback was displayed, 0 otherwise. */
2429
2430static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002431_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002432{
2433 PyObject *ferr, *res;
2434 PyObject *exception, *v, *tb;
2435 int has_tb;
2436
Victor Stinnerb45d2592019-06-20 00:05:23 +02002437 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002438 if (exception == NULL) {
2439 /* No current exception */
2440 return 0;
2441 }
2442
2443 ferr = _PySys_GetObjectId(&PyId_stderr);
2444 if (ferr == NULL || ferr == Py_None) {
2445 /* sys.stderr is not set yet or set to None,
2446 no need to try to display the exception */
2447 return 0;
2448 }
2449
Victor Stinnerb45d2592019-06-20 00:05:23 +02002450 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002451 if (tb == NULL) {
2452 tb = Py_None;
2453 Py_INCREF(tb);
2454 }
2455 PyException_SetTraceback(v, tb);
2456 if (exception == NULL) {
2457 /* PyErr_NormalizeException() failed */
2458 return 0;
2459 }
2460
2461 has_tb = (tb != Py_None);
2462 PyErr_Display(exception, v, tb);
2463 Py_XDECREF(exception);
2464 Py_XDECREF(v);
2465 Py_XDECREF(tb);
2466
2467 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002468 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002469 if (res == NULL) {
2470 _PyErr_Clear(tstate);
2471 }
2472 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002473 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002474 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002475
2476 return has_tb;
2477}
2478
Nick Coghland6009512014-11-20 21:39:37 +10002479/* Print fatal error message and abort */
2480
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002481#ifdef MS_WINDOWS
2482static void
2483fatal_output_debug(const char *msg)
2484{
2485 /* buffer of 256 bytes allocated on the stack */
2486 WCHAR buffer[256 / sizeof(WCHAR)];
2487 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2488 size_t msglen;
2489
2490 OutputDebugStringW(L"Fatal Python error: ");
2491
2492 msglen = strlen(msg);
2493 while (msglen) {
2494 size_t i;
2495
2496 if (buflen > msglen) {
2497 buflen = msglen;
2498 }
2499
2500 /* Convert the message to wchar_t. This uses a simple one-to-one
2501 conversion, assuming that the this error message actually uses
2502 ASCII only. If this ceases to be true, we will have to convert. */
2503 for (i=0; i < buflen; ++i) {
2504 buffer[i] = msg[i];
2505 }
2506 buffer[i] = L'\0';
2507 OutputDebugStringW(buffer);
2508
2509 msg += buflen;
2510 msglen -= buflen;
2511 }
2512 OutputDebugStringW(L"\n");
2513}
2514#endif
2515
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002516
2517static void
Victor Stinner314b8782021-01-18 18:34:56 +01002518fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002519{
Victor Stinner314b8782021-01-18 18:34:56 +01002520 PUTS(fd, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002521 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2522 if (finalizing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002523 PUTS(fd, "finalizing (tstate=0x");
2524 _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
2525 PUTS(fd, ")");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002526 }
2527 else if (runtime->initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002528 PUTS(fd, "initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002529 }
2530 else if (runtime->core_initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002531 PUTS(fd, "core initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002532 }
2533 else if (runtime->preinitialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002534 PUTS(fd, "preinitialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002535 }
2536 else if (runtime->preinitializing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002537 PUTS(fd, "preinitializing");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002538 }
2539 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002540 PUTS(fd, "unknown");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002541 }
Victor Stinner314b8782021-01-18 18:34:56 +01002542 PUTS(fd, "\n");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002543}
2544
2545
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002546static inline void _Py_NO_RETURN
2547fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002548{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002549 if (status < 0) {
2550#if defined(MS_WINDOWS) && defined(_DEBUG)
2551 DebugBreak();
2552#endif
2553 abort();
2554 }
2555 else {
2556 exit(status);
2557 }
2558}
2559
2560
Victor Stinner66f77ca2021-01-19 23:35:27 +01002561// Dump the list of extension modules of sys.modules, excluding stdlib modules
Victor Stinner9852cb32021-01-25 23:12:50 +01002562// (sys.stdlib_module_names), into fd file descriptor.
Victor Stinner66f77ca2021-01-19 23:35:27 +01002563//
Victor Stinner250035d2021-01-18 20:47:13 +01002564// This function is called by a signal handler in faulthandler: avoid memory
Victor Stinner66f77ca2021-01-19 23:35:27 +01002565// allocations and keep the implementation simple. For example, the list is not
2566// sorted on purpose.
Victor Stinner250035d2021-01-18 20:47:13 +01002567void
2568_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
2569{
2570 if (interp == NULL) {
2571 return;
2572 }
2573 PyObject *modules = interp->modules;
Victor Stinner66f77ca2021-01-19 23:35:27 +01002574 if (modules == NULL || !PyDict_Check(modules)) {
Victor Stinner250035d2021-01-18 20:47:13 +01002575 return;
2576 }
2577
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002578 Py_ssize_t pos;
2579 PyObject *key, *value;
2580
2581 // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
2582 // memory cannot be allocated on the heap in a signal handler.
2583 // Iterate on the dict instead.
Victor Stinner9852cb32021-01-25 23:12:50 +01002584 PyObject *stdlib_module_names = NULL;
Victor Stinner3d55aa92021-04-07 23:12:45 +02002585 if (interp->sysdict != NULL) {
2586 pos = 0;
2587 while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
2588 if (PyUnicode_Check(key)
2589 && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
2590 stdlib_module_names = value;
2591 break;
2592 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002593 }
2594 }
Victor Stinner9852cb32021-01-25 23:12:50 +01002595 // If we failed to get sys.stdlib_module_names or it's not a frozenset,
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002596 // don't exclude stdlib modules.
Victor Stinner9852cb32021-01-25 23:12:50 +01002597 if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
2598 stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002599 }
2600
2601 // List extensions
Victor Stinner66f77ca2021-01-19 23:35:27 +01002602 int header = 1;
2603 Py_ssize_t count = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002604 pos = 0;
Victor Stinner250035d2021-01-18 20:47:13 +01002605 while (PyDict_Next(modules, &pos, &key, &value)) {
2606 if (!PyUnicode_Check(key)) {
2607 continue;
2608 }
2609 if (!_PyModule_IsExtension(value)) {
2610 continue;
2611 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002612 // Use the module name from the sys.modules key,
2613 // don't attempt to get the module object name.
Victor Stinner9852cb32021-01-25 23:12:50 +01002614 if (stdlib_module_names != NULL) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002615 int is_stdlib_ext = 0;
2616
Victor Stinner9852cb32021-01-25 23:12:50 +01002617 Py_ssize_t i = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002618 PyObject *item;
2619 Py_hash_t hash;
Victor Stinner9852cb32021-01-25 23:12:50 +01002620 while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002621 if (PyUnicode_Check(item)
2622 && PyUnicode_Compare(key, item) == 0)
2623 {
2624 is_stdlib_ext = 1;
2625 break;
2626 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002627 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002628 if (is_stdlib_ext) {
2629 // Ignore stdlib extension
2630 continue;
2631 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002632 }
2633
2634 if (header) {
2635 PUTS(fd, "\nExtension modules: ");
2636 header = 0;
2637 }
2638 else {
Victor Stinner250035d2021-01-18 20:47:13 +01002639 PUTS(fd, ", ");
2640 }
Victor Stinner250035d2021-01-18 20:47:13 +01002641
2642 _Py_DumpASCII(fd, key);
Victor Stinner66f77ca2021-01-19 23:35:27 +01002643 count++;
Victor Stinner250035d2021-01-18 20:47:13 +01002644 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002645
2646 if (count) {
2647 PUTS(fd, " (total: ");
2648 _Py_DumpDecimal(fd, count);
2649 PUTS(fd, ")");
2650 PUTS(fd, "\n");
2651 }
Victor Stinner250035d2021-01-18 20:47:13 +01002652}
2653
2654
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002655static void _Py_NO_RETURN
Victor Stinner314b8782021-01-18 18:34:56 +01002656fatal_error(int fd, int header, const char *prefix, const char *msg,
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002657 int status)
2658{
Victor Stinner53345a42015-03-25 01:55:14 +01002659 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002660
2661 if (reentrant) {
2662 /* Py_FatalError() caused a second fatal error.
2663 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002664 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002665 }
2666 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002667
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002668 if (header) {
Victor Stinner314b8782021-01-18 18:34:56 +01002669 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002670 if (prefix) {
Victor Stinner314b8782021-01-18 18:34:56 +01002671 PUTS(fd, prefix);
2672 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002673 }
2674 if (msg) {
Victor Stinner314b8782021-01-18 18:34:56 +01002675 PUTS(fd, msg);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002676 }
2677 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002678 PUTS(fd, "<message not set>");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002679 }
Victor Stinner314b8782021-01-18 18:34:56 +01002680 PUTS(fd, "\n");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002681 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002682
2683 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner314b8782021-01-18 18:34:56 +01002684 fatal_error_dump_runtime(fd, runtime);
Victor Stinner10dc4842015-03-24 12:01:30 +01002685
Victor Stinner3a228ab2018-11-01 00:26:41 +01002686 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002687 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002688
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002689 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2690 has no Python thread state.
2691
2692 tss_tstate != tstate if the current Python thread does not hold the GIL.
2693 */
Victor Stinner314b8782021-01-18 18:34:56 +01002694 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2695 PyInterpreterState *interp = NULL;
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002696 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
Victor Stinner314b8782021-01-18 18:34:56 +01002697 if (tstate != NULL) {
2698 interp = tstate->interp;
2699 }
2700 else if (tss_tstate != NULL) {
2701 interp = tss_tstate->interp;
2702 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002703 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner314b8782021-01-18 18:34:56 +01002704
Victor Stinner3a228ab2018-11-01 00:26:41 +01002705 if (has_tstate_and_gil) {
2706 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002707 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002708 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002709 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002710 }
2711 }
2712 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002713 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002714 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002715
Victor Stinner250035d2021-01-18 20:47:13 +01002716 _Py_DumpExtensionModules(fd, interp);
2717
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002718 /* The main purpose of faulthandler is to display the traceback.
2719 This function already did its best to display a traceback.
2720 Disable faulthandler to prevent writing a second traceback
2721 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002722 _PyFaulthandler_Fini();
2723
Victor Stinner791da1c2016-03-14 16:53:12 +01002724 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002725 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002726 /* Flush sys.stdout and sys.stderr */
2727 flush_std_files();
2728 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002729
Nick Coghland6009512014-11-20 21:39:37 +10002730#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002731 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002732#endif /* MS_WINDOWS */
2733
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002734 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002735}
2736
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002737
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002738#undef Py_FatalError
2739
Victor Stinner19760862017-12-20 01:41:59 +01002740void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002741Py_FatalError(const char *msg)
2742{
Victor Stinner314b8782021-01-18 18:34:56 +01002743 fatal_error(fileno(stderr), 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002744}
2745
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002746
Victor Stinner19760862017-12-20 01:41:59 +01002747void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002748_Py_FatalErrorFunc(const char *func, const char *msg)
2749{
Victor Stinner314b8782021-01-18 18:34:56 +01002750 fatal_error(fileno(stderr), 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002751}
2752
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002753
2754void _Py_NO_RETURN
2755_Py_FatalErrorFormat(const char *func, const char *format, ...)
2756{
2757 static int reentrant = 0;
2758 if (reentrant) {
2759 /* _Py_FatalErrorFormat() caused a second fatal error */
2760 fatal_error_exit(-1);
2761 }
2762 reentrant = 1;
2763
2764 FILE *stream = stderr;
Victor Stinner314b8782021-01-18 18:34:56 +01002765 const int fd = fileno(stream);
2766 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002767 if (func) {
Victor Stinner314b8782021-01-18 18:34:56 +01002768 PUTS(fd, func);
2769 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002770 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002771
2772 va_list vargs;
2773#ifdef HAVE_STDARG_PROTOTYPES
2774 va_start(vargs, format);
2775#else
2776 va_start(vargs);
2777#endif
2778 vfprintf(stream, format, vargs);
2779 va_end(vargs);
2780
2781 fputs("\n", stream);
2782 fflush(stream);
2783
Victor Stinner314b8782021-01-18 18:34:56 +01002784 fatal_error(fd, 0, NULL, NULL, -1);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002785}
2786
2787
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002788void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002789Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002790{
Victor Stinner331a6a52019-05-27 16:39:22 +02002791 if (_PyStatus_IS_EXIT(status)) {
2792 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002793 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002794 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner314b8782021-01-18 18:34:56 +01002795 fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002796 }
2797 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002798 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002799 }
Nick Coghland6009512014-11-20 21:39:37 +10002800}
2801
Victor Stinner357704c2020-12-14 23:07:54 +01002802
Nick Coghland6009512014-11-20 21:39:37 +10002803/* Wait until threading._shutdown completes, provided
2804 the threading module was imported in the first place.
2805 The shutdown routine will wait until all non-daemon
2806 "threading" threads have completed. */
2807static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002808wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002809{
Nick Coghland6009512014-11-20 21:39:37 +10002810 _Py_IDENTIFIER(_shutdown);
2811 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002812 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002813 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002814 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002815 PyErr_WriteUnraisable(NULL);
2816 }
2817 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002818 return;
2819 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002820 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002821 if (result == NULL) {
2822 PyErr_WriteUnraisable(threading);
2823 }
2824 else {
2825 Py_DECREF(result);
2826 }
2827 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002828}
2829
2830#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002831int Py_AtExit(void (*func)(void))
2832{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002833 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002834 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002835 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002836 return 0;
2837}
2838
2839static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002840call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002841{
Victor Stinner8e91c242019-04-24 17:24:01 +02002842 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002843 /* pop last function from the list */
2844 runtime->nexitfuncs--;
2845 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2846 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2847
2848 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002849 }
Nick Coghland6009512014-11-20 21:39:37 +10002850
2851 fflush(stdout);
2852 fflush(stderr);
2853}
2854
Victor Stinnercfc88312018-08-01 16:41:25 +02002855void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002856Py_Exit(int sts)
2857{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002858 if (Py_FinalizeEx() < 0) {
2859 sts = 120;
2860 }
Nick Coghland6009512014-11-20 21:39:37 +10002861
2862 exit(sts);
2863}
2864
Nick Coghland6009512014-11-20 21:39:37 +10002865
Nick Coghland6009512014-11-20 21:39:37 +10002866/*
2867 * The file descriptor fd is considered ``interactive'' if either
2868 * a) isatty(fd) is TRUE, or
2869 * b) the -i flag was given, and the filename associated with
2870 * the descriptor is NULL or "<stdin>" or "???".
2871 */
2872int
2873Py_FdIsInteractive(FILE *fp, const char *filename)
2874{
2875 if (isatty((int)fileno(fp)))
2876 return 1;
2877 if (!Py_InteractiveFlag)
2878 return 0;
2879 return (filename == NULL) ||
2880 (strcmp(filename, "<stdin>") == 0) ||
2881 (strcmp(filename, "???") == 0);
2882}
2883
2884
Victor Stinnera82f63f2020-12-09 22:37:27 +01002885int
2886_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2887{
2888 if (isatty((int)fileno(fp))) {
2889 return 1;
2890 }
2891 if (!Py_InteractiveFlag) {
2892 return 0;
2893 }
2894 return (filename == NULL) ||
2895 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2896 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2897}
2898
2899
Nick Coghland6009512014-11-20 21:39:37 +10002900/* Wrappers around sigaction() or signal(). */
2901
2902PyOS_sighandler_t
2903PyOS_getsig(int sig)
2904{
2905#ifdef HAVE_SIGACTION
2906 struct sigaction context;
2907 if (sigaction(sig, NULL, &context) == -1)
2908 return SIG_ERR;
2909 return context.sa_handler;
2910#else
2911 PyOS_sighandler_t handler;
2912/* Special signal handling for the secure CRT in Visual Studio 2005 */
2913#if defined(_MSC_VER) && _MSC_VER >= 1400
2914 switch (sig) {
2915 /* Only these signals are valid */
2916 case SIGINT:
2917 case SIGILL:
2918 case SIGFPE:
2919 case SIGSEGV:
2920 case SIGTERM:
2921 case SIGBREAK:
2922 case SIGABRT:
2923 break;
2924 /* Don't call signal() with other values or it will assert */
2925 default:
2926 return SIG_ERR;
2927 }
2928#endif /* _MSC_VER && _MSC_VER >= 1400 */
2929 handler = signal(sig, SIG_IGN);
2930 if (handler != SIG_ERR)
2931 signal(sig, handler);
2932 return handler;
2933#endif
2934}
2935
2936/*
2937 * All of the code in this function must only use async-signal-safe functions,
2938 * listed at `man 7 signal` or
2939 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2940 */
2941PyOS_sighandler_t
2942PyOS_setsig(int sig, PyOS_sighandler_t handler)
2943{
2944#ifdef HAVE_SIGACTION
2945 /* Some code in Modules/signalmodule.c depends on sigaction() being
2946 * used here if HAVE_SIGACTION is defined. Fix that if this code
2947 * changes to invalidate that assumption.
2948 */
2949 struct sigaction context, ocontext;
2950 context.sa_handler = handler;
2951 sigemptyset(&context.sa_mask);
Gregory P. Smith02ac6f42021-03-04 21:49:30 -08002952 /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
2953 * extension module or embedding code may use where tiny thread stacks
2954 * are used. https://bugs.python.org/issue43390 */
2955 context.sa_flags = SA_ONSTACK;
Nick Coghland6009512014-11-20 21:39:37 +10002956 if (sigaction(sig, &context, &ocontext) == -1)
2957 return SIG_ERR;
2958 return ocontext.sa_handler;
2959#else
2960 PyOS_sighandler_t oldhandler;
2961 oldhandler = signal(sig, handler);
2962#ifdef HAVE_SIGINTERRUPT
2963 siginterrupt(sig, 1);
2964#endif
2965 return oldhandler;
2966#endif
2967}
2968
2969#ifdef __cplusplus
2970}
2971#endif