blob: 8309477806f7a3bfcd22fa1140f8bc0defd99260 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
Victor Stinner4f98f462020-04-15 04:01:58 +02005#include "pycore_ceval.h" // _PyEval_FiniGIL()
6#include "pycore_context.h" // _PyContext_Init()
7#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner62230712020-11-18 23:18:29 +01008#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner4f98f462020-04-15 04:01:58 +02009#include "pycore_initconfig.h" // _PyStatus_OK()
10#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
11#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
12#include "pycore_pyerrors.h" // _PyErr_Occurred()
13#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020014#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020015#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
16#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
17
Victor Stinner4f98f462020-04-15 04:01:58 +020018#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100019
20#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020021# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100022#endif
23
24#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020025# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100026#endif
27
28#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020029# undef BYTE
30# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070031
Victor Stinner4f98f462020-04-15 04:01:58 +020032 extern PyTypeObject PyWindowsConsoleIO_Type;
33# define PyWindowsConsoleIO_Check(op) \
34 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100035#endif
36
Victor Stinner4f98f462020-04-15 04:01:58 +020037
Victor Stinner314b8782021-01-18 18:34:56 +010038#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
39
40
Nick Coghland6009512014-11-20 21:39:37 +100041_Py_IDENTIFIER(flush);
42_Py_IDENTIFIER(name);
43_Py_IDENTIFIER(stdin);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060046_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100047
48#ifdef __cplusplus
49extern "C" {
50#endif
51
Nick Coghland6009512014-11-20 21:39:37 +100052
Victor Stinnerb45d2592019-06-20 00:05:23 +020053/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020054static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020055static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050056static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020057static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020058static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020059static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100060
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080061int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010063static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060064
Victor Stinner331a6a52019-05-27 16:39:22 +020065PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066_PyRuntime_Initialize(void)
67{
68 /* XXX We only initialize once in the process, which aligns with
69 the static initialization of the former globals now found in
70 _PyRuntime. However, _PyRuntime *should* be initialized with
71 every Py_Initialize() call, but doing so breaks the runtime.
72 This is because the runtime state is not properly finalized
73 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010074 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020075 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010077 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078
79 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080}
81
82void
83_PyRuntime_Finalize(void)
84{
85 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
88
89int
90_Py_IsFinalizing(void)
91{
Victor Stinner7b3c2522020-03-07 00:24:23 +010092 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060093}
94
Nick Coghland6009512014-11-20 21:39:37 +100095/* Hack to force loading of object files */
96int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
97 PyOS_mystrnicmp; /* Python/pystrcmp.o */
98
Eric Snowc7ec9982017-05-23 23:00:52 -070099
Eric Snow1abcf672017-05-23 21:46:51 -0700100/* APIs to access the initialization flags
101 *
102 * Can be called prior to Py_Initialize.
103 */
Nick Coghland6009512014-11-20 21:39:37 +1000104
Eric Snow1abcf672017-05-23 21:46:51 -0700105int
106_Py_IsCoreInitialized(void)
107{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600108 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700109}
Nick Coghland6009512014-11-20 21:39:37 +1000110
111int
112Py_IsInitialized(void)
113{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000115}
116
Nick Coghlan6ea41862017-06-11 13:16:15 +1000117
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000118/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
119 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000120 initializations fail, a fatal error is issued and the function does
121 not return. On return, the first thread and interpreter state have
122 been created.
123
124 Locking: you must hold the interpreter lock while calling this.
125 (If the lock has not yet been initialized, that's equivalent to
126 having the lock, but you cannot use multiple threads.)
127
128*/
Victor Stinneref75a622020-11-12 15:14:13 +0100129static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200130init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000131{
Victor Stinneref75a622020-11-12 15:14:13 +0100132 assert(!_PyErr_Occurred(tstate));
133
Victor Stinnerb45d2592019-06-20 00:05:23 +0200134 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200135 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000136
Victor Stinneref75a622020-11-12 15:14:13 +0100137 // Import _importlib through its frozen version, _frozen_importlib.
138 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000139 PySys_FormatStderr("import _frozen_importlib # frozen\n");
140 }
Victor Stinneref75a622020-11-12 15:14:13 +0100141 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
142 return -1;
143 }
144 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000145 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100146 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000147 }
Victor Stinneref75a622020-11-12 15:14:13 +0100148 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000149
Victor Stinneref75a622020-11-12 15:14:13 +0100150 // Import the _imp module
151 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200152 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000153 }
Victor Stinner62230712020-11-18 23:18:29 +0100154 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100155 if (imp_mod == NULL) {
156 return -1;
157 }
158 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
159 Py_DECREF(imp_mod);
160 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000161 }
162
Victor Stinneref75a622020-11-12 15:14:13 +0100163 // Install importlib as the implementation of import
164 PyObject *value = PyObject_CallMethod(importlib, "_install",
165 "OO", sysmod, imp_mod);
166 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000167 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100168 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000169 }
170 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000171
Victor Stinneref75a622020-11-12 15:14:13 +0100172 assert(!_PyErr_Occurred(tstate));
173 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000174}
175
Victor Stinneref75a622020-11-12 15:14:13 +0100176
Victor Stinner331a6a52019-05-27 16:39:22 +0200177static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200178init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700179{
180 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200181 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700182 "_install_external_importers", "");
183 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200184 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200185 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700186 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200187 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200188 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700189}
Nick Coghland6009512014-11-20 21:39:37 +1000190
Nick Coghlan6ea41862017-06-11 13:16:15 +1000191/* Helper functions to better handle the legacy C locale
192 *
193 * The legacy C locale assumes ASCII as the default text encoding, which
194 * causes problems not only for the CPython runtime, but also other
195 * components like GNU readline.
196 *
197 * Accordingly, when the CLI detects it, it attempts to coerce it to a
198 * more capable UTF-8 based alternative as follows:
199 *
200 * if (_Py_LegacyLocaleDetected()) {
201 * _Py_CoerceLegacyLocale();
202 * }
203 *
204 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
205 *
206 * Locale coercion also impacts the default error handler for the standard
207 * streams: while the usual default is "strict", the default for the legacy
208 * C locale and for any of the coercion target locales is "surrogateescape".
209 */
210
211int
Victor Stinner0f721472019-05-20 17:16:38 +0200212_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000213{
214#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200215 if (!warn) {
216 const char *locale_override = getenv("LC_ALL");
217 if (locale_override != NULL && *locale_override != '\0') {
218 /* Don't coerce C locale if the LC_ALL environment variable
219 is set */
220 return 0;
221 }
222 }
223
Nick Coghlan6ea41862017-06-11 13:16:15 +1000224 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000225 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
226 * the POSIX locale as a simple alias for the C locale, so
227 * we may also want to check for that explicitly.
228 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000229 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
230 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
231#else
232 /* Windows uses code pages instead of locales, so no locale is legacy */
233 return 0;
234#endif
235}
236
Victor Stinnerb0051362019-11-22 17:52:42 +0100237#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000238static const char *_C_LOCALE_WARNING =
239 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
240 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
241 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
242 "locales is recommended.\n";
243
Nick Coghlaneb817952017-06-18 12:29:42 +1000244static void
Victor Stinner43125222019-04-24 18:23:53 +0200245emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000246{
Victor Stinner331a6a52019-05-27 16:39:22 +0200247 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200248 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200249 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000250 }
251}
Victor Stinnerb0051362019-11-22 17:52:42 +0100252#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000253
Nick Coghlan6ea41862017-06-11 13:16:15 +1000254typedef struct _CandidateLocale {
255 const char *locale_name; /* The locale to try as a coercion target */
256} _LocaleCoercionTarget;
257
258static _LocaleCoercionTarget _TARGET_LOCALES[] = {
259 {"C.UTF-8"},
260 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000261 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000262 {NULL}
263};
264
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200265
266int
267_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000268{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200269 const _LocaleCoercionTarget *target = NULL;
270 for (target = _TARGET_LOCALES; target->locale_name; target++) {
271 if (strcmp(ctype_loc, target->locale_name) == 0) {
272 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000273 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200274 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200275 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276}
277
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200278
Nick Coghlan6ea41862017-06-11 13:16:15 +1000279#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100280static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000281 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
282 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
283
Victor Stinner0f721472019-05-20 17:16:38 +0200284static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200285_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000286{
287 const char *newloc = target->locale_name;
288
289 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100290 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291
292 /* Set the relevant locale environment variable */
293 if (setenv("LC_CTYPE", newloc, 1)) {
294 fprintf(stderr,
295 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200296 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200298 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100299 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000300 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301
302 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100303 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200304 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305}
306#endif
307
Victor Stinner0f721472019-05-20 17:16:38 +0200308int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200309_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310{
Victor Stinner0f721472019-05-20 17:16:38 +0200311 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200313 char *oldloc = NULL;
314
315 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
316 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200317 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200318 }
319
Victor Stinner94540602017-12-16 04:54:22 +0100320 const char *locale_override = getenv("LC_ALL");
321 if (locale_override == NULL || *locale_override == '\0') {
322 /* LC_ALL is also not set (or is set to an empty string) */
323 const _LocaleCoercionTarget *target = NULL;
324 for (target = _TARGET_LOCALES; target->locale_name; target++) {
325 const char *new_locale = setlocale(LC_CTYPE,
326 target->locale_name);
327 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400328#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100329 /* Also ensure that nl_langinfo works in this locale */
330 char *codeset = nl_langinfo(CODESET);
331 if (!codeset || *codeset == '\0') {
332 /* CODESET is not set or empty, so skip coercion */
333 new_locale = NULL;
334 _Py_SetLocaleFromEnv(LC_CTYPE);
335 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000336 }
Victor Stinner94540602017-12-16 04:54:22 +0100337#endif
338 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200339 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200340 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000341 }
342 }
343 }
344 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200345
346 setlocale(LC_CTYPE, oldloc);
347
348done:
349 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200351 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000352}
353
xdegaye1588be62017-11-12 12:45:59 +0100354/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
355 * isolate the idiosyncrasies of different libc implementations. It reads the
356 * appropriate environment variable and uses its value to select the locale for
357 * 'category'. */
358char *
359_Py_SetLocaleFromEnv(int category)
360{
Victor Stinner353933e2018-11-23 13:08:26 +0100361 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100362#ifdef __ANDROID__
363 const char *locale;
364 const char **pvar;
365#ifdef PY_COERCE_C_LOCALE
366 const char *coerce_c_locale;
367#endif
368 const char *utf8_locale = "C.UTF-8";
369 const char *env_var_set[] = {
370 "LC_ALL",
371 "LC_CTYPE",
372 "LANG",
373 NULL,
374 };
375
376 /* Android setlocale(category, "") doesn't check the environment variables
377 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
378 * check the environment variables listed in env_var_set. */
379 for (pvar=env_var_set; *pvar; pvar++) {
380 locale = getenv(*pvar);
381 if (locale != NULL && *locale != '\0') {
382 if (strcmp(locale, utf8_locale) == 0 ||
383 strcmp(locale, "en_US.UTF-8") == 0) {
384 return setlocale(category, utf8_locale);
385 }
386 return setlocale(category, "C");
387 }
388 }
389
390 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
391 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
392 * Quote from POSIX section "8.2 Internationalization Variables":
393 * "4. If the LANG environment variable is not set or is set to the empty
394 * string, the implementation-defined default locale shall be used." */
395
396#ifdef PY_COERCE_C_LOCALE
397 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
398 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
399 /* Some other ported code may check the environment variables (e.g. in
400 * extension modules), so we make sure that they match the locale
401 * configuration */
402 if (setenv("LC_CTYPE", utf8_locale, 1)) {
403 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
404 "environment variable to %s\n", utf8_locale);
405 }
406 }
407#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100408 res = setlocale(category, utf8_locale);
409#else /* !defined(__ANDROID__) */
410 res = setlocale(category, "");
411#endif
412 _Py_ResetForceASCII();
413 return res;
xdegaye1588be62017-11-12 12:45:59 +0100414}
415
Nick Coghlan6ea41862017-06-11 13:16:15 +1000416
Victor Stinner048a3562020-11-05 00:45:56 +0100417static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100418interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100419{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100420 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100421
Victor Stinner9e1b8282020-11-10 13:21:52 +0100422 if (!only_update_path_config) {
423 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
424 if (_PyStatus_EXCEPTION(status)) {
425 _PyErr_SetFromPyStatus(status);
426 return -1;
427 }
Victor Stinner048a3562020-11-05 00:45:56 +0100428 }
429
Victor Stinner101bf692021-02-19 13:33:31 +0100430 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner9e1b8282020-11-10 13:21:52 +0100431 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100432 if (_PyStatus_EXCEPTION(status)) {
433 _PyErr_SetFromPyStatus(status);
434 return -1;
435 }
436 }
437
438 // Update the sys module for the new configuration
439 if (_PySys_UpdateConfig(tstate) < 0) {
440 return -1;
441 }
442 return 0;
443}
444
445
446int
447_PyInterpreterState_SetConfig(const PyConfig *src_config)
448{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100449 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100450 int res = -1;
451
452 PyConfig config;
453 PyConfig_InitPythonConfig(&config);
454 PyStatus status = _PyConfig_Copy(&config, src_config);
455 if (_PyStatus_EXCEPTION(status)) {
456 _PyErr_SetFromPyStatus(status);
457 goto done;
458 }
459
460 status = PyConfig_Read(&config);
461 if (_PyStatus_EXCEPTION(status)) {
462 _PyErr_SetFromPyStatus(status);
463 goto done;
464 }
465
Victor Stinner9e1b8282020-11-10 13:21:52 +0100466 status = _PyConfig_Copy(&tstate->interp->config, &config);
467 if (_PyStatus_EXCEPTION(status)) {
468 _PyErr_SetFromPyStatus(status);
469 goto done;
470 }
471
472 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100473
474done:
475 PyConfig_Clear(&config);
476 return res;
477}
478
479
Eric Snow1abcf672017-05-23 21:46:51 -0700480/* Global initializations. Can be undone by Py_Finalize(). Don't
481 call this twice without an intervening Py_Finalize() call.
482
Victor Stinner331a6a52019-05-27 16:39:22 +0200483 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700484 must have a corresponding call to Py_Finalize.
485
486 Locking: you must hold the interpreter lock while calling these APIs.
487 (If the lock has not yet been initialized, that's equivalent to
488 having the lock, but you cannot use multiple threads.)
489
490*/
491
Victor Stinner331a6a52019-05-27 16:39:22 +0200492static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200493pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200494 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200495 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200496{
Victor Stinner331a6a52019-05-27 16:39:22 +0200497 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100498 PyThreadState *tstate = _PyThreadState_GET();
499 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200500 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100501 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200502 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100503
504 PyInterpreterState *interp = tstate->interp;
505 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200506 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100507 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100508
Victor Stinnere81f6e62020-06-08 18:12:59 +0200509 status = _PyConfig_Write(config, runtime);
510 if (_PyStatus_EXCEPTION(status)) {
511 return status;
512 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200513
Victor Stinner048a3562020-11-05 00:45:56 +0100514 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200515 if (_PyStatus_EXCEPTION(status)) {
516 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200517 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200518 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200519
Victor Stinner331a6a52019-05-27 16:39:22 +0200520 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200521 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200522 if (_PyStatus_EXCEPTION(status)) {
523 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200524 }
525 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200526 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527}
528
529
Victor Stinner331a6a52019-05-27 16:39:22 +0200530static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200531pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200532 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000533{
Victor Stinner43125222019-04-24 18:23:53 +0200534 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200536 }
Victor Stinnerda273412017-12-15 01:46:02 +0100537
Victor Stinnere81f6e62020-06-08 18:12:59 +0200538 PyStatus status = _PyConfig_Write(config, runtime);
539 if (_PyStatus_EXCEPTION(status)) {
540 return status;
541 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600542
Eric Snow1abcf672017-05-23 21:46:51 -0700543 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
544 * threads behave a little more gracefully at interpreter shutdown.
545 * We clobber it here so the new interpreter can start with a clean
546 * slate.
547 *
548 * However, this may still lead to misbehaviour if there are daemon
549 * threads still hanging around from a previous Py_Initialize/Finalize
550 * pair :(
551 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100552 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600553
Victor Stinnere81f6e62020-06-08 18:12:59 +0200554 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200555 if (_PyStatus_EXCEPTION(status)) {
556 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800557 }
558
Victor Stinner331a6a52019-05-27 16:39:22 +0200559 status = _PyInterpreterState_Enable(runtime);
560 if (_PyStatus_EXCEPTION(status)) {
561 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800562 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200563 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100564}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800565
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100566
Victor Stinner331a6a52019-05-27 16:39:22 +0200567static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200568init_interp_create_gil(PyThreadState *tstate)
569{
570 PyStatus status;
571
572 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
573 only called here. */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100574 _PyEval_FiniGIL(tstate->interp);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200575
576 /* Auto-thread-state API */
Victor Stinner87f649a2021-03-10 20:00:46 +0100577 status = _PyGILState_SetTstate(tstate);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200578 if (_PyStatus_EXCEPTION(status)) {
579 return status;
580 }
581
582 /* Create the GIL and take it */
583 status = _PyEval_InitGIL(tstate);
584 if (_PyStatus_EXCEPTION(status)) {
585 return status;
586 }
587
588 return _PyStatus_OK();
589}
590
591
592static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200593pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200594 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200595 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596{
Victor Stinner87f649a2021-03-10 20:00:46 +0100597 /* Auto-thread-state API */
598 PyStatus status = _PyGILState_Init(runtime);
599 if (_PyStatus_EXCEPTION(status)) {
600 return status;
601 }
602
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100603 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100604 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200605 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100606 }
Victor Stinner87f649a2021-03-10 20:00:46 +0100607 assert(_Py_IsMainInterpreter(interp));
Victor Stinnerda273412017-12-15 01:46:02 +0100608
Victor Stinner87f649a2021-03-10 20:00:46 +0100609 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200610 if (_PyStatus_EXCEPTION(status)) {
611 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100612 }
Nick Coghland6009512014-11-20 21:39:37 +1000613
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200614 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200615 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200616 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200617 }
Nick Coghland6009512014-11-20 21:39:37 +1000618 (void) PyThreadState_Swap(tstate);
619
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200620 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100621 if (_PyStatus_EXCEPTION(status)) {
622 return status;
623 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100624
Victor Stinnerb45d2592019-06-20 00:05:23 +0200625 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200626 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100627}
Nick Coghland6009512014-11-20 21:39:37 +1000628
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100629
Victor Stinner331a6a52019-05-27 16:39:22 +0200630static PyStatus
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100631pycore_init_types(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100632{
Victor Stinner444b39b2019-11-20 01:18:11 +0100633 PyStatus status;
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100634 int is_main_interp = _Py_IsMainInterpreter(interp);
Victor Stinner444b39b2019-11-20 01:18:11 +0100635
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100636 status = _PyGC_Init(interp);
Victor Stinner444b39b2019-11-20 01:18:11 +0100637 if (_PyStatus_EXCEPTION(status)) {
638 return status;
639 }
640
Victor Stinner0430dfa2020-06-24 15:21:54 +0200641 // Create the empty tuple singleton. It must be created before the first
642 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
643 // for example.
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100644 status = _PyTuple_Init(interp);
Victor Stinner0430dfa2020-06-24 15:21:54 +0200645 if (_PyStatus_EXCEPTION(status)) {
646 return status;
647 }
648
Victor Stinnere7e699e2019-11-20 12:08:13 +0100649 if (is_main_interp) {
650 status = _PyTypes_Init();
651 if (_PyStatus_EXCEPTION(status)) {
652 return status;
653 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100654 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100656 if (!_PyLong_Init(interp)) {
Victor Stinner630c8df2019-12-17 13:02:18 +0100657 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100658 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100659
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100660 status = _PyUnicode_Init(interp);
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200661 if (_PyStatus_EXCEPTION(status)) {
662 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100663 }
664
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100665 status = _PyBytes_Init(interp);
Victor Stinner91698d82020-06-25 14:07:40 +0200666 if (_PyStatus_EXCEPTION(status)) {
667 return status;
668 }
669
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100670 status = _PyExc_Init(interp);
Victor Stinner331a6a52019-05-27 16:39:22 +0200671 if (_PyStatus_EXCEPTION(status)) {
672 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100673 }
674
Victor Stinnere7e699e2019-11-20 12:08:13 +0100675 if (is_main_interp) {
676 if (!_PyFloat_Init()) {
677 return _PyStatus_ERR("can't init float");
678 }
Nick Coghland6009512014-11-20 21:39:37 +1000679
Victor Stinnere7e699e2019-11-20 12:08:13 +0100680 if (_PyStructSequence_Init() < 0) {
681 return _PyStatus_ERR("can't initialize structseq");
682 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100683 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200684
Victor Stinner331a6a52019-05-27 16:39:22 +0200685 status = _PyErr_Init();
686 if (_PyStatus_EXCEPTION(status)) {
687 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200688 }
689
Victor Stinnere7e699e2019-11-20 12:08:13 +0100690 if (is_main_interp) {
691 if (!_PyContext_Init()) {
692 return _PyStatus_ERR("can't init context");
693 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100694 }
695
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100696 if (_PyWarnings_InitState(interp) < 0) {
Victor Stinneref75a622020-11-12 15:14:13 +0100697 return _PyStatus_ERR("can't initialize warnings");
698 }
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100699
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100700 status = _PyAtExit_Init(interp);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100701 if (_PyStatus_EXCEPTION(status)) {
702 return status;
703 }
704
Victor Stinner331a6a52019-05-27 16:39:22 +0200705 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100706}
707
708
Victor Stinner331a6a52019-05-27 16:39:22 +0200709static PyStatus
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100710pycore_init_builtins(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100712 PyObject *bimod = _PyBuiltin_Init(interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100713 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100714 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100715 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100716
Victor Stinner2582d462019-11-22 19:24:49 +0100717 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
718 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100719 }
Victor Stinner2582d462019-11-22 19:24:49 +0100720
721 PyObject *builtins_dict = PyModule_GetDict(bimod);
722 if (builtins_dict == NULL) {
723 goto error;
724 }
725 Py_INCREF(builtins_dict);
726 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100727
Victor Stinner331a6a52019-05-27 16:39:22 +0200728 PyStatus status = _PyBuiltins_AddExceptions(bimod);
729 if (_PyStatus_EXCEPTION(status)) {
730 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100731 }
Victor Stinner2582d462019-11-22 19:24:49 +0100732
733 interp->builtins_copy = PyDict_Copy(interp->builtins);
734 if (interp->builtins_copy == NULL) {
735 goto error;
736 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000737 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100738
Victor Stinner62230712020-11-18 23:18:29 +0100739 // Get the __import__ function
740 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
741 "__import__");
742 if (import_func == NULL) {
743 goto error;
744 }
745 interp->import_func = Py_NewRef(import_func);
746
Victor Stinner331a6a52019-05-27 16:39:22 +0200747 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100748
749error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000750 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100751 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100752}
753
754
Victor Stinner331a6a52019-05-27 16:39:22 +0200755static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100756pycore_interp_init(PyThreadState *tstate)
757{
758 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100759 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100760
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100761 status = pycore_init_types(tstate->interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100762 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100763 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100764 }
765
Victor Stinnerd863ade2019-12-06 03:37:07 +0100766 status = _PySys_Create(tstate, &sysmod);
767 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100768 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100769 }
770
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100771 assert(!_PyErr_Occurred(tstate));
772
773 status = pycore_init_builtins(tstate->interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100774 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100775 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100776 }
777
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100778 assert(!_PyErr_Occurred(tstate));
779
Victor Stinneref75a622020-11-12 15:14:13 +0100780 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
781 if (config->_install_importlib) {
782 /* This call sets up builtin and frozen import support */
783 if (init_importlib(tstate, sysmod) < 0) {
784 return _PyStatus_ERR("failed to initialize importlib");
785 }
786 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100787
788done:
789 /* sys.modules['sys'] contains a strong reference to the module */
790 Py_XDECREF(sysmod);
791 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100792}
793
794
795static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200796pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200797 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200798 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100799{
Victor Stinner331a6a52019-05-27 16:39:22 +0200800 PyStatus status = pycore_init_runtime(runtime, config);
801 if (_PyStatus_EXCEPTION(status)) {
802 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100803 }
804
Victor Stinnerb45d2592019-06-20 00:05:23 +0200805 PyThreadState *tstate;
806 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200807 if (_PyStatus_EXCEPTION(status)) {
808 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100809 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200810 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100811
Victor Stinnerd863ade2019-12-06 03:37:07 +0100812 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200813 if (_PyStatus_EXCEPTION(status)) {
814 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100815 }
Eric Snow1abcf672017-05-23 21:46:51 -0700816
817 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200818 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200819 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700820}
821
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100822
Victor Stinner331a6a52019-05-27 16:39:22 +0200823PyStatus
824_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100825{
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100827
Victor Stinner6d1c4672019-05-20 11:02:00 +0200828 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200829 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200830 }
831
Victor Stinner331a6a52019-05-27 16:39:22 +0200832 status = _PyRuntime_Initialize();
833 if (_PyStatus_EXCEPTION(status)) {
834 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100835 }
Victor Stinner43125222019-04-24 18:23:53 +0200836 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100837
Victor Stinnerd3b90412019-09-17 23:59:51 +0200838 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100839 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200840 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100841 }
842
Victor Stinnerd3b90412019-09-17 23:59:51 +0200843 /* Note: preinitialized remains 1 on error, it is only set to 0
844 at exit on success. */
845 runtime->preinitializing = 1;
846
Victor Stinner331a6a52019-05-27 16:39:22 +0200847 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200848
849 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
850 if (_PyStatus_EXCEPTION(status)) {
851 return status;
852 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100853
Victor Stinner331a6a52019-05-27 16:39:22 +0200854 status = _PyPreConfig_Read(&config, args);
855 if (_PyStatus_EXCEPTION(status)) {
856 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100857 }
858
Victor Stinner331a6a52019-05-27 16:39:22 +0200859 status = _PyPreConfig_Write(&config);
860 if (_PyStatus_EXCEPTION(status)) {
861 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100862 }
863
Victor Stinnerd3b90412019-09-17 23:59:51 +0200864 runtime->preinitializing = 0;
865 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200866 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100867}
868
Victor Stinner70005ac2019-05-02 15:25:34 -0400869
Victor Stinner331a6a52019-05-27 16:39:22 +0200870PyStatus
871Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100872{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100873 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400874 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100875}
876
877
Victor Stinner331a6a52019-05-27 16:39:22 +0200878PyStatus
879Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100880{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100881 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400882 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100883}
884
885
Victor Stinner331a6a52019-05-27 16:39:22 +0200886PyStatus
887Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100888{
Victor Stinner70005ac2019-05-02 15:25:34 -0400889 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100890}
891
892
Victor Stinner331a6a52019-05-27 16:39:22 +0200893PyStatus
894_Py_PreInitializeFromConfig(const PyConfig *config,
895 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100896{
Victor Stinner331a6a52019-05-27 16:39:22 +0200897 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200898
Victor Stinner331a6a52019-05-27 16:39:22 +0200899 PyStatus status = _PyRuntime_Initialize();
900 if (_PyStatus_EXCEPTION(status)) {
901 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200902 }
903 _PyRuntimeState *runtime = &_PyRuntime;
904
Victor Stinnerd3b90412019-09-17 23:59:51 +0200905 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200906 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200907 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400908 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200909
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200911
Victor Stinner3c30a762019-10-01 10:56:37 +0200912 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200913
Victor Stinner331a6a52019-05-27 16:39:22 +0200914 if (!config->parse_argv) {
915 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200916 }
917 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200918 _PyArgv config_args = {
919 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200920 .argc = config->argv.length,
921 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200922 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200923 }
924 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200925 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200926 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100927}
928
929
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100930/* Begin interpreter initialization
931 *
932 * On return, the first thread and interpreter state have been created,
933 * but the compiler, signal handling, multithreading and
934 * multiple interpreter support, and codec infrastructure are not yet
935 * available.
936 *
937 * The import system will support builtin and frozen modules only.
938 * The only supported io is writing to sys.stderr
939 *
940 * If any operation invoked by this function fails, a fatal error is
941 * issued and the function does not return.
942 *
943 * Any code invoked from this function should *not* assume it has access
944 * to the Python C API (unless the API is explicitly listed as being
945 * safe to call without calling Py_Initialize first)
946 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200947static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200948pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200949 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200950 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200951{
Victor Stinner331a6a52019-05-27 16:39:22 +0200952 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200953
Victor Stinner331a6a52019-05-27 16:39:22 +0200954 status = _Py_PreInitializeFromConfig(src_config, NULL);
955 if (_PyStatus_EXCEPTION(status)) {
956 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200957 }
958
Victor Stinner331a6a52019-05-27 16:39:22 +0200959 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100960 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200961
Victor Stinner331a6a52019-05-27 16:39:22 +0200962 status = _PyConfig_Copy(&config, src_config);
963 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200964 goto done;
965 }
966
Victor Stinner9e1b8282020-11-10 13:21:52 +0100967 // Read the configuration, but don't compute the path configuration
968 // (it is computed in the main init).
969 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200970 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200971 goto done;
972 }
973
974 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200975 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200976 }
977 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200978 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200979 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200980 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200981 goto done;
982 }
983
984done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200985 PyConfig_Clear(&config);
986 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200987}
988
Victor Stinner5ac27a52019-03-27 13:40:14 +0100989
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200990/* Py_Initialize() has already been called: update the main interpreter
991 configuration. Example of bpo-34008: Py_Main() called after
992 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200993static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100994pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200995{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100996 if (interpreter_update_config(tstate, 0) < 0) {
997 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200998 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200999 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001000}
1001
Victor Stinnerb0051362019-11-22 17:52:42 +01001002
1003static PyStatus
1004init_interp_main(PyThreadState *tstate)
1005{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001006 assert(!_PyErr_Occurred(tstate));
1007
Victor Stinnerb0051362019-11-22 17:52:42 +01001008 PyStatus status;
Victor Stinner101bf692021-02-19 13:33:31 +01001009 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001010 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001011 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001012
1013 if (!config->_install_importlib) {
1014 /* Special mode for freeze_importlib: run with no import system
1015 *
1016 * This means anything which needs support from extension modules
1017 * or pure Python code in the standard library won't work.
1018 */
1019 if (is_main_interp) {
1020 interp->runtime->initialized = 1;
1021 }
1022 return _PyStatus_OK();
1023 }
1024
Victor Stinner9e1b8282020-11-10 13:21:52 +01001025 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001026 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001027 if (_PyStatus_EXCEPTION(status)) {
1028 return status;
1029 }
1030
Victor Stinner9e1b8282020-11-10 13:21:52 +01001031 if (interpreter_update_config(tstate, 1) < 0) {
1032 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001033 }
1034
1035 status = init_importlib_external(tstate);
1036 if (_PyStatus_EXCEPTION(status)) {
1037 return status;
1038 }
1039
1040 if (is_main_interp) {
1041 /* initialize the faulthandler module */
1042 status = _PyFaulthandler_Init(config->faulthandler);
1043 if (_PyStatus_EXCEPTION(status)) {
1044 return status;
1045 }
1046 }
1047
1048 status = _PyUnicode_InitEncodings(tstate);
1049 if (_PyStatus_EXCEPTION(status)) {
1050 return status;
1051 }
1052
1053 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001054 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1055 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001056 }
1057
1058 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1059 return _PyStatus_ERR("can't initialize tracemalloc");
1060 }
1061 }
1062
1063 status = init_sys_streams(tstate);
1064 if (_PyStatus_EXCEPTION(status)) {
1065 return status;
1066 }
1067
Andy Lester75cd5bf2020-03-12 02:49:05 -05001068 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001069 if (_PyStatus_EXCEPTION(status)) {
1070 return status;
1071 }
1072
1073 status = add_main_module(interp);
1074 if (_PyStatus_EXCEPTION(status)) {
1075 return status;
1076 }
1077
1078 if (is_main_interp) {
1079 /* Initialize warnings. */
1080 PyObject *warnoptions = PySys_GetObject("warnoptions");
1081 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1082 {
1083 PyObject *warnings_module = PyImport_ImportModule("warnings");
1084 if (warnings_module == NULL) {
1085 fprintf(stderr, "'import warnings' failed; traceback:\n");
1086 _PyErr_Print(tstate);
1087 }
1088 Py_XDECREF(warnings_module);
1089 }
1090
1091 interp->runtime->initialized = 1;
1092 }
1093
1094 if (config->site_import) {
1095 status = init_import_site();
1096 if (_PyStatus_EXCEPTION(status)) {
1097 return status;
1098 }
1099 }
1100
1101 if (is_main_interp) {
1102#ifndef MS_WINDOWS
1103 emit_stderr_warning_for_legacy_locale(interp->runtime);
1104#endif
1105 }
1106
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001107 assert(!_PyErr_Occurred(tstate));
1108
Victor Stinnerb0051362019-11-22 17:52:42 +01001109 return _PyStatus_OK();
1110}
1111
1112
Eric Snowc7ec9982017-05-23 23:00:52 -07001113/* Update interpreter state based on supplied configuration settings
1114 *
1115 * After calling this function, most of the restrictions on the interpreter
1116 * are lifted. The only remaining incomplete settings are those related
1117 * to the main module (sys.argv[0], __main__ metadata)
1118 *
1119 * Calling this when the interpreter is not initializing, is already
1120 * initialized or without a valid current thread state is a fatal error.
1121 * Other errors should be reported as normal Python exceptions with a
1122 * non-zero return code.
1123 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001124static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001125pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001126{
Victor Stinnerb0051362019-11-22 17:52:42 +01001127 PyInterpreterState *interp = tstate->interp;
1128 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001129 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001130 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001131
Victor Stinnerb0051362019-11-22 17:52:42 +01001132 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001133 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001134 }
1135
Victor Stinnerb0051362019-11-22 17:52:42 +01001136 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001137 if (_PyStatus_EXCEPTION(status)) {
1138 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001139 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001140 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001141}
1142
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001143
Victor Stinner331a6a52019-05-27 16:39:22 +02001144PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001145Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001146{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001147 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001148 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001149 }
1150
Victor Stinner331a6a52019-05-27 16:39:22 +02001151 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001152
Victor Stinner331a6a52019-05-27 16:39:22 +02001153 status = _PyRuntime_Initialize();
1154 if (_PyStatus_EXCEPTION(status)) {
1155 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001156 }
1157 _PyRuntimeState *runtime = &_PyRuntime;
1158
Victor Stinnerb45d2592019-06-20 00:05:23 +02001159 PyThreadState *tstate = NULL;
1160 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001161 if (_PyStatus_EXCEPTION(status)) {
1162 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001163 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001164 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001165
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001166 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001167 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001168 if (_PyStatus_EXCEPTION(status)) {
1169 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001170 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001171 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001172
Victor Stinner331a6a52019-05-27 16:39:22 +02001173 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001174}
1175
1176
Eric Snow1abcf672017-05-23 21:46:51 -07001177void
Nick Coghland6009512014-11-20 21:39:37 +10001178Py_InitializeEx(int install_sigs)
1179{
Victor Stinner331a6a52019-05-27 16:39:22 +02001180 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001181
Victor Stinner331a6a52019-05-27 16:39:22 +02001182 status = _PyRuntime_Initialize();
1183 if (_PyStatus_EXCEPTION(status)) {
1184 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001185 }
1186 _PyRuntimeState *runtime = &_PyRuntime;
1187
1188 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001189 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1190 return;
1191 }
1192
Victor Stinner331a6a52019-05-27 16:39:22 +02001193 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001194 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001195
Victor Stinner1dc6e392018-07-25 02:49:17 +02001196 config.install_signal_handlers = install_sigs;
1197
Victor Stinner331a6a52019-05-27 16:39:22 +02001198 status = Py_InitializeFromConfig(&config);
1199 if (_PyStatus_EXCEPTION(status)) {
1200 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001201 }
Nick Coghland6009512014-11-20 21:39:37 +10001202}
1203
1204void
1205Py_Initialize(void)
1206{
1207 Py_InitializeEx(1);
1208}
1209
1210
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001211PyStatus
1212_Py_InitializeMain(void)
1213{
1214 PyStatus status = _PyRuntime_Initialize();
1215 if (_PyStatus_EXCEPTION(status)) {
1216 return status;
1217 }
1218 _PyRuntimeState *runtime = &_PyRuntime;
1219 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1220 return pyinit_main(tstate);
1221}
1222
1223
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001224static void
1225finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1226{
1227 // List of names to clear in sys
1228 static const char * const sys_deletes[] = {
1229 "path", "argv", "ps1", "ps2",
1230 "last_type", "last_value", "last_traceback",
1231 "path_hooks", "path_importer_cache", "meta_path",
1232 "__interactivehook__",
1233 NULL
1234 };
1235
1236 static const char * const sys_files[] = {
1237 "stdin", "__stdin__",
1238 "stdout", "__stdout__",
1239 "stderr", "__stderr__",
1240 NULL
1241 };
1242
1243 PyInterpreterState *interp = tstate->interp;
1244 if (verbose) {
1245 PySys_WriteStderr("# clear builtins._\n");
1246 }
1247 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1248 PyErr_WriteUnraisable(NULL);
1249 }
1250
1251 const char * const *p;
1252 for (p = sys_deletes; *p != NULL; p++) {
1253 if (verbose) {
1254 PySys_WriteStderr("# clear sys.%s\n", *p);
1255 }
1256 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1257 PyErr_WriteUnraisable(NULL);
1258 }
1259 }
1260 for (p = sys_files; *p != NULL; p+=2) {
1261 const char *name = p[0];
1262 const char *orig_name = p[1];
1263 if (verbose) {
1264 PySys_WriteStderr("# restore sys.%s\n", name);
1265 }
1266 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1267 orig_name);
1268 if (value == NULL) {
1269 if (_PyErr_Occurred(tstate)) {
1270 PyErr_WriteUnraisable(NULL);
1271 }
1272 value = Py_None;
1273 }
1274 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1275 PyErr_WriteUnraisable(NULL);
1276 }
1277 }
1278}
1279
1280
1281static PyObject*
1282finalize_remove_modules(PyObject *modules, int verbose)
1283{
1284 PyObject *weaklist = PyList_New(0);
1285 if (weaklist == NULL) {
1286 PyErr_WriteUnraisable(NULL);
1287 }
1288
1289#define STORE_MODULE_WEAKREF(name, mod) \
1290 if (weaklist != NULL) { \
1291 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1292 if (wr) { \
1293 PyObject *tup = PyTuple_Pack(2, name, wr); \
1294 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1295 PyErr_WriteUnraisable(NULL); \
1296 } \
1297 Py_XDECREF(tup); \
1298 Py_DECREF(wr); \
1299 } \
1300 else { \
1301 PyErr_WriteUnraisable(NULL); \
1302 } \
1303 }
1304
1305#define CLEAR_MODULE(name, mod) \
1306 if (PyModule_Check(mod)) { \
1307 if (verbose && PyUnicode_Check(name)) { \
1308 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1309 } \
1310 STORE_MODULE_WEAKREF(name, mod); \
1311 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1312 PyErr_WriteUnraisable(NULL); \
1313 } \
1314 }
1315
1316 if (PyDict_CheckExact(modules)) {
1317 Py_ssize_t pos = 0;
1318 PyObject *key, *value;
1319 while (PyDict_Next(modules, &pos, &key, &value)) {
1320 CLEAR_MODULE(key, value);
1321 }
1322 }
1323 else {
1324 PyObject *iterator = PyObject_GetIter(modules);
1325 if (iterator == NULL) {
1326 PyErr_WriteUnraisable(NULL);
1327 }
1328 else {
1329 PyObject *key;
1330 while ((key = PyIter_Next(iterator))) {
1331 PyObject *value = PyObject_GetItem(modules, key);
1332 if (value == NULL) {
1333 PyErr_WriteUnraisable(NULL);
1334 continue;
1335 }
1336 CLEAR_MODULE(key, value);
1337 Py_DECREF(value);
1338 Py_DECREF(key);
1339 }
1340 if (PyErr_Occurred()) {
1341 PyErr_WriteUnraisable(NULL);
1342 }
1343 Py_DECREF(iterator);
1344 }
1345 }
1346#undef CLEAR_MODULE
1347#undef STORE_MODULE_WEAKREF
1348
1349 return weaklist;
1350}
1351
1352
1353static void
1354finalize_clear_modules_dict(PyObject *modules)
1355{
1356 if (PyDict_CheckExact(modules)) {
1357 PyDict_Clear(modules);
1358 }
1359 else {
1360 _Py_IDENTIFIER(clear);
1361 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1362 PyErr_WriteUnraisable(NULL);
1363 }
1364 }
1365}
1366
1367
1368static void
1369finalize_restore_builtins(PyThreadState *tstate)
1370{
1371 PyInterpreterState *interp = tstate->interp;
1372 PyObject *dict = PyDict_Copy(interp->builtins);
1373 if (dict == NULL) {
1374 PyErr_WriteUnraisable(NULL);
1375 }
1376 PyDict_Clear(interp->builtins);
1377 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1378 _PyErr_Clear(tstate);
1379 }
1380 Py_XDECREF(dict);
1381}
1382
1383
1384static void
1385finalize_modules_clear_weaklist(PyInterpreterState *interp,
1386 PyObject *weaklist, int verbose)
1387{
1388 // First clear modules imported later
1389 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1390 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1391 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1392 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1393 if (mod == Py_None) {
1394 continue;
1395 }
1396 assert(PyModule_Check(mod));
1397 PyObject *dict = PyModule_GetDict(mod);
1398 if (dict == interp->builtins || dict == interp->sysdict) {
1399 continue;
1400 }
1401 Py_INCREF(mod);
1402 if (verbose && PyUnicode_Check(name)) {
1403 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1404 }
1405 _PyModule_Clear(mod);
1406 Py_DECREF(mod);
1407 }
1408}
1409
1410
1411static void
1412finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1413{
1414 // Clear sys dict
1415 if (verbose) {
1416 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1417 }
1418 _PyModule_ClearDict(interp->sysdict);
1419
1420 // Clear builtins dict
1421 if (verbose) {
1422 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1423 }
1424 _PyModule_ClearDict(interp->builtins);
1425}
1426
1427
1428/* Clear modules, as good as we can */
1429static void
1430finalize_modules(PyThreadState *tstate)
1431{
1432 PyInterpreterState *interp = tstate->interp;
1433 PyObject *modules = interp->modules;
1434 if (modules == NULL) {
1435 // Already done
1436 return;
1437 }
1438 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1439
1440 // Delete some special builtins._ and sys attributes first. These are
1441 // common places where user values hide and people complain when their
1442 // destructors fail. Since the modules containing them are
1443 // deleted *last* of all, they would come too late in the normal
1444 // destruction order. Sigh.
1445 //
1446 // XXX Perhaps these precautions are obsolete. Who knows?
1447 finalize_modules_delete_special(tstate, verbose);
1448
1449 // Remove all modules from sys.modules, hoping that garbage collection
1450 // can reclaim most of them: set all sys.modules values to None.
1451 //
1452 // We prepare a list which will receive (name, weakref) tuples of
1453 // modules when they are removed from sys.modules. The name is used
1454 // for diagnosis messages (in verbose mode), while the weakref helps
1455 // detect those modules which have been held alive.
1456 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1457
1458 // Clear the modules dict
1459 finalize_clear_modules_dict(modules);
1460
1461 // Restore the original builtins dict, to ensure that any
1462 // user data gets cleared.
1463 finalize_restore_builtins(tstate);
1464
1465 // Collect garbage
1466 _PyGC_CollectNoFail(tstate);
1467
1468 // Dump GC stats before it's too late, since it uses the warnings
1469 // machinery.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001470 _PyGC_DumpShutdownStats(interp);
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001471
1472 if (weaklist != NULL) {
1473 // Now, if there are any modules left alive, clear their globals to
1474 // minimize potential leaks. All C extension modules actually end
1475 // up here, since they are kept alive in the interpreter state.
1476 //
1477 // The special treatment of "builtins" here is because even
1478 // when it's not referenced as a module, its dictionary is
1479 // referenced by almost every module's __builtins__. Since
1480 // deleting a module clears its dictionary (even if there are
1481 // references left to it), we need to delete the "builtins"
1482 // module last. Likewise, we don't delete sys until the very
1483 // end because it is implicitly referenced (e.g. by print).
1484 //
1485 // Since dict is ordered in CPython 3.6+, modules are saved in
1486 // importing order. First clear modules imported later.
1487 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1488 Py_DECREF(weaklist);
1489 }
1490
1491 // Clear sys and builtins modules dict
1492 finalize_clear_sys_builtins_dict(interp, verbose);
1493
1494 // Clear module dict copies stored in the interpreter state:
1495 // clear PyInterpreterState.modules_by_index and
1496 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1497 // initialization API)
1498 _PyInterpreterState_ClearModules(interp);
1499
1500 // Clear and delete the modules directory. Actual modules will
1501 // still be there only if imported during the execution of some
1502 // destructor.
1503 Py_SETREF(interp->modules, NULL);
1504
1505 // Collect garbage once more
1506 _PyGC_CollectNoFail(tstate);
1507}
1508
1509
Nick Coghland6009512014-11-20 21:39:37 +10001510/* Flush stdout and stderr */
1511
1512static int
1513file_is_closed(PyObject *fobj)
1514{
1515 int r;
1516 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1517 if (tmp == NULL) {
1518 PyErr_Clear();
1519 return 0;
1520 }
1521 r = PyObject_IsTrue(tmp);
1522 Py_DECREF(tmp);
1523 if (r < 0)
1524 PyErr_Clear();
1525 return r > 0;
1526}
1527
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001528
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001529static int
Nick Coghland6009512014-11-20 21:39:37 +10001530flush_std_files(void)
1531{
1532 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1533 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1534 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001535 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001536
1537 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001538 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001539 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001540 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001541 status = -1;
1542 }
Nick Coghland6009512014-11-20 21:39:37 +10001543 else
1544 Py_DECREF(tmp);
1545 }
1546
1547 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001548 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001549 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001550 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001551 status = -1;
1552 }
Nick Coghland6009512014-11-20 21:39:37 +10001553 else
1554 Py_DECREF(tmp);
1555 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001556
1557 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001558}
1559
1560/* Undo the effect of Py_Initialize().
1561
1562 Beware: if multiple interpreter and/or thread states exist, these
1563 are not wiped out; only the current thread and interpreter state
1564 are deleted. But since everything else is deleted, those other
1565 interpreter and thread states should no longer be used.
1566
1567 (XXX We should do better, e.g. wipe out all interpreters and
1568 threads.)
1569
1570 Locking: as above.
1571
1572*/
1573
Victor Stinner7eee5be2019-11-20 10:38:34 +01001574
1575static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001576finalize_interp_types(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001577{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001578 _PyExc_Fini(interp);
1579 _PyFrame_Fini(interp);
1580 _PyAsyncGen_Fini(interp);
1581 _PyContext_Fini(interp);
1582 _PyType_Fini(interp);
Victor Stinnerea251802020-12-26 02:58:33 +01001583 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1584 // a dict internally.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001585 _PyUnicode_ClearInterned(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001586
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001587 _PyDict_Fini(interp);
1588 _PyList_Fini(interp);
1589 _PyTuple_Fini(interp);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001590
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001591 _PySlice_Fini(interp);
Victor Stinner3d483342019-11-22 12:27:50 +01001592
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001593 _PyBytes_Fini(interp);
1594 _PyUnicode_Fini(interp);
1595 _PyFloat_Fini(interp);
1596 _PyLong_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001597}
1598
1599
1600static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001601finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001602{
Victor Stinner101bf692021-02-19 13:33:31 +01001603 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001604
Victor Stinner7eee5be2019-11-20 10:38:34 +01001605 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001606 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001607
Kongedaa0fe02020-07-04 05:06:46 +08001608 /* Clear all loghooks */
1609 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1610 Call _PySys_ClearAuditHooks when PyObject available. */
1611 if (is_main_interp) {
1612 _PySys_ClearAuditHooks(tstate);
1613 }
1614
Victor Stinner7907f8c2020-06-08 01:22:36 +02001615 if (is_main_interp) {
1616 _Py_HashRandomization_Fini();
1617 _PyArg_Fini();
1618 _Py_ClearFileSystemEncoding();
1619 }
1620
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001621 finalize_interp_types(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001622}
1623
1624
1625static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001626finalize_interp_delete(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001627{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001628 if (_Py_IsMainInterpreter(interp)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001629 /* Cleanup auto-thread-state */
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001630 _PyGILState_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001631 }
1632
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001633 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1634 fail when it is being awaited by another running daemon thread (see
1635 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1636 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1637 called multiple times. */
1638
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001639 PyInterpreterState_Delete(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001640}
1641
1642
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001643int
1644Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001645{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001646 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001647
Victor Stinner8e91c242019-04-24 17:24:01 +02001648 _PyRuntimeState *runtime = &_PyRuntime;
1649 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001650 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001651 }
Nick Coghland6009512014-11-20 21:39:37 +10001652
Victor Stinnere225beb2019-06-03 18:14:24 +02001653 /* Get current thread state and interpreter pointer */
1654 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001655
Victor Stinnerb45d2592019-06-20 00:05:23 +02001656 // Wrap up existing "threading"-module-created, non-daemon threads.
1657 wait_for_thread_shutdown(tstate);
1658
1659 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001660 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001661
Nick Coghland6009512014-11-20 21:39:37 +10001662 /* The interpreter is still entirely intact at this point, and the
1663 * exit funcs may be relying on that. In particular, if some thread
1664 * or exit func is still waiting to do an import, the import machinery
1665 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001666 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001667 * Note that Threading.py uses an exit func to do a join on all the
1668 * threads created thru it, so this also protects pending imports in
1669 * the threads created via Threading.
1670 */
Nick Coghland6009512014-11-20 21:39:37 +10001671
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001672 _PyAtExit_Call(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001673
Victor Stinnerda273412017-12-15 01:46:02 +01001674 /* Copy the core config, PyInterpreterState_Delete() free
1675 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001676#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001677 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001678#endif
1679#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001680 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001681#endif
1682#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001683 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001684#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001685
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001686 /* Remaining daemon threads will automatically exit
1687 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001688 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001689 runtime->initialized = 0;
1690 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001691
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001692 /* Destroy the state of all threads of the interpreter, except of the
1693 current thread. In practice, only daemon threads should still be alive,
1694 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1695 Clear frames of other threads to call objects destructors. Destructors
1696 will be called in the current Python thread. Since
1697 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1698 can take the GIL at this point: if they try, they will exit
1699 immediately. */
1700 _PyThreadState_DeleteExcept(runtime, tstate);
1701
Victor Stinnere0deff32015-03-24 13:46:18 +01001702 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001703 if (flush_std_files() < 0) {
1704 status = -1;
1705 }
Nick Coghland6009512014-11-20 21:39:37 +10001706
1707 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001708 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001709
1710 /* Collect garbage. This may call finalizers; it's nice to call these
1711 * before all modules are destroyed.
1712 * XXX If a __del__ or weakref callback is triggered here, and tries to
1713 * XXX import a module, bad things can happen, because Python no
1714 * XXX longer believes it's initialized.
1715 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1716 * XXX is easy to provoke that way. I've also seen, e.g.,
1717 * XXX Exception exceptions.ImportError: 'No module named sha'
1718 * XXX in <function callback at 0x008F5718> ignored
1719 * XXX but I'm unclear on exactly how that one happens. In any case,
1720 * XXX I haven't seen a real-life report of either of these.
1721 */
Victor Stinner8b341482020-10-30 17:00:00 +01001722 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001723
Nick Coghland6009512014-11-20 21:39:37 +10001724 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001725 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001726
Inada Naoki91234a12019-06-03 21:30:58 +09001727 /* Print debug stats if any */
1728 _PyEval_Fini();
1729
Victor Stinnere0deff32015-03-24 13:46:18 +01001730 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001731 if (flush_std_files() < 0) {
1732 status = -1;
1733 }
Nick Coghland6009512014-11-20 21:39:37 +10001734
1735 /* Collect final garbage. This disposes of cycles created by
1736 * class definitions, for example.
1737 * XXX This is disabled because it caused too many problems. If
1738 * XXX a __del__ or weakref callback triggers here, Python code has
1739 * XXX a hard time running, because even the sys module has been
1740 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1741 * XXX One symptom is a sequence of information-free messages
1742 * XXX coming from threads (if a __del__ or callback is invoked,
1743 * XXX other threads can execute too, and any exception they encounter
1744 * XXX triggers a comedy of errors as subsystem after subsystem
1745 * XXX fails to find what it *expects* to find in sys to help report
1746 * XXX the exception and consequent unexpected failures). I've also
1747 * XXX seen segfaults then, after adding print statements to the
1748 * XXX Python code getting called.
1749 */
1750#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001751 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001752#endif
1753
1754 /* Disable tracemalloc after all Python objects have been destroyed,
1755 so it is possible to use tracemalloc in objects destructor. */
1756 _PyTraceMalloc_Fini();
1757
1758 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1759 _PyImport_Fini();
1760
Nick Coghland6009512014-11-20 21:39:37 +10001761 /* unload faulthandler module */
1762 _PyFaulthandler_Fini();
1763
Nick Coghland6009512014-11-20 21:39:37 +10001764 /* dump hash stats */
1765 _PyHash_Fini();
1766
Eric Snowdae02762017-09-14 00:35:58 -07001767#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001768 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001769 _PyDebug_PrintTotalRefs();
1770 }
Eric Snowdae02762017-09-14 00:35:58 -07001771#endif
Nick Coghland6009512014-11-20 21:39:37 +10001772
1773#ifdef Py_TRACE_REFS
1774 /* Display all objects still alive -- this can invoke arbitrary
1775 * __repr__ overrides, so requires a mostly-intact interpreter.
1776 * Alas, a lot of stuff may still be alive now that will be cleaned
1777 * up later.
1778 */
Victor Stinnerda273412017-12-15 01:46:02 +01001779 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001780 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001781 }
Nick Coghland6009512014-11-20 21:39:37 +10001782#endif /* Py_TRACE_REFS */
1783
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001784 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001785 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001786
1787#ifdef Py_TRACE_REFS
1788 /* Display addresses (& refcnts) of all objects still alive.
1789 * An address can be used to find the repr of the object, printed
1790 * above by _Py_PrintReferences.
1791 */
Victor Stinnerda273412017-12-15 01:46:02 +01001792 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001793 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001794 }
Nick Coghland6009512014-11-20 21:39:37 +10001795#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001796#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001797 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001798 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001799 }
Nick Coghland6009512014-11-20 21:39:37 +10001800#endif
1801
Victor Stinner8e91c242019-04-24 17:24:01 +02001802 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001803
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001804 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001805 return status;
1806}
1807
1808void
1809Py_Finalize(void)
1810{
1811 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001812}
1813
Victor Stinnerb0051362019-11-22 17:52:42 +01001814
Nick Coghland6009512014-11-20 21:39:37 +10001815/* Create and initialize a new interpreter and thread, and return the
1816 new thread. This requires that Py_Initialize() has been called
1817 first.
1818
1819 Unsuccessful initialization yields a NULL pointer. Note that *no*
1820 exception information is available even in this case -- the
1821 exception information is held in the thread, and there is no
1822 thread.
1823
1824 Locking: as above.
1825
1826*/
1827
Victor Stinner331a6a52019-05-27 16:39:22 +02001828static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001829new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001830{
Victor Stinner331a6a52019-05-27 16:39:22 +02001831 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001832
Victor Stinner331a6a52019-05-27 16:39:22 +02001833 status = _PyRuntime_Initialize();
1834 if (_PyStatus_EXCEPTION(status)) {
1835 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001836 }
1837 _PyRuntimeState *runtime = &_PyRuntime;
1838
1839 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001840 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001841 }
Nick Coghland6009512014-11-20 21:39:37 +10001842
Victor Stinner8a1be612016-03-14 22:07:55 +01001843 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1844 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001845 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001846
Victor Stinner43125222019-04-24 18:23:53 +02001847 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001848 if (interp == NULL) {
1849 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001850 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001851 }
Nick Coghland6009512014-11-20 21:39:37 +10001852
Victor Stinner43125222019-04-24 18:23:53 +02001853 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001854 if (tstate == NULL) {
1855 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001856 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001857 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001858 }
1859
Victor Stinner43125222019-04-24 18:23:53 +02001860 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001861
Eric Snow1abcf672017-05-23 21:46:51 -07001862 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001863 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001864#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001865 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001866 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001867 }
1868 else
1869#endif
1870 {
Eric Snow1abcf672017-05-23 21:46:51 -07001871 /* No current thread state, copy from the main interpreter */
1872 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001873 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001874 }
1875
Victor Stinner048a3562020-11-05 00:45:56 +01001876
1877 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001878 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001879 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001880 }
Victor Stinner252346a2020-05-01 11:33:44 +02001881 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001882
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001883 status = init_interp_create_gil(tstate);
1884 if (_PyStatus_EXCEPTION(status)) {
1885 goto error;
1886 }
1887
Victor Stinnerd863ade2019-12-06 03:37:07 +01001888 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001889 if (_PyStatus_EXCEPTION(status)) {
1890 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001891 }
1892
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001893 status = init_interp_main(tstate);
1894 if (_PyStatus_EXCEPTION(status)) {
1895 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001896 }
Nick Coghland6009512014-11-20 21:39:37 +10001897
Victor Stinnera7368ac2017-11-15 18:11:45 -08001898 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001899 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001900
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001901error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001902 *tstate_p = NULL;
1903
1904 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001905 PyErr_PrintEx(0);
1906 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001907 PyThreadState_Delete(tstate);
1908 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001909 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001910
Victor Stinnerb0051362019-11-22 17:52:42 +01001911 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001912}
1913
1914PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001915_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001916{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001917 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001918 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001919 if (_PyStatus_EXCEPTION(status)) {
1920 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001921 }
1922 return tstate;
1923
Nick Coghland6009512014-11-20 21:39:37 +10001924}
1925
Victor Stinner252346a2020-05-01 11:33:44 +02001926PyThreadState *
1927Py_NewInterpreter(void)
1928{
1929 return _Py_NewInterpreter(0);
1930}
1931
Nick Coghland6009512014-11-20 21:39:37 +10001932/* Delete an interpreter and its last thread. This requires that the
1933 given thread state is current, that the thread has no remaining
1934 frames, and that it is its interpreter's only remaining thread.
1935 It is a fatal error to violate these constraints.
1936
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001937 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001938 everything, regardless.)
1939
1940 Locking: as above.
1941
1942*/
1943
1944void
1945Py_EndInterpreter(PyThreadState *tstate)
1946{
1947 PyInterpreterState *interp = tstate->interp;
1948
Victor Stinnerb45d2592019-06-20 00:05:23 +02001949 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001950 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001951 }
1952 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001953 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001954 }
Eric Snow5be45a62019-03-08 22:47:07 -07001955 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001956
Eric Snow842a2f02019-03-15 15:47:51 -06001957 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001958 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001959
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001960 _PyAtExit_Call(tstate->interp);
Marcel Plch776407f2017-12-20 11:17:58 +01001961
Victor Stinnerb45d2592019-06-20 00:05:23 +02001962 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001963 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001964 }
Nick Coghland6009512014-11-20 21:39:37 +10001965
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001966 finalize_modules(tstate);
1967
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001968 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001969 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001970}
1971
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001972/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001973
Victor Stinner331a6a52019-05-27 16:39:22 +02001974static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001976{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001977 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001978 m = PyImport_AddModule("__main__");
1979 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001980 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001981
Nick Coghland6009512014-11-20 21:39:37 +10001982 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001983 ann_dict = PyDict_New();
1984 if ((ann_dict == NULL) ||
1985 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001986 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001987 }
1988 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001989
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001990 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1991 if (PyErr_Occurred()) {
1992 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1993 }
Nick Coghland6009512014-11-20 21:39:37 +10001994 PyObject *bimod = PyImport_ImportModule("builtins");
1995 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001996 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001997 }
1998 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001999 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002000 }
2001 Py_DECREF(bimod);
2002 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002003
Nick Coghland6009512014-11-20 21:39:37 +10002004 /* Main is a little special - imp.is_builtin("__main__") will return
2005 * False, but BuiltinImporter is still the most appropriate initial
2006 * setting for its __loader__ attribute. A more suitable value will
2007 * be set if __main__ gets further initialized later in the startup
2008 * process.
2009 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002010 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002011 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002012 if (PyErr_Occurred()) {
2013 return _PyStatus_ERR("Failed to test __main__.__loader__");
2014 }
Nick Coghland6009512014-11-20 21:39:37 +10002015 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2016 "BuiltinImporter");
2017 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002018 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002019 }
2020 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002021 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002022 }
2023 Py_DECREF(loader);
2024 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002025 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002026}
2027
Nick Coghland6009512014-11-20 21:39:37 +10002028/* Import the site module (not into __main__ though) */
2029
Victor Stinner331a6a52019-05-27 16:39:22 +02002030static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002031init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002032{
2033 PyObject *m;
2034 m = PyImport_ImportModule("site");
2035 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002036 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002037 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002038 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002039 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002040}
2041
Victor Stinner874dbe82015-09-04 17:29:57 +02002042/* Check if a file descriptor is valid or not.
2043 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2044static int
2045is_valid_fd(int fd)
2046{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002047/* dup() is faster than fstat(): fstat() can require input/output operations,
2048 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2049 startup. Problem: dup() doesn't check if the file descriptor is valid on
2050 some platforms.
2051
2052 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2053 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2054 EBADF. FreeBSD has similar issue (bpo-32849).
2055
2056 Only use dup() on platforms where dup() is enough to detect invalid FD in
2057 corner cases: on Linux and Windows (bpo-32849). */
2058#if defined(__linux__) || defined(MS_WINDOWS)
2059 if (fd < 0) {
2060 return 0;
2061 }
2062 int fd2;
2063
2064 _Py_BEGIN_SUPPRESS_IPH
2065 fd2 = dup(fd);
2066 if (fd2 >= 0) {
2067 close(fd2);
2068 }
2069 _Py_END_SUPPRESS_IPH
2070
2071 return (fd2 >= 0);
2072#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002073 struct stat st;
2074 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002075#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002076}
2077
2078/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002079static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002080create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002081 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002082 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002083{
2084 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2085 const char* mode;
2086 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002087 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002088 int buffering, isatty;
2089 _Py_IDENTIFIER(open);
2090 _Py_IDENTIFIER(isatty);
2091 _Py_IDENTIFIER(TextIOWrapper);
2092 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002093 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002094
Victor Stinner874dbe82015-09-04 17:29:57 +02002095 if (!is_valid_fd(fd))
2096 Py_RETURN_NONE;
2097
Nick Coghland6009512014-11-20 21:39:37 +10002098 /* stdin is always opened in buffered mode, first because it shouldn't
2099 make a difference in common use cases, second because TextIOWrapper
2100 depends on the presence of a read1() method which only exists on
2101 buffered streams.
2102 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002103 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002104 buffering = 0;
2105 else
2106 buffering = -1;
2107 if (write_mode)
2108 mode = "wb";
2109 else
2110 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002111 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002112 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002113 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002114 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002115 if (buf == NULL)
2116 goto error;
2117
2118 if (buffering) {
2119 _Py_IDENTIFIER(raw);
2120 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2121 if (raw == NULL)
2122 goto error;
2123 }
2124 else {
2125 raw = buf;
2126 Py_INCREF(raw);
2127 }
2128
Steve Dower39294992016-08-30 21:22:36 -07002129#ifdef MS_WINDOWS
2130 /* Windows console IO is always UTF-8 encoded */
2131 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002132 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002133#endif
2134
Nick Coghland6009512014-11-20 21:39:37 +10002135 text = PyUnicode_FromString(name);
2136 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2137 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002138 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002139 if (res == NULL)
2140 goto error;
2141 isatty = PyObject_IsTrue(res);
2142 Py_DECREF(res);
2143 if (isatty == -1)
2144 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002145 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002146 write_through = Py_True;
2147 else
2148 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002149 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002150 line_buffering = Py_True;
2151 else
2152 line_buffering = Py_False;
2153
2154 Py_CLEAR(raw);
2155 Py_CLEAR(text);
2156
2157#ifdef MS_WINDOWS
2158 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2159 newlines to "\n".
2160 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2161 newline = NULL;
2162#else
2163 /* sys.stdin: split lines at "\n".
2164 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2165 newline = "\n";
2166#endif
2167
Victor Stinner709d23d2019-05-02 14:56:30 -04002168 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2169 if (encoding_str == NULL) {
2170 Py_CLEAR(buf);
2171 goto error;
2172 }
2173
2174 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2175 if (errors_str == NULL) {
2176 Py_CLEAR(buf);
2177 Py_CLEAR(encoding_str);
2178 goto error;
2179 }
2180
2181 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2182 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002183 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002184 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002185 Py_CLEAR(encoding_str);
2186 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002187 if (stream == NULL)
2188 goto error;
2189
2190 if (write_mode)
2191 mode = "w";
2192 else
2193 mode = "r";
2194 text = PyUnicode_FromString(mode);
2195 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2196 goto error;
2197 Py_CLEAR(text);
2198 return stream;
2199
2200error:
2201 Py_XDECREF(buf);
2202 Py_XDECREF(stream);
2203 Py_XDECREF(text);
2204 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002205
Victor Stinner874dbe82015-09-04 17:29:57 +02002206 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2207 /* Issue #24891: the file descriptor was closed after the first
2208 is_valid_fd() check was called. Ignore the OSError and set the
2209 stream to None. */
2210 PyErr_Clear();
2211 Py_RETURN_NONE;
2212 }
2213 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002214}
2215
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002216/* Set builtins.open to io.OpenWrapper */
2217static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002218init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002219{
2220 PyObject *iomod = NULL, *wrapper;
2221 PyObject *bimod = NULL;
2222 PyStatus res = _PyStatus_OK();
2223
2224 if (!(iomod = PyImport_ImportModule("io"))) {
2225 goto error;
2226 }
2227
2228 if (!(bimod = PyImport_ImportModule("builtins"))) {
2229 goto error;
2230 }
2231
2232 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2233 goto error;
2234 }
2235
2236 /* Set builtins.open */
2237 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2238 Py_DECREF(wrapper);
2239 goto error;
2240 }
2241 Py_DECREF(wrapper);
2242 goto done;
2243
2244error:
2245 res = _PyStatus_ERR("can't initialize io.open");
2246
2247done:
2248 Py_XDECREF(bimod);
2249 Py_XDECREF(iomod);
2250 return res;
2251}
2252
2253
Nick Coghland6009512014-11-20 21:39:37 +10002254/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002255static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002256init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002257{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002258 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002259 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002260 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002261 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002262 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002263 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002264
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002265 /* Check that stdin is not a directory
2266 Using shell redirection, you can redirect stdin to a directory,
2267 crashing the Python interpreter. Catch this common mistake here
2268 and output a useful error message. Note that under MS Windows,
2269 the shell already prevents that. */
2270#ifndef MS_WINDOWS
2271 struct _Py_stat_struct sb;
2272 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2273 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002274 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002275 }
2276#endif
2277
Nick Coghland6009512014-11-20 21:39:37 +10002278 if (!(iomod = PyImport_ImportModule("io"))) {
2279 goto error;
2280 }
Nick Coghland6009512014-11-20 21:39:37 +10002281
Nick Coghland6009512014-11-20 21:39:37 +10002282 /* Set sys.stdin */
2283 fd = fileno(stdin);
2284 /* Under some conditions stdin, stdout and stderr may not be connected
2285 * and fileno() may point to an invalid file descriptor. For example
2286 * GUI apps don't have valid standard streams by default.
2287 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002288 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002289 config->stdio_encoding,
2290 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002291 if (std == NULL)
2292 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002293 PySys_SetObject("__stdin__", std);
2294 _PySys_SetObjectId(&PyId_stdin, std);
2295 Py_DECREF(std);
2296
2297 /* Set sys.stdout */
2298 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002299 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002300 config->stdio_encoding,
2301 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002302 if (std == NULL)
2303 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002304 PySys_SetObject("__stdout__", std);
2305 _PySys_SetObjectId(&PyId_stdout, std);
2306 Py_DECREF(std);
2307
2308#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2309 /* Set sys.stderr, replaces the preliminary stderr */
2310 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002311 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002312 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002313 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002314 if (std == NULL)
2315 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002316
2317 /* Same as hack above, pre-import stderr's codec to avoid recursion
2318 when import.c tries to write to stderr in verbose mode. */
2319 encoding_attr = PyObject_GetAttrString(std, "encoding");
2320 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002321 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002322 if (std_encoding != NULL) {
2323 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2324 Py_XDECREF(codec_info);
2325 }
2326 Py_DECREF(encoding_attr);
2327 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002328 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002329
2330 if (PySys_SetObject("__stderr__", std) < 0) {
2331 Py_DECREF(std);
2332 goto error;
2333 }
2334 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2335 Py_DECREF(std);
2336 goto error;
2337 }
2338 Py_DECREF(std);
2339#endif
2340
Victor Stinnera7368ac2017-11-15 18:11:45 -08002341 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002342
Victor Stinnera7368ac2017-11-15 18:11:45 -08002343error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002344 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002345
2346done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002347 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002348 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002349 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002350}
2351
2352
Victor Stinner10dc4842015-03-24 12:01:30 +01002353static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002354_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2355 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002356{
Victor Stinner314b8782021-01-18 18:34:56 +01002357 PUTS(fd, "\n");
Victor Stinner10dc4842015-03-24 12:01:30 +01002358
2359 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002360 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002361}
Victor Stinner791da1c2016-03-14 16:53:12 +01002362
2363/* Print the current exception (if an exception is set) with its traceback,
2364 or display the current Python stack.
2365
2366 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2367 called on catastrophic cases.
2368
2369 Return 1 if the traceback was displayed, 0 otherwise. */
2370
2371static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002372_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002373{
2374 PyObject *ferr, *res;
2375 PyObject *exception, *v, *tb;
2376 int has_tb;
2377
Victor Stinnerb45d2592019-06-20 00:05:23 +02002378 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002379 if (exception == NULL) {
2380 /* No current exception */
2381 return 0;
2382 }
2383
2384 ferr = _PySys_GetObjectId(&PyId_stderr);
2385 if (ferr == NULL || ferr == Py_None) {
2386 /* sys.stderr is not set yet or set to None,
2387 no need to try to display the exception */
2388 return 0;
2389 }
2390
Victor Stinnerb45d2592019-06-20 00:05:23 +02002391 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002392 if (tb == NULL) {
2393 tb = Py_None;
2394 Py_INCREF(tb);
2395 }
2396 PyException_SetTraceback(v, tb);
2397 if (exception == NULL) {
2398 /* PyErr_NormalizeException() failed */
2399 return 0;
2400 }
2401
2402 has_tb = (tb != Py_None);
2403 PyErr_Display(exception, v, tb);
2404 Py_XDECREF(exception);
2405 Py_XDECREF(v);
2406 Py_XDECREF(tb);
2407
2408 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002409 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002410 if (res == NULL) {
2411 _PyErr_Clear(tstate);
2412 }
2413 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002414 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002415 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002416
2417 return has_tb;
2418}
2419
Nick Coghland6009512014-11-20 21:39:37 +10002420/* Print fatal error message and abort */
2421
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002422#ifdef MS_WINDOWS
2423static void
2424fatal_output_debug(const char *msg)
2425{
2426 /* buffer of 256 bytes allocated on the stack */
2427 WCHAR buffer[256 / sizeof(WCHAR)];
2428 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2429 size_t msglen;
2430
2431 OutputDebugStringW(L"Fatal Python error: ");
2432
2433 msglen = strlen(msg);
2434 while (msglen) {
2435 size_t i;
2436
2437 if (buflen > msglen) {
2438 buflen = msglen;
2439 }
2440
2441 /* Convert the message to wchar_t. This uses a simple one-to-one
2442 conversion, assuming that the this error message actually uses
2443 ASCII only. If this ceases to be true, we will have to convert. */
2444 for (i=0; i < buflen; ++i) {
2445 buffer[i] = msg[i];
2446 }
2447 buffer[i] = L'\0';
2448 OutputDebugStringW(buffer);
2449
2450 msg += buflen;
2451 msglen -= buflen;
2452 }
2453 OutputDebugStringW(L"\n");
2454}
2455#endif
2456
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002457
2458static void
Victor Stinner314b8782021-01-18 18:34:56 +01002459fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002460{
Victor Stinner314b8782021-01-18 18:34:56 +01002461 PUTS(fd, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002462 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2463 if (finalizing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002464 PUTS(fd, "finalizing (tstate=0x");
2465 _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
2466 PUTS(fd, ")");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002467 }
2468 else if (runtime->initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002469 PUTS(fd, "initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002470 }
2471 else if (runtime->core_initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002472 PUTS(fd, "core initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002473 }
2474 else if (runtime->preinitialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002475 PUTS(fd, "preinitialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002476 }
2477 else if (runtime->preinitializing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002478 PUTS(fd, "preinitializing");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002479 }
2480 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002481 PUTS(fd, "unknown");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002482 }
Victor Stinner314b8782021-01-18 18:34:56 +01002483 PUTS(fd, "\n");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002484}
2485
2486
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002487static inline void _Py_NO_RETURN
2488fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002489{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002490 if (status < 0) {
2491#if defined(MS_WINDOWS) && defined(_DEBUG)
2492 DebugBreak();
2493#endif
2494 abort();
2495 }
2496 else {
2497 exit(status);
2498 }
2499}
2500
2501
Victor Stinner66f77ca2021-01-19 23:35:27 +01002502// Dump the list of extension modules of sys.modules, excluding stdlib modules
Victor Stinner9852cb32021-01-25 23:12:50 +01002503// (sys.stdlib_module_names), into fd file descriptor.
Victor Stinner66f77ca2021-01-19 23:35:27 +01002504//
Victor Stinner250035d2021-01-18 20:47:13 +01002505// This function is called by a signal handler in faulthandler: avoid memory
Victor Stinner66f77ca2021-01-19 23:35:27 +01002506// allocations and keep the implementation simple. For example, the list is not
2507// sorted on purpose.
Victor Stinner250035d2021-01-18 20:47:13 +01002508void
2509_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
2510{
2511 if (interp == NULL) {
2512 return;
2513 }
2514 PyObject *modules = interp->modules;
Victor Stinner66f77ca2021-01-19 23:35:27 +01002515 if (modules == NULL || !PyDict_Check(modules)) {
Victor Stinner250035d2021-01-18 20:47:13 +01002516 return;
2517 }
2518
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002519 Py_ssize_t pos;
2520 PyObject *key, *value;
2521
2522 // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
2523 // memory cannot be allocated on the heap in a signal handler.
2524 // Iterate on the dict instead.
Victor Stinner9852cb32021-01-25 23:12:50 +01002525 PyObject *stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002526 pos = 0;
2527 while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
2528 if (PyUnicode_Check(key)
Victor Stinner9852cb32021-01-25 23:12:50 +01002529 && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
2530 stdlib_module_names = value;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002531 break;
2532 }
2533 }
Victor Stinner9852cb32021-01-25 23:12:50 +01002534 // If we failed to get sys.stdlib_module_names or it's not a frozenset,
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002535 // don't exclude stdlib modules.
Victor Stinner9852cb32021-01-25 23:12:50 +01002536 if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
2537 stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002538 }
2539
2540 // List extensions
Victor Stinner66f77ca2021-01-19 23:35:27 +01002541 int header = 1;
2542 Py_ssize_t count = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002543 pos = 0;
Victor Stinner250035d2021-01-18 20:47:13 +01002544 while (PyDict_Next(modules, &pos, &key, &value)) {
2545 if (!PyUnicode_Check(key)) {
2546 continue;
2547 }
2548 if (!_PyModule_IsExtension(value)) {
2549 continue;
2550 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002551 // Use the module name from the sys.modules key,
2552 // don't attempt to get the module object name.
Victor Stinner9852cb32021-01-25 23:12:50 +01002553 if (stdlib_module_names != NULL) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002554 int is_stdlib_ext = 0;
2555
Victor Stinner9852cb32021-01-25 23:12:50 +01002556 Py_ssize_t i = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002557 PyObject *item;
2558 Py_hash_t hash;
Victor Stinner9852cb32021-01-25 23:12:50 +01002559 while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002560 if (PyUnicode_Check(item)
2561 && PyUnicode_Compare(key, item) == 0)
2562 {
2563 is_stdlib_ext = 1;
2564 break;
2565 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002566 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002567 if (is_stdlib_ext) {
2568 // Ignore stdlib extension
2569 continue;
2570 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002571 }
2572
2573 if (header) {
2574 PUTS(fd, "\nExtension modules: ");
2575 header = 0;
2576 }
2577 else {
Victor Stinner250035d2021-01-18 20:47:13 +01002578 PUTS(fd, ", ");
2579 }
Victor Stinner250035d2021-01-18 20:47:13 +01002580
2581 _Py_DumpASCII(fd, key);
Victor Stinner66f77ca2021-01-19 23:35:27 +01002582 count++;
Victor Stinner250035d2021-01-18 20:47:13 +01002583 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002584
2585 if (count) {
2586 PUTS(fd, " (total: ");
2587 _Py_DumpDecimal(fd, count);
2588 PUTS(fd, ")");
2589 PUTS(fd, "\n");
2590 }
Victor Stinner250035d2021-01-18 20:47:13 +01002591}
2592
2593
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002594static void _Py_NO_RETURN
Victor Stinner314b8782021-01-18 18:34:56 +01002595fatal_error(int fd, int header, const char *prefix, const char *msg,
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002596 int status)
2597{
Victor Stinner53345a42015-03-25 01:55:14 +01002598 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002599
2600 if (reentrant) {
2601 /* Py_FatalError() caused a second fatal error.
2602 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002603 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002604 }
2605 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002606
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002607 if (header) {
Victor Stinner314b8782021-01-18 18:34:56 +01002608 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002609 if (prefix) {
Victor Stinner314b8782021-01-18 18:34:56 +01002610 PUTS(fd, prefix);
2611 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002612 }
2613 if (msg) {
Victor Stinner314b8782021-01-18 18:34:56 +01002614 PUTS(fd, msg);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002615 }
2616 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002617 PUTS(fd, "<message not set>");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002618 }
Victor Stinner314b8782021-01-18 18:34:56 +01002619 PUTS(fd, "\n");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002620 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002621
2622 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner314b8782021-01-18 18:34:56 +01002623 fatal_error_dump_runtime(fd, runtime);
Victor Stinner10dc4842015-03-24 12:01:30 +01002624
Victor Stinner3a228ab2018-11-01 00:26:41 +01002625 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002626 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002627
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002628 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2629 has no Python thread state.
2630
2631 tss_tstate != tstate if the current Python thread does not hold the GIL.
2632 */
Victor Stinner314b8782021-01-18 18:34:56 +01002633 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2634 PyInterpreterState *interp = NULL;
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002635 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
Victor Stinner314b8782021-01-18 18:34:56 +01002636 if (tstate != NULL) {
2637 interp = tstate->interp;
2638 }
2639 else if (tss_tstate != NULL) {
2640 interp = tss_tstate->interp;
2641 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002642 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner314b8782021-01-18 18:34:56 +01002643
Victor Stinner3a228ab2018-11-01 00:26:41 +01002644 if (has_tstate_and_gil) {
2645 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002646 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002647 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002648 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002649 }
2650 }
2651 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002652 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002653 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002654
Victor Stinner250035d2021-01-18 20:47:13 +01002655 _Py_DumpExtensionModules(fd, interp);
2656
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002657 /* The main purpose of faulthandler is to display the traceback.
2658 This function already did its best to display a traceback.
2659 Disable faulthandler to prevent writing a second traceback
2660 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002661 _PyFaulthandler_Fini();
2662
Victor Stinner791da1c2016-03-14 16:53:12 +01002663 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002664 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002665 /* Flush sys.stdout and sys.stderr */
2666 flush_std_files();
2667 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002668
Nick Coghland6009512014-11-20 21:39:37 +10002669#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002670 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002671#endif /* MS_WINDOWS */
2672
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002673 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002674}
2675
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002676
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002677#undef Py_FatalError
2678
Victor Stinner19760862017-12-20 01:41:59 +01002679void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002680Py_FatalError(const char *msg)
2681{
Victor Stinner314b8782021-01-18 18:34:56 +01002682 fatal_error(fileno(stderr), 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002683}
2684
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002685
Victor Stinner19760862017-12-20 01:41:59 +01002686void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002687_Py_FatalErrorFunc(const char *func, const char *msg)
2688{
Victor Stinner314b8782021-01-18 18:34:56 +01002689 fatal_error(fileno(stderr), 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002690}
2691
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002692
2693void _Py_NO_RETURN
2694_Py_FatalErrorFormat(const char *func, const char *format, ...)
2695{
2696 static int reentrant = 0;
2697 if (reentrant) {
2698 /* _Py_FatalErrorFormat() caused a second fatal error */
2699 fatal_error_exit(-1);
2700 }
2701 reentrant = 1;
2702
2703 FILE *stream = stderr;
Victor Stinner314b8782021-01-18 18:34:56 +01002704 const int fd = fileno(stream);
2705 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002706 if (func) {
Victor Stinner314b8782021-01-18 18:34:56 +01002707 PUTS(fd, func);
2708 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002709 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002710
2711 va_list vargs;
2712#ifdef HAVE_STDARG_PROTOTYPES
2713 va_start(vargs, format);
2714#else
2715 va_start(vargs);
2716#endif
2717 vfprintf(stream, format, vargs);
2718 va_end(vargs);
2719
2720 fputs("\n", stream);
2721 fflush(stream);
2722
Victor Stinner314b8782021-01-18 18:34:56 +01002723 fatal_error(fd, 0, NULL, NULL, -1);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002724}
2725
2726
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002727void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002728Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002729{
Victor Stinner331a6a52019-05-27 16:39:22 +02002730 if (_PyStatus_IS_EXIT(status)) {
2731 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002732 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002733 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner314b8782021-01-18 18:34:56 +01002734 fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002735 }
2736 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002737 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002738 }
Nick Coghland6009512014-11-20 21:39:37 +10002739}
2740
Victor Stinner357704c2020-12-14 23:07:54 +01002741
Nick Coghland6009512014-11-20 21:39:37 +10002742/* Wait until threading._shutdown completes, provided
2743 the threading module was imported in the first place.
2744 The shutdown routine will wait until all non-daemon
2745 "threading" threads have completed. */
2746static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002747wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002748{
Nick Coghland6009512014-11-20 21:39:37 +10002749 _Py_IDENTIFIER(_shutdown);
2750 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002751 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002752 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002753 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002754 PyErr_WriteUnraisable(NULL);
2755 }
2756 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002757 return;
2758 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002759 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002760 if (result == NULL) {
2761 PyErr_WriteUnraisable(threading);
2762 }
2763 else {
2764 Py_DECREF(result);
2765 }
2766 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002767}
2768
2769#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002770int Py_AtExit(void (*func)(void))
2771{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002772 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002773 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002774 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002775 return 0;
2776}
2777
2778static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002779call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002780{
Victor Stinner8e91c242019-04-24 17:24:01 +02002781 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002782 /* pop last function from the list */
2783 runtime->nexitfuncs--;
2784 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2785 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2786
2787 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002788 }
Nick Coghland6009512014-11-20 21:39:37 +10002789
2790 fflush(stdout);
2791 fflush(stderr);
2792}
2793
Victor Stinnercfc88312018-08-01 16:41:25 +02002794void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002795Py_Exit(int sts)
2796{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002797 if (Py_FinalizeEx() < 0) {
2798 sts = 120;
2799 }
Nick Coghland6009512014-11-20 21:39:37 +10002800
2801 exit(sts);
2802}
2803
Nick Coghland6009512014-11-20 21:39:37 +10002804
Nick Coghland6009512014-11-20 21:39:37 +10002805/*
2806 * The file descriptor fd is considered ``interactive'' if either
2807 * a) isatty(fd) is TRUE, or
2808 * b) the -i flag was given, and the filename associated with
2809 * the descriptor is NULL or "<stdin>" or "???".
2810 */
2811int
2812Py_FdIsInteractive(FILE *fp, const char *filename)
2813{
2814 if (isatty((int)fileno(fp)))
2815 return 1;
2816 if (!Py_InteractiveFlag)
2817 return 0;
2818 return (filename == NULL) ||
2819 (strcmp(filename, "<stdin>") == 0) ||
2820 (strcmp(filename, "???") == 0);
2821}
2822
2823
Victor Stinnera82f63f2020-12-09 22:37:27 +01002824int
2825_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2826{
2827 if (isatty((int)fileno(fp))) {
2828 return 1;
2829 }
2830 if (!Py_InteractiveFlag) {
2831 return 0;
2832 }
2833 return (filename == NULL) ||
2834 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2835 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2836}
2837
2838
Nick Coghland6009512014-11-20 21:39:37 +10002839/* Wrappers around sigaction() or signal(). */
2840
2841PyOS_sighandler_t
2842PyOS_getsig(int sig)
2843{
2844#ifdef HAVE_SIGACTION
2845 struct sigaction context;
2846 if (sigaction(sig, NULL, &context) == -1)
2847 return SIG_ERR;
2848 return context.sa_handler;
2849#else
2850 PyOS_sighandler_t handler;
2851/* Special signal handling for the secure CRT in Visual Studio 2005 */
2852#if defined(_MSC_VER) && _MSC_VER >= 1400
2853 switch (sig) {
2854 /* Only these signals are valid */
2855 case SIGINT:
2856 case SIGILL:
2857 case SIGFPE:
2858 case SIGSEGV:
2859 case SIGTERM:
2860 case SIGBREAK:
2861 case SIGABRT:
2862 break;
2863 /* Don't call signal() with other values or it will assert */
2864 default:
2865 return SIG_ERR;
2866 }
2867#endif /* _MSC_VER && _MSC_VER >= 1400 */
2868 handler = signal(sig, SIG_IGN);
2869 if (handler != SIG_ERR)
2870 signal(sig, handler);
2871 return handler;
2872#endif
2873}
2874
2875/*
2876 * All of the code in this function must only use async-signal-safe functions,
2877 * listed at `man 7 signal` or
2878 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2879 */
2880PyOS_sighandler_t
2881PyOS_setsig(int sig, PyOS_sighandler_t handler)
2882{
2883#ifdef HAVE_SIGACTION
2884 /* Some code in Modules/signalmodule.c depends on sigaction() being
2885 * used here if HAVE_SIGACTION is defined. Fix that if this code
2886 * changes to invalidate that assumption.
2887 */
2888 struct sigaction context, ocontext;
2889 context.sa_handler = handler;
2890 sigemptyset(&context.sa_mask);
Gregory P. Smith02ac6f42021-03-04 21:49:30 -08002891 /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
2892 * extension module or embedding code may use where tiny thread stacks
2893 * are used. https://bugs.python.org/issue43390 */
2894 context.sa_flags = SA_ONSTACK;
Nick Coghland6009512014-11-20 21:39:37 +10002895 if (sigaction(sig, &context, &ocontext) == -1)
2896 return SIG_ERR;
2897 return ocontext.sa_handler;
2898#else
2899 PyOS_sighandler_t oldhandler;
2900 oldhandler = signal(sig, handler);
2901#ifdef HAVE_SIGINTERRUPT
2902 siginterrupt(sig, 1);
2903#endif
2904 return oldhandler;
2905#endif
2906}
2907
2908#ifdef __cplusplus
2909}
2910#endif