blob: 428c887ef41c5006ad176db3d41ee5bf5729902a [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
Nick Coghland6009512014-11-20 21:39:37 +100041_Py_IDENTIFIER(flush);
42_Py_IDENTIFIER(name);
43_Py_IDENTIFIER(stdin);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060046_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100047
48#ifdef __cplusplus
49extern "C" {
50#endif
51
Nick Coghland6009512014-11-20 21:39:37 +100052
Victor Stinnerb45d2592019-06-20 00:05:23 +020053/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020054static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020055static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050056static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020057static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020058static void call_py_exitfuncs(PyThreadState *tstate);
59static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020060static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100061
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080062int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010064static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065
Victor Stinner331a6a52019-05-27 16:39:22 +020066PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067_PyRuntime_Initialize(void)
68{
69 /* XXX We only initialize once in the process, which aligns with
70 the static initialization of the former globals now found in
71 _PyRuntime. However, _PyRuntime *should* be initialized with
72 every Py_Initialize() call, but doing so breaks the runtime.
73 This is because the runtime state is not properly finalized
74 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010075 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020076 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010078 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079
80 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081}
82
83void
84_PyRuntime_Finalize(void)
85{
86 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010087 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
89
90int
91_Py_IsFinalizing(void)
92{
Victor Stinner7b3c2522020-03-07 00:24:23 +010093 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
Nick Coghland6009512014-11-20 21:39:37 +100096/* Hack to force loading of object files */
97int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
98 PyOS_mystrnicmp; /* Python/pystrcmp.o */
99
100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
104{
105 return PyImport_ImportModule("warnings");
106}
107
Eric Snowc7ec9982017-05-23 23:00:52 -0700108
Eric Snow1abcf672017-05-23 21:46:51 -0700109/* APIs to access the initialization flags
110 *
111 * Can be called prior to Py_Initialize.
112 */
Nick Coghland6009512014-11-20 21:39:37 +1000113
Eric Snow1abcf672017-05-23 21:46:51 -0700114int
115_Py_IsCoreInitialized(void)
116{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700118}
Nick Coghland6009512014-11-20 21:39:37 +1000119
120int
121Py_IsInitialized(void)
122{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600123 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000124}
125
Nick Coghlan6ea41862017-06-11 13:16:15 +1000126
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000127/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
128 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000129 initializations fail, a fatal error is issued and the function does
130 not return. On return, the first thread and interpreter state have
131 been created.
132
133 Locking: you must hold the interpreter lock while calling this.
134 (If the lock has not yet been initialized, that's equivalent to
135 having the lock, but you cannot use multiple threads.)
136
137*/
Victor Stinneref75a622020-11-12 15:14:13 +0100138static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200139init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000140{
Victor Stinneref75a622020-11-12 15:14:13 +0100141 assert(!_PyErr_Occurred(tstate));
142
Victor Stinnerb45d2592019-06-20 00:05:23 +0200143 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200144 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000145
Victor Stinneref75a622020-11-12 15:14:13 +0100146 // Import _importlib through its frozen version, _frozen_importlib.
147 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000148 PySys_FormatStderr("import _frozen_importlib # frozen\n");
149 }
Victor Stinneref75a622020-11-12 15:14:13 +0100150 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
151 return -1;
152 }
153 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000154 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100155 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000156 }
Victor Stinneref75a622020-11-12 15:14:13 +0100157 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000158
Victor Stinneref75a622020-11-12 15:14:13 +0100159 // Import the _imp module
160 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200161 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000162 }
Victor Stinner62230712020-11-18 23:18:29 +0100163 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100164 if (imp_mod == NULL) {
165 return -1;
166 }
167 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
168 Py_DECREF(imp_mod);
169 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000170 }
171
Victor Stinneref75a622020-11-12 15:14:13 +0100172 // Install importlib as the implementation of import
173 PyObject *value = PyObject_CallMethod(importlib, "_install",
174 "OO", sysmod, imp_mod);
175 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000176 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100177 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000178 }
179 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000180
Victor Stinneref75a622020-11-12 15:14:13 +0100181 assert(!_PyErr_Occurred(tstate));
182 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000183}
184
Victor Stinneref75a622020-11-12 15:14:13 +0100185
Victor Stinner331a6a52019-05-27 16:39:22 +0200186static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200187init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700188{
189 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200190 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700191 "_install_external_importers", "");
192 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200193 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200194 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700195 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200196 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200197 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700198}
Nick Coghland6009512014-11-20 21:39:37 +1000199
Nick Coghlan6ea41862017-06-11 13:16:15 +1000200/* Helper functions to better handle the legacy C locale
201 *
202 * The legacy C locale assumes ASCII as the default text encoding, which
203 * causes problems not only for the CPython runtime, but also other
204 * components like GNU readline.
205 *
206 * Accordingly, when the CLI detects it, it attempts to coerce it to a
207 * more capable UTF-8 based alternative as follows:
208 *
209 * if (_Py_LegacyLocaleDetected()) {
210 * _Py_CoerceLegacyLocale();
211 * }
212 *
213 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
214 *
215 * Locale coercion also impacts the default error handler for the standard
216 * streams: while the usual default is "strict", the default for the legacy
217 * C locale and for any of the coercion target locales is "surrogateescape".
218 */
219
220int
Victor Stinner0f721472019-05-20 17:16:38 +0200221_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000222{
223#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200224 if (!warn) {
225 const char *locale_override = getenv("LC_ALL");
226 if (locale_override != NULL && *locale_override != '\0') {
227 /* Don't coerce C locale if the LC_ALL environment variable
228 is set */
229 return 0;
230 }
231 }
232
Nick Coghlan6ea41862017-06-11 13:16:15 +1000233 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000234 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
235 * the POSIX locale as a simple alias for the C locale, so
236 * we may also want to check for that explicitly.
237 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000238 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
239 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
240#else
241 /* Windows uses code pages instead of locales, so no locale is legacy */
242 return 0;
243#endif
244}
245
Victor Stinnerb0051362019-11-22 17:52:42 +0100246#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000247static const char *_C_LOCALE_WARNING =
248 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
249 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
250 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
251 "locales is recommended.\n";
252
Nick Coghlaneb817952017-06-18 12:29:42 +1000253static void
Victor Stinner43125222019-04-24 18:23:53 +0200254emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000255{
Victor Stinner331a6a52019-05-27 16:39:22 +0200256 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200257 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200258 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000259 }
260}
Victor Stinnerb0051362019-11-22 17:52:42 +0100261#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000262
Nick Coghlan6ea41862017-06-11 13:16:15 +1000263typedef struct _CandidateLocale {
264 const char *locale_name; /* The locale to try as a coercion target */
265} _LocaleCoercionTarget;
266
267static _LocaleCoercionTarget _TARGET_LOCALES[] = {
268 {"C.UTF-8"},
269 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000270 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000271 {NULL}
272};
273
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200274
275int
276_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000277{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200278 const _LocaleCoercionTarget *target = NULL;
279 for (target = _TARGET_LOCALES; target->locale_name; target++) {
280 if (strcmp(ctype_loc, target->locale_name) == 0) {
281 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200283 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200284 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000285}
286
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200287
Nick Coghlan6ea41862017-06-11 13:16:15 +1000288#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100289static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000290 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
291 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
292
Victor Stinner0f721472019-05-20 17:16:38 +0200293static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200294_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295{
296 const char *newloc = target->locale_name;
297
298 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100299 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300
301 /* Set the relevant locale environment variable */
302 if (setenv("LC_CTYPE", newloc, 1)) {
303 fprintf(stderr,
304 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200305 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000306 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200307 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100308 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000309 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310
311 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100312 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200313 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000314}
315#endif
316
Victor Stinner0f721472019-05-20 17:16:38 +0200317int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200318_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319{
Victor Stinner0f721472019-05-20 17:16:38 +0200320 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000321#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200322 char *oldloc = NULL;
323
324 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
325 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200326 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200327 }
328
Victor Stinner94540602017-12-16 04:54:22 +0100329 const char *locale_override = getenv("LC_ALL");
330 if (locale_override == NULL || *locale_override == '\0') {
331 /* LC_ALL is also not set (or is set to an empty string) */
332 const _LocaleCoercionTarget *target = NULL;
333 for (target = _TARGET_LOCALES; target->locale_name; target++) {
334 const char *new_locale = setlocale(LC_CTYPE,
335 target->locale_name);
336 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400337#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100338 /* Also ensure that nl_langinfo works in this locale */
339 char *codeset = nl_langinfo(CODESET);
340 if (!codeset || *codeset == '\0') {
341 /* CODESET is not set or empty, so skip coercion */
342 new_locale = NULL;
343 _Py_SetLocaleFromEnv(LC_CTYPE);
344 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000345 }
Victor Stinner94540602017-12-16 04:54:22 +0100346#endif
347 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200348 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200349 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350 }
351 }
352 }
353 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200354
355 setlocale(LC_CTYPE, oldloc);
356
357done:
358 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000359#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200360 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000361}
362
xdegaye1588be62017-11-12 12:45:59 +0100363/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
364 * isolate the idiosyncrasies of different libc implementations. It reads the
365 * appropriate environment variable and uses its value to select the locale for
366 * 'category'. */
367char *
368_Py_SetLocaleFromEnv(int category)
369{
Victor Stinner353933e2018-11-23 13:08:26 +0100370 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100371#ifdef __ANDROID__
372 const char *locale;
373 const char **pvar;
374#ifdef PY_COERCE_C_LOCALE
375 const char *coerce_c_locale;
376#endif
377 const char *utf8_locale = "C.UTF-8";
378 const char *env_var_set[] = {
379 "LC_ALL",
380 "LC_CTYPE",
381 "LANG",
382 NULL,
383 };
384
385 /* Android setlocale(category, "") doesn't check the environment variables
386 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
387 * check the environment variables listed in env_var_set. */
388 for (pvar=env_var_set; *pvar; pvar++) {
389 locale = getenv(*pvar);
390 if (locale != NULL && *locale != '\0') {
391 if (strcmp(locale, utf8_locale) == 0 ||
392 strcmp(locale, "en_US.UTF-8") == 0) {
393 return setlocale(category, utf8_locale);
394 }
395 return setlocale(category, "C");
396 }
397 }
398
399 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
400 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
401 * Quote from POSIX section "8.2 Internationalization Variables":
402 * "4. If the LANG environment variable is not set or is set to the empty
403 * string, the implementation-defined default locale shall be used." */
404
405#ifdef PY_COERCE_C_LOCALE
406 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
407 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
408 /* Some other ported code may check the environment variables (e.g. in
409 * extension modules), so we make sure that they match the locale
410 * configuration */
411 if (setenv("LC_CTYPE", utf8_locale, 1)) {
412 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
413 "environment variable to %s\n", utf8_locale);
414 }
415 }
416#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100417 res = setlocale(category, utf8_locale);
418#else /* !defined(__ANDROID__) */
419 res = setlocale(category, "");
420#endif
421 _Py_ResetForceASCII();
422 return res;
xdegaye1588be62017-11-12 12:45:59 +0100423}
424
Nick Coghlan6ea41862017-06-11 13:16:15 +1000425
Victor Stinner048a3562020-11-05 00:45:56 +0100426static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100427interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100428{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100429 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100430
Victor Stinner9e1b8282020-11-10 13:21:52 +0100431 if (!only_update_path_config) {
432 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
433 if (_PyStatus_EXCEPTION(status)) {
434 _PyErr_SetFromPyStatus(status);
435 return -1;
436 }
Victor Stinner048a3562020-11-05 00:45:56 +0100437 }
438
Victor Stinner9e1b8282020-11-10 13:21:52 +0100439 if (_Py_IsMainInterpreter(tstate)) {
440 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100441 if (_PyStatus_EXCEPTION(status)) {
442 _PyErr_SetFromPyStatus(status);
443 return -1;
444 }
445 }
446
447 // Update the sys module for the new configuration
448 if (_PySys_UpdateConfig(tstate) < 0) {
449 return -1;
450 }
451 return 0;
452}
453
454
455int
456_PyInterpreterState_SetConfig(const PyConfig *src_config)
457{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100458 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100459 int res = -1;
460
461 PyConfig config;
462 PyConfig_InitPythonConfig(&config);
463 PyStatus status = _PyConfig_Copy(&config, src_config);
464 if (_PyStatus_EXCEPTION(status)) {
465 _PyErr_SetFromPyStatus(status);
466 goto done;
467 }
468
469 status = PyConfig_Read(&config);
470 if (_PyStatus_EXCEPTION(status)) {
471 _PyErr_SetFromPyStatus(status);
472 goto done;
473 }
474
Victor Stinner9e1b8282020-11-10 13:21:52 +0100475 status = _PyConfig_Copy(&tstate->interp->config, &config);
476 if (_PyStatus_EXCEPTION(status)) {
477 _PyErr_SetFromPyStatus(status);
478 goto done;
479 }
480
481 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100482
483done:
484 PyConfig_Clear(&config);
485 return res;
486}
487
488
Eric Snow1abcf672017-05-23 21:46:51 -0700489/* Global initializations. Can be undone by Py_Finalize(). Don't
490 call this twice without an intervening Py_Finalize() call.
491
Victor Stinner331a6a52019-05-27 16:39:22 +0200492 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700493 must have a corresponding call to Py_Finalize.
494
495 Locking: you must hold the interpreter lock while calling these APIs.
496 (If the lock has not yet been initialized, that's equivalent to
497 having the lock, but you cannot use multiple threads.)
498
499*/
500
Victor Stinner331a6a52019-05-27 16:39:22 +0200501static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200502pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200503 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200504 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200505{
Victor Stinner331a6a52019-05-27 16:39:22 +0200506 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100507 PyThreadState *tstate = _PyThreadState_GET();
508 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200509 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100510 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200511 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100512
513 PyInterpreterState *interp = tstate->interp;
514 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200515 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100516 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517
Victor Stinnere81f6e62020-06-08 18:12:59 +0200518 status = _PyConfig_Write(config, runtime);
519 if (_PyStatus_EXCEPTION(status)) {
520 return status;
521 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200522
Victor Stinner048a3562020-11-05 00:45:56 +0100523 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200524 if (_PyStatus_EXCEPTION(status)) {
525 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200526 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200527 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200528
Victor Stinner331a6a52019-05-27 16:39:22 +0200529 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200530 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200531 if (_PyStatus_EXCEPTION(status)) {
532 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200533 }
534 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200536}
537
538
Victor Stinner331a6a52019-05-27 16:39:22 +0200539static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200540pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200541 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000542{
Victor Stinner43125222019-04-24 18:23:53 +0200543 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200544 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200545 }
Victor Stinnerda273412017-12-15 01:46:02 +0100546
Victor Stinnere81f6e62020-06-08 18:12:59 +0200547 PyStatus status = _PyConfig_Write(config, runtime);
548 if (_PyStatus_EXCEPTION(status)) {
549 return status;
550 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600551
Eric Snow1abcf672017-05-23 21:46:51 -0700552 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
553 * threads behave a little more gracefully at interpreter shutdown.
554 * We clobber it here so the new interpreter can start with a clean
555 * slate.
556 *
557 * However, this may still lead to misbehaviour if there are daemon
558 * threads still hanging around from a previous Py_Initialize/Finalize
559 * pair :(
560 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100561 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600562
Victor Stinnere81f6e62020-06-08 18:12:59 +0200563 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200564 if (_PyStatus_EXCEPTION(status)) {
565 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800566 }
567
Victor Stinner331a6a52019-05-27 16:39:22 +0200568 status = _PyInterpreterState_Enable(runtime);
569 if (_PyStatus_EXCEPTION(status)) {
570 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800571 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200572 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800574
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100575
Victor Stinner331a6a52019-05-27 16:39:22 +0200576static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200577init_interp_create_gil(PyThreadState *tstate)
578{
579 PyStatus status;
580
581 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
582 only called here. */
583 _PyEval_FiniGIL(tstate);
584
585 /* Auto-thread-state API */
586 status = _PyGILState_Init(tstate);
587 if (_PyStatus_EXCEPTION(status)) {
588 return status;
589 }
590
591 /* Create the GIL and take it */
592 status = _PyEval_InitGIL(tstate);
593 if (_PyStatus_EXCEPTION(status)) {
594 return status;
595 }
596
597 return _PyStatus_OK();
598}
599
600
601static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200602pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200603 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200604 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100605{
606 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100607 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200608 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100609 }
610
Victor Stinner048a3562020-11-05 00:45:56 +0100611 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200612 if (_PyStatus_EXCEPTION(status)) {
613 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100614 }
Nick Coghland6009512014-11-20 21:39:37 +1000615
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200616 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200617 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200618 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200619 }
Nick Coghland6009512014-11-20 21:39:37 +1000620 (void) PyThreadState_Swap(tstate);
621
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200622 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100623 if (_PyStatus_EXCEPTION(status)) {
624 return status;
625 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100626
Victor Stinnerb45d2592019-06-20 00:05:23 +0200627 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200628 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100629}
Nick Coghland6009512014-11-20 21:39:37 +1000630
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100631
Victor Stinner331a6a52019-05-27 16:39:22 +0200632static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100633pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100634{
Victor Stinner444b39b2019-11-20 01:18:11 +0100635 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100636 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100637
Victor Stinner01b1cc12019-11-20 02:27:56 +0100638 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100639 if (_PyStatus_EXCEPTION(status)) {
640 return status;
641 }
642
Victor Stinner0430dfa2020-06-24 15:21:54 +0200643 // Create the empty tuple singleton. It must be created before the first
644 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
645 // for example.
646 status = _PyTuple_Init(tstate);
647 if (_PyStatus_EXCEPTION(status)) {
648 return status;
649 }
650
Victor Stinnere7e699e2019-11-20 12:08:13 +0100651 if (is_main_interp) {
652 status = _PyTypes_Init();
653 if (_PyStatus_EXCEPTION(status)) {
654 return status;
655 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100656 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100657
Victor Stinner630c8df2019-12-17 13:02:18 +0100658 if (!_PyLong_Init(tstate)) {
659 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100660 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100661
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200662 status = _PyUnicode_Init(tstate);
663 if (_PyStatus_EXCEPTION(status)) {
664 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100665 }
666
Victor Stinner91698d82020-06-25 14:07:40 +0200667 status = _PyBytes_Init(tstate);
668 if (_PyStatus_EXCEPTION(status)) {
669 return status;
670 }
671
Victor Stinner281cce12020-06-23 22:55:46 +0200672 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200673 if (_PyStatus_EXCEPTION(status)) {
674 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100675 }
676
Victor Stinnere7e699e2019-11-20 12:08:13 +0100677 if (is_main_interp) {
678 if (!_PyFloat_Init()) {
679 return _PyStatus_ERR("can't init float");
680 }
Nick Coghland6009512014-11-20 21:39:37 +1000681
Victor Stinnere7e699e2019-11-20 12:08:13 +0100682 if (_PyStructSequence_Init() < 0) {
683 return _PyStatus_ERR("can't initialize structseq");
684 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100685 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200686
Victor Stinner331a6a52019-05-27 16:39:22 +0200687 status = _PyErr_Init();
688 if (_PyStatus_EXCEPTION(status)) {
689 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200690 }
691
Victor Stinnere7e699e2019-11-20 12:08:13 +0100692 if (is_main_interp) {
693 if (!_PyContext_Init()) {
694 return _PyStatus_ERR("can't init context");
695 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100696 }
697
Victor Stinneref75a622020-11-12 15:14:13 +0100698 if (_PyWarnings_InitState(tstate) < 0) {
699 return _PyStatus_ERR("can't initialize warnings");
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 Stinner666ecfb2020-07-02 01:19:57 +02001579 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001580
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001581 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001582 _PyList_Fini(tstate);
1583 _PyTuple_Fini(tstate);
1584
1585 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001586
Victor Stinnerc41eed12020-06-23 15:54:35 +02001587 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001588 _PyUnicode_Fini(tstate);
1589 _PyFloat_Fini(tstate);
1590 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001591}
1592
1593
1594static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001595finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001596{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001597 int is_main_interp = _Py_IsMainInterpreter(tstate);
1598
Victor Stinner7eee5be2019-11-20 10:38:34 +01001599 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001600 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001601
Kongedaa0fe02020-07-04 05:06:46 +08001602 /* Clear all loghooks */
1603 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1604 Call _PySys_ClearAuditHooks when PyObject available. */
1605 if (is_main_interp) {
1606 _PySys_ClearAuditHooks(tstate);
1607 }
1608
Victor Stinner7907f8c2020-06-08 01:22:36 +02001609 if (is_main_interp) {
1610 _Py_HashRandomization_Fini();
1611 _PyArg_Fini();
1612 _Py_ClearFileSystemEncoding();
1613 }
1614
Victor Stinner90db4652020-07-01 23:21:36 +02001615 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001616}
1617
1618
1619static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001620finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001621{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001622 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001623 /* Cleanup auto-thread-state */
1624 _PyGILState_Fini(tstate);
1625 }
1626
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001627 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1628 fail when it is being awaited by another running daemon thread (see
1629 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1630 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1631 called multiple times. */
1632
Victor Stinner7eee5be2019-11-20 10:38:34 +01001633 PyInterpreterState_Delete(tstate->interp);
1634}
1635
1636
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001637int
1638Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001639{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001640 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001641
Victor Stinner8e91c242019-04-24 17:24:01 +02001642 _PyRuntimeState *runtime = &_PyRuntime;
1643 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001644 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001645 }
Nick Coghland6009512014-11-20 21:39:37 +10001646
Victor Stinnere225beb2019-06-03 18:14:24 +02001647 /* Get current thread state and interpreter pointer */
1648 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001649
Victor Stinnerb45d2592019-06-20 00:05:23 +02001650 // Wrap up existing "threading"-module-created, non-daemon threads.
1651 wait_for_thread_shutdown(tstate);
1652
1653 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001654 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001655
Nick Coghland6009512014-11-20 21:39:37 +10001656 /* The interpreter is still entirely intact at this point, and the
1657 * exit funcs may be relying on that. In particular, if some thread
1658 * or exit func is still waiting to do an import, the import machinery
1659 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001660 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001661 * Note that Threading.py uses an exit func to do a join on all the
1662 * threads created thru it, so this also protects pending imports in
1663 * the threads created via Threading.
1664 */
Nick Coghland6009512014-11-20 21:39:37 +10001665
Victor Stinnerb45d2592019-06-20 00:05:23 +02001666 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001667
Victor Stinnerda273412017-12-15 01:46:02 +01001668 /* Copy the core config, PyInterpreterState_Delete() free
1669 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001670#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001671 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001672#endif
1673#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001674 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001675#endif
1676#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001677 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001678#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001679
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001680 /* Remaining daemon threads will automatically exit
1681 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001682 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001683 runtime->initialized = 0;
1684 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001685
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001686 /* Destroy the state of all threads of the interpreter, except of the
1687 current thread. In practice, only daemon threads should still be alive,
1688 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1689 Clear frames of other threads to call objects destructors. Destructors
1690 will be called in the current Python thread. Since
1691 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1692 can take the GIL at this point: if they try, they will exit
1693 immediately. */
1694 _PyThreadState_DeleteExcept(runtime, tstate);
1695
Victor Stinnere0deff32015-03-24 13:46:18 +01001696 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001697 if (flush_std_files() < 0) {
1698 status = -1;
1699 }
Nick Coghland6009512014-11-20 21:39:37 +10001700
1701 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001702 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001703
1704 /* Collect garbage. This may call finalizers; it's nice to call these
1705 * before all modules are destroyed.
1706 * XXX If a __del__ or weakref callback is triggered here, and tries to
1707 * XXX import a module, bad things can happen, because Python no
1708 * XXX longer believes it's initialized.
1709 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1710 * XXX is easy to provoke that way. I've also seen, e.g.,
1711 * XXX Exception exceptions.ImportError: 'No module named sha'
1712 * XXX in <function callback at 0x008F5718> ignored
1713 * XXX but I'm unclear on exactly how that one happens. In any case,
1714 * XXX I haven't seen a real-life report of either of these.
1715 */
Victor Stinner8b341482020-10-30 17:00:00 +01001716 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001717
Nick Coghland6009512014-11-20 21:39:37 +10001718 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001719 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001720
Inada Naoki91234a12019-06-03 21:30:58 +09001721 /* Print debug stats if any */
1722 _PyEval_Fini();
1723
Victor Stinnere0deff32015-03-24 13:46:18 +01001724 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001725 if (flush_std_files() < 0) {
1726 status = -1;
1727 }
Nick Coghland6009512014-11-20 21:39:37 +10001728
1729 /* Collect final garbage. This disposes of cycles created by
1730 * class definitions, for example.
1731 * XXX This is disabled because it caused too many problems. If
1732 * XXX a __del__ or weakref callback triggers here, Python code has
1733 * XXX a hard time running, because even the sys module has been
1734 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1735 * XXX One symptom is a sequence of information-free messages
1736 * XXX coming from threads (if a __del__ or callback is invoked,
1737 * XXX other threads can execute too, and any exception they encounter
1738 * XXX triggers a comedy of errors as subsystem after subsystem
1739 * XXX fails to find what it *expects* to find in sys to help report
1740 * XXX the exception and consequent unexpected failures). I've also
1741 * XXX seen segfaults then, after adding print statements to the
1742 * XXX Python code getting called.
1743 */
1744#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001745 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001746#endif
1747
1748 /* Disable tracemalloc after all Python objects have been destroyed,
1749 so it is possible to use tracemalloc in objects destructor. */
1750 _PyTraceMalloc_Fini();
1751
1752 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1753 _PyImport_Fini();
1754
1755 /* Cleanup typeobject.c's internal caches. */
1756 _PyType_Fini();
1757
1758 /* 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 Stinnerb45d2592019-06-20 00:05:23 +02001957 call_py_exitfuncs(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 Stinner10dc4842015-03-24 12:01:30 +01002354 fputc('\n', stderr);
2355 fflush(stderr);
2356
2357 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002358 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002359}
Victor Stinner791da1c2016-03-14 16:53:12 +01002360
2361/* Print the current exception (if an exception is set) with its traceback,
2362 or display the current Python stack.
2363
2364 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2365 called on catastrophic cases.
2366
2367 Return 1 if the traceback was displayed, 0 otherwise. */
2368
2369static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002370_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002371{
2372 PyObject *ferr, *res;
2373 PyObject *exception, *v, *tb;
2374 int has_tb;
2375
Victor Stinnerb45d2592019-06-20 00:05:23 +02002376 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002377 if (exception == NULL) {
2378 /* No current exception */
2379 return 0;
2380 }
2381
2382 ferr = _PySys_GetObjectId(&PyId_stderr);
2383 if (ferr == NULL || ferr == Py_None) {
2384 /* sys.stderr is not set yet or set to None,
2385 no need to try to display the exception */
2386 return 0;
2387 }
2388
Victor Stinnerb45d2592019-06-20 00:05:23 +02002389 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002390 if (tb == NULL) {
2391 tb = Py_None;
2392 Py_INCREF(tb);
2393 }
2394 PyException_SetTraceback(v, tb);
2395 if (exception == NULL) {
2396 /* PyErr_NormalizeException() failed */
2397 return 0;
2398 }
2399
2400 has_tb = (tb != Py_None);
2401 PyErr_Display(exception, v, tb);
2402 Py_XDECREF(exception);
2403 Py_XDECREF(v);
2404 Py_XDECREF(tb);
2405
2406 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002407 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002408 if (res == NULL) {
2409 _PyErr_Clear(tstate);
2410 }
2411 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002412 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002413 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002414
2415 return has_tb;
2416}
2417
Nick Coghland6009512014-11-20 21:39:37 +10002418/* Print fatal error message and abort */
2419
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002420#ifdef MS_WINDOWS
2421static void
2422fatal_output_debug(const char *msg)
2423{
2424 /* buffer of 256 bytes allocated on the stack */
2425 WCHAR buffer[256 / sizeof(WCHAR)];
2426 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2427 size_t msglen;
2428
2429 OutputDebugStringW(L"Fatal Python error: ");
2430
2431 msglen = strlen(msg);
2432 while (msglen) {
2433 size_t i;
2434
2435 if (buflen > msglen) {
2436 buflen = msglen;
2437 }
2438
2439 /* Convert the message to wchar_t. This uses a simple one-to-one
2440 conversion, assuming that the this error message actually uses
2441 ASCII only. If this ceases to be true, we will have to convert. */
2442 for (i=0; i < buflen; ++i) {
2443 buffer[i] = msg[i];
2444 }
2445 buffer[i] = L'\0';
2446 OutputDebugStringW(buffer);
2447
2448 msg += buflen;
2449 msglen -= buflen;
2450 }
2451 OutputDebugStringW(L"\n");
2452}
2453#endif
2454
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002455
2456static void
2457fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2458{
2459 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002460 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2461 if (finalizing) {
2462 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002463 }
2464 else if (runtime->initialized) {
2465 fprintf(stream, "initialized");
2466 }
2467 else if (runtime->core_initialized) {
2468 fprintf(stream, "core initialized");
2469 }
2470 else if (runtime->preinitialized) {
2471 fprintf(stream, "preinitialized");
2472 }
2473 else if (runtime->preinitializing) {
2474 fprintf(stream, "preinitializing");
2475 }
2476 else {
2477 fprintf(stream, "unknown");
2478 }
2479 fprintf(stream, "\n");
2480 fflush(stream);
2481}
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
2499static void _Py_NO_RETURN
2500fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2501 int status)
2502{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002503 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002504 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002505
2506 if (reentrant) {
2507 /* Py_FatalError() caused a second fatal error.
2508 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002509 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002510 }
2511 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002512
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002513 if (header) {
2514 fprintf(stream, "Fatal Python error: ");
2515 if (prefix) {
2516 fputs(prefix, stream);
2517 fputs(": ", stream);
2518 }
2519 if (msg) {
2520 fputs(msg, stream);
2521 }
2522 else {
2523 fprintf(stream, "<message not set>");
2524 }
2525 fputs("\n", stream);
2526 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002527 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002528
2529 _PyRuntimeState *runtime = &_PyRuntime;
2530 fatal_error_dump_runtime(stream, runtime);
2531
2532 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2533 PyInterpreterState *interp = NULL;
2534 if (tstate != NULL) {
2535 interp = tstate->interp;
2536 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002537
Victor Stinner3a228ab2018-11-01 00:26:41 +01002538 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002539 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002540
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002541 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2542 has no Python thread state.
2543
2544 tss_tstate != tstate if the current Python thread does not hold the GIL.
2545 */
2546 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2547 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002548 if (has_tstate_and_gil) {
2549 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002550 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002551 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002552 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002553 }
2554 }
2555 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002556 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002557 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002558
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002559 /* The main purpose of faulthandler is to display the traceback.
2560 This function already did its best to display a traceback.
2561 Disable faulthandler to prevent writing a second traceback
2562 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002563 _PyFaulthandler_Fini();
2564
Victor Stinner791da1c2016-03-14 16:53:12 +01002565 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002566 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002567 /* Flush sys.stdout and sys.stderr */
2568 flush_std_files();
2569 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002570
Nick Coghland6009512014-11-20 21:39:37 +10002571#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002572 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002573#endif /* MS_WINDOWS */
2574
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002575 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002576}
2577
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002578
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002579#undef Py_FatalError
2580
Victor Stinner19760862017-12-20 01:41:59 +01002581void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002582Py_FatalError(const char *msg)
2583{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002584 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002585}
2586
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002587
Victor Stinner19760862017-12-20 01:41:59 +01002588void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002589_Py_FatalErrorFunc(const char *func, const char *msg)
2590{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002591 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002592}
2593
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002594
2595void _Py_NO_RETURN
2596_Py_FatalErrorFormat(const char *func, const char *format, ...)
2597{
2598 static int reentrant = 0;
2599 if (reentrant) {
2600 /* _Py_FatalErrorFormat() caused a second fatal error */
2601 fatal_error_exit(-1);
2602 }
2603 reentrant = 1;
2604
2605 FILE *stream = stderr;
2606 fprintf(stream, "Fatal Python error: ");
2607 if (func) {
2608 fputs(func, stream);
2609 fputs(": ", stream);
2610 }
2611 fflush(stream);
2612
2613 va_list vargs;
2614#ifdef HAVE_STDARG_PROTOTYPES
2615 va_start(vargs, format);
2616#else
2617 va_start(vargs);
2618#endif
2619 vfprintf(stream, format, vargs);
2620 va_end(vargs);
2621
2622 fputs("\n", stream);
2623 fflush(stream);
2624
2625 fatal_error(stream, 0, NULL, NULL, -1);
2626}
2627
2628
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002629void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002630Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002631{
Victor Stinner331a6a52019-05-27 16:39:22 +02002632 if (_PyStatus_IS_EXIT(status)) {
2633 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002634 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002635 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002636 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002637 }
2638 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002639 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002640 }
Nick Coghland6009512014-11-20 21:39:37 +10002641}
2642
2643/* Clean up and exit */
2644
Nick Coghland6009512014-11-20 21:39:37 +10002645/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002646void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002647{
Victor Stinner81a7be32020-04-14 15:14:01 +02002648 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002649
Antoine Pitroufc5db952017-12-13 02:29:07 +01002650 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002651 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2652
2653 is->pyexitfunc = func;
2654 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002655}
2656
2657static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002658call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002659{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002660 PyInterpreterState *interp = tstate->interp;
2661 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002662 return;
2663
Victor Stinnerb45d2592019-06-20 00:05:23 +02002664 (*interp->pyexitfunc)(interp->pyexitmodule);
2665 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002666}
2667
2668/* Wait until threading._shutdown completes, provided
2669 the threading module was imported in the first place.
2670 The shutdown routine will wait until all non-daemon
2671 "threading" threads have completed. */
2672static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002673wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002674{
Nick Coghland6009512014-11-20 21:39:37 +10002675 _Py_IDENTIFIER(_shutdown);
2676 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002677 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002678 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002679 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002680 PyErr_WriteUnraisable(NULL);
2681 }
2682 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002683 return;
2684 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002685 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002686 if (result == NULL) {
2687 PyErr_WriteUnraisable(threading);
2688 }
2689 else {
2690 Py_DECREF(result);
2691 }
2692 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002693}
2694
2695#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002696int Py_AtExit(void (*func)(void))
2697{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002698 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002699 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002700 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002701 return 0;
2702}
2703
2704static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002705call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002706{
Victor Stinner8e91c242019-04-24 17:24:01 +02002707 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002708 /* pop last function from the list */
2709 runtime->nexitfuncs--;
2710 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2711 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2712
2713 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002714 }
Nick Coghland6009512014-11-20 21:39:37 +10002715
2716 fflush(stdout);
2717 fflush(stderr);
2718}
2719
Victor Stinnercfc88312018-08-01 16:41:25 +02002720void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002721Py_Exit(int sts)
2722{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002723 if (Py_FinalizeEx() < 0) {
2724 sts = 120;
2725 }
Nick Coghland6009512014-11-20 21:39:37 +10002726
2727 exit(sts);
2728}
2729
Nick Coghland6009512014-11-20 21:39:37 +10002730
Nick Coghland6009512014-11-20 21:39:37 +10002731/*
2732 * The file descriptor fd is considered ``interactive'' if either
2733 * a) isatty(fd) is TRUE, or
2734 * b) the -i flag was given, and the filename associated with
2735 * the descriptor is NULL or "<stdin>" or "???".
2736 */
2737int
2738Py_FdIsInteractive(FILE *fp, const char *filename)
2739{
2740 if (isatty((int)fileno(fp)))
2741 return 1;
2742 if (!Py_InteractiveFlag)
2743 return 0;
2744 return (filename == NULL) ||
2745 (strcmp(filename, "<stdin>") == 0) ||
2746 (strcmp(filename, "???") == 0);
2747}
2748
2749
Nick Coghland6009512014-11-20 21:39:37 +10002750/* Wrappers around sigaction() or signal(). */
2751
2752PyOS_sighandler_t
2753PyOS_getsig(int sig)
2754{
2755#ifdef HAVE_SIGACTION
2756 struct sigaction context;
2757 if (sigaction(sig, NULL, &context) == -1)
2758 return SIG_ERR;
2759 return context.sa_handler;
2760#else
2761 PyOS_sighandler_t handler;
2762/* Special signal handling for the secure CRT in Visual Studio 2005 */
2763#if defined(_MSC_VER) && _MSC_VER >= 1400
2764 switch (sig) {
2765 /* Only these signals are valid */
2766 case SIGINT:
2767 case SIGILL:
2768 case SIGFPE:
2769 case SIGSEGV:
2770 case SIGTERM:
2771 case SIGBREAK:
2772 case SIGABRT:
2773 break;
2774 /* Don't call signal() with other values or it will assert */
2775 default:
2776 return SIG_ERR;
2777 }
2778#endif /* _MSC_VER && _MSC_VER >= 1400 */
2779 handler = signal(sig, SIG_IGN);
2780 if (handler != SIG_ERR)
2781 signal(sig, handler);
2782 return handler;
2783#endif
2784}
2785
2786/*
2787 * All of the code in this function must only use async-signal-safe functions,
2788 * listed at `man 7 signal` or
2789 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2790 */
2791PyOS_sighandler_t
2792PyOS_setsig(int sig, PyOS_sighandler_t handler)
2793{
2794#ifdef HAVE_SIGACTION
2795 /* Some code in Modules/signalmodule.c depends on sigaction() being
2796 * used here if HAVE_SIGACTION is defined. Fix that if this code
2797 * changes to invalidate that assumption.
2798 */
2799 struct sigaction context, ocontext;
2800 context.sa_handler = handler;
2801 sigemptyset(&context.sa_mask);
2802 context.sa_flags = 0;
2803 if (sigaction(sig, &context, &ocontext) == -1)
2804 return SIG_ERR;
2805 return ocontext.sa_handler;
2806#else
2807 PyOS_sighandler_t oldhandler;
2808 oldhandler = signal(sig, handler);
2809#ifdef HAVE_SIGINTERRUPT
2810 siginterrupt(sig, 1);
2811#endif
2812 return oldhandler;
2813#endif
2814}
2815
2816#ifdef __cplusplus
2817}
2818#endif