blob: bf5dcdd107e20faa077e54b745ff8ed3568b6247 [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 Stinner9e1b8282020-11-10 13:21:52 +0100433 if (_Py_IsMainInterpreter(tstate)) {
434 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. */
577 _PyEval_FiniGIL(tstate);
578
579 /* Auto-thread-state API */
580 status = _PyGILState_Init(tstate);
581 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{
600 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100601 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200602 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100603 }
604
Victor Stinner048a3562020-11-05 00:45:56 +0100605 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200606 if (_PyStatus_EXCEPTION(status)) {
607 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100608 }
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200610 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200611 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200612 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200613 }
Nick Coghland6009512014-11-20 21:39:37 +1000614 (void) PyThreadState_Swap(tstate);
615
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200616 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100617 if (_PyStatus_EXCEPTION(status)) {
618 return status;
619 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100620
Victor Stinnerb45d2592019-06-20 00:05:23 +0200621 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200622 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100623}
Nick Coghland6009512014-11-20 21:39:37 +1000624
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100625
Victor Stinner331a6a52019-05-27 16:39:22 +0200626static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100627pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100628{
Victor Stinner444b39b2019-11-20 01:18:11 +0100629 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100630 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100631
Victor Stinner01b1cc12019-11-20 02:27:56 +0100632 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100633 if (_PyStatus_EXCEPTION(status)) {
634 return status;
635 }
636
Victor Stinner0430dfa2020-06-24 15:21:54 +0200637 // Create the empty tuple singleton. It must be created before the first
638 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
639 // for example.
640 status = _PyTuple_Init(tstate);
641 if (_PyStatus_EXCEPTION(status)) {
642 return status;
643 }
644
Victor Stinnere7e699e2019-11-20 12:08:13 +0100645 if (is_main_interp) {
646 status = _PyTypes_Init();
647 if (_PyStatus_EXCEPTION(status)) {
648 return status;
649 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100650 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100651
Victor Stinner630c8df2019-12-17 13:02:18 +0100652 if (!_PyLong_Init(tstate)) {
653 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100654 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100655
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200656 status = _PyUnicode_Init(tstate);
657 if (_PyStatus_EXCEPTION(status)) {
658 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100659 }
660
Victor Stinner91698d82020-06-25 14:07:40 +0200661 status = _PyBytes_Init(tstate);
662 if (_PyStatus_EXCEPTION(status)) {
663 return status;
664 }
665
Victor Stinner281cce12020-06-23 22:55:46 +0200666 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200667 if (_PyStatus_EXCEPTION(status)) {
668 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 }
670
Victor Stinnere7e699e2019-11-20 12:08:13 +0100671 if (is_main_interp) {
672 if (!_PyFloat_Init()) {
673 return _PyStatus_ERR("can't init float");
674 }
Nick Coghland6009512014-11-20 21:39:37 +1000675
Victor Stinnere7e699e2019-11-20 12:08:13 +0100676 if (_PyStructSequence_Init() < 0) {
677 return _PyStatus_ERR("can't initialize structseq");
678 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100679 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200680
Victor Stinner331a6a52019-05-27 16:39:22 +0200681 status = _PyErr_Init();
682 if (_PyStatus_EXCEPTION(status)) {
683 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200684 }
685
Victor Stinnere7e699e2019-11-20 12:08:13 +0100686 if (is_main_interp) {
687 if (!_PyContext_Init()) {
688 return _PyStatus_ERR("can't init context");
689 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100690 }
691
Victor Stinneref75a622020-11-12 15:14:13 +0100692 if (_PyWarnings_InitState(tstate) < 0) {
693 return _PyStatus_ERR("can't initialize warnings");
694 }
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100695
696 status = _PyAtExit_Init(tstate);
697 if (_PyStatus_EXCEPTION(status)) {
698 return status;
699 }
700
Victor Stinner331a6a52019-05-27 16:39:22 +0200701 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100702}
703
704
Victor Stinner331a6a52019-05-27 16:39:22 +0200705static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200706pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100707{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100708 assert(!_PyErr_Occurred(tstate));
709
Victor Stinnerb45d2592019-06-20 00:05:23 +0200710 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100712 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100713 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100714
Victor Stinner2582d462019-11-22 19:24:49 +0100715 PyInterpreterState *interp = tstate->interp;
716 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
717 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100718 }
Victor Stinner2582d462019-11-22 19:24:49 +0100719
720 PyObject *builtins_dict = PyModule_GetDict(bimod);
721 if (builtins_dict == NULL) {
722 goto error;
723 }
724 Py_INCREF(builtins_dict);
725 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100726
Victor Stinner331a6a52019-05-27 16:39:22 +0200727 PyStatus status = _PyBuiltins_AddExceptions(bimod);
728 if (_PyStatus_EXCEPTION(status)) {
729 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100730 }
Victor Stinner2582d462019-11-22 19:24:49 +0100731
732 interp->builtins_copy = PyDict_Copy(interp->builtins);
733 if (interp->builtins_copy == NULL) {
734 goto error;
735 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000736 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100737
Victor Stinner62230712020-11-18 23:18:29 +0100738 // Get the __import__ function
739 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
740 "__import__");
741 if (import_func == NULL) {
742 goto error;
743 }
744 interp->import_func = Py_NewRef(import_func);
745
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100746 assert(!_PyErr_Occurred(tstate));
747
Victor Stinner331a6a52019-05-27 16:39:22 +0200748 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100749
750error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000751 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100752 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100753}
754
755
Victor Stinner331a6a52019-05-27 16:39:22 +0200756static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100757pycore_interp_init(PyThreadState *tstate)
758{
759 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100760 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100761
762 status = pycore_init_types(tstate);
763 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100764 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100765 }
766
Victor Stinnerd863ade2019-12-06 03:37:07 +0100767 status = _PySys_Create(tstate, &sysmod);
768 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100769 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100770 }
771
772 status = pycore_init_builtins(tstate);
773 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100774 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100775 }
776
Victor Stinneref75a622020-11-12 15:14:13 +0100777 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
778 if (config->_install_importlib) {
779 /* This call sets up builtin and frozen import support */
780 if (init_importlib(tstate, sysmod) < 0) {
781 return _PyStatus_ERR("failed to initialize importlib");
782 }
783 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100784
785done:
786 /* sys.modules['sys'] contains a strong reference to the module */
787 Py_XDECREF(sysmod);
788 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100789}
790
791
792static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200793pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200794 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200795 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100796{
Victor Stinner331a6a52019-05-27 16:39:22 +0200797 PyStatus status = pycore_init_runtime(runtime, config);
798 if (_PyStatus_EXCEPTION(status)) {
799 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100800 }
801
Victor Stinnerb45d2592019-06-20 00:05:23 +0200802 PyThreadState *tstate;
803 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200804 if (_PyStatus_EXCEPTION(status)) {
805 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100806 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200807 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100808
Victor Stinnerd863ade2019-12-06 03:37:07 +0100809 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200810 if (_PyStatus_EXCEPTION(status)) {
811 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100812 }
Eric Snow1abcf672017-05-23 21:46:51 -0700813
814 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200815 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200816 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700817}
818
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100819
Victor Stinner331a6a52019-05-27 16:39:22 +0200820PyStatus
821_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100822{
Victor Stinner331a6a52019-05-27 16:39:22 +0200823 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100824
Victor Stinner6d1c4672019-05-20 11:02:00 +0200825 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200827 }
828
Victor Stinner331a6a52019-05-27 16:39:22 +0200829 status = _PyRuntime_Initialize();
830 if (_PyStatus_EXCEPTION(status)) {
831 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100832 }
Victor Stinner43125222019-04-24 18:23:53 +0200833 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100834
Victor Stinnerd3b90412019-09-17 23:59:51 +0200835 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100836 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200837 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100838 }
839
Victor Stinnerd3b90412019-09-17 23:59:51 +0200840 /* Note: preinitialized remains 1 on error, it is only set to 0
841 at exit on success. */
842 runtime->preinitializing = 1;
843
Victor Stinner331a6a52019-05-27 16:39:22 +0200844 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200845
846 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
847 if (_PyStatus_EXCEPTION(status)) {
848 return status;
849 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100850
Victor Stinner331a6a52019-05-27 16:39:22 +0200851 status = _PyPreConfig_Read(&config, args);
852 if (_PyStatus_EXCEPTION(status)) {
853 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100854 }
855
Victor Stinner331a6a52019-05-27 16:39:22 +0200856 status = _PyPreConfig_Write(&config);
857 if (_PyStatus_EXCEPTION(status)) {
858 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100859 }
860
Victor Stinnerd3b90412019-09-17 23:59:51 +0200861 runtime->preinitializing = 0;
862 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200863 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100864}
865
Victor Stinner70005ac2019-05-02 15:25:34 -0400866
Victor Stinner331a6a52019-05-27 16:39:22 +0200867PyStatus
868Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100869{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100870 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400871 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100872}
873
874
Victor Stinner331a6a52019-05-27 16:39:22 +0200875PyStatus
876Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100877{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100878 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400879 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100880}
881
882
Victor Stinner331a6a52019-05-27 16:39:22 +0200883PyStatus
884Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100885{
Victor Stinner70005ac2019-05-02 15:25:34 -0400886 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100887}
888
889
Victor Stinner331a6a52019-05-27 16:39:22 +0200890PyStatus
891_Py_PreInitializeFromConfig(const PyConfig *config,
892 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100893{
Victor Stinner331a6a52019-05-27 16:39:22 +0200894 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200895
Victor Stinner331a6a52019-05-27 16:39:22 +0200896 PyStatus status = _PyRuntime_Initialize();
897 if (_PyStatus_EXCEPTION(status)) {
898 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200899 }
900 _PyRuntimeState *runtime = &_PyRuntime;
901
Victor Stinnerd3b90412019-09-17 23:59:51 +0200902 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200903 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200904 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400905 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200906
Victor Stinner331a6a52019-05-27 16:39:22 +0200907 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200908
Victor Stinner3c30a762019-10-01 10:56:37 +0200909 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200910
Victor Stinner331a6a52019-05-27 16:39:22 +0200911 if (!config->parse_argv) {
912 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200913 }
914 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200915 _PyArgv config_args = {
916 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200917 .argc = config->argv.length,
918 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200919 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200920 }
921 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200922 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200923 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100924}
925
926
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100927/* Begin interpreter initialization
928 *
929 * On return, the first thread and interpreter state have been created,
930 * but the compiler, signal handling, multithreading and
931 * multiple interpreter support, and codec infrastructure are not yet
932 * available.
933 *
934 * The import system will support builtin and frozen modules only.
935 * The only supported io is writing to sys.stderr
936 *
937 * If any operation invoked by this function fails, a fatal error is
938 * issued and the function does not return.
939 *
940 * Any code invoked from this function should *not* assume it has access
941 * to the Python C API (unless the API is explicitly listed as being
942 * safe to call without calling Py_Initialize first)
943 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200944static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200945pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200946 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200947 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200948{
Victor Stinner331a6a52019-05-27 16:39:22 +0200949 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200950
Victor Stinner331a6a52019-05-27 16:39:22 +0200951 status = _Py_PreInitializeFromConfig(src_config, NULL);
952 if (_PyStatus_EXCEPTION(status)) {
953 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200954 }
955
Victor Stinner331a6a52019-05-27 16:39:22 +0200956 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100957 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200958
Victor Stinner331a6a52019-05-27 16:39:22 +0200959 status = _PyConfig_Copy(&config, src_config);
960 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200961 goto done;
962 }
963
Victor Stinner9e1b8282020-11-10 13:21:52 +0100964 // Read the configuration, but don't compute the path configuration
965 // (it is computed in the main init).
966 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200967 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200968 goto done;
969 }
970
971 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200972 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200973 }
974 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200975 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200976 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200977 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200978 goto done;
979 }
980
981done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200982 PyConfig_Clear(&config);
983 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200984}
985
Victor Stinner5ac27a52019-03-27 13:40:14 +0100986
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200987/* Py_Initialize() has already been called: update the main interpreter
988 configuration. Example of bpo-34008: Py_Main() called after
989 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200990static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100991pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200992{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100993 if (interpreter_update_config(tstate, 0) < 0) {
994 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200995 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200996 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200997}
998
Victor Stinnerb0051362019-11-22 17:52:42 +0100999
1000static PyStatus
1001init_interp_main(PyThreadState *tstate)
1002{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001003 assert(!_PyErr_Occurred(tstate));
1004
Victor Stinnerb0051362019-11-22 17:52:42 +01001005 PyStatus status;
1006 int is_main_interp = _Py_IsMainInterpreter(tstate);
1007 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001008 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001009
1010 if (!config->_install_importlib) {
1011 /* Special mode for freeze_importlib: run with no import system
1012 *
1013 * This means anything which needs support from extension modules
1014 * or pure Python code in the standard library won't work.
1015 */
1016 if (is_main_interp) {
1017 interp->runtime->initialized = 1;
1018 }
1019 return _PyStatus_OK();
1020 }
1021
Victor Stinner9e1b8282020-11-10 13:21:52 +01001022 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001023 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001024 if (_PyStatus_EXCEPTION(status)) {
1025 return status;
1026 }
1027
Victor Stinner9e1b8282020-11-10 13:21:52 +01001028 if (interpreter_update_config(tstate, 1) < 0) {
1029 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001030 }
1031
1032 status = init_importlib_external(tstate);
1033 if (_PyStatus_EXCEPTION(status)) {
1034 return status;
1035 }
1036
1037 if (is_main_interp) {
1038 /* initialize the faulthandler module */
1039 status = _PyFaulthandler_Init(config->faulthandler);
1040 if (_PyStatus_EXCEPTION(status)) {
1041 return status;
1042 }
1043 }
1044
1045 status = _PyUnicode_InitEncodings(tstate);
1046 if (_PyStatus_EXCEPTION(status)) {
1047 return status;
1048 }
1049
1050 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001051 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1052 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001053 }
1054
1055 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1056 return _PyStatus_ERR("can't initialize tracemalloc");
1057 }
1058 }
1059
1060 status = init_sys_streams(tstate);
1061 if (_PyStatus_EXCEPTION(status)) {
1062 return status;
1063 }
1064
Andy Lester75cd5bf2020-03-12 02:49:05 -05001065 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001066 if (_PyStatus_EXCEPTION(status)) {
1067 return status;
1068 }
1069
1070 status = add_main_module(interp);
1071 if (_PyStatus_EXCEPTION(status)) {
1072 return status;
1073 }
1074
1075 if (is_main_interp) {
1076 /* Initialize warnings. */
1077 PyObject *warnoptions = PySys_GetObject("warnoptions");
1078 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1079 {
1080 PyObject *warnings_module = PyImport_ImportModule("warnings");
1081 if (warnings_module == NULL) {
1082 fprintf(stderr, "'import warnings' failed; traceback:\n");
1083 _PyErr_Print(tstate);
1084 }
1085 Py_XDECREF(warnings_module);
1086 }
1087
1088 interp->runtime->initialized = 1;
1089 }
1090
1091 if (config->site_import) {
1092 status = init_import_site();
1093 if (_PyStatus_EXCEPTION(status)) {
1094 return status;
1095 }
1096 }
1097
1098 if (is_main_interp) {
1099#ifndef MS_WINDOWS
1100 emit_stderr_warning_for_legacy_locale(interp->runtime);
1101#endif
1102 }
1103
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001104 assert(!_PyErr_Occurred(tstate));
1105
Victor Stinnerb0051362019-11-22 17:52:42 +01001106 return _PyStatus_OK();
1107}
1108
1109
Eric Snowc7ec9982017-05-23 23:00:52 -07001110/* Update interpreter state based on supplied configuration settings
1111 *
1112 * After calling this function, most of the restrictions on the interpreter
1113 * are lifted. The only remaining incomplete settings are those related
1114 * to the main module (sys.argv[0], __main__ metadata)
1115 *
1116 * Calling this when the interpreter is not initializing, is already
1117 * initialized or without a valid current thread state is a fatal error.
1118 * Other errors should be reported as normal Python exceptions with a
1119 * non-zero return code.
1120 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001121static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001122pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001123{
Victor Stinnerb0051362019-11-22 17:52:42 +01001124 PyInterpreterState *interp = tstate->interp;
1125 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001126 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001127 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001128
Victor Stinnerb0051362019-11-22 17:52:42 +01001129 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001130 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001131 }
1132
Victor Stinnerb0051362019-11-22 17:52:42 +01001133 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001134 if (_PyStatus_EXCEPTION(status)) {
1135 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001136 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001137 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001138}
1139
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001140
Victor Stinner331a6a52019-05-27 16:39:22 +02001141PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001142Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001143{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001144 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001145 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001146 }
1147
Victor Stinner331a6a52019-05-27 16:39:22 +02001148 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001149
Victor Stinner331a6a52019-05-27 16:39:22 +02001150 status = _PyRuntime_Initialize();
1151 if (_PyStatus_EXCEPTION(status)) {
1152 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001153 }
1154 _PyRuntimeState *runtime = &_PyRuntime;
1155
Victor Stinnerb45d2592019-06-20 00:05:23 +02001156 PyThreadState *tstate = NULL;
1157 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001158 if (_PyStatus_EXCEPTION(status)) {
1159 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001160 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001161 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001162
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001163 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001164 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001165 if (_PyStatus_EXCEPTION(status)) {
1166 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001167 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001168 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001169
Victor Stinner331a6a52019-05-27 16:39:22 +02001170 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001171}
1172
1173
Eric Snow1abcf672017-05-23 21:46:51 -07001174void
Nick Coghland6009512014-11-20 21:39:37 +10001175Py_InitializeEx(int install_sigs)
1176{
Victor Stinner331a6a52019-05-27 16:39:22 +02001177 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001178
Victor Stinner331a6a52019-05-27 16:39:22 +02001179 status = _PyRuntime_Initialize();
1180 if (_PyStatus_EXCEPTION(status)) {
1181 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001182 }
1183 _PyRuntimeState *runtime = &_PyRuntime;
1184
1185 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001186 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1187 return;
1188 }
1189
Victor Stinner331a6a52019-05-27 16:39:22 +02001190 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001191 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001192
Victor Stinner1dc6e392018-07-25 02:49:17 +02001193 config.install_signal_handlers = install_sigs;
1194
Victor Stinner331a6a52019-05-27 16:39:22 +02001195 status = Py_InitializeFromConfig(&config);
1196 if (_PyStatus_EXCEPTION(status)) {
1197 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001198 }
Nick Coghland6009512014-11-20 21:39:37 +10001199}
1200
1201void
1202Py_Initialize(void)
1203{
1204 Py_InitializeEx(1);
1205}
1206
1207
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001208PyStatus
1209_Py_InitializeMain(void)
1210{
1211 PyStatus status = _PyRuntime_Initialize();
1212 if (_PyStatus_EXCEPTION(status)) {
1213 return status;
1214 }
1215 _PyRuntimeState *runtime = &_PyRuntime;
1216 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1217 return pyinit_main(tstate);
1218}
1219
1220
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001221static void
1222finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1223{
1224 // List of names to clear in sys
1225 static const char * const sys_deletes[] = {
1226 "path", "argv", "ps1", "ps2",
1227 "last_type", "last_value", "last_traceback",
1228 "path_hooks", "path_importer_cache", "meta_path",
1229 "__interactivehook__",
1230 NULL
1231 };
1232
1233 static const char * const sys_files[] = {
1234 "stdin", "__stdin__",
1235 "stdout", "__stdout__",
1236 "stderr", "__stderr__",
1237 NULL
1238 };
1239
1240 PyInterpreterState *interp = tstate->interp;
1241 if (verbose) {
1242 PySys_WriteStderr("# clear builtins._\n");
1243 }
1244 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1245 PyErr_WriteUnraisable(NULL);
1246 }
1247
1248 const char * const *p;
1249 for (p = sys_deletes; *p != NULL; p++) {
1250 if (verbose) {
1251 PySys_WriteStderr("# clear sys.%s\n", *p);
1252 }
1253 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1254 PyErr_WriteUnraisable(NULL);
1255 }
1256 }
1257 for (p = sys_files; *p != NULL; p+=2) {
1258 const char *name = p[0];
1259 const char *orig_name = p[1];
1260 if (verbose) {
1261 PySys_WriteStderr("# restore sys.%s\n", name);
1262 }
1263 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1264 orig_name);
1265 if (value == NULL) {
1266 if (_PyErr_Occurred(tstate)) {
1267 PyErr_WriteUnraisable(NULL);
1268 }
1269 value = Py_None;
1270 }
1271 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1272 PyErr_WriteUnraisable(NULL);
1273 }
1274 }
1275}
1276
1277
1278static PyObject*
1279finalize_remove_modules(PyObject *modules, int verbose)
1280{
1281 PyObject *weaklist = PyList_New(0);
1282 if (weaklist == NULL) {
1283 PyErr_WriteUnraisable(NULL);
1284 }
1285
1286#define STORE_MODULE_WEAKREF(name, mod) \
1287 if (weaklist != NULL) { \
1288 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1289 if (wr) { \
1290 PyObject *tup = PyTuple_Pack(2, name, wr); \
1291 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1292 PyErr_WriteUnraisable(NULL); \
1293 } \
1294 Py_XDECREF(tup); \
1295 Py_DECREF(wr); \
1296 } \
1297 else { \
1298 PyErr_WriteUnraisable(NULL); \
1299 } \
1300 }
1301
1302#define CLEAR_MODULE(name, mod) \
1303 if (PyModule_Check(mod)) { \
1304 if (verbose && PyUnicode_Check(name)) { \
1305 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1306 } \
1307 STORE_MODULE_WEAKREF(name, mod); \
1308 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1309 PyErr_WriteUnraisable(NULL); \
1310 } \
1311 }
1312
1313 if (PyDict_CheckExact(modules)) {
1314 Py_ssize_t pos = 0;
1315 PyObject *key, *value;
1316 while (PyDict_Next(modules, &pos, &key, &value)) {
1317 CLEAR_MODULE(key, value);
1318 }
1319 }
1320 else {
1321 PyObject *iterator = PyObject_GetIter(modules);
1322 if (iterator == NULL) {
1323 PyErr_WriteUnraisable(NULL);
1324 }
1325 else {
1326 PyObject *key;
1327 while ((key = PyIter_Next(iterator))) {
1328 PyObject *value = PyObject_GetItem(modules, key);
1329 if (value == NULL) {
1330 PyErr_WriteUnraisable(NULL);
1331 continue;
1332 }
1333 CLEAR_MODULE(key, value);
1334 Py_DECREF(value);
1335 Py_DECREF(key);
1336 }
1337 if (PyErr_Occurred()) {
1338 PyErr_WriteUnraisable(NULL);
1339 }
1340 Py_DECREF(iterator);
1341 }
1342 }
1343#undef CLEAR_MODULE
1344#undef STORE_MODULE_WEAKREF
1345
1346 return weaklist;
1347}
1348
1349
1350static void
1351finalize_clear_modules_dict(PyObject *modules)
1352{
1353 if (PyDict_CheckExact(modules)) {
1354 PyDict_Clear(modules);
1355 }
1356 else {
1357 _Py_IDENTIFIER(clear);
1358 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1359 PyErr_WriteUnraisable(NULL);
1360 }
1361 }
1362}
1363
1364
1365static void
1366finalize_restore_builtins(PyThreadState *tstate)
1367{
1368 PyInterpreterState *interp = tstate->interp;
1369 PyObject *dict = PyDict_Copy(interp->builtins);
1370 if (dict == NULL) {
1371 PyErr_WriteUnraisable(NULL);
1372 }
1373 PyDict_Clear(interp->builtins);
1374 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1375 _PyErr_Clear(tstate);
1376 }
1377 Py_XDECREF(dict);
1378}
1379
1380
1381static void
1382finalize_modules_clear_weaklist(PyInterpreterState *interp,
1383 PyObject *weaklist, int verbose)
1384{
1385 // First clear modules imported later
1386 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1387 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1388 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1389 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1390 if (mod == Py_None) {
1391 continue;
1392 }
1393 assert(PyModule_Check(mod));
1394 PyObject *dict = PyModule_GetDict(mod);
1395 if (dict == interp->builtins || dict == interp->sysdict) {
1396 continue;
1397 }
1398 Py_INCREF(mod);
1399 if (verbose && PyUnicode_Check(name)) {
1400 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1401 }
1402 _PyModule_Clear(mod);
1403 Py_DECREF(mod);
1404 }
1405}
1406
1407
1408static void
1409finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1410{
1411 // Clear sys dict
1412 if (verbose) {
1413 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1414 }
1415 _PyModule_ClearDict(interp->sysdict);
1416
1417 // Clear builtins dict
1418 if (verbose) {
1419 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1420 }
1421 _PyModule_ClearDict(interp->builtins);
1422}
1423
1424
1425/* Clear modules, as good as we can */
1426static void
1427finalize_modules(PyThreadState *tstate)
1428{
1429 PyInterpreterState *interp = tstate->interp;
1430 PyObject *modules = interp->modules;
1431 if (modules == NULL) {
1432 // Already done
1433 return;
1434 }
1435 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1436
1437 // Delete some special builtins._ and sys attributes first. These are
1438 // common places where user values hide and people complain when their
1439 // destructors fail. Since the modules containing them are
1440 // deleted *last* of all, they would come too late in the normal
1441 // destruction order. Sigh.
1442 //
1443 // XXX Perhaps these precautions are obsolete. Who knows?
1444 finalize_modules_delete_special(tstate, verbose);
1445
1446 // Remove all modules from sys.modules, hoping that garbage collection
1447 // can reclaim most of them: set all sys.modules values to None.
1448 //
1449 // We prepare a list which will receive (name, weakref) tuples of
1450 // modules when they are removed from sys.modules. The name is used
1451 // for diagnosis messages (in verbose mode), while the weakref helps
1452 // detect those modules which have been held alive.
1453 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1454
1455 // Clear the modules dict
1456 finalize_clear_modules_dict(modules);
1457
1458 // Restore the original builtins dict, to ensure that any
1459 // user data gets cleared.
1460 finalize_restore_builtins(tstate);
1461
1462 // Collect garbage
1463 _PyGC_CollectNoFail(tstate);
1464
1465 // Dump GC stats before it's too late, since it uses the warnings
1466 // machinery.
1467 _PyGC_DumpShutdownStats(tstate);
1468
1469 if (weaklist != NULL) {
1470 // Now, if there are any modules left alive, clear their globals to
1471 // minimize potential leaks. All C extension modules actually end
1472 // up here, since they are kept alive in the interpreter state.
1473 //
1474 // The special treatment of "builtins" here is because even
1475 // when it's not referenced as a module, its dictionary is
1476 // referenced by almost every module's __builtins__. Since
1477 // deleting a module clears its dictionary (even if there are
1478 // references left to it), we need to delete the "builtins"
1479 // module last. Likewise, we don't delete sys until the very
1480 // end because it is implicitly referenced (e.g. by print).
1481 //
1482 // Since dict is ordered in CPython 3.6+, modules are saved in
1483 // importing order. First clear modules imported later.
1484 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1485 Py_DECREF(weaklist);
1486 }
1487
1488 // Clear sys and builtins modules dict
1489 finalize_clear_sys_builtins_dict(interp, verbose);
1490
1491 // Clear module dict copies stored in the interpreter state:
1492 // clear PyInterpreterState.modules_by_index and
1493 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1494 // initialization API)
1495 _PyInterpreterState_ClearModules(interp);
1496
1497 // Clear and delete the modules directory. Actual modules will
1498 // still be there only if imported during the execution of some
1499 // destructor.
1500 Py_SETREF(interp->modules, NULL);
1501
1502 // Collect garbage once more
1503 _PyGC_CollectNoFail(tstate);
1504}
1505
1506
Nick Coghland6009512014-11-20 21:39:37 +10001507/* Flush stdout and stderr */
1508
1509static int
1510file_is_closed(PyObject *fobj)
1511{
1512 int r;
1513 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1514 if (tmp == NULL) {
1515 PyErr_Clear();
1516 return 0;
1517 }
1518 r = PyObject_IsTrue(tmp);
1519 Py_DECREF(tmp);
1520 if (r < 0)
1521 PyErr_Clear();
1522 return r > 0;
1523}
1524
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001525
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001526static int
Nick Coghland6009512014-11-20 21:39:37 +10001527flush_std_files(void)
1528{
1529 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1530 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1531 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001532 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001533
1534 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001535 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001536 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001537 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001538 status = -1;
1539 }
Nick Coghland6009512014-11-20 21:39:37 +10001540 else
1541 Py_DECREF(tmp);
1542 }
1543
1544 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001545 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001546 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001547 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001548 status = -1;
1549 }
Nick Coghland6009512014-11-20 21:39:37 +10001550 else
1551 Py_DECREF(tmp);
1552 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001553
1554 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001555}
1556
1557/* Undo the effect of Py_Initialize().
1558
1559 Beware: if multiple interpreter and/or thread states exist, these
1560 are not wiped out; only the current thread and interpreter state
1561 are deleted. But since everything else is deleted, those other
1562 interpreter and thread states should no longer be used.
1563
1564 (XXX We should do better, e.g. wipe out all interpreters and
1565 threads.)
1566
1567 Locking: as above.
1568
1569*/
1570
Victor Stinner7eee5be2019-11-20 10:38:34 +01001571
1572static void
Victor Stinner90db4652020-07-01 23:21:36 +02001573finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001574{
Victor Stinner281cce12020-06-23 22:55:46 +02001575 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001576 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001577 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001578 _PyContext_Fini(tstate);
Victor Stinnerf4507232020-12-26 20:26:08 +01001579 _PyType_Fini(tstate);
Victor Stinnerea251802020-12-26 02:58:33 +01001580 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1581 // a dict internally.
Victor Stinner666ecfb2020-07-02 01:19:57 +02001582 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001583
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001584 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001585 _PyList_Fini(tstate);
1586 _PyTuple_Fini(tstate);
1587
1588 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001589
Victor Stinnerc41eed12020-06-23 15:54:35 +02001590 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001591 _PyUnicode_Fini(tstate);
1592 _PyFloat_Fini(tstate);
1593 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001594}
1595
1596
1597static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001598finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001599{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001600 int is_main_interp = _Py_IsMainInterpreter(tstate);
1601
Victor Stinner7eee5be2019-11-20 10:38:34 +01001602 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001603 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001604
Kongedaa0fe02020-07-04 05:06:46 +08001605 /* Clear all loghooks */
1606 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1607 Call _PySys_ClearAuditHooks when PyObject available. */
1608 if (is_main_interp) {
1609 _PySys_ClearAuditHooks(tstate);
1610 }
1611
Victor Stinner7907f8c2020-06-08 01:22:36 +02001612 if (is_main_interp) {
1613 _Py_HashRandomization_Fini();
1614 _PyArg_Fini();
1615 _Py_ClearFileSystemEncoding();
1616 }
1617
Victor Stinner90db4652020-07-01 23:21:36 +02001618 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001619}
1620
1621
1622static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001623finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001624{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001625 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001626 /* Cleanup auto-thread-state */
1627 _PyGILState_Fini(tstate);
1628 }
1629
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001630 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1631 fail when it is being awaited by another running daemon thread (see
1632 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1633 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1634 called multiple times. */
1635
Victor Stinner7eee5be2019-11-20 10:38:34 +01001636 PyInterpreterState_Delete(tstate->interp);
1637}
1638
1639
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001640int
1641Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001642{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001643 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001644
Victor Stinner8e91c242019-04-24 17:24:01 +02001645 _PyRuntimeState *runtime = &_PyRuntime;
1646 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001647 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001648 }
Nick Coghland6009512014-11-20 21:39:37 +10001649
Victor Stinnere225beb2019-06-03 18:14:24 +02001650 /* Get current thread state and interpreter pointer */
1651 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001652
Victor Stinnerb45d2592019-06-20 00:05:23 +02001653 // Wrap up existing "threading"-module-created, non-daemon threads.
1654 wait_for_thread_shutdown(tstate);
1655
1656 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001657 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001658
Nick Coghland6009512014-11-20 21:39:37 +10001659 /* The interpreter is still entirely intact at this point, and the
1660 * exit funcs may be relying on that. In particular, if some thread
1661 * or exit func is still waiting to do an import, the import machinery
1662 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001663 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001664 * Note that Threading.py uses an exit func to do a join on all the
1665 * threads created thru it, so this also protects pending imports in
1666 * the threads created via Threading.
1667 */
Nick Coghland6009512014-11-20 21:39:37 +10001668
Victor Stinnerb8fa1352020-12-15 14:34:19 +01001669 _PyAtExit_Call(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001670
Victor Stinnerda273412017-12-15 01:46:02 +01001671 /* Copy the core config, PyInterpreterState_Delete() free
1672 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001673#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001674 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001675#endif
1676#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001677 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001678#endif
1679#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001680 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001681#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001682
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001683 /* Remaining daemon threads will automatically exit
1684 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001685 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001686 runtime->initialized = 0;
1687 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001688
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001689 /* Destroy the state of all threads of the interpreter, except of the
1690 current thread. In practice, only daemon threads should still be alive,
1691 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1692 Clear frames of other threads to call objects destructors. Destructors
1693 will be called in the current Python thread. Since
1694 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1695 can take the GIL at this point: if they try, they will exit
1696 immediately. */
1697 _PyThreadState_DeleteExcept(runtime, tstate);
1698
Victor Stinnere0deff32015-03-24 13:46:18 +01001699 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001700 if (flush_std_files() < 0) {
1701 status = -1;
1702 }
Nick Coghland6009512014-11-20 21:39:37 +10001703
1704 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001705 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001706
1707 /* Collect garbage. This may call finalizers; it's nice to call these
1708 * before all modules are destroyed.
1709 * XXX If a __del__ or weakref callback is triggered here, and tries to
1710 * XXX import a module, bad things can happen, because Python no
1711 * XXX longer believes it's initialized.
1712 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1713 * XXX is easy to provoke that way. I've also seen, e.g.,
1714 * XXX Exception exceptions.ImportError: 'No module named sha'
1715 * XXX in <function callback at 0x008F5718> ignored
1716 * XXX but I'm unclear on exactly how that one happens. In any case,
1717 * XXX I haven't seen a real-life report of either of these.
1718 */
Victor Stinner8b341482020-10-30 17:00:00 +01001719 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001720
Nick Coghland6009512014-11-20 21:39:37 +10001721 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001722 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001723
Inada Naoki91234a12019-06-03 21:30:58 +09001724 /* Print debug stats if any */
1725 _PyEval_Fini();
1726
Victor Stinnere0deff32015-03-24 13:46:18 +01001727 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001728 if (flush_std_files() < 0) {
1729 status = -1;
1730 }
Nick Coghland6009512014-11-20 21:39:37 +10001731
1732 /* Collect final garbage. This disposes of cycles created by
1733 * class definitions, for example.
1734 * XXX This is disabled because it caused too many problems. If
1735 * XXX a __del__ or weakref callback triggers here, Python code has
1736 * XXX a hard time running, because even the sys module has been
1737 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1738 * XXX One symptom is a sequence of information-free messages
1739 * XXX coming from threads (if a __del__ or callback is invoked,
1740 * XXX other threads can execute too, and any exception they encounter
1741 * XXX triggers a comedy of errors as subsystem after subsystem
1742 * XXX fails to find what it *expects* to find in sys to help report
1743 * XXX the exception and consequent unexpected failures). I've also
1744 * XXX seen segfaults then, after adding print statements to the
1745 * XXX Python code getting called.
1746 */
1747#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001748 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001749#endif
1750
1751 /* Disable tracemalloc after all Python objects have been destroyed,
1752 so it is possible to use tracemalloc in objects destructor. */
1753 _PyTraceMalloc_Fini();
1754
1755 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1756 _PyImport_Fini();
1757
Nick Coghland6009512014-11-20 21:39:37 +10001758 /* unload faulthandler module */
1759 _PyFaulthandler_Fini();
1760
Nick Coghland6009512014-11-20 21:39:37 +10001761 /* dump hash stats */
1762 _PyHash_Fini();
1763
Eric Snowdae02762017-09-14 00:35:58 -07001764#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001765 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001766 _PyDebug_PrintTotalRefs();
1767 }
Eric Snowdae02762017-09-14 00:35:58 -07001768#endif
Nick Coghland6009512014-11-20 21:39:37 +10001769
1770#ifdef Py_TRACE_REFS
1771 /* Display all objects still alive -- this can invoke arbitrary
1772 * __repr__ overrides, so requires a mostly-intact interpreter.
1773 * Alas, a lot of stuff may still be alive now that will be cleaned
1774 * up later.
1775 */
Victor Stinnerda273412017-12-15 01:46:02 +01001776 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001777 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001778 }
Nick Coghland6009512014-11-20 21:39:37 +10001779#endif /* Py_TRACE_REFS */
1780
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001781 finalize_interp_clear(tstate);
1782 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001783
1784#ifdef Py_TRACE_REFS
1785 /* Display addresses (& refcnts) of all objects still alive.
1786 * An address can be used to find the repr of the object, printed
1787 * above by _Py_PrintReferences.
1788 */
Victor Stinnerda273412017-12-15 01:46:02 +01001789 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001790 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001791 }
Nick Coghland6009512014-11-20 21:39:37 +10001792#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001793#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001794 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001795 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001796 }
Nick Coghland6009512014-11-20 21:39:37 +10001797#endif
1798
Victor Stinner8e91c242019-04-24 17:24:01 +02001799 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001800
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001801 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001802 return status;
1803}
1804
1805void
1806Py_Finalize(void)
1807{
1808 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001809}
1810
Victor Stinnerb0051362019-11-22 17:52:42 +01001811
Nick Coghland6009512014-11-20 21:39:37 +10001812/* Create and initialize a new interpreter and thread, and return the
1813 new thread. This requires that Py_Initialize() has been called
1814 first.
1815
1816 Unsuccessful initialization yields a NULL pointer. Note that *no*
1817 exception information is available even in this case -- the
1818 exception information is held in the thread, and there is no
1819 thread.
1820
1821 Locking: as above.
1822
1823*/
1824
Victor Stinner331a6a52019-05-27 16:39:22 +02001825static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001826new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001827{
Victor Stinner331a6a52019-05-27 16:39:22 +02001828 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001829
Victor Stinner331a6a52019-05-27 16:39:22 +02001830 status = _PyRuntime_Initialize();
1831 if (_PyStatus_EXCEPTION(status)) {
1832 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001833 }
1834 _PyRuntimeState *runtime = &_PyRuntime;
1835
1836 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001837 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001838 }
Nick Coghland6009512014-11-20 21:39:37 +10001839
Victor Stinner8a1be612016-03-14 22:07:55 +01001840 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1841 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001842 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001843
Victor Stinner43125222019-04-24 18:23:53 +02001844 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001845 if (interp == NULL) {
1846 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001847 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001848 }
Nick Coghland6009512014-11-20 21:39:37 +10001849
Victor Stinner43125222019-04-24 18:23:53 +02001850 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001851 if (tstate == NULL) {
1852 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001853 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001854 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001855 }
1856
Victor Stinner43125222019-04-24 18:23:53 +02001857 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001858
Eric Snow1abcf672017-05-23 21:46:51 -07001859 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001860 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001861#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001862 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001863 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001864 }
1865 else
1866#endif
1867 {
Eric Snow1abcf672017-05-23 21:46:51 -07001868 /* No current thread state, copy from the main interpreter */
1869 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001870 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001871 }
1872
Victor Stinner048a3562020-11-05 00:45:56 +01001873
1874 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001875 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001876 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001877 }
Victor Stinner252346a2020-05-01 11:33:44 +02001878 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001879
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001880 status = init_interp_create_gil(tstate);
1881 if (_PyStatus_EXCEPTION(status)) {
1882 goto error;
1883 }
1884
Victor Stinnerd863ade2019-12-06 03:37:07 +01001885 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001886 if (_PyStatus_EXCEPTION(status)) {
1887 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001888 }
1889
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001890 status = init_interp_main(tstate);
1891 if (_PyStatus_EXCEPTION(status)) {
1892 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001893 }
Nick Coghland6009512014-11-20 21:39:37 +10001894
Victor Stinnera7368ac2017-11-15 18:11:45 -08001895 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001896 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001897
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001898error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001899 *tstate_p = NULL;
1900
1901 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001902 PyErr_PrintEx(0);
1903 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001904 PyThreadState_Delete(tstate);
1905 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001906 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001907
Victor Stinnerb0051362019-11-22 17:52:42 +01001908 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001909}
1910
1911PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001912_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001913{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001914 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001915 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001916 if (_PyStatus_EXCEPTION(status)) {
1917 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001918 }
1919 return tstate;
1920
Nick Coghland6009512014-11-20 21:39:37 +10001921}
1922
Victor Stinner252346a2020-05-01 11:33:44 +02001923PyThreadState *
1924Py_NewInterpreter(void)
1925{
1926 return _Py_NewInterpreter(0);
1927}
1928
Nick Coghland6009512014-11-20 21:39:37 +10001929/* Delete an interpreter and its last thread. This requires that the
1930 given thread state is current, that the thread has no remaining
1931 frames, and that it is its interpreter's only remaining thread.
1932 It is a fatal error to violate these constraints.
1933
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001934 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001935 everything, regardless.)
1936
1937 Locking: as above.
1938
1939*/
1940
1941void
1942Py_EndInterpreter(PyThreadState *tstate)
1943{
1944 PyInterpreterState *interp = tstate->interp;
1945
Victor Stinnerb45d2592019-06-20 00:05:23 +02001946 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001947 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001948 }
1949 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001950 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001951 }
Eric Snow5be45a62019-03-08 22:47:07 -07001952 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001953
Eric Snow842a2f02019-03-15 15:47:51 -06001954 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001955 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001956
Victor Stinnerb8fa1352020-12-15 14:34:19 +01001957 _PyAtExit_Call(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001958
Victor Stinnerb45d2592019-06-20 00:05:23 +02001959 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001960 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001961 }
Nick Coghland6009512014-11-20 21:39:37 +10001962
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001963 finalize_modules(tstate);
1964
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001965 finalize_interp_clear(tstate);
1966 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001967}
1968
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001969/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001970
Victor Stinner331a6a52019-05-27 16:39:22 +02001971static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001972add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001973{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001974 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001975 m = PyImport_AddModule("__main__");
1976 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001977 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001978
Nick Coghland6009512014-11-20 21:39:37 +10001979 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001980 ann_dict = PyDict_New();
1981 if ((ann_dict == NULL) ||
1982 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001983 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001984 }
1985 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001986
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001987 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1988 if (PyErr_Occurred()) {
1989 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1990 }
Nick Coghland6009512014-11-20 21:39:37 +10001991 PyObject *bimod = PyImport_ImportModule("builtins");
1992 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001993 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001994 }
1995 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001996 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001997 }
1998 Py_DECREF(bimod);
1999 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002000
Nick Coghland6009512014-11-20 21:39:37 +10002001 /* Main is a little special - imp.is_builtin("__main__") will return
2002 * False, but BuiltinImporter is still the most appropriate initial
2003 * setting for its __loader__ attribute. A more suitable value will
2004 * be set if __main__ gets further initialized later in the startup
2005 * process.
2006 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002007 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002008 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002009 if (PyErr_Occurred()) {
2010 return _PyStatus_ERR("Failed to test __main__.__loader__");
2011 }
Nick Coghland6009512014-11-20 21:39:37 +10002012 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2013 "BuiltinImporter");
2014 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002015 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002016 }
2017 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002018 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002019 }
2020 Py_DECREF(loader);
2021 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002022 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002023}
2024
Nick Coghland6009512014-11-20 21:39:37 +10002025/* Import the site module (not into __main__ though) */
2026
Victor Stinner331a6a52019-05-27 16:39:22 +02002027static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002028init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002029{
2030 PyObject *m;
2031 m = PyImport_ImportModule("site");
2032 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002033 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002034 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002035 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002036 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002037}
2038
Victor Stinner874dbe82015-09-04 17:29:57 +02002039/* Check if a file descriptor is valid or not.
2040 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2041static int
2042is_valid_fd(int fd)
2043{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002044/* dup() is faster than fstat(): fstat() can require input/output operations,
2045 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2046 startup. Problem: dup() doesn't check if the file descriptor is valid on
2047 some platforms.
2048
2049 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2050 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2051 EBADF. FreeBSD has similar issue (bpo-32849).
2052
2053 Only use dup() on platforms where dup() is enough to detect invalid FD in
2054 corner cases: on Linux and Windows (bpo-32849). */
2055#if defined(__linux__) || defined(MS_WINDOWS)
2056 if (fd < 0) {
2057 return 0;
2058 }
2059 int fd2;
2060
2061 _Py_BEGIN_SUPPRESS_IPH
2062 fd2 = dup(fd);
2063 if (fd2 >= 0) {
2064 close(fd2);
2065 }
2066 _Py_END_SUPPRESS_IPH
2067
2068 return (fd2 >= 0);
2069#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002070 struct stat st;
2071 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002072#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002073}
2074
2075/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002076static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002077create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002078 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002079 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002080{
2081 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2082 const char* mode;
2083 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002084 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002085 int buffering, isatty;
2086 _Py_IDENTIFIER(open);
2087 _Py_IDENTIFIER(isatty);
2088 _Py_IDENTIFIER(TextIOWrapper);
2089 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002090 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002091
Victor Stinner874dbe82015-09-04 17:29:57 +02002092 if (!is_valid_fd(fd))
2093 Py_RETURN_NONE;
2094
Nick Coghland6009512014-11-20 21:39:37 +10002095 /* stdin is always opened in buffered mode, first because it shouldn't
2096 make a difference in common use cases, second because TextIOWrapper
2097 depends on the presence of a read1() method which only exists on
2098 buffered streams.
2099 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002100 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002101 buffering = 0;
2102 else
2103 buffering = -1;
2104 if (write_mode)
2105 mode = "wb";
2106 else
2107 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002108 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002109 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002110 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002111 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002112 if (buf == NULL)
2113 goto error;
2114
2115 if (buffering) {
2116 _Py_IDENTIFIER(raw);
2117 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2118 if (raw == NULL)
2119 goto error;
2120 }
2121 else {
2122 raw = buf;
2123 Py_INCREF(raw);
2124 }
2125
Steve Dower39294992016-08-30 21:22:36 -07002126#ifdef MS_WINDOWS
2127 /* Windows console IO is always UTF-8 encoded */
2128 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002129 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002130#endif
2131
Nick Coghland6009512014-11-20 21:39:37 +10002132 text = PyUnicode_FromString(name);
2133 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2134 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002135 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002136 if (res == NULL)
2137 goto error;
2138 isatty = PyObject_IsTrue(res);
2139 Py_DECREF(res);
2140 if (isatty == -1)
2141 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002142 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002143 write_through = Py_True;
2144 else
2145 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002146 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002147 line_buffering = Py_True;
2148 else
2149 line_buffering = Py_False;
2150
2151 Py_CLEAR(raw);
2152 Py_CLEAR(text);
2153
2154#ifdef MS_WINDOWS
2155 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2156 newlines to "\n".
2157 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2158 newline = NULL;
2159#else
2160 /* sys.stdin: split lines at "\n".
2161 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2162 newline = "\n";
2163#endif
2164
Victor Stinner709d23d2019-05-02 14:56:30 -04002165 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2166 if (encoding_str == NULL) {
2167 Py_CLEAR(buf);
2168 goto error;
2169 }
2170
2171 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2172 if (errors_str == NULL) {
2173 Py_CLEAR(buf);
2174 Py_CLEAR(encoding_str);
2175 goto error;
2176 }
2177
2178 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2179 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002180 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002181 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002182 Py_CLEAR(encoding_str);
2183 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002184 if (stream == NULL)
2185 goto error;
2186
2187 if (write_mode)
2188 mode = "w";
2189 else
2190 mode = "r";
2191 text = PyUnicode_FromString(mode);
2192 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2193 goto error;
2194 Py_CLEAR(text);
2195 return stream;
2196
2197error:
2198 Py_XDECREF(buf);
2199 Py_XDECREF(stream);
2200 Py_XDECREF(text);
2201 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002202
Victor Stinner874dbe82015-09-04 17:29:57 +02002203 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2204 /* Issue #24891: the file descriptor was closed after the first
2205 is_valid_fd() check was called. Ignore the OSError and set the
2206 stream to None. */
2207 PyErr_Clear();
2208 Py_RETURN_NONE;
2209 }
2210 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002211}
2212
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002213/* Set builtins.open to io.OpenWrapper */
2214static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002215init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002216{
2217 PyObject *iomod = NULL, *wrapper;
2218 PyObject *bimod = NULL;
2219 PyStatus res = _PyStatus_OK();
2220
2221 if (!(iomod = PyImport_ImportModule("io"))) {
2222 goto error;
2223 }
2224
2225 if (!(bimod = PyImport_ImportModule("builtins"))) {
2226 goto error;
2227 }
2228
2229 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2230 goto error;
2231 }
2232
2233 /* Set builtins.open */
2234 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2235 Py_DECREF(wrapper);
2236 goto error;
2237 }
2238 Py_DECREF(wrapper);
2239 goto done;
2240
2241error:
2242 res = _PyStatus_ERR("can't initialize io.open");
2243
2244done:
2245 Py_XDECREF(bimod);
2246 Py_XDECREF(iomod);
2247 return res;
2248}
2249
2250
Nick Coghland6009512014-11-20 21:39:37 +10002251/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002252static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002253init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002254{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002255 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002256 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002257 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002258 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002259 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002260 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002261
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002262 /* Check that stdin is not a directory
2263 Using shell redirection, you can redirect stdin to a directory,
2264 crashing the Python interpreter. Catch this common mistake here
2265 and output a useful error message. Note that under MS Windows,
2266 the shell already prevents that. */
2267#ifndef MS_WINDOWS
2268 struct _Py_stat_struct sb;
2269 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2270 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002271 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002272 }
2273#endif
2274
Nick Coghland6009512014-11-20 21:39:37 +10002275 if (!(iomod = PyImport_ImportModule("io"))) {
2276 goto error;
2277 }
Nick Coghland6009512014-11-20 21:39:37 +10002278
Nick Coghland6009512014-11-20 21:39:37 +10002279 /* Set sys.stdin */
2280 fd = fileno(stdin);
2281 /* Under some conditions stdin, stdout and stderr may not be connected
2282 * and fileno() may point to an invalid file descriptor. For example
2283 * GUI apps don't have valid standard streams by default.
2284 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002285 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002286 config->stdio_encoding,
2287 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002288 if (std == NULL)
2289 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002290 PySys_SetObject("__stdin__", std);
2291 _PySys_SetObjectId(&PyId_stdin, std);
2292 Py_DECREF(std);
2293
2294 /* Set sys.stdout */
2295 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002296 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002297 config->stdio_encoding,
2298 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002299 if (std == NULL)
2300 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002301 PySys_SetObject("__stdout__", std);
2302 _PySys_SetObjectId(&PyId_stdout, std);
2303 Py_DECREF(std);
2304
2305#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2306 /* Set sys.stderr, replaces the preliminary stderr */
2307 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002308 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002309 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002310 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002311 if (std == NULL)
2312 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002313
2314 /* Same as hack above, pre-import stderr's codec to avoid recursion
2315 when import.c tries to write to stderr in verbose mode. */
2316 encoding_attr = PyObject_GetAttrString(std, "encoding");
2317 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002318 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002319 if (std_encoding != NULL) {
2320 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2321 Py_XDECREF(codec_info);
2322 }
2323 Py_DECREF(encoding_attr);
2324 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002325 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002326
2327 if (PySys_SetObject("__stderr__", std) < 0) {
2328 Py_DECREF(std);
2329 goto error;
2330 }
2331 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2332 Py_DECREF(std);
2333 goto error;
2334 }
2335 Py_DECREF(std);
2336#endif
2337
Victor Stinnera7368ac2017-11-15 18:11:45 -08002338 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002339
Victor Stinnera7368ac2017-11-15 18:11:45 -08002340error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002341 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002342
2343done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002344 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002345 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002346 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002347}
2348
2349
Victor Stinner10dc4842015-03-24 12:01:30 +01002350static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002351_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2352 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002353{
Victor Stinner314b8782021-01-18 18:34:56 +01002354 PUTS(fd, "\n");
Victor Stinner10dc4842015-03-24 12:01:30 +01002355
2356 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002357 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002358}
Victor Stinner791da1c2016-03-14 16:53:12 +01002359
2360/* Print the current exception (if an exception is set) with its traceback,
2361 or display the current Python stack.
2362
2363 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2364 called on catastrophic cases.
2365
2366 Return 1 if the traceback was displayed, 0 otherwise. */
2367
2368static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002369_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002370{
2371 PyObject *ferr, *res;
2372 PyObject *exception, *v, *tb;
2373 int has_tb;
2374
Victor Stinnerb45d2592019-06-20 00:05:23 +02002375 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002376 if (exception == NULL) {
2377 /* No current exception */
2378 return 0;
2379 }
2380
2381 ferr = _PySys_GetObjectId(&PyId_stderr);
2382 if (ferr == NULL || ferr == Py_None) {
2383 /* sys.stderr is not set yet or set to None,
2384 no need to try to display the exception */
2385 return 0;
2386 }
2387
Victor Stinnerb45d2592019-06-20 00:05:23 +02002388 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002389 if (tb == NULL) {
2390 tb = Py_None;
2391 Py_INCREF(tb);
2392 }
2393 PyException_SetTraceback(v, tb);
2394 if (exception == NULL) {
2395 /* PyErr_NormalizeException() failed */
2396 return 0;
2397 }
2398
2399 has_tb = (tb != Py_None);
2400 PyErr_Display(exception, v, tb);
2401 Py_XDECREF(exception);
2402 Py_XDECREF(v);
2403 Py_XDECREF(tb);
2404
2405 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002406 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002407 if (res == NULL) {
2408 _PyErr_Clear(tstate);
2409 }
2410 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002411 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002412 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002413
2414 return has_tb;
2415}
2416
Nick Coghland6009512014-11-20 21:39:37 +10002417/* Print fatal error message and abort */
2418
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002419#ifdef MS_WINDOWS
2420static void
2421fatal_output_debug(const char *msg)
2422{
2423 /* buffer of 256 bytes allocated on the stack */
2424 WCHAR buffer[256 / sizeof(WCHAR)];
2425 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2426 size_t msglen;
2427
2428 OutputDebugStringW(L"Fatal Python error: ");
2429
2430 msglen = strlen(msg);
2431 while (msglen) {
2432 size_t i;
2433
2434 if (buflen > msglen) {
2435 buflen = msglen;
2436 }
2437
2438 /* Convert the message to wchar_t. This uses a simple one-to-one
2439 conversion, assuming that the this error message actually uses
2440 ASCII only. If this ceases to be true, we will have to convert. */
2441 for (i=0; i < buflen; ++i) {
2442 buffer[i] = msg[i];
2443 }
2444 buffer[i] = L'\0';
2445 OutputDebugStringW(buffer);
2446
2447 msg += buflen;
2448 msglen -= buflen;
2449 }
2450 OutputDebugStringW(L"\n");
2451}
2452#endif
2453
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002454
2455static void
Victor Stinner314b8782021-01-18 18:34:56 +01002456fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002457{
Victor Stinner314b8782021-01-18 18:34:56 +01002458 PUTS(fd, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002459 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2460 if (finalizing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002461 PUTS(fd, "finalizing (tstate=0x");
2462 _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
2463 PUTS(fd, ")");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002464 }
2465 else if (runtime->initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002466 PUTS(fd, "initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002467 }
2468 else if (runtime->core_initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002469 PUTS(fd, "core initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002470 }
2471 else if (runtime->preinitialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002472 PUTS(fd, "preinitialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002473 }
2474 else if (runtime->preinitializing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002475 PUTS(fd, "preinitializing");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002476 }
2477 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002478 PUTS(fd, "unknown");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002479 }
Victor Stinner314b8782021-01-18 18:34:56 +01002480 PUTS(fd, "\n");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002481}
2482
2483
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002484static inline void _Py_NO_RETURN
2485fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002486{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002487 if (status < 0) {
2488#if defined(MS_WINDOWS) && defined(_DEBUG)
2489 DebugBreak();
2490#endif
2491 abort();
2492 }
2493 else {
2494 exit(status);
2495 }
2496}
2497
2498
Victor Stinner66f77ca2021-01-19 23:35:27 +01002499// Dump the list of extension modules of sys.modules, excluding stdlib modules
Victor Stinner9852cb32021-01-25 23:12:50 +01002500// (sys.stdlib_module_names), into fd file descriptor.
Victor Stinner66f77ca2021-01-19 23:35:27 +01002501//
Victor Stinner250035d2021-01-18 20:47:13 +01002502// This function is called by a signal handler in faulthandler: avoid memory
Victor Stinner66f77ca2021-01-19 23:35:27 +01002503// allocations and keep the implementation simple. For example, the list is not
2504// sorted on purpose.
Victor Stinner250035d2021-01-18 20:47:13 +01002505void
2506_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
2507{
2508 if (interp == NULL) {
2509 return;
2510 }
2511 PyObject *modules = interp->modules;
Victor Stinner66f77ca2021-01-19 23:35:27 +01002512 if (modules == NULL || !PyDict_Check(modules)) {
Victor Stinner250035d2021-01-18 20:47:13 +01002513 return;
2514 }
2515
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002516 Py_ssize_t pos;
2517 PyObject *key, *value;
2518
2519 // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
2520 // memory cannot be allocated on the heap in a signal handler.
2521 // Iterate on the dict instead.
Victor Stinner9852cb32021-01-25 23:12:50 +01002522 PyObject *stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002523 pos = 0;
2524 while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
2525 if (PyUnicode_Check(key)
Victor Stinner9852cb32021-01-25 23:12:50 +01002526 && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
2527 stdlib_module_names = value;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002528 break;
2529 }
2530 }
Victor Stinner9852cb32021-01-25 23:12:50 +01002531 // If we failed to get sys.stdlib_module_names or it's not a frozenset,
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002532 // don't exclude stdlib modules.
Victor Stinner9852cb32021-01-25 23:12:50 +01002533 if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
2534 stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002535 }
2536
2537 // List extensions
Victor Stinner66f77ca2021-01-19 23:35:27 +01002538 int header = 1;
2539 Py_ssize_t count = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002540 pos = 0;
Victor Stinner250035d2021-01-18 20:47:13 +01002541 while (PyDict_Next(modules, &pos, &key, &value)) {
2542 if (!PyUnicode_Check(key)) {
2543 continue;
2544 }
2545 if (!_PyModule_IsExtension(value)) {
2546 continue;
2547 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002548 // Use the module name from the sys.modules key,
2549 // don't attempt to get the module object name.
Victor Stinner9852cb32021-01-25 23:12:50 +01002550 if (stdlib_module_names != NULL) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002551 int is_stdlib_ext = 0;
2552
Victor Stinner9852cb32021-01-25 23:12:50 +01002553 Py_ssize_t i = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002554 PyObject *item;
2555 Py_hash_t hash;
Victor Stinner9852cb32021-01-25 23:12:50 +01002556 while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002557 if (PyUnicode_Check(item)
2558 && PyUnicode_Compare(key, item) == 0)
2559 {
2560 is_stdlib_ext = 1;
2561 break;
2562 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002563 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002564 if (is_stdlib_ext) {
2565 // Ignore stdlib extension
2566 continue;
2567 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002568 }
2569
2570 if (header) {
2571 PUTS(fd, "\nExtension modules: ");
2572 header = 0;
2573 }
2574 else {
Victor Stinner250035d2021-01-18 20:47:13 +01002575 PUTS(fd, ", ");
2576 }
Victor Stinner250035d2021-01-18 20:47:13 +01002577
2578 _Py_DumpASCII(fd, key);
Victor Stinner66f77ca2021-01-19 23:35:27 +01002579 count++;
Victor Stinner250035d2021-01-18 20:47:13 +01002580 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002581
2582 if (count) {
2583 PUTS(fd, " (total: ");
2584 _Py_DumpDecimal(fd, count);
2585 PUTS(fd, ")");
2586 PUTS(fd, "\n");
2587 }
Victor Stinner250035d2021-01-18 20:47:13 +01002588}
2589
2590
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002591static void _Py_NO_RETURN
Victor Stinner314b8782021-01-18 18:34:56 +01002592fatal_error(int fd, int header, const char *prefix, const char *msg,
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002593 int status)
2594{
Victor Stinner53345a42015-03-25 01:55:14 +01002595 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002596
2597 if (reentrant) {
2598 /* Py_FatalError() caused a second fatal error.
2599 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002600 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002601 }
2602 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002603
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002604 if (header) {
Victor Stinner314b8782021-01-18 18:34:56 +01002605 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002606 if (prefix) {
Victor Stinner314b8782021-01-18 18:34:56 +01002607 PUTS(fd, prefix);
2608 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002609 }
2610 if (msg) {
Victor Stinner314b8782021-01-18 18:34:56 +01002611 PUTS(fd, msg);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002612 }
2613 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002614 PUTS(fd, "<message not set>");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002615 }
Victor Stinner314b8782021-01-18 18:34:56 +01002616 PUTS(fd, "\n");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002617 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002618
2619 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner314b8782021-01-18 18:34:56 +01002620 fatal_error_dump_runtime(fd, runtime);
Victor Stinner10dc4842015-03-24 12:01:30 +01002621
Victor Stinner3a228ab2018-11-01 00:26:41 +01002622 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002623 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002624
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002625 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2626 has no Python thread state.
2627
2628 tss_tstate != tstate if the current Python thread does not hold the GIL.
2629 */
Victor Stinner314b8782021-01-18 18:34:56 +01002630 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2631 PyInterpreterState *interp = NULL;
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002632 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
Victor Stinner314b8782021-01-18 18:34:56 +01002633 if (tstate != NULL) {
2634 interp = tstate->interp;
2635 }
2636 else if (tss_tstate != NULL) {
2637 interp = tss_tstate->interp;
2638 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002639 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner314b8782021-01-18 18:34:56 +01002640
Victor Stinner3a228ab2018-11-01 00:26:41 +01002641 if (has_tstate_and_gil) {
2642 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002643 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002644 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002645 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002646 }
2647 }
2648 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002649 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002650 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002651
Victor Stinner250035d2021-01-18 20:47:13 +01002652 _Py_DumpExtensionModules(fd, interp);
2653
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002654 /* The main purpose of faulthandler is to display the traceback.
2655 This function already did its best to display a traceback.
2656 Disable faulthandler to prevent writing a second traceback
2657 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002658 _PyFaulthandler_Fini();
2659
Victor Stinner791da1c2016-03-14 16:53:12 +01002660 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002661 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002662 /* Flush sys.stdout and sys.stderr */
2663 flush_std_files();
2664 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002665
Nick Coghland6009512014-11-20 21:39:37 +10002666#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002667 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002668#endif /* MS_WINDOWS */
2669
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002670 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002671}
2672
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002673
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002674#undef Py_FatalError
2675
Victor Stinner19760862017-12-20 01:41:59 +01002676void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002677Py_FatalError(const char *msg)
2678{
Victor Stinner314b8782021-01-18 18:34:56 +01002679 fatal_error(fileno(stderr), 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002680}
2681
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002682
Victor Stinner19760862017-12-20 01:41:59 +01002683void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002684_Py_FatalErrorFunc(const char *func, const char *msg)
2685{
Victor Stinner314b8782021-01-18 18:34:56 +01002686 fatal_error(fileno(stderr), 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002687}
2688
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002689
2690void _Py_NO_RETURN
2691_Py_FatalErrorFormat(const char *func, const char *format, ...)
2692{
2693 static int reentrant = 0;
2694 if (reentrant) {
2695 /* _Py_FatalErrorFormat() caused a second fatal error */
2696 fatal_error_exit(-1);
2697 }
2698 reentrant = 1;
2699
2700 FILE *stream = stderr;
Victor Stinner314b8782021-01-18 18:34:56 +01002701 const int fd = fileno(stream);
2702 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002703 if (func) {
Victor Stinner314b8782021-01-18 18:34:56 +01002704 PUTS(fd, func);
2705 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002706 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002707
2708 va_list vargs;
2709#ifdef HAVE_STDARG_PROTOTYPES
2710 va_start(vargs, format);
2711#else
2712 va_start(vargs);
2713#endif
2714 vfprintf(stream, format, vargs);
2715 va_end(vargs);
2716
2717 fputs("\n", stream);
2718 fflush(stream);
2719
Victor Stinner314b8782021-01-18 18:34:56 +01002720 fatal_error(fd, 0, NULL, NULL, -1);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002721}
2722
2723
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002724void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002725Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002726{
Victor Stinner331a6a52019-05-27 16:39:22 +02002727 if (_PyStatus_IS_EXIT(status)) {
2728 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002729 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002730 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner314b8782021-01-18 18:34:56 +01002731 fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002732 }
2733 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002734 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002735 }
Nick Coghland6009512014-11-20 21:39:37 +10002736}
2737
Victor Stinner357704c2020-12-14 23:07:54 +01002738
Nick Coghland6009512014-11-20 21:39:37 +10002739/* Wait until threading._shutdown completes, provided
2740 the threading module was imported in the first place.
2741 The shutdown routine will wait until all non-daemon
2742 "threading" threads have completed. */
2743static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002744wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002745{
Nick Coghland6009512014-11-20 21:39:37 +10002746 _Py_IDENTIFIER(_shutdown);
2747 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002748 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002749 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002750 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002751 PyErr_WriteUnraisable(NULL);
2752 }
2753 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002754 return;
2755 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002756 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002757 if (result == NULL) {
2758 PyErr_WriteUnraisable(threading);
2759 }
2760 else {
2761 Py_DECREF(result);
2762 }
2763 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002764}
2765
2766#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002767int Py_AtExit(void (*func)(void))
2768{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002769 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002770 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002771 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002772 return 0;
2773}
2774
2775static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002776call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002777{
Victor Stinner8e91c242019-04-24 17:24:01 +02002778 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002779 /* pop last function from the list */
2780 runtime->nexitfuncs--;
2781 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2782 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2783
2784 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002785 }
Nick Coghland6009512014-11-20 21:39:37 +10002786
2787 fflush(stdout);
2788 fflush(stderr);
2789}
2790
Victor Stinnercfc88312018-08-01 16:41:25 +02002791void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002792Py_Exit(int sts)
2793{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002794 if (Py_FinalizeEx() < 0) {
2795 sts = 120;
2796 }
Nick Coghland6009512014-11-20 21:39:37 +10002797
2798 exit(sts);
2799}
2800
Nick Coghland6009512014-11-20 21:39:37 +10002801
Nick Coghland6009512014-11-20 21:39:37 +10002802/*
2803 * The file descriptor fd is considered ``interactive'' if either
2804 * a) isatty(fd) is TRUE, or
2805 * b) the -i flag was given, and the filename associated with
2806 * the descriptor is NULL or "<stdin>" or "???".
2807 */
2808int
2809Py_FdIsInteractive(FILE *fp, const char *filename)
2810{
2811 if (isatty((int)fileno(fp)))
2812 return 1;
2813 if (!Py_InteractiveFlag)
2814 return 0;
2815 return (filename == NULL) ||
2816 (strcmp(filename, "<stdin>") == 0) ||
2817 (strcmp(filename, "???") == 0);
2818}
2819
2820
Victor Stinnera82f63f2020-12-09 22:37:27 +01002821int
2822_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2823{
2824 if (isatty((int)fileno(fp))) {
2825 return 1;
2826 }
2827 if (!Py_InteractiveFlag) {
2828 return 0;
2829 }
2830 return (filename == NULL) ||
2831 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2832 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2833}
2834
2835
Nick Coghland6009512014-11-20 21:39:37 +10002836/* Wrappers around sigaction() or signal(). */
2837
2838PyOS_sighandler_t
2839PyOS_getsig(int sig)
2840{
2841#ifdef HAVE_SIGACTION
2842 struct sigaction context;
2843 if (sigaction(sig, NULL, &context) == -1)
2844 return SIG_ERR;
2845 return context.sa_handler;
2846#else
2847 PyOS_sighandler_t handler;
2848/* Special signal handling for the secure CRT in Visual Studio 2005 */
2849#if defined(_MSC_VER) && _MSC_VER >= 1400
2850 switch (sig) {
2851 /* Only these signals are valid */
2852 case SIGINT:
2853 case SIGILL:
2854 case SIGFPE:
2855 case SIGSEGV:
2856 case SIGTERM:
2857 case SIGBREAK:
2858 case SIGABRT:
2859 break;
2860 /* Don't call signal() with other values or it will assert */
2861 default:
2862 return SIG_ERR;
2863 }
2864#endif /* _MSC_VER && _MSC_VER >= 1400 */
2865 handler = signal(sig, SIG_IGN);
2866 if (handler != SIG_ERR)
2867 signal(sig, handler);
2868 return handler;
2869#endif
2870}
2871
2872/*
2873 * All of the code in this function must only use async-signal-safe functions,
2874 * listed at `man 7 signal` or
2875 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2876 */
2877PyOS_sighandler_t
2878PyOS_setsig(int sig, PyOS_sighandler_t handler)
2879{
2880#ifdef HAVE_SIGACTION
2881 /* Some code in Modules/signalmodule.c depends on sigaction() being
2882 * used here if HAVE_SIGACTION is defined. Fix that if this code
2883 * changes to invalidate that assumption.
2884 */
2885 struct sigaction context, ocontext;
2886 context.sa_handler = handler;
2887 sigemptyset(&context.sa_mask);
2888 context.sa_flags = 0;
2889 if (sigaction(sig, &context, &ocontext) == -1)
2890 return SIG_ERR;
2891 return ocontext.sa_handler;
2892#else
2893 PyOS_sighandler_t oldhandler;
2894 oldhandler = signal(sig, handler);
2895#ifdef HAVE_SIGINTERRUPT
2896 siginterrupt(sig, 1);
2897#endif
2898 return oldhandler;
2899#endif
2900}
2901
2902#ifdef __cplusplus
2903}
2904#endif