blob: 1b8c4357362d2787818c317faee97f13f7d36a07 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +02007
8#include "pycore_ceval.h" // _PyEval_FiniGIL()
9#include "pycore_context.h" // _PyContext_Init()
10#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner62230712020-11-18 23:18:29 +010011#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner4f98f462020-04-15 04:01:58 +020012#include "pycore_initconfig.h" // _PyStatus_OK()
13#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
14#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
15#include "pycore_pyerrors.h" // _PyErr_Occurred()
16#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020017#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020018#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
19#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
20
Victor Stinner4f98f462020-04-15 04:01:58 +020021#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100022
23#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020024# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100025#endif
26
27#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020028# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100029#endif
30
31#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020032# undef BYTE
33# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070034
Victor Stinner4f98f462020-04-15 04:01:58 +020035 extern PyTypeObject PyWindowsConsoleIO_Type;
36# define PyWindowsConsoleIO_Check(op) \
37 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
Victor Stinner4f98f462020-04-15 04:01:58 +020040
Victor Stinner314b8782021-01-18 18:34:56 +010041#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
42
43
Nick Coghland6009512014-11-20 21:39:37 +100044_Py_IDENTIFIER(flush);
45_Py_IDENTIFIER(name);
46_Py_IDENTIFIER(stdin);
47_Py_IDENTIFIER(stdout);
48_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060049_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100050
51#ifdef __cplusplus
52extern "C" {
53#endif
54
Nick Coghland6009512014-11-20 21:39:37 +100055
Victor Stinnerb45d2592019-06-20 00:05:23 +020056/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020057static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020058static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050059static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020060static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020061static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020062static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100063
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080064int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080065_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010066static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067
Victor Stinner331a6a52019-05-27 16:39:22 +020068PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060069_PyRuntime_Initialize(void)
70{
71 /* XXX We only initialize once in the process, which aligns with
72 the static initialization of the former globals now found in
73 _PyRuntime. However, _PyRuntime *should* be initialized with
74 every Py_Initialize() call, but doing so breaks the runtime.
75 This is because the runtime state is not properly finalized
76 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010077 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020078 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010080 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081
82 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083}
84
85void
86_PyRuntime_Finalize(void)
87{
88 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010089 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090}
91
92int
93_Py_IsFinalizing(void)
94{
Victor Stinner7b3c2522020-03-07 00:24:23 +010095 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
Nick Coghland6009512014-11-20 21:39:37 +100098/* Hack to force loading of object files */
99int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
100 PyOS_mystrnicmp; /* Python/pystrcmp.o */
101
Eric Snowc7ec9982017-05-23 23:00:52 -0700102
Eric Snow1abcf672017-05-23 21:46:51 -0700103/* APIs to access the initialization flags
104 *
105 * Can be called prior to Py_Initialize.
106 */
Nick Coghland6009512014-11-20 21:39:37 +1000107
Eric Snow1abcf672017-05-23 21:46:51 -0700108int
109_Py_IsCoreInitialized(void)
110{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600111 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700112}
Nick Coghland6009512014-11-20 21:39:37 +1000113
114int
115Py_IsInitialized(void)
116{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000118}
119
Nick Coghlan6ea41862017-06-11 13:16:15 +1000120
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000121/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
122 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000123 initializations fail, a fatal error is issued and the function does
124 not return. On return, the first thread and interpreter state have
125 been created.
126
127 Locking: you must hold the interpreter lock while calling this.
128 (If the lock has not yet been initialized, that's equivalent to
129 having the lock, but you cannot use multiple threads.)
130
131*/
Victor Stinneref75a622020-11-12 15:14:13 +0100132static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200133init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000134{
Victor Stinneref75a622020-11-12 15:14:13 +0100135 assert(!_PyErr_Occurred(tstate));
136
Victor Stinnerb45d2592019-06-20 00:05:23 +0200137 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200138 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000139
Victor Stinneref75a622020-11-12 15:14:13 +0100140 // Import _importlib through its frozen version, _frozen_importlib.
141 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000142 PySys_FormatStderr("import _frozen_importlib # frozen\n");
143 }
Victor Stinneref75a622020-11-12 15:14:13 +0100144 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
145 return -1;
146 }
147 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000148 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100149 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000150 }
Victor Stinneref75a622020-11-12 15:14:13 +0100151 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000152
Victor Stinneref75a622020-11-12 15:14:13 +0100153 // Import the _imp module
154 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200155 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000156 }
Victor Stinner62230712020-11-18 23:18:29 +0100157 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100158 if (imp_mod == NULL) {
159 return -1;
160 }
161 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
162 Py_DECREF(imp_mod);
163 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000164 }
165
Victor Stinneref75a622020-11-12 15:14:13 +0100166 // Install importlib as the implementation of import
167 PyObject *value = PyObject_CallMethod(importlib, "_install",
168 "OO", sysmod, imp_mod);
169 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000170 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100171 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000172 }
173 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000174
Victor Stinneref75a622020-11-12 15:14:13 +0100175 assert(!_PyErr_Occurred(tstate));
176 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000177}
178
Victor Stinneref75a622020-11-12 15:14:13 +0100179
Victor Stinner331a6a52019-05-27 16:39:22 +0200180static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200181init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700182{
183 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200184 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700185 "_install_external_importers", "");
186 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200187 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700189 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200190 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200191 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700192}
Nick Coghland6009512014-11-20 21:39:37 +1000193
Nick Coghlan6ea41862017-06-11 13:16:15 +1000194/* Helper functions to better handle the legacy C locale
195 *
196 * The legacy C locale assumes ASCII as the default text encoding, which
197 * causes problems not only for the CPython runtime, but also other
198 * components like GNU readline.
199 *
200 * Accordingly, when the CLI detects it, it attempts to coerce it to a
201 * more capable UTF-8 based alternative as follows:
202 *
203 * if (_Py_LegacyLocaleDetected()) {
204 * _Py_CoerceLegacyLocale();
205 * }
206 *
207 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
208 *
209 * Locale coercion also impacts the default error handler for the standard
210 * streams: while the usual default is "strict", the default for the legacy
211 * C locale and for any of the coercion target locales is "surrogateescape".
212 */
213
214int
Victor Stinner0f721472019-05-20 17:16:38 +0200215_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000216{
217#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200218 if (!warn) {
219 const char *locale_override = getenv("LC_ALL");
220 if (locale_override != NULL && *locale_override != '\0') {
221 /* Don't coerce C locale if the LC_ALL environment variable
222 is set */
223 return 0;
224 }
225 }
226
Nick Coghlan6ea41862017-06-11 13:16:15 +1000227 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000228 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
229 * the POSIX locale as a simple alias for the C locale, so
230 * we may also want to check for that explicitly.
231 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000232 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
233 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
234#else
235 /* Windows uses code pages instead of locales, so no locale is legacy */
236 return 0;
237#endif
238}
239
Victor Stinnerb0051362019-11-22 17:52:42 +0100240#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000241static const char *_C_LOCALE_WARNING =
242 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
243 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
244 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
245 "locales is recommended.\n";
246
Nick Coghlaneb817952017-06-18 12:29:42 +1000247static void
Victor Stinner43125222019-04-24 18:23:53 +0200248emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000249{
Victor Stinner331a6a52019-05-27 16:39:22 +0200250 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200251 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200252 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000253 }
254}
Victor Stinnerb0051362019-11-22 17:52:42 +0100255#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000256
Nick Coghlan6ea41862017-06-11 13:16:15 +1000257typedef struct _CandidateLocale {
258 const char *locale_name; /* The locale to try as a coercion target */
259} _LocaleCoercionTarget;
260
261static _LocaleCoercionTarget _TARGET_LOCALES[] = {
262 {"C.UTF-8"},
263 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000264 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000265 {NULL}
266};
267
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200268
269int
270_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000271{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200272 const _LocaleCoercionTarget *target = NULL;
273 for (target = _TARGET_LOCALES; target->locale_name; target++) {
274 if (strcmp(ctype_loc, target->locale_name) == 0) {
275 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200277 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200278 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000279}
280
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200281
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100283static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000284 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
285 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
286
Victor Stinner0f721472019-05-20 17:16:38 +0200287static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200288_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289{
290 const char *newloc = target->locale_name;
291
292 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100293 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294
295 /* Set the relevant locale environment variable */
296 if (setenv("LC_CTYPE", newloc, 1)) {
297 fprintf(stderr,
298 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200299 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200301 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100302 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000303 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000304
305 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100306 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200307 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000308}
309#endif
310
Victor Stinner0f721472019-05-20 17:16:38 +0200311int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200312_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313{
Victor Stinner0f721472019-05-20 17:16:38 +0200314 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200316 char *oldloc = NULL;
317
318 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
319 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200320 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200321 }
322
Victor Stinner94540602017-12-16 04:54:22 +0100323 const char *locale_override = getenv("LC_ALL");
324 if (locale_override == NULL || *locale_override == '\0') {
325 /* LC_ALL is also not set (or is set to an empty string) */
326 const _LocaleCoercionTarget *target = NULL;
327 for (target = _TARGET_LOCALES; target->locale_name; target++) {
328 const char *new_locale = setlocale(LC_CTYPE,
329 target->locale_name);
330 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400331#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100332 /* Also ensure that nl_langinfo works in this locale */
333 char *codeset = nl_langinfo(CODESET);
334 if (!codeset || *codeset == '\0') {
335 /* CODESET is not set or empty, so skip coercion */
336 new_locale = NULL;
337 _Py_SetLocaleFromEnv(LC_CTYPE);
338 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000339 }
Victor Stinner94540602017-12-16 04:54:22 +0100340#endif
341 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200342 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200343 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000344 }
345 }
346 }
347 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200348
349 setlocale(LC_CTYPE, oldloc);
350
351done:
352 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000353#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200354 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000355}
356
xdegaye1588be62017-11-12 12:45:59 +0100357/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
358 * isolate the idiosyncrasies of different libc implementations. It reads the
359 * appropriate environment variable and uses its value to select the locale for
360 * 'category'. */
361char *
362_Py_SetLocaleFromEnv(int category)
363{
Victor Stinner353933e2018-11-23 13:08:26 +0100364 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100365#ifdef __ANDROID__
366 const char *locale;
367 const char **pvar;
368#ifdef PY_COERCE_C_LOCALE
369 const char *coerce_c_locale;
370#endif
371 const char *utf8_locale = "C.UTF-8";
372 const char *env_var_set[] = {
373 "LC_ALL",
374 "LC_CTYPE",
375 "LANG",
376 NULL,
377 };
378
379 /* Android setlocale(category, "") doesn't check the environment variables
380 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
381 * check the environment variables listed in env_var_set. */
382 for (pvar=env_var_set; *pvar; pvar++) {
383 locale = getenv(*pvar);
384 if (locale != NULL && *locale != '\0') {
385 if (strcmp(locale, utf8_locale) == 0 ||
386 strcmp(locale, "en_US.UTF-8") == 0) {
387 return setlocale(category, utf8_locale);
388 }
389 return setlocale(category, "C");
390 }
391 }
392
393 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
394 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
395 * Quote from POSIX section "8.2 Internationalization Variables":
396 * "4. If the LANG environment variable is not set or is set to the empty
397 * string, the implementation-defined default locale shall be used." */
398
399#ifdef PY_COERCE_C_LOCALE
400 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
401 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
402 /* Some other ported code may check the environment variables (e.g. in
403 * extension modules), so we make sure that they match the locale
404 * configuration */
405 if (setenv("LC_CTYPE", utf8_locale, 1)) {
406 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
407 "environment variable to %s\n", utf8_locale);
408 }
409 }
410#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100411 res = setlocale(category, utf8_locale);
412#else /* !defined(__ANDROID__) */
413 res = setlocale(category, "");
414#endif
415 _Py_ResetForceASCII();
416 return res;
xdegaye1588be62017-11-12 12:45:59 +0100417}
418
Nick Coghlan6ea41862017-06-11 13:16:15 +1000419
Victor Stinner048a3562020-11-05 00:45:56 +0100420static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100421interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100422{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100423 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100424
Victor Stinner9e1b8282020-11-10 13:21:52 +0100425 if (!only_update_path_config) {
426 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
427 if (_PyStatus_EXCEPTION(status)) {
428 _PyErr_SetFromPyStatus(status);
429 return -1;
430 }
Victor Stinner048a3562020-11-05 00:45:56 +0100431 }
432
Victor Stinner101bf692021-02-19 13:33:31 +0100433 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner9e1b8282020-11-10 13:21:52 +0100434 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100435 if (_PyStatus_EXCEPTION(status)) {
436 _PyErr_SetFromPyStatus(status);
437 return -1;
438 }
439 }
440
441 // Update the sys module for the new configuration
442 if (_PySys_UpdateConfig(tstate) < 0) {
443 return -1;
444 }
445 return 0;
446}
447
448
449int
450_PyInterpreterState_SetConfig(const PyConfig *src_config)
451{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100452 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100453 int res = -1;
454
455 PyConfig config;
456 PyConfig_InitPythonConfig(&config);
457 PyStatus status = _PyConfig_Copy(&config, src_config);
458 if (_PyStatus_EXCEPTION(status)) {
459 _PyErr_SetFromPyStatus(status);
460 goto done;
461 }
462
463 status = PyConfig_Read(&config);
464 if (_PyStatus_EXCEPTION(status)) {
465 _PyErr_SetFromPyStatus(status);
466 goto done;
467 }
468
Victor Stinner9e1b8282020-11-10 13:21:52 +0100469 status = _PyConfig_Copy(&tstate->interp->config, &config);
470 if (_PyStatus_EXCEPTION(status)) {
471 _PyErr_SetFromPyStatus(status);
472 goto done;
473 }
474
475 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100476
477done:
478 PyConfig_Clear(&config);
479 return res;
480}
481
482
Eric Snow1abcf672017-05-23 21:46:51 -0700483/* Global initializations. Can be undone by Py_Finalize(). Don't
484 call this twice without an intervening Py_Finalize() call.
485
Victor Stinner331a6a52019-05-27 16:39:22 +0200486 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700487 must have a corresponding call to Py_Finalize.
488
489 Locking: you must hold the interpreter lock while calling these APIs.
490 (If the lock has not yet been initialized, that's equivalent to
491 having the lock, but you cannot use multiple threads.)
492
493*/
494
Victor Stinner331a6a52019-05-27 16:39:22 +0200495static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200496pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200497 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200498 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200499{
Victor Stinner331a6a52019-05-27 16:39:22 +0200500 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100501 PyThreadState *tstate = _PyThreadState_GET();
502 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200503 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100504 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200505 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100506
507 PyInterpreterState *interp = tstate->interp;
508 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200509 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100510 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100511
Victor Stinnere81f6e62020-06-08 18:12:59 +0200512 status = _PyConfig_Write(config, runtime);
513 if (_PyStatus_EXCEPTION(status)) {
514 return status;
515 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200516
Victor Stinner048a3562020-11-05 00:45:56 +0100517 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200518 if (_PyStatus_EXCEPTION(status)) {
519 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200520 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200521 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200522
Victor Stinner331a6a52019-05-27 16:39:22 +0200523 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200524 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200525 if (_PyStatus_EXCEPTION(status)) {
526 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527 }
528 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200529 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200530}
531
532
Victor Stinner331a6a52019-05-27 16:39:22 +0200533static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200534pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000536{
Victor Stinner43125222019-04-24 18:23:53 +0200537 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200538 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200539 }
Victor Stinnerda273412017-12-15 01:46:02 +0100540
Victor Stinnere81f6e62020-06-08 18:12:59 +0200541 PyStatus status = _PyConfig_Write(config, runtime);
542 if (_PyStatus_EXCEPTION(status)) {
543 return status;
544 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600545
Eric Snow1abcf672017-05-23 21:46:51 -0700546 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
547 * threads behave a little more gracefully at interpreter shutdown.
548 * We clobber it here so the new interpreter can start with a clean
549 * slate.
550 *
551 * However, this may still lead to misbehaviour if there are daemon
552 * threads still hanging around from a previous Py_Initialize/Finalize
553 * pair :(
554 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100555 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600556
Victor Stinnere81f6e62020-06-08 18:12:59 +0200557 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200558 if (_PyStatus_EXCEPTION(status)) {
559 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800560 }
561
Victor Stinner331a6a52019-05-27 16:39:22 +0200562 status = _PyInterpreterState_Enable(runtime);
563 if (_PyStatus_EXCEPTION(status)) {
564 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800565 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200566 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100567}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800568
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100569
Victor Stinner331a6a52019-05-27 16:39:22 +0200570static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200571init_interp_create_gil(PyThreadState *tstate)
572{
573 PyStatus status;
574
575 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
576 only called here. */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100577 _PyEval_FiniGIL(tstate->interp);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200578
579 /* Auto-thread-state API */
Victor Stinner87f649a2021-03-10 20:00:46 +0100580 status = _PyGILState_SetTstate(tstate);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200581 if (_PyStatus_EXCEPTION(status)) {
582 return status;
583 }
584
585 /* Create the GIL and take it */
586 status = _PyEval_InitGIL(tstate);
587 if (_PyStatus_EXCEPTION(status)) {
588 return status;
589 }
590
591 return _PyStatus_OK();
592}
593
594
595static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200596pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200597 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200598 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100599{
Victor Stinner87f649a2021-03-10 20:00:46 +0100600 /* Auto-thread-state API */
601 PyStatus status = _PyGILState_Init(runtime);
602 if (_PyStatus_EXCEPTION(status)) {
603 return status;
604 }
605
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100606 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100607 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200608 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100609 }
Victor Stinner87f649a2021-03-10 20:00:46 +0100610 assert(_Py_IsMainInterpreter(interp));
Victor Stinnerda273412017-12-15 01:46:02 +0100611
Victor Stinner87f649a2021-03-10 20:00:46 +0100612 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200613 if (_PyStatus_EXCEPTION(status)) {
614 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100615 }
Nick Coghland6009512014-11-20 21:39:37 +1000616
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200617 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200618 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200619 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200620 }
Nick Coghland6009512014-11-20 21:39:37 +1000621 (void) PyThreadState_Swap(tstate);
622
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200623 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100624 if (_PyStatus_EXCEPTION(status)) {
625 return status;
626 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100627
Victor Stinnerb45d2592019-06-20 00:05:23 +0200628 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200629 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100630}
Nick Coghland6009512014-11-20 21:39:37 +1000631
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100632
Victor Stinner331a6a52019-05-27 16:39:22 +0200633static PyStatus
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100634pycore_init_types(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100635{
Victor Stinner444b39b2019-11-20 01:18:11 +0100636 PyStatus status;
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100637 int is_main_interp = _Py_IsMainInterpreter(interp);
Victor Stinner444b39b2019-11-20 01:18:11 +0100638
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100639 status = _PyGC_Init(interp);
Victor Stinner444b39b2019-11-20 01:18:11 +0100640 if (_PyStatus_EXCEPTION(status)) {
641 return status;
642 }
643
Victor Stinner0430dfa2020-06-24 15:21:54 +0200644 // Create the empty tuple singleton. It must be created before the first
645 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
646 // for example.
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100647 status = _PyTuple_Init(interp);
Victor Stinner0430dfa2020-06-24 15:21:54 +0200648 if (_PyStatus_EXCEPTION(status)) {
649 return status;
650 }
651
Victor Stinnere7e699e2019-11-20 12:08:13 +0100652 if (is_main_interp) {
653 status = _PyTypes_Init();
654 if (_PyStatus_EXCEPTION(status)) {
655 return status;
656 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100657 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100658
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100659 if (!_PyLong_Init(interp)) {
Victor Stinner630c8df2019-12-17 13:02:18 +0100660 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100661 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100662
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100663 status = _PyUnicode_Init(interp);
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200664 if (_PyStatus_EXCEPTION(status)) {
665 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100666 }
667
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100668 status = _PyBytes_Init(interp);
Victor Stinner91698d82020-06-25 14:07:40 +0200669 if (_PyStatus_EXCEPTION(status)) {
670 return status;
671 }
672
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100673 status = _PyExc_Init(interp);
Victor Stinner331a6a52019-05-27 16:39:22 +0200674 if (_PyStatus_EXCEPTION(status)) {
675 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100676 }
677
Victor Stinnere7e699e2019-11-20 12:08:13 +0100678 if (is_main_interp) {
679 if (!_PyFloat_Init()) {
680 return _PyStatus_ERR("can't init float");
681 }
Nick Coghland6009512014-11-20 21:39:37 +1000682
Victor Stinnere7e699e2019-11-20 12:08:13 +0100683 if (_PyStructSequence_Init() < 0) {
684 return _PyStatus_ERR("can't initialize structseq");
685 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100686 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200687
Victor Stinner331a6a52019-05-27 16:39:22 +0200688 status = _PyErr_Init();
689 if (_PyStatus_EXCEPTION(status)) {
690 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200691 }
692
Victor Stinnere7e699e2019-11-20 12:08:13 +0100693 if (is_main_interp) {
694 if (!_PyContext_Init()) {
695 return _PyStatus_ERR("can't init context");
696 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100697 }
698
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100699 if (_PyWarnings_InitState(interp) < 0) {
Victor Stinneref75a622020-11-12 15:14:13 +0100700 return _PyStatus_ERR("can't initialize warnings");
701 }
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100702
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100703 status = _PyAtExit_Init(interp);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100704 if (_PyStatus_EXCEPTION(status)) {
705 return status;
706 }
707
Victor Stinner331a6a52019-05-27 16:39:22 +0200708 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100709}
710
711
Victor Stinner331a6a52019-05-27 16:39:22 +0200712static PyStatus
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100713pycore_init_builtins(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100714{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100715 PyObject *bimod = _PyBuiltin_Init(interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100716 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100717 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100718 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100719
Victor Stinner2582d462019-11-22 19:24:49 +0100720 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
721 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100722 }
Victor Stinner2582d462019-11-22 19:24:49 +0100723
724 PyObject *builtins_dict = PyModule_GetDict(bimod);
725 if (builtins_dict == NULL) {
726 goto error;
727 }
728 Py_INCREF(builtins_dict);
729 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100730
Victor Stinner331a6a52019-05-27 16:39:22 +0200731 PyStatus status = _PyBuiltins_AddExceptions(bimod);
732 if (_PyStatus_EXCEPTION(status)) {
733 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100734 }
Victor Stinner2582d462019-11-22 19:24:49 +0100735
736 interp->builtins_copy = PyDict_Copy(interp->builtins);
737 if (interp->builtins_copy == NULL) {
738 goto error;
739 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000740 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100741
Victor Stinner62230712020-11-18 23:18:29 +0100742 // Get the __import__ function
743 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
744 "__import__");
745 if (import_func == NULL) {
746 goto error;
747 }
748 interp->import_func = Py_NewRef(import_func);
749
Victor Stinner331a6a52019-05-27 16:39:22 +0200750 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100751
752error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000753 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100754 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100755}
756
757
Victor Stinner331a6a52019-05-27 16:39:22 +0200758static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100759pycore_interp_init(PyThreadState *tstate)
760{
761 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100762 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100763
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100764 status = pycore_init_types(tstate->interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100765 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100766 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100767 }
768
Victor Stinnerd863ade2019-12-06 03:37:07 +0100769 status = _PySys_Create(tstate, &sysmod);
770 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100771 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100772 }
773
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100774 assert(!_PyErr_Occurred(tstate));
775
776 status = pycore_init_builtins(tstate->interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100777 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100778 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100779 }
780
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100781 assert(!_PyErr_Occurred(tstate));
782
Victor Stinneref75a622020-11-12 15:14:13 +0100783 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
784 if (config->_install_importlib) {
785 /* This call sets up builtin and frozen import support */
786 if (init_importlib(tstate, sysmod) < 0) {
787 return _PyStatus_ERR("failed to initialize importlib");
788 }
789 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100790
791done:
792 /* sys.modules['sys'] contains a strong reference to the module */
793 Py_XDECREF(sysmod);
794 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100795}
796
797
798static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200799pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200800 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200801 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100802{
Victor Stinner331a6a52019-05-27 16:39:22 +0200803 PyStatus status = pycore_init_runtime(runtime, config);
804 if (_PyStatus_EXCEPTION(status)) {
805 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100806 }
807
Victor Stinnerb45d2592019-06-20 00:05:23 +0200808 PyThreadState *tstate;
809 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200810 if (_PyStatus_EXCEPTION(status)) {
811 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100812 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200813 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100814
Victor Stinnerd863ade2019-12-06 03:37:07 +0100815 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200816 if (_PyStatus_EXCEPTION(status)) {
817 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100818 }
Eric Snow1abcf672017-05-23 21:46:51 -0700819
820 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200821 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200822 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700823}
824
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100825
Victor Stinner331a6a52019-05-27 16:39:22 +0200826PyStatus
827_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100828{
Victor Stinner331a6a52019-05-27 16:39:22 +0200829 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100830
Victor Stinner6d1c4672019-05-20 11:02:00 +0200831 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200832 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200833 }
834
Victor Stinner331a6a52019-05-27 16:39:22 +0200835 status = _PyRuntime_Initialize();
836 if (_PyStatus_EXCEPTION(status)) {
837 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100838 }
Victor Stinner43125222019-04-24 18:23:53 +0200839 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100840
Victor Stinnerd3b90412019-09-17 23:59:51 +0200841 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100842 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200843 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100844 }
845
Victor Stinnerd3b90412019-09-17 23:59:51 +0200846 /* Note: preinitialized remains 1 on error, it is only set to 0
847 at exit on success. */
848 runtime->preinitializing = 1;
849
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200851
852 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
853 if (_PyStatus_EXCEPTION(status)) {
854 return status;
855 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100856
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 status = _PyPreConfig_Read(&config, args);
858 if (_PyStatus_EXCEPTION(status)) {
859 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100860 }
861
Victor Stinner331a6a52019-05-27 16:39:22 +0200862 status = _PyPreConfig_Write(&config);
863 if (_PyStatus_EXCEPTION(status)) {
864 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100865 }
866
Victor Stinnerd3b90412019-09-17 23:59:51 +0200867 runtime->preinitializing = 0;
868 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200869 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100870}
871
Victor Stinner70005ac2019-05-02 15:25:34 -0400872
Victor Stinner331a6a52019-05-27 16:39:22 +0200873PyStatus
874Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100875{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100876 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400877 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100878}
879
880
Victor Stinner331a6a52019-05-27 16:39:22 +0200881PyStatus
882Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100883{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100884 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400885 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100886}
887
888
Victor Stinner331a6a52019-05-27 16:39:22 +0200889PyStatus
890Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100891{
Victor Stinner70005ac2019-05-02 15:25:34 -0400892 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100893}
894
895
Victor Stinner331a6a52019-05-27 16:39:22 +0200896PyStatus
897_Py_PreInitializeFromConfig(const PyConfig *config,
898 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100899{
Victor Stinner331a6a52019-05-27 16:39:22 +0200900 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200901
Victor Stinner331a6a52019-05-27 16:39:22 +0200902 PyStatus status = _PyRuntime_Initialize();
903 if (_PyStatus_EXCEPTION(status)) {
904 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200905 }
906 _PyRuntimeState *runtime = &_PyRuntime;
907
Victor Stinnerd3b90412019-09-17 23:59:51 +0200908 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200909 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400911 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200912
Victor Stinner331a6a52019-05-27 16:39:22 +0200913 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200914
Victor Stinner3c30a762019-10-01 10:56:37 +0200915 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200916
Victor Stinner331a6a52019-05-27 16:39:22 +0200917 if (!config->parse_argv) {
918 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200919 }
920 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200921 _PyArgv config_args = {
922 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200923 .argc = config->argv.length,
924 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200925 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200926 }
927 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200928 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200929 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100930}
931
932
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100933/* Begin interpreter initialization
934 *
935 * On return, the first thread and interpreter state have been created,
936 * but the compiler, signal handling, multithreading and
937 * multiple interpreter support, and codec infrastructure are not yet
938 * available.
939 *
940 * The import system will support builtin and frozen modules only.
941 * The only supported io is writing to sys.stderr
942 *
943 * If any operation invoked by this function fails, a fatal error is
944 * issued and the function does not return.
945 *
946 * Any code invoked from this function should *not* assume it has access
947 * to the Python C API (unless the API is explicitly listed as being
948 * safe to call without calling Py_Initialize first)
949 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200950static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200951pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200952 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200953 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200954{
Victor Stinner331a6a52019-05-27 16:39:22 +0200955 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200956
Victor Stinner331a6a52019-05-27 16:39:22 +0200957 status = _Py_PreInitializeFromConfig(src_config, NULL);
958 if (_PyStatus_EXCEPTION(status)) {
959 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200960 }
961
Victor Stinner331a6a52019-05-27 16:39:22 +0200962 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100963 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200964
Victor Stinner331a6a52019-05-27 16:39:22 +0200965 status = _PyConfig_Copy(&config, src_config);
966 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200967 goto done;
968 }
969
Victor Stinner9e1b8282020-11-10 13:21:52 +0100970 // Read the configuration, but don't compute the path configuration
971 // (it is computed in the main init).
972 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200973 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200974 goto done;
975 }
976
977 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200978 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200979 }
980 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200981 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200982 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200983 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200984 goto done;
985 }
986
987done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200988 PyConfig_Clear(&config);
989 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200990}
991
Victor Stinner5ac27a52019-03-27 13:40:14 +0100992
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200993/* Py_Initialize() has already been called: update the main interpreter
994 configuration. Example of bpo-34008: Py_Main() called after
995 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200996static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100997pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200998{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100999 if (interpreter_update_config(tstate, 0) < 0) {
1000 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001001 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001002 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001003}
1004
Victor Stinnerb0051362019-11-22 17:52:42 +01001005
1006static PyStatus
1007init_interp_main(PyThreadState *tstate)
1008{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001009 assert(!_PyErr_Occurred(tstate));
1010
Victor Stinnerb0051362019-11-22 17:52:42 +01001011 PyStatus status;
Victor Stinner101bf692021-02-19 13:33:31 +01001012 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001013 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001014 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001015
1016 if (!config->_install_importlib) {
1017 /* Special mode for freeze_importlib: run with no import system
1018 *
1019 * This means anything which needs support from extension modules
1020 * or pure Python code in the standard library won't work.
1021 */
1022 if (is_main_interp) {
1023 interp->runtime->initialized = 1;
1024 }
1025 return _PyStatus_OK();
1026 }
1027
Victor Stinner9e1b8282020-11-10 13:21:52 +01001028 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001029 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001030 if (_PyStatus_EXCEPTION(status)) {
1031 return status;
1032 }
1033
Victor Stinner9e1b8282020-11-10 13:21:52 +01001034 if (interpreter_update_config(tstate, 1) < 0) {
1035 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001036 }
1037
1038 status = init_importlib_external(tstate);
1039 if (_PyStatus_EXCEPTION(status)) {
1040 return status;
1041 }
1042
1043 if (is_main_interp) {
1044 /* initialize the faulthandler module */
1045 status = _PyFaulthandler_Init(config->faulthandler);
1046 if (_PyStatus_EXCEPTION(status)) {
1047 return status;
1048 }
1049 }
1050
1051 status = _PyUnicode_InitEncodings(tstate);
1052 if (_PyStatus_EXCEPTION(status)) {
1053 return status;
1054 }
1055
1056 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001057 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1058 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001059 }
1060
1061 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1062 return _PyStatus_ERR("can't initialize tracemalloc");
1063 }
1064 }
1065
1066 status = init_sys_streams(tstate);
1067 if (_PyStatus_EXCEPTION(status)) {
1068 return status;
1069 }
1070
Andy Lester75cd5bf2020-03-12 02:49:05 -05001071 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001072 if (_PyStatus_EXCEPTION(status)) {
1073 return status;
1074 }
1075
1076 status = add_main_module(interp);
1077 if (_PyStatus_EXCEPTION(status)) {
1078 return status;
1079 }
1080
1081 if (is_main_interp) {
1082 /* Initialize warnings. */
1083 PyObject *warnoptions = PySys_GetObject("warnoptions");
1084 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1085 {
1086 PyObject *warnings_module = PyImport_ImportModule("warnings");
1087 if (warnings_module == NULL) {
1088 fprintf(stderr, "'import warnings' failed; traceback:\n");
1089 _PyErr_Print(tstate);
1090 }
1091 Py_XDECREF(warnings_module);
1092 }
1093
1094 interp->runtime->initialized = 1;
1095 }
1096
1097 if (config->site_import) {
1098 status = init_import_site();
1099 if (_PyStatus_EXCEPTION(status)) {
1100 return status;
1101 }
1102 }
1103
1104 if (is_main_interp) {
1105#ifndef MS_WINDOWS
1106 emit_stderr_warning_for_legacy_locale(interp->runtime);
1107#endif
1108 }
1109
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001110 assert(!_PyErr_Occurred(tstate));
1111
Victor Stinnerb0051362019-11-22 17:52:42 +01001112 return _PyStatus_OK();
1113}
1114
1115
Eric Snowc7ec9982017-05-23 23:00:52 -07001116/* Update interpreter state based on supplied configuration settings
1117 *
1118 * After calling this function, most of the restrictions on the interpreter
1119 * are lifted. The only remaining incomplete settings are those related
1120 * to the main module (sys.argv[0], __main__ metadata)
1121 *
1122 * Calling this when the interpreter is not initializing, is already
1123 * initialized or without a valid current thread state is a fatal error.
1124 * Other errors should be reported as normal Python exceptions with a
1125 * non-zero return code.
1126 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001127static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001128pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001129{
Victor Stinnerb0051362019-11-22 17:52:42 +01001130 PyInterpreterState *interp = tstate->interp;
1131 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001132 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001133 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001134
Victor Stinnerb0051362019-11-22 17:52:42 +01001135 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001136 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001137 }
1138
Victor Stinnerb0051362019-11-22 17:52:42 +01001139 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001140 if (_PyStatus_EXCEPTION(status)) {
1141 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001142 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001143 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001144}
1145
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001146
Victor Stinner331a6a52019-05-27 16:39:22 +02001147PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001148Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001149{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001150 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001151 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001152 }
1153
Victor Stinner331a6a52019-05-27 16:39:22 +02001154 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001155
Victor Stinner331a6a52019-05-27 16:39:22 +02001156 status = _PyRuntime_Initialize();
1157 if (_PyStatus_EXCEPTION(status)) {
1158 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001159 }
1160 _PyRuntimeState *runtime = &_PyRuntime;
1161
Victor Stinnerb45d2592019-06-20 00:05:23 +02001162 PyThreadState *tstate = NULL;
1163 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001164 if (_PyStatus_EXCEPTION(status)) {
1165 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001166 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001167 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001168
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001169 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001170 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001171 if (_PyStatus_EXCEPTION(status)) {
1172 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001173 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001174 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001175
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001177}
1178
1179
Eric Snow1abcf672017-05-23 21:46:51 -07001180void
Nick Coghland6009512014-11-20 21:39:37 +10001181Py_InitializeEx(int install_sigs)
1182{
Victor Stinner331a6a52019-05-27 16:39:22 +02001183 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001184
Victor Stinner331a6a52019-05-27 16:39:22 +02001185 status = _PyRuntime_Initialize();
1186 if (_PyStatus_EXCEPTION(status)) {
1187 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001188 }
1189 _PyRuntimeState *runtime = &_PyRuntime;
1190
1191 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001192 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1193 return;
1194 }
1195
Victor Stinner331a6a52019-05-27 16:39:22 +02001196 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001197 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001198
Victor Stinner1dc6e392018-07-25 02:49:17 +02001199 config.install_signal_handlers = install_sigs;
1200
Victor Stinner331a6a52019-05-27 16:39:22 +02001201 status = Py_InitializeFromConfig(&config);
1202 if (_PyStatus_EXCEPTION(status)) {
1203 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001204 }
Nick Coghland6009512014-11-20 21:39:37 +10001205}
1206
1207void
1208Py_Initialize(void)
1209{
1210 Py_InitializeEx(1);
1211}
1212
1213
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001214PyStatus
1215_Py_InitializeMain(void)
1216{
1217 PyStatus status = _PyRuntime_Initialize();
1218 if (_PyStatus_EXCEPTION(status)) {
1219 return status;
1220 }
1221 _PyRuntimeState *runtime = &_PyRuntime;
1222 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1223 return pyinit_main(tstate);
1224}
1225
1226
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001227static void
1228finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1229{
1230 // List of names to clear in sys
1231 static const char * const sys_deletes[] = {
1232 "path", "argv", "ps1", "ps2",
1233 "last_type", "last_value", "last_traceback",
1234 "path_hooks", "path_importer_cache", "meta_path",
1235 "__interactivehook__",
1236 NULL
1237 };
1238
1239 static const char * const sys_files[] = {
1240 "stdin", "__stdin__",
1241 "stdout", "__stdout__",
1242 "stderr", "__stderr__",
1243 NULL
1244 };
1245
1246 PyInterpreterState *interp = tstate->interp;
1247 if (verbose) {
1248 PySys_WriteStderr("# clear builtins._\n");
1249 }
1250 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1251 PyErr_WriteUnraisable(NULL);
1252 }
1253
1254 const char * const *p;
1255 for (p = sys_deletes; *p != NULL; p++) {
1256 if (verbose) {
1257 PySys_WriteStderr("# clear sys.%s\n", *p);
1258 }
1259 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1260 PyErr_WriteUnraisable(NULL);
1261 }
1262 }
1263 for (p = sys_files; *p != NULL; p+=2) {
1264 const char *name = p[0];
1265 const char *orig_name = p[1];
1266 if (verbose) {
1267 PySys_WriteStderr("# restore sys.%s\n", name);
1268 }
1269 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1270 orig_name);
1271 if (value == NULL) {
1272 if (_PyErr_Occurred(tstate)) {
1273 PyErr_WriteUnraisable(NULL);
1274 }
1275 value = Py_None;
1276 }
1277 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1278 PyErr_WriteUnraisable(NULL);
1279 }
1280 }
1281}
1282
1283
1284static PyObject*
1285finalize_remove_modules(PyObject *modules, int verbose)
1286{
1287 PyObject *weaklist = PyList_New(0);
1288 if (weaklist == NULL) {
1289 PyErr_WriteUnraisable(NULL);
1290 }
1291
1292#define STORE_MODULE_WEAKREF(name, mod) \
1293 if (weaklist != NULL) { \
1294 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1295 if (wr) { \
1296 PyObject *tup = PyTuple_Pack(2, name, wr); \
1297 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1298 PyErr_WriteUnraisable(NULL); \
1299 } \
1300 Py_XDECREF(tup); \
1301 Py_DECREF(wr); \
1302 } \
1303 else { \
1304 PyErr_WriteUnraisable(NULL); \
1305 } \
1306 }
1307
1308#define CLEAR_MODULE(name, mod) \
1309 if (PyModule_Check(mod)) { \
1310 if (verbose && PyUnicode_Check(name)) { \
1311 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1312 } \
1313 STORE_MODULE_WEAKREF(name, mod); \
1314 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1315 PyErr_WriteUnraisable(NULL); \
1316 } \
1317 }
1318
1319 if (PyDict_CheckExact(modules)) {
1320 Py_ssize_t pos = 0;
1321 PyObject *key, *value;
1322 while (PyDict_Next(modules, &pos, &key, &value)) {
1323 CLEAR_MODULE(key, value);
1324 }
1325 }
1326 else {
1327 PyObject *iterator = PyObject_GetIter(modules);
1328 if (iterator == NULL) {
1329 PyErr_WriteUnraisable(NULL);
1330 }
1331 else {
1332 PyObject *key;
1333 while ((key = PyIter_Next(iterator))) {
1334 PyObject *value = PyObject_GetItem(modules, key);
1335 if (value == NULL) {
1336 PyErr_WriteUnraisable(NULL);
1337 continue;
1338 }
1339 CLEAR_MODULE(key, value);
1340 Py_DECREF(value);
1341 Py_DECREF(key);
1342 }
1343 if (PyErr_Occurred()) {
1344 PyErr_WriteUnraisable(NULL);
1345 }
1346 Py_DECREF(iterator);
1347 }
1348 }
1349#undef CLEAR_MODULE
1350#undef STORE_MODULE_WEAKREF
1351
1352 return weaklist;
1353}
1354
1355
1356static void
1357finalize_clear_modules_dict(PyObject *modules)
1358{
1359 if (PyDict_CheckExact(modules)) {
1360 PyDict_Clear(modules);
1361 }
1362 else {
1363 _Py_IDENTIFIER(clear);
1364 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1365 PyErr_WriteUnraisable(NULL);
1366 }
1367 }
1368}
1369
1370
1371static void
1372finalize_restore_builtins(PyThreadState *tstate)
1373{
1374 PyInterpreterState *interp = tstate->interp;
1375 PyObject *dict = PyDict_Copy(interp->builtins);
1376 if (dict == NULL) {
1377 PyErr_WriteUnraisable(NULL);
1378 }
1379 PyDict_Clear(interp->builtins);
1380 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1381 _PyErr_Clear(tstate);
1382 }
1383 Py_XDECREF(dict);
1384}
1385
1386
1387static void
1388finalize_modules_clear_weaklist(PyInterpreterState *interp,
1389 PyObject *weaklist, int verbose)
1390{
1391 // First clear modules imported later
1392 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1393 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1394 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1395 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1396 if (mod == Py_None) {
1397 continue;
1398 }
1399 assert(PyModule_Check(mod));
1400 PyObject *dict = PyModule_GetDict(mod);
1401 if (dict == interp->builtins || dict == interp->sysdict) {
1402 continue;
1403 }
1404 Py_INCREF(mod);
1405 if (verbose && PyUnicode_Check(name)) {
1406 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1407 }
1408 _PyModule_Clear(mod);
1409 Py_DECREF(mod);
1410 }
1411}
1412
1413
1414static void
1415finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1416{
1417 // Clear sys dict
1418 if (verbose) {
1419 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1420 }
1421 _PyModule_ClearDict(interp->sysdict);
1422
1423 // Clear builtins dict
1424 if (verbose) {
1425 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1426 }
1427 _PyModule_ClearDict(interp->builtins);
1428}
1429
1430
1431/* Clear modules, as good as we can */
1432static void
1433finalize_modules(PyThreadState *tstate)
1434{
1435 PyInterpreterState *interp = tstate->interp;
1436 PyObject *modules = interp->modules;
1437 if (modules == NULL) {
1438 // Already done
1439 return;
1440 }
1441 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1442
1443 // Delete some special builtins._ and sys attributes first. These are
1444 // common places where user values hide and people complain when their
1445 // destructors fail. Since the modules containing them are
1446 // deleted *last* of all, they would come too late in the normal
1447 // destruction order. Sigh.
1448 //
1449 // XXX Perhaps these precautions are obsolete. Who knows?
1450 finalize_modules_delete_special(tstate, verbose);
1451
1452 // Remove all modules from sys.modules, hoping that garbage collection
1453 // can reclaim most of them: set all sys.modules values to None.
1454 //
1455 // We prepare a list which will receive (name, weakref) tuples of
1456 // modules when they are removed from sys.modules. The name is used
1457 // for diagnosis messages (in verbose mode), while the weakref helps
1458 // detect those modules which have been held alive.
1459 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1460
1461 // Clear the modules dict
1462 finalize_clear_modules_dict(modules);
1463
1464 // Restore the original builtins dict, to ensure that any
1465 // user data gets cleared.
1466 finalize_restore_builtins(tstate);
1467
1468 // Collect garbage
1469 _PyGC_CollectNoFail(tstate);
1470
1471 // Dump GC stats before it's too late, since it uses the warnings
1472 // machinery.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001473 _PyGC_DumpShutdownStats(interp);
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001474
1475 if (weaklist != NULL) {
1476 // Now, if there are any modules left alive, clear their globals to
1477 // minimize potential leaks. All C extension modules actually end
1478 // up here, since they are kept alive in the interpreter state.
1479 //
1480 // The special treatment of "builtins" here is because even
1481 // when it's not referenced as a module, its dictionary is
1482 // referenced by almost every module's __builtins__. Since
1483 // deleting a module clears its dictionary (even if there are
1484 // references left to it), we need to delete the "builtins"
1485 // module last. Likewise, we don't delete sys until the very
1486 // end because it is implicitly referenced (e.g. by print).
1487 //
1488 // Since dict is ordered in CPython 3.6+, modules are saved in
1489 // importing order. First clear modules imported later.
1490 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1491 Py_DECREF(weaklist);
1492 }
1493
1494 // Clear sys and builtins modules dict
1495 finalize_clear_sys_builtins_dict(interp, verbose);
1496
1497 // Clear module dict copies stored in the interpreter state:
1498 // clear PyInterpreterState.modules_by_index and
1499 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1500 // initialization API)
1501 _PyInterpreterState_ClearModules(interp);
1502
1503 // Clear and delete the modules directory. Actual modules will
1504 // still be there only if imported during the execution of some
1505 // destructor.
1506 Py_SETREF(interp->modules, NULL);
1507
1508 // Collect garbage once more
1509 _PyGC_CollectNoFail(tstate);
1510}
1511
1512
Nick Coghland6009512014-11-20 21:39:37 +10001513/* Flush stdout and stderr */
1514
1515static int
1516file_is_closed(PyObject *fobj)
1517{
1518 int r;
1519 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1520 if (tmp == NULL) {
1521 PyErr_Clear();
1522 return 0;
1523 }
1524 r = PyObject_IsTrue(tmp);
1525 Py_DECREF(tmp);
1526 if (r < 0)
1527 PyErr_Clear();
1528 return r > 0;
1529}
1530
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001531
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001532static int
Nick Coghland6009512014-11-20 21:39:37 +10001533flush_std_files(void)
1534{
1535 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1536 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1537 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001538 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001539
1540 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001541 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001542 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001543 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001544 status = -1;
1545 }
Nick Coghland6009512014-11-20 21:39:37 +10001546 else
1547 Py_DECREF(tmp);
1548 }
1549
1550 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001551 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001552 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001553 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001554 status = -1;
1555 }
Nick Coghland6009512014-11-20 21:39:37 +10001556 else
1557 Py_DECREF(tmp);
1558 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001559
1560 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001561}
1562
1563/* Undo the effect of Py_Initialize().
1564
1565 Beware: if multiple interpreter and/or thread states exist, these
1566 are not wiped out; only the current thread and interpreter state
1567 are deleted. But since everything else is deleted, those other
1568 interpreter and thread states should no longer be used.
1569
1570 (XXX We should do better, e.g. wipe out all interpreters and
1571 threads.)
1572
1573 Locking: as above.
1574
1575*/
1576
Victor Stinner7eee5be2019-11-20 10:38:34 +01001577
1578static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001579finalize_interp_types(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001580{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001581 _PyExc_Fini(interp);
1582 _PyFrame_Fini(interp);
1583 _PyAsyncGen_Fini(interp);
1584 _PyContext_Fini(interp);
1585 _PyType_Fini(interp);
Victor Stinnerea251802020-12-26 02:58:33 +01001586 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1587 // a dict internally.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001588 _PyUnicode_ClearInterned(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001589
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001590 _PyDict_Fini(interp);
1591 _PyList_Fini(interp);
1592 _PyTuple_Fini(interp);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001593
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001594 _PySlice_Fini(interp);
Victor Stinner3d483342019-11-22 12:27:50 +01001595
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001596 _PyBytes_Fini(interp);
1597 _PyUnicode_Fini(interp);
1598 _PyFloat_Fini(interp);
1599 _PyLong_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001600}
1601
1602
1603static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001604finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001605{
Victor Stinner101bf692021-02-19 13:33:31 +01001606 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001607
Victor Stinner7eee5be2019-11-20 10:38:34 +01001608 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001609 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001610
Kongedaa0fe02020-07-04 05:06:46 +08001611 /* Clear all loghooks */
1612 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1613 Call _PySys_ClearAuditHooks when PyObject available. */
1614 if (is_main_interp) {
1615 _PySys_ClearAuditHooks(tstate);
1616 }
1617
Victor Stinner7907f8c2020-06-08 01:22:36 +02001618 if (is_main_interp) {
1619 _Py_HashRandomization_Fini();
1620 _PyArg_Fini();
1621 _Py_ClearFileSystemEncoding();
1622 }
1623
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001624 finalize_interp_types(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001625}
1626
1627
1628static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001629finalize_interp_delete(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001630{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001631 if (_Py_IsMainInterpreter(interp)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001632 /* Cleanup auto-thread-state */
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001633 _PyGILState_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001634 }
1635
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001636 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1637 fail when it is being awaited by another running daemon thread (see
1638 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1639 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1640 called multiple times. */
1641
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001642 PyInterpreterState_Delete(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001643}
1644
1645
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001646int
1647Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001648{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001649 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001650
Victor Stinner8e91c242019-04-24 17:24:01 +02001651 _PyRuntimeState *runtime = &_PyRuntime;
1652 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001653 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001654 }
Nick Coghland6009512014-11-20 21:39:37 +10001655
Victor Stinnere225beb2019-06-03 18:14:24 +02001656 /* Get current thread state and interpreter pointer */
1657 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001658
Victor Stinnerb45d2592019-06-20 00:05:23 +02001659 // Wrap up existing "threading"-module-created, non-daemon threads.
1660 wait_for_thread_shutdown(tstate);
1661
1662 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001663 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001664
Nick Coghland6009512014-11-20 21:39:37 +10001665 /* The interpreter is still entirely intact at this point, and the
1666 * exit funcs may be relying on that. In particular, if some thread
1667 * or exit func is still waiting to do an import, the import machinery
1668 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001669 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001670 * Note that Threading.py uses an exit func to do a join on all the
1671 * threads created thru it, so this also protects pending imports in
1672 * the threads created via Threading.
1673 */
Nick Coghland6009512014-11-20 21:39:37 +10001674
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001675 _PyAtExit_Call(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001676
Victor Stinnerda273412017-12-15 01:46:02 +01001677 /* Copy the core config, PyInterpreterState_Delete() free
1678 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001679#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001680 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001681#endif
1682#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001683 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001684#endif
1685#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001686 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001687#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001688
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001689 /* Remaining daemon threads will automatically exit
1690 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001691 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001692 runtime->initialized = 0;
1693 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001694
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001695 /* Destroy the state of all threads of the interpreter, except of the
1696 current thread. In practice, only daemon threads should still be alive,
1697 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1698 Clear frames of other threads to call objects destructors. Destructors
1699 will be called in the current Python thread. Since
1700 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1701 can take the GIL at this point: if they try, they will exit
1702 immediately. */
1703 _PyThreadState_DeleteExcept(runtime, tstate);
1704
Victor Stinnere0deff32015-03-24 13:46:18 +01001705 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001706 if (flush_std_files() < 0) {
1707 status = -1;
1708 }
Nick Coghland6009512014-11-20 21:39:37 +10001709
1710 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001711 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001712
1713 /* Collect garbage. This may call finalizers; it's nice to call these
1714 * before all modules are destroyed.
1715 * XXX If a __del__ or weakref callback is triggered here, and tries to
1716 * XXX import a module, bad things can happen, because Python no
1717 * XXX longer believes it's initialized.
1718 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1719 * XXX is easy to provoke that way. I've also seen, e.g.,
1720 * XXX Exception exceptions.ImportError: 'No module named sha'
1721 * XXX in <function callback at 0x008F5718> ignored
1722 * XXX but I'm unclear on exactly how that one happens. In any case,
1723 * XXX I haven't seen a real-life report of either of these.
1724 */
Victor Stinner8b341482020-10-30 17:00:00 +01001725 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001726
Nick Coghland6009512014-11-20 21:39:37 +10001727 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001728 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001729
Inada Naoki91234a12019-06-03 21:30:58 +09001730 /* Print debug stats if any */
1731 _PyEval_Fini();
1732
Victor Stinnere0deff32015-03-24 13:46:18 +01001733 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001734 if (flush_std_files() < 0) {
1735 status = -1;
1736 }
Nick Coghland6009512014-11-20 21:39:37 +10001737
1738 /* Collect final garbage. This disposes of cycles created by
1739 * class definitions, for example.
1740 * XXX This is disabled because it caused too many problems. If
1741 * XXX a __del__ or weakref callback triggers here, Python code has
1742 * XXX a hard time running, because even the sys module has been
1743 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1744 * XXX One symptom is a sequence of information-free messages
1745 * XXX coming from threads (if a __del__ or callback is invoked,
1746 * XXX other threads can execute too, and any exception they encounter
1747 * XXX triggers a comedy of errors as subsystem after subsystem
1748 * XXX fails to find what it *expects* to find in sys to help report
1749 * XXX the exception and consequent unexpected failures). I've also
1750 * XXX seen segfaults then, after adding print statements to the
1751 * XXX Python code getting called.
1752 */
1753#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001754 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001755#endif
1756
1757 /* Disable tracemalloc after all Python objects have been destroyed,
1758 so it is possible to use tracemalloc in objects destructor. */
1759 _PyTraceMalloc_Fini();
1760
1761 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1762 _PyImport_Fini();
1763
Nick Coghland6009512014-11-20 21:39:37 +10001764 /* unload faulthandler module */
1765 _PyFaulthandler_Fini();
1766
Nick Coghland6009512014-11-20 21:39:37 +10001767 /* dump hash stats */
1768 _PyHash_Fini();
1769
Eric Snowdae02762017-09-14 00:35:58 -07001770#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001771 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001772 _PyDebug_PrintTotalRefs();
1773 }
Eric Snowdae02762017-09-14 00:35:58 -07001774#endif
Nick Coghland6009512014-11-20 21:39:37 +10001775
1776#ifdef Py_TRACE_REFS
1777 /* Display all objects still alive -- this can invoke arbitrary
1778 * __repr__ overrides, so requires a mostly-intact interpreter.
1779 * Alas, a lot of stuff may still be alive now that will be cleaned
1780 * up later.
1781 */
Victor Stinnerda273412017-12-15 01:46:02 +01001782 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001783 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001784 }
Nick Coghland6009512014-11-20 21:39:37 +10001785#endif /* Py_TRACE_REFS */
1786
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001787 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001788 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001789
1790#ifdef Py_TRACE_REFS
1791 /* Display addresses (& refcnts) of all objects still alive.
1792 * An address can be used to find the repr of the object, printed
1793 * above by _Py_PrintReferences.
1794 */
Victor Stinnerda273412017-12-15 01:46:02 +01001795 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001796 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001797 }
Nick Coghland6009512014-11-20 21:39:37 +10001798#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001799#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001800 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001801 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001802 }
Nick Coghland6009512014-11-20 21:39:37 +10001803#endif
1804
Victor Stinner8e91c242019-04-24 17:24:01 +02001805 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001806
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001807 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001808 return status;
1809}
1810
1811void
1812Py_Finalize(void)
1813{
1814 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001815}
1816
Victor Stinnerb0051362019-11-22 17:52:42 +01001817
Nick Coghland6009512014-11-20 21:39:37 +10001818/* Create and initialize a new interpreter and thread, and return the
1819 new thread. This requires that Py_Initialize() has been called
1820 first.
1821
1822 Unsuccessful initialization yields a NULL pointer. Note that *no*
1823 exception information is available even in this case -- the
1824 exception information is held in the thread, and there is no
1825 thread.
1826
1827 Locking: as above.
1828
1829*/
1830
Victor Stinner331a6a52019-05-27 16:39:22 +02001831static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001832new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001833{
Victor Stinner331a6a52019-05-27 16:39:22 +02001834 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001835
Victor Stinner331a6a52019-05-27 16:39:22 +02001836 status = _PyRuntime_Initialize();
1837 if (_PyStatus_EXCEPTION(status)) {
1838 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001839 }
1840 _PyRuntimeState *runtime = &_PyRuntime;
1841
1842 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001843 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001844 }
Nick Coghland6009512014-11-20 21:39:37 +10001845
Victor Stinner8a1be612016-03-14 22:07:55 +01001846 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1847 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001848 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001849
Victor Stinner43125222019-04-24 18:23:53 +02001850 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001851 if (interp == NULL) {
1852 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001853 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001854 }
Nick Coghland6009512014-11-20 21:39:37 +10001855
Victor Stinner43125222019-04-24 18:23:53 +02001856 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001857 if (tstate == NULL) {
1858 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001859 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001860 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001861 }
1862
Victor Stinner43125222019-04-24 18:23:53 +02001863 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001864
Eric Snow1abcf672017-05-23 21:46:51 -07001865 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001866 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001867#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001868 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001869 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001870 }
1871 else
1872#endif
1873 {
Eric Snow1abcf672017-05-23 21:46:51 -07001874 /* No current thread state, copy from the main interpreter */
1875 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001876 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001877 }
1878
Victor Stinner048a3562020-11-05 00:45:56 +01001879
1880 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001881 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001882 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001883 }
Victor Stinner252346a2020-05-01 11:33:44 +02001884 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001885
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001886 status = init_interp_create_gil(tstate);
1887 if (_PyStatus_EXCEPTION(status)) {
1888 goto error;
1889 }
1890
Victor Stinnerd863ade2019-12-06 03:37:07 +01001891 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001892 if (_PyStatus_EXCEPTION(status)) {
1893 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001894 }
1895
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001896 status = init_interp_main(tstate);
1897 if (_PyStatus_EXCEPTION(status)) {
1898 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001899 }
Nick Coghland6009512014-11-20 21:39:37 +10001900
Victor Stinnera7368ac2017-11-15 18:11:45 -08001901 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001902 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001903
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001904error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001905 *tstate_p = NULL;
1906
1907 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001908 PyErr_PrintEx(0);
1909 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001910 PyThreadState_Delete(tstate);
1911 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001912 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001913
Victor Stinnerb0051362019-11-22 17:52:42 +01001914 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001915}
1916
1917PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001918_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001919{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001920 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001921 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001922 if (_PyStatus_EXCEPTION(status)) {
1923 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001924 }
1925 return tstate;
1926
Nick Coghland6009512014-11-20 21:39:37 +10001927}
1928
Victor Stinner252346a2020-05-01 11:33:44 +02001929PyThreadState *
1930Py_NewInterpreter(void)
1931{
1932 return _Py_NewInterpreter(0);
1933}
1934
Nick Coghland6009512014-11-20 21:39:37 +10001935/* Delete an interpreter and its last thread. This requires that the
1936 given thread state is current, that the thread has no remaining
1937 frames, and that it is its interpreter's only remaining thread.
1938 It is a fatal error to violate these constraints.
1939
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001940 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001941 everything, regardless.)
1942
1943 Locking: as above.
1944
1945*/
1946
1947void
1948Py_EndInterpreter(PyThreadState *tstate)
1949{
1950 PyInterpreterState *interp = tstate->interp;
1951
Victor Stinnerb45d2592019-06-20 00:05:23 +02001952 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001953 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001954 }
1955 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001956 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001957 }
Eric Snow5be45a62019-03-08 22:47:07 -07001958 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001959
Eric Snow842a2f02019-03-15 15:47:51 -06001960 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001961 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001962
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001963 _PyAtExit_Call(tstate->interp);
Marcel Plch776407f2017-12-20 11:17:58 +01001964
Victor Stinnerb45d2592019-06-20 00:05:23 +02001965 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001966 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001967 }
Nick Coghland6009512014-11-20 21:39:37 +10001968
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001969 finalize_modules(tstate);
1970
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001971 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001972 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001973}
1974
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001976
Victor Stinner331a6a52019-05-27 16:39:22 +02001977static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001978add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001979{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001980 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001981 m = PyImport_AddModule("__main__");
1982 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001983 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001984
Nick Coghland6009512014-11-20 21:39:37 +10001985 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001986 ann_dict = PyDict_New();
1987 if ((ann_dict == NULL) ||
1988 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001989 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001990 }
1991 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001992
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001993 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1994 if (PyErr_Occurred()) {
1995 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1996 }
Nick Coghland6009512014-11-20 21:39:37 +10001997 PyObject *bimod = PyImport_ImportModule("builtins");
1998 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001999 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10002000 }
2001 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002002 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002003 }
2004 Py_DECREF(bimod);
2005 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002006
Nick Coghland6009512014-11-20 21:39:37 +10002007 /* Main is a little special - imp.is_builtin("__main__") will return
2008 * False, but BuiltinImporter is still the most appropriate initial
2009 * setting for its __loader__ attribute. A more suitable value will
2010 * be set if __main__ gets further initialized later in the startup
2011 * process.
2012 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002013 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002014 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002015 if (PyErr_Occurred()) {
2016 return _PyStatus_ERR("Failed to test __main__.__loader__");
2017 }
Nick Coghland6009512014-11-20 21:39:37 +10002018 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2019 "BuiltinImporter");
2020 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002021 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002022 }
2023 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002024 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002025 }
2026 Py_DECREF(loader);
2027 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002028 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002029}
2030
Nick Coghland6009512014-11-20 21:39:37 +10002031/* Import the site module (not into __main__ though) */
2032
Victor Stinner331a6a52019-05-27 16:39:22 +02002033static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002034init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002035{
2036 PyObject *m;
2037 m = PyImport_ImportModule("site");
2038 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002039 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002040 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002041 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002042 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002043}
2044
Victor Stinner874dbe82015-09-04 17:29:57 +02002045/* Check if a file descriptor is valid or not.
2046 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2047static int
2048is_valid_fd(int fd)
2049{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002050/* dup() is faster than fstat(): fstat() can require input/output operations,
2051 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2052 startup. Problem: dup() doesn't check if the file descriptor is valid on
2053 some platforms.
2054
2055 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2056 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2057 EBADF. FreeBSD has similar issue (bpo-32849).
2058
2059 Only use dup() on platforms where dup() is enough to detect invalid FD in
2060 corner cases: on Linux and Windows (bpo-32849). */
2061#if defined(__linux__) || defined(MS_WINDOWS)
2062 if (fd < 0) {
2063 return 0;
2064 }
2065 int fd2;
2066
2067 _Py_BEGIN_SUPPRESS_IPH
2068 fd2 = dup(fd);
2069 if (fd2 >= 0) {
2070 close(fd2);
2071 }
2072 _Py_END_SUPPRESS_IPH
2073
2074 return (fd2 >= 0);
2075#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002076 struct stat st;
2077 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002078#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002079}
2080
2081/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002082static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002083create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002084 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002085 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002086{
2087 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2088 const char* mode;
2089 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002090 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002091 int buffering, isatty;
2092 _Py_IDENTIFIER(open);
2093 _Py_IDENTIFIER(isatty);
2094 _Py_IDENTIFIER(TextIOWrapper);
2095 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002096 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002097
Victor Stinner874dbe82015-09-04 17:29:57 +02002098 if (!is_valid_fd(fd))
2099 Py_RETURN_NONE;
2100
Nick Coghland6009512014-11-20 21:39:37 +10002101 /* stdin is always opened in buffered mode, first because it shouldn't
2102 make a difference in common use cases, second because TextIOWrapper
2103 depends on the presence of a read1() method which only exists on
2104 buffered streams.
2105 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002106 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002107 buffering = 0;
2108 else
2109 buffering = -1;
2110 if (write_mode)
2111 mode = "wb";
2112 else
2113 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002114 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002115 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002116 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002117 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002118 if (buf == NULL)
2119 goto error;
2120
2121 if (buffering) {
2122 _Py_IDENTIFIER(raw);
2123 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2124 if (raw == NULL)
2125 goto error;
2126 }
2127 else {
2128 raw = buf;
2129 Py_INCREF(raw);
2130 }
2131
Steve Dower39294992016-08-30 21:22:36 -07002132#ifdef MS_WINDOWS
2133 /* Windows console IO is always UTF-8 encoded */
2134 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002135 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002136#endif
2137
Nick Coghland6009512014-11-20 21:39:37 +10002138 text = PyUnicode_FromString(name);
2139 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2140 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002141 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002142 if (res == NULL)
2143 goto error;
2144 isatty = PyObject_IsTrue(res);
2145 Py_DECREF(res);
2146 if (isatty == -1)
2147 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002148 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002149 write_through = Py_True;
2150 else
2151 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002152 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002153 line_buffering = Py_True;
2154 else
2155 line_buffering = Py_False;
2156
2157 Py_CLEAR(raw);
2158 Py_CLEAR(text);
2159
2160#ifdef MS_WINDOWS
2161 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2162 newlines to "\n".
2163 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2164 newline = NULL;
2165#else
2166 /* sys.stdin: split lines at "\n".
2167 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2168 newline = "\n";
2169#endif
2170
Victor Stinner709d23d2019-05-02 14:56:30 -04002171 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2172 if (encoding_str == NULL) {
2173 Py_CLEAR(buf);
2174 goto error;
2175 }
2176
2177 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2178 if (errors_str == NULL) {
2179 Py_CLEAR(buf);
2180 Py_CLEAR(encoding_str);
2181 goto error;
2182 }
2183
2184 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2185 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002186 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002187 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002188 Py_CLEAR(encoding_str);
2189 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002190 if (stream == NULL)
2191 goto error;
2192
2193 if (write_mode)
2194 mode = "w";
2195 else
2196 mode = "r";
2197 text = PyUnicode_FromString(mode);
2198 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2199 goto error;
2200 Py_CLEAR(text);
2201 return stream;
2202
2203error:
2204 Py_XDECREF(buf);
2205 Py_XDECREF(stream);
2206 Py_XDECREF(text);
2207 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002208
Victor Stinner874dbe82015-09-04 17:29:57 +02002209 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2210 /* Issue #24891: the file descriptor was closed after the first
2211 is_valid_fd() check was called. Ignore the OSError and set the
2212 stream to None. */
2213 PyErr_Clear();
2214 Py_RETURN_NONE;
2215 }
2216 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002217}
2218
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002219/* Set builtins.open to io.OpenWrapper */
2220static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002221init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002222{
2223 PyObject *iomod = NULL, *wrapper;
2224 PyObject *bimod = NULL;
2225 PyStatus res = _PyStatus_OK();
2226
2227 if (!(iomod = PyImport_ImportModule("io"))) {
2228 goto error;
2229 }
2230
2231 if (!(bimod = PyImport_ImportModule("builtins"))) {
2232 goto error;
2233 }
2234
2235 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2236 goto error;
2237 }
2238
2239 /* Set builtins.open */
2240 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2241 Py_DECREF(wrapper);
2242 goto error;
2243 }
2244 Py_DECREF(wrapper);
2245 goto done;
2246
2247error:
2248 res = _PyStatus_ERR("can't initialize io.open");
2249
2250done:
2251 Py_XDECREF(bimod);
2252 Py_XDECREF(iomod);
2253 return res;
2254}
2255
2256
Nick Coghland6009512014-11-20 21:39:37 +10002257/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002258static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002259init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002260{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002261 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002262 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002263 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002264 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002265 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002266 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002267
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002268 /* Check that stdin is not a directory
2269 Using shell redirection, you can redirect stdin to a directory,
2270 crashing the Python interpreter. Catch this common mistake here
2271 and output a useful error message. Note that under MS Windows,
2272 the shell already prevents that. */
2273#ifndef MS_WINDOWS
2274 struct _Py_stat_struct sb;
2275 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2276 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002277 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002278 }
2279#endif
2280
Nick Coghland6009512014-11-20 21:39:37 +10002281 if (!(iomod = PyImport_ImportModule("io"))) {
2282 goto error;
2283 }
Nick Coghland6009512014-11-20 21:39:37 +10002284
Nick Coghland6009512014-11-20 21:39:37 +10002285 /* Set sys.stdin */
2286 fd = fileno(stdin);
2287 /* Under some conditions stdin, stdout and stderr may not be connected
2288 * and fileno() may point to an invalid file descriptor. For example
2289 * GUI apps don't have valid standard streams by default.
2290 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002291 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002292 config->stdio_encoding,
2293 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002294 if (std == NULL)
2295 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002296 PySys_SetObject("__stdin__", std);
2297 _PySys_SetObjectId(&PyId_stdin, std);
2298 Py_DECREF(std);
2299
2300 /* Set sys.stdout */
2301 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002302 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002303 config->stdio_encoding,
2304 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002305 if (std == NULL)
2306 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002307 PySys_SetObject("__stdout__", std);
2308 _PySys_SetObjectId(&PyId_stdout, std);
2309 Py_DECREF(std);
2310
2311#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2312 /* Set sys.stderr, replaces the preliminary stderr */
2313 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002314 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002315 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002316 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002317 if (std == NULL)
2318 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002319
2320 /* Same as hack above, pre-import stderr's codec to avoid recursion
2321 when import.c tries to write to stderr in verbose mode. */
2322 encoding_attr = PyObject_GetAttrString(std, "encoding");
2323 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002324 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002325 if (std_encoding != NULL) {
2326 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2327 Py_XDECREF(codec_info);
2328 }
2329 Py_DECREF(encoding_attr);
2330 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002331 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002332
2333 if (PySys_SetObject("__stderr__", std) < 0) {
2334 Py_DECREF(std);
2335 goto error;
2336 }
2337 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2338 Py_DECREF(std);
2339 goto error;
2340 }
2341 Py_DECREF(std);
2342#endif
2343
Victor Stinnera7368ac2017-11-15 18:11:45 -08002344 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002345
Victor Stinnera7368ac2017-11-15 18:11:45 -08002346error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002347 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002348
2349done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002350 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002351 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002352 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002353}
2354
2355
Victor Stinner10dc4842015-03-24 12:01:30 +01002356static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002357_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2358 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002359{
Victor Stinner314b8782021-01-18 18:34:56 +01002360 PUTS(fd, "\n");
Victor Stinner10dc4842015-03-24 12:01:30 +01002361
2362 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002363 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002364}
Victor Stinner791da1c2016-03-14 16:53:12 +01002365
2366/* Print the current exception (if an exception is set) with its traceback,
2367 or display the current Python stack.
2368
2369 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2370 called on catastrophic cases.
2371
2372 Return 1 if the traceback was displayed, 0 otherwise. */
2373
2374static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002375_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002376{
2377 PyObject *ferr, *res;
2378 PyObject *exception, *v, *tb;
2379 int has_tb;
2380
Victor Stinnerb45d2592019-06-20 00:05:23 +02002381 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002382 if (exception == NULL) {
2383 /* No current exception */
2384 return 0;
2385 }
2386
2387 ferr = _PySys_GetObjectId(&PyId_stderr);
2388 if (ferr == NULL || ferr == Py_None) {
2389 /* sys.stderr is not set yet or set to None,
2390 no need to try to display the exception */
2391 return 0;
2392 }
2393
Victor Stinnerb45d2592019-06-20 00:05:23 +02002394 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002395 if (tb == NULL) {
2396 tb = Py_None;
2397 Py_INCREF(tb);
2398 }
2399 PyException_SetTraceback(v, tb);
2400 if (exception == NULL) {
2401 /* PyErr_NormalizeException() failed */
2402 return 0;
2403 }
2404
2405 has_tb = (tb != Py_None);
2406 PyErr_Display(exception, v, tb);
2407 Py_XDECREF(exception);
2408 Py_XDECREF(v);
2409 Py_XDECREF(tb);
2410
2411 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002412 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002413 if (res == NULL) {
2414 _PyErr_Clear(tstate);
2415 }
2416 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002417 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002418 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002419
2420 return has_tb;
2421}
2422
Nick Coghland6009512014-11-20 21:39:37 +10002423/* Print fatal error message and abort */
2424
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002425#ifdef MS_WINDOWS
2426static void
2427fatal_output_debug(const char *msg)
2428{
2429 /* buffer of 256 bytes allocated on the stack */
2430 WCHAR buffer[256 / sizeof(WCHAR)];
2431 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2432 size_t msglen;
2433
2434 OutputDebugStringW(L"Fatal Python error: ");
2435
2436 msglen = strlen(msg);
2437 while (msglen) {
2438 size_t i;
2439
2440 if (buflen > msglen) {
2441 buflen = msglen;
2442 }
2443
2444 /* Convert the message to wchar_t. This uses a simple one-to-one
2445 conversion, assuming that the this error message actually uses
2446 ASCII only. If this ceases to be true, we will have to convert. */
2447 for (i=0; i < buflen; ++i) {
2448 buffer[i] = msg[i];
2449 }
2450 buffer[i] = L'\0';
2451 OutputDebugStringW(buffer);
2452
2453 msg += buflen;
2454 msglen -= buflen;
2455 }
2456 OutputDebugStringW(L"\n");
2457}
2458#endif
2459
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002460
2461static void
Victor Stinner314b8782021-01-18 18:34:56 +01002462fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002463{
Victor Stinner314b8782021-01-18 18:34:56 +01002464 PUTS(fd, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002465 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2466 if (finalizing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002467 PUTS(fd, "finalizing (tstate=0x");
2468 _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
2469 PUTS(fd, ")");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002470 }
2471 else if (runtime->initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002472 PUTS(fd, "initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002473 }
2474 else if (runtime->core_initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002475 PUTS(fd, "core initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002476 }
2477 else if (runtime->preinitialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002478 PUTS(fd, "preinitialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002479 }
2480 else if (runtime->preinitializing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002481 PUTS(fd, "preinitializing");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002482 }
2483 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002484 PUTS(fd, "unknown");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002485 }
Victor Stinner314b8782021-01-18 18:34:56 +01002486 PUTS(fd, "\n");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002487}
2488
2489
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002490static inline void _Py_NO_RETURN
2491fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002492{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002493 if (status < 0) {
2494#if defined(MS_WINDOWS) && defined(_DEBUG)
2495 DebugBreak();
2496#endif
2497 abort();
2498 }
2499 else {
2500 exit(status);
2501 }
2502}
2503
2504
Victor Stinner66f77ca2021-01-19 23:35:27 +01002505// Dump the list of extension modules of sys.modules, excluding stdlib modules
Victor Stinner9852cb32021-01-25 23:12:50 +01002506// (sys.stdlib_module_names), into fd file descriptor.
Victor Stinner66f77ca2021-01-19 23:35:27 +01002507//
Victor Stinner250035d2021-01-18 20:47:13 +01002508// This function is called by a signal handler in faulthandler: avoid memory
Victor Stinner66f77ca2021-01-19 23:35:27 +01002509// allocations and keep the implementation simple. For example, the list is not
2510// sorted on purpose.
Victor Stinner250035d2021-01-18 20:47:13 +01002511void
2512_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
2513{
2514 if (interp == NULL) {
2515 return;
2516 }
2517 PyObject *modules = interp->modules;
Victor Stinner66f77ca2021-01-19 23:35:27 +01002518 if (modules == NULL || !PyDict_Check(modules)) {
Victor Stinner250035d2021-01-18 20:47:13 +01002519 return;
2520 }
2521
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002522 Py_ssize_t pos;
2523 PyObject *key, *value;
2524
2525 // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
2526 // memory cannot be allocated on the heap in a signal handler.
2527 // Iterate on the dict instead.
Victor Stinner9852cb32021-01-25 23:12:50 +01002528 PyObject *stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002529 pos = 0;
2530 while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
2531 if (PyUnicode_Check(key)
Victor Stinner9852cb32021-01-25 23:12:50 +01002532 && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
2533 stdlib_module_names = value;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002534 break;
2535 }
2536 }
Victor Stinner9852cb32021-01-25 23:12:50 +01002537 // If we failed to get sys.stdlib_module_names or it's not a frozenset,
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002538 // don't exclude stdlib modules.
Victor Stinner9852cb32021-01-25 23:12:50 +01002539 if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
2540 stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002541 }
2542
2543 // List extensions
Victor Stinner66f77ca2021-01-19 23:35:27 +01002544 int header = 1;
2545 Py_ssize_t count = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002546 pos = 0;
Victor Stinner250035d2021-01-18 20:47:13 +01002547 while (PyDict_Next(modules, &pos, &key, &value)) {
2548 if (!PyUnicode_Check(key)) {
2549 continue;
2550 }
2551 if (!_PyModule_IsExtension(value)) {
2552 continue;
2553 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002554 // Use the module name from the sys.modules key,
2555 // don't attempt to get the module object name.
Victor Stinner9852cb32021-01-25 23:12:50 +01002556 if (stdlib_module_names != NULL) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002557 int is_stdlib_ext = 0;
2558
Victor Stinner9852cb32021-01-25 23:12:50 +01002559 Py_ssize_t i = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002560 PyObject *item;
2561 Py_hash_t hash;
Victor Stinner9852cb32021-01-25 23:12:50 +01002562 while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002563 if (PyUnicode_Check(item)
2564 && PyUnicode_Compare(key, item) == 0)
2565 {
2566 is_stdlib_ext = 1;
2567 break;
2568 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002569 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002570 if (is_stdlib_ext) {
2571 // Ignore stdlib extension
2572 continue;
2573 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002574 }
2575
2576 if (header) {
2577 PUTS(fd, "\nExtension modules: ");
2578 header = 0;
2579 }
2580 else {
Victor Stinner250035d2021-01-18 20:47:13 +01002581 PUTS(fd, ", ");
2582 }
Victor Stinner250035d2021-01-18 20:47:13 +01002583
2584 _Py_DumpASCII(fd, key);
Victor Stinner66f77ca2021-01-19 23:35:27 +01002585 count++;
Victor Stinner250035d2021-01-18 20:47:13 +01002586 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002587
2588 if (count) {
2589 PUTS(fd, " (total: ");
2590 _Py_DumpDecimal(fd, count);
2591 PUTS(fd, ")");
2592 PUTS(fd, "\n");
2593 }
Victor Stinner250035d2021-01-18 20:47:13 +01002594}
2595
2596
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002597static void _Py_NO_RETURN
Victor Stinner314b8782021-01-18 18:34:56 +01002598fatal_error(int fd, int header, const char *prefix, const char *msg,
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002599 int status)
2600{
Victor Stinner53345a42015-03-25 01:55:14 +01002601 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002602
2603 if (reentrant) {
2604 /* Py_FatalError() caused a second fatal error.
2605 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002606 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002607 }
2608 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002609
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002610 if (header) {
Victor Stinner314b8782021-01-18 18:34:56 +01002611 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002612 if (prefix) {
Victor Stinner314b8782021-01-18 18:34:56 +01002613 PUTS(fd, prefix);
2614 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002615 }
2616 if (msg) {
Victor Stinner314b8782021-01-18 18:34:56 +01002617 PUTS(fd, msg);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002618 }
2619 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002620 PUTS(fd, "<message not set>");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002621 }
Victor Stinner314b8782021-01-18 18:34:56 +01002622 PUTS(fd, "\n");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002623 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002624
2625 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner314b8782021-01-18 18:34:56 +01002626 fatal_error_dump_runtime(fd, runtime);
Victor Stinner10dc4842015-03-24 12:01:30 +01002627
Victor Stinner3a228ab2018-11-01 00:26:41 +01002628 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002629 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002630
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002631 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2632 has no Python thread state.
2633
2634 tss_tstate != tstate if the current Python thread does not hold the GIL.
2635 */
Victor Stinner314b8782021-01-18 18:34:56 +01002636 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2637 PyInterpreterState *interp = NULL;
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002638 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
Victor Stinner314b8782021-01-18 18:34:56 +01002639 if (tstate != NULL) {
2640 interp = tstate->interp;
2641 }
2642 else if (tss_tstate != NULL) {
2643 interp = tss_tstate->interp;
2644 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002645 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner314b8782021-01-18 18:34:56 +01002646
Victor Stinner3a228ab2018-11-01 00:26:41 +01002647 if (has_tstate_and_gil) {
2648 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002649 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002650 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002651 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002652 }
2653 }
2654 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002655 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002656 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002657
Victor Stinner250035d2021-01-18 20:47:13 +01002658 _Py_DumpExtensionModules(fd, interp);
2659
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002660 /* The main purpose of faulthandler is to display the traceback.
2661 This function already did its best to display a traceback.
2662 Disable faulthandler to prevent writing a second traceback
2663 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002664 _PyFaulthandler_Fini();
2665
Victor Stinner791da1c2016-03-14 16:53:12 +01002666 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002667 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002668 /* Flush sys.stdout and sys.stderr */
2669 flush_std_files();
2670 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002671
Nick Coghland6009512014-11-20 21:39:37 +10002672#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002673 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002674#endif /* MS_WINDOWS */
2675
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002676 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002677}
2678
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002679
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002680#undef Py_FatalError
2681
Victor Stinner19760862017-12-20 01:41:59 +01002682void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002683Py_FatalError(const char *msg)
2684{
Victor Stinner314b8782021-01-18 18:34:56 +01002685 fatal_error(fileno(stderr), 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002686}
2687
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002688
Victor Stinner19760862017-12-20 01:41:59 +01002689void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002690_Py_FatalErrorFunc(const char *func, const char *msg)
2691{
Victor Stinner314b8782021-01-18 18:34:56 +01002692 fatal_error(fileno(stderr), 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002693}
2694
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002695
2696void _Py_NO_RETURN
2697_Py_FatalErrorFormat(const char *func, const char *format, ...)
2698{
2699 static int reentrant = 0;
2700 if (reentrant) {
2701 /* _Py_FatalErrorFormat() caused a second fatal error */
2702 fatal_error_exit(-1);
2703 }
2704 reentrant = 1;
2705
2706 FILE *stream = stderr;
Victor Stinner314b8782021-01-18 18:34:56 +01002707 const int fd = fileno(stream);
2708 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002709 if (func) {
Victor Stinner314b8782021-01-18 18:34:56 +01002710 PUTS(fd, func);
2711 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002712 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002713
2714 va_list vargs;
2715#ifdef HAVE_STDARG_PROTOTYPES
2716 va_start(vargs, format);
2717#else
2718 va_start(vargs);
2719#endif
2720 vfprintf(stream, format, vargs);
2721 va_end(vargs);
2722
2723 fputs("\n", stream);
2724 fflush(stream);
2725
Victor Stinner314b8782021-01-18 18:34:56 +01002726 fatal_error(fd, 0, NULL, NULL, -1);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002727}
2728
2729
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002730void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002731Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002732{
Victor Stinner331a6a52019-05-27 16:39:22 +02002733 if (_PyStatus_IS_EXIT(status)) {
2734 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002735 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002736 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner314b8782021-01-18 18:34:56 +01002737 fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002738 }
2739 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002740 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002741 }
Nick Coghland6009512014-11-20 21:39:37 +10002742}
2743
Victor Stinner357704c2020-12-14 23:07:54 +01002744
Nick Coghland6009512014-11-20 21:39:37 +10002745/* Wait until threading._shutdown completes, provided
2746 the threading module was imported in the first place.
2747 The shutdown routine will wait until all non-daemon
2748 "threading" threads have completed. */
2749static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002750wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002751{
Nick Coghland6009512014-11-20 21:39:37 +10002752 _Py_IDENTIFIER(_shutdown);
2753 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002754 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002755 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002756 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002757 PyErr_WriteUnraisable(NULL);
2758 }
2759 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002760 return;
2761 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002762 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002763 if (result == NULL) {
2764 PyErr_WriteUnraisable(threading);
2765 }
2766 else {
2767 Py_DECREF(result);
2768 }
2769 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002770}
2771
2772#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002773int Py_AtExit(void (*func)(void))
2774{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002775 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002776 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002777 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002778 return 0;
2779}
2780
2781static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002782call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002783{
Victor Stinner8e91c242019-04-24 17:24:01 +02002784 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002785 /* pop last function from the list */
2786 runtime->nexitfuncs--;
2787 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2788 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2789
2790 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002791 }
Nick Coghland6009512014-11-20 21:39:37 +10002792
2793 fflush(stdout);
2794 fflush(stderr);
2795}
2796
Victor Stinnercfc88312018-08-01 16:41:25 +02002797void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002798Py_Exit(int sts)
2799{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002800 if (Py_FinalizeEx() < 0) {
2801 sts = 120;
2802 }
Nick Coghland6009512014-11-20 21:39:37 +10002803
2804 exit(sts);
2805}
2806
Nick Coghland6009512014-11-20 21:39:37 +10002807
Nick Coghland6009512014-11-20 21:39:37 +10002808/*
2809 * The file descriptor fd is considered ``interactive'' if either
2810 * a) isatty(fd) is TRUE, or
2811 * b) the -i flag was given, and the filename associated with
2812 * the descriptor is NULL or "<stdin>" or "???".
2813 */
2814int
2815Py_FdIsInteractive(FILE *fp, const char *filename)
2816{
2817 if (isatty((int)fileno(fp)))
2818 return 1;
2819 if (!Py_InteractiveFlag)
2820 return 0;
2821 return (filename == NULL) ||
2822 (strcmp(filename, "<stdin>") == 0) ||
2823 (strcmp(filename, "???") == 0);
2824}
2825
2826
Victor Stinnera82f63f2020-12-09 22:37:27 +01002827int
2828_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2829{
2830 if (isatty((int)fileno(fp))) {
2831 return 1;
2832 }
2833 if (!Py_InteractiveFlag) {
2834 return 0;
2835 }
2836 return (filename == NULL) ||
2837 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2838 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2839}
2840
2841
Nick Coghland6009512014-11-20 21:39:37 +10002842/* Wrappers around sigaction() or signal(). */
2843
2844PyOS_sighandler_t
2845PyOS_getsig(int sig)
2846{
2847#ifdef HAVE_SIGACTION
2848 struct sigaction context;
2849 if (sigaction(sig, NULL, &context) == -1)
2850 return SIG_ERR;
2851 return context.sa_handler;
2852#else
2853 PyOS_sighandler_t handler;
2854/* Special signal handling for the secure CRT in Visual Studio 2005 */
2855#if defined(_MSC_VER) && _MSC_VER >= 1400
2856 switch (sig) {
2857 /* Only these signals are valid */
2858 case SIGINT:
2859 case SIGILL:
2860 case SIGFPE:
2861 case SIGSEGV:
2862 case SIGTERM:
2863 case SIGBREAK:
2864 case SIGABRT:
2865 break;
2866 /* Don't call signal() with other values or it will assert */
2867 default:
2868 return SIG_ERR;
2869 }
2870#endif /* _MSC_VER && _MSC_VER >= 1400 */
2871 handler = signal(sig, SIG_IGN);
2872 if (handler != SIG_ERR)
2873 signal(sig, handler);
2874 return handler;
2875#endif
2876}
2877
2878/*
2879 * All of the code in this function must only use async-signal-safe functions,
2880 * listed at `man 7 signal` or
2881 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2882 */
2883PyOS_sighandler_t
2884PyOS_setsig(int sig, PyOS_sighandler_t handler)
2885{
2886#ifdef HAVE_SIGACTION
2887 /* Some code in Modules/signalmodule.c depends on sigaction() being
2888 * used here if HAVE_SIGACTION is defined. Fix that if this code
2889 * changes to invalidate that assumption.
2890 */
2891 struct sigaction context, ocontext;
2892 context.sa_handler = handler;
2893 sigemptyset(&context.sa_mask);
Gregory P. Smith02ac6f42021-03-04 21:49:30 -08002894 /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
2895 * extension module or embedding code may use where tiny thread stacks
2896 * are used. https://bugs.python.org/issue43390 */
2897 context.sa_flags = SA_ONSTACK;
Nick Coghland6009512014-11-20 21:39:37 +10002898 if (sigaction(sig, &context, &ocontext) == -1)
2899 return SIG_ERR;
2900 return ocontext.sa_handler;
2901#else
2902 PyOS_sighandler_t oldhandler;
2903 oldhandler = signal(sig, handler);
2904#ifdef HAVE_SIGINTERRUPT
2905 siginterrupt(sig, 1);
2906#endif
2907 return oldhandler;
2908#endif
2909}
2910
2911#ifdef __cplusplus
2912}
2913#endif