blob: 6a705b4d2b4b9e38024f77ca195962e5d5dc52ab [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
Eric Snowc7ec9982017-05-23 23:00:52 -0700100
Eric Snow1abcf672017-05-23 21:46:51 -0700101/* APIs to access the initialization flags
102 *
103 * Can be called prior to Py_Initialize.
104 */
Nick Coghland6009512014-11-20 21:39:37 +1000105
Eric Snow1abcf672017-05-23 21:46:51 -0700106int
107_Py_IsCoreInitialized(void)
108{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600109 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700110}
Nick Coghland6009512014-11-20 21:39:37 +1000111
112int
113Py_IsInitialized(void)
114{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600115 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000116}
117
Nick Coghlan6ea41862017-06-11 13:16:15 +1000118
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000119/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
120 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000121 initializations fail, a fatal error is issued and the function does
122 not return. On return, the first thread and interpreter state have
123 been created.
124
125 Locking: you must hold the interpreter lock while calling this.
126 (If the lock has not yet been initialized, that's equivalent to
127 having the lock, but you cannot use multiple threads.)
128
129*/
Victor Stinneref75a622020-11-12 15:14:13 +0100130static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200131init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000132{
Victor Stinneref75a622020-11-12 15:14:13 +0100133 assert(!_PyErr_Occurred(tstate));
134
Victor Stinnerb45d2592019-06-20 00:05:23 +0200135 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200136 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000137
Victor Stinneref75a622020-11-12 15:14:13 +0100138 // Import _importlib through its frozen version, _frozen_importlib.
139 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000140 PySys_FormatStderr("import _frozen_importlib # frozen\n");
141 }
Victor Stinneref75a622020-11-12 15:14:13 +0100142 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
143 return -1;
144 }
145 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000146 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100147 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000148 }
Victor Stinneref75a622020-11-12 15:14:13 +0100149 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000150
Victor Stinneref75a622020-11-12 15:14:13 +0100151 // Import the _imp module
152 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200153 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000154 }
Victor Stinner62230712020-11-18 23:18:29 +0100155 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100156 if (imp_mod == NULL) {
157 return -1;
158 }
159 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
160 Py_DECREF(imp_mod);
161 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000162 }
163
Victor Stinneref75a622020-11-12 15:14:13 +0100164 // Install importlib as the implementation of import
165 PyObject *value = PyObject_CallMethod(importlib, "_install",
166 "OO", sysmod, imp_mod);
167 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000168 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100169 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000170 }
171 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000172
Victor Stinneref75a622020-11-12 15:14:13 +0100173 assert(!_PyErr_Occurred(tstate));
174 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000175}
176
Victor Stinneref75a622020-11-12 15:14:13 +0100177
Victor Stinner331a6a52019-05-27 16:39:22 +0200178static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200179init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700180{
181 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200182 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700183 "_install_external_importers", "");
184 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200185 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200186 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700187 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200188 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200189 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700190}
Nick Coghland6009512014-11-20 21:39:37 +1000191
Nick Coghlan6ea41862017-06-11 13:16:15 +1000192/* Helper functions to better handle the legacy C locale
193 *
194 * The legacy C locale assumes ASCII as the default text encoding, which
195 * causes problems not only for the CPython runtime, but also other
196 * components like GNU readline.
197 *
198 * Accordingly, when the CLI detects it, it attempts to coerce it to a
199 * more capable UTF-8 based alternative as follows:
200 *
201 * if (_Py_LegacyLocaleDetected()) {
202 * _Py_CoerceLegacyLocale();
203 * }
204 *
205 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
206 *
207 * Locale coercion also impacts the default error handler for the standard
208 * streams: while the usual default is "strict", the default for the legacy
209 * C locale and for any of the coercion target locales is "surrogateescape".
210 */
211
212int
Victor Stinner0f721472019-05-20 17:16:38 +0200213_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000214{
215#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200216 if (!warn) {
217 const char *locale_override = getenv("LC_ALL");
218 if (locale_override != NULL && *locale_override != '\0') {
219 /* Don't coerce C locale if the LC_ALL environment variable
220 is set */
221 return 0;
222 }
223 }
224
Nick Coghlan6ea41862017-06-11 13:16:15 +1000225 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000226 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
227 * the POSIX locale as a simple alias for the C locale, so
228 * we may also want to check for that explicitly.
229 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000230 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
231 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
232#else
233 /* Windows uses code pages instead of locales, so no locale is legacy */
234 return 0;
235#endif
236}
237
Victor Stinnerb0051362019-11-22 17:52:42 +0100238#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000239static const char *_C_LOCALE_WARNING =
240 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
241 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
242 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
243 "locales is recommended.\n";
244
Nick Coghlaneb817952017-06-18 12:29:42 +1000245static void
Victor Stinner43125222019-04-24 18:23:53 +0200246emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000247{
Victor Stinner331a6a52019-05-27 16:39:22 +0200248 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200249 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200250 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000251 }
252}
Victor Stinnerb0051362019-11-22 17:52:42 +0100253#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000254
Nick Coghlan6ea41862017-06-11 13:16:15 +1000255typedef struct _CandidateLocale {
256 const char *locale_name; /* The locale to try as a coercion target */
257} _LocaleCoercionTarget;
258
259static _LocaleCoercionTarget _TARGET_LOCALES[] = {
260 {"C.UTF-8"},
261 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000262 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000263 {NULL}
264};
265
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200266
267int
268_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000269{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200270 const _LocaleCoercionTarget *target = NULL;
271 for (target = _TARGET_LOCALES; target->locale_name; target++) {
272 if (strcmp(ctype_loc, target->locale_name) == 0) {
273 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000274 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200275 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200276 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000277}
278
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200279
Nick Coghlan6ea41862017-06-11 13:16:15 +1000280#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100281static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
283 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
284
Victor Stinner0f721472019-05-20 17:16:38 +0200285static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200286_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000287{
288 const char *newloc = target->locale_name;
289
290 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100291 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000292
293 /* Set the relevant locale environment variable */
294 if (setenv("LC_CTYPE", newloc, 1)) {
295 fprintf(stderr,
296 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200297 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000298 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200299 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100300 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000301 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302
303 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100304 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200305 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000306}
307#endif
308
Victor Stinner0f721472019-05-20 17:16:38 +0200309int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200310_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311{
Victor Stinner0f721472019-05-20 17:16:38 +0200312 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200314 char *oldloc = NULL;
315
316 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
317 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200318 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200319 }
320
Victor Stinner94540602017-12-16 04:54:22 +0100321 const char *locale_override = getenv("LC_ALL");
322 if (locale_override == NULL || *locale_override == '\0') {
323 /* LC_ALL is also not set (or is set to an empty string) */
324 const _LocaleCoercionTarget *target = NULL;
325 for (target = _TARGET_LOCALES; target->locale_name; target++) {
326 const char *new_locale = setlocale(LC_CTYPE,
327 target->locale_name);
328 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400329#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100330 /* Also ensure that nl_langinfo works in this locale */
331 char *codeset = nl_langinfo(CODESET);
332 if (!codeset || *codeset == '\0') {
333 /* CODESET is not set or empty, so skip coercion */
334 new_locale = NULL;
335 _Py_SetLocaleFromEnv(LC_CTYPE);
336 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000337 }
Victor Stinner94540602017-12-16 04:54:22 +0100338#endif
339 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200340 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200341 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000342 }
343 }
344 }
345 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200346
347 setlocale(LC_CTYPE, oldloc);
348
349done:
350 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000351#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200352 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000353}
354
xdegaye1588be62017-11-12 12:45:59 +0100355/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
356 * isolate the idiosyncrasies of different libc implementations. It reads the
357 * appropriate environment variable and uses its value to select the locale for
358 * 'category'. */
359char *
360_Py_SetLocaleFromEnv(int category)
361{
Victor Stinner353933e2018-11-23 13:08:26 +0100362 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100363#ifdef __ANDROID__
364 const char *locale;
365 const char **pvar;
366#ifdef PY_COERCE_C_LOCALE
367 const char *coerce_c_locale;
368#endif
369 const char *utf8_locale = "C.UTF-8";
370 const char *env_var_set[] = {
371 "LC_ALL",
372 "LC_CTYPE",
373 "LANG",
374 NULL,
375 };
376
377 /* Android setlocale(category, "") doesn't check the environment variables
378 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
379 * check the environment variables listed in env_var_set. */
380 for (pvar=env_var_set; *pvar; pvar++) {
381 locale = getenv(*pvar);
382 if (locale != NULL && *locale != '\0') {
383 if (strcmp(locale, utf8_locale) == 0 ||
384 strcmp(locale, "en_US.UTF-8") == 0) {
385 return setlocale(category, utf8_locale);
386 }
387 return setlocale(category, "C");
388 }
389 }
390
391 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
392 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
393 * Quote from POSIX section "8.2 Internationalization Variables":
394 * "4. If the LANG environment variable is not set or is set to the empty
395 * string, the implementation-defined default locale shall be used." */
396
397#ifdef PY_COERCE_C_LOCALE
398 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
399 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
400 /* Some other ported code may check the environment variables (e.g. in
401 * extension modules), so we make sure that they match the locale
402 * configuration */
403 if (setenv("LC_CTYPE", utf8_locale, 1)) {
404 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
405 "environment variable to %s\n", utf8_locale);
406 }
407 }
408#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100409 res = setlocale(category, utf8_locale);
410#else /* !defined(__ANDROID__) */
411 res = setlocale(category, "");
412#endif
413 _Py_ResetForceASCII();
414 return res;
xdegaye1588be62017-11-12 12:45:59 +0100415}
416
Nick Coghlan6ea41862017-06-11 13:16:15 +1000417
Victor Stinner048a3562020-11-05 00:45:56 +0100418static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100419interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100420{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100421 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100422
Victor Stinner9e1b8282020-11-10 13:21:52 +0100423 if (!only_update_path_config) {
424 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
425 if (_PyStatus_EXCEPTION(status)) {
426 _PyErr_SetFromPyStatus(status);
427 return -1;
428 }
Victor Stinner048a3562020-11-05 00:45:56 +0100429 }
430
Victor Stinner9e1b8282020-11-10 13:21:52 +0100431 if (_Py_IsMainInterpreter(tstate)) {
432 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100433 if (_PyStatus_EXCEPTION(status)) {
434 _PyErr_SetFromPyStatus(status);
435 return -1;
436 }
437 }
438
439 // Update the sys module for the new configuration
440 if (_PySys_UpdateConfig(tstate) < 0) {
441 return -1;
442 }
443 return 0;
444}
445
446
447int
448_PyInterpreterState_SetConfig(const PyConfig *src_config)
449{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100450 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100451 int res = -1;
452
453 PyConfig config;
454 PyConfig_InitPythonConfig(&config);
455 PyStatus status = _PyConfig_Copy(&config, src_config);
456 if (_PyStatus_EXCEPTION(status)) {
457 _PyErr_SetFromPyStatus(status);
458 goto done;
459 }
460
461 status = PyConfig_Read(&config);
462 if (_PyStatus_EXCEPTION(status)) {
463 _PyErr_SetFromPyStatus(status);
464 goto done;
465 }
466
Victor Stinner9e1b8282020-11-10 13:21:52 +0100467 status = _PyConfig_Copy(&tstate->interp->config, &config);
468 if (_PyStatus_EXCEPTION(status)) {
469 _PyErr_SetFromPyStatus(status);
470 goto done;
471 }
472
473 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100474
475done:
476 PyConfig_Clear(&config);
477 return res;
478}
479
480
Eric Snow1abcf672017-05-23 21:46:51 -0700481/* Global initializations. Can be undone by Py_Finalize(). Don't
482 call this twice without an intervening Py_Finalize() call.
483
Victor Stinner331a6a52019-05-27 16:39:22 +0200484 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700485 must have a corresponding call to Py_Finalize.
486
487 Locking: you must hold the interpreter lock while calling these APIs.
488 (If the lock has not yet been initialized, that's equivalent to
489 having the lock, but you cannot use multiple threads.)
490
491*/
492
Victor Stinner331a6a52019-05-27 16:39:22 +0200493static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200494pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200495 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200496 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200497{
Victor Stinner331a6a52019-05-27 16:39:22 +0200498 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100499 PyThreadState *tstate = _PyThreadState_GET();
500 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200501 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100502 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200503 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100504
505 PyInterpreterState *interp = tstate->interp;
506 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200507 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100508 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100509
Victor Stinnere81f6e62020-06-08 18:12:59 +0200510 status = _PyConfig_Write(config, runtime);
511 if (_PyStatus_EXCEPTION(status)) {
512 return status;
513 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200514
Victor Stinner048a3562020-11-05 00:45:56 +0100515 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200516 if (_PyStatus_EXCEPTION(status)) {
517 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200518 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200519 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200520
Victor Stinner331a6a52019-05-27 16:39:22 +0200521 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200522 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200523 if (_PyStatus_EXCEPTION(status)) {
524 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200525 }
526 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200527 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200528}
529
530
Victor Stinner331a6a52019-05-27 16:39:22 +0200531static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200532pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200533 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000534{
Victor Stinner43125222019-04-24 18:23:53 +0200535 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200536 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200537 }
Victor Stinnerda273412017-12-15 01:46:02 +0100538
Victor Stinnere81f6e62020-06-08 18:12:59 +0200539 PyStatus status = _PyConfig_Write(config, runtime);
540 if (_PyStatus_EXCEPTION(status)) {
541 return status;
542 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600543
Eric Snow1abcf672017-05-23 21:46:51 -0700544 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
545 * threads behave a little more gracefully at interpreter shutdown.
546 * We clobber it here so the new interpreter can start with a clean
547 * slate.
548 *
549 * However, this may still lead to misbehaviour if there are daemon
550 * threads still hanging around from a previous Py_Initialize/Finalize
551 * pair :(
552 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100553 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600554
Victor Stinnere81f6e62020-06-08 18:12:59 +0200555 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200556 if (_PyStatus_EXCEPTION(status)) {
557 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800558 }
559
Victor Stinner331a6a52019-05-27 16:39:22 +0200560 status = _PyInterpreterState_Enable(runtime);
561 if (_PyStatus_EXCEPTION(status)) {
562 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800563 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200564 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100565}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800566
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100567
Victor Stinner331a6a52019-05-27 16:39:22 +0200568static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200569init_interp_create_gil(PyThreadState *tstate)
570{
571 PyStatus status;
572
573 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
574 only called here. */
575 _PyEval_FiniGIL(tstate);
576
577 /* Auto-thread-state API */
578 status = _PyGILState_Init(tstate);
579 if (_PyStatus_EXCEPTION(status)) {
580 return status;
581 }
582
583 /* Create the GIL and take it */
584 status = _PyEval_InitGIL(tstate);
585 if (_PyStatus_EXCEPTION(status)) {
586 return status;
587 }
588
589 return _PyStatus_OK();
590}
591
592
593static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200594pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200595 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200596 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100597{
598 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100599 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200600 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100601 }
602
Victor Stinner048a3562020-11-05 00:45:56 +0100603 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200604 if (_PyStatus_EXCEPTION(status)) {
605 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100606 }
Nick Coghland6009512014-11-20 21:39:37 +1000607
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200608 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200609 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200610 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200611 }
Nick Coghland6009512014-11-20 21:39:37 +1000612 (void) PyThreadState_Swap(tstate);
613
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200614 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100615 if (_PyStatus_EXCEPTION(status)) {
616 return status;
617 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100618
Victor Stinnerb45d2592019-06-20 00:05:23 +0200619 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200620 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100621}
Nick Coghland6009512014-11-20 21:39:37 +1000622
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100623
Victor Stinner331a6a52019-05-27 16:39:22 +0200624static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100625pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100626{
Victor Stinner444b39b2019-11-20 01:18:11 +0100627 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100628 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100629
Victor Stinner01b1cc12019-11-20 02:27:56 +0100630 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100631 if (_PyStatus_EXCEPTION(status)) {
632 return status;
633 }
634
Victor Stinner0430dfa2020-06-24 15:21:54 +0200635 // Create the empty tuple singleton. It must be created before the first
636 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
637 // for example.
638 status = _PyTuple_Init(tstate);
639 if (_PyStatus_EXCEPTION(status)) {
640 return status;
641 }
642
Victor Stinnere7e699e2019-11-20 12:08:13 +0100643 if (is_main_interp) {
644 status = _PyTypes_Init();
645 if (_PyStatus_EXCEPTION(status)) {
646 return status;
647 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100648 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100649
Victor Stinner630c8df2019-12-17 13:02:18 +0100650 if (!_PyLong_Init(tstate)) {
651 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100652 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100653
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200654 status = _PyUnicode_Init(tstate);
655 if (_PyStatus_EXCEPTION(status)) {
656 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100657 }
658
Victor Stinner91698d82020-06-25 14:07:40 +0200659 status = _PyBytes_Init(tstate);
660 if (_PyStatus_EXCEPTION(status)) {
661 return status;
662 }
663
Victor Stinner281cce12020-06-23 22:55:46 +0200664 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200665 if (_PyStatus_EXCEPTION(status)) {
666 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100667 }
668
Victor Stinnere7e699e2019-11-20 12:08:13 +0100669 if (is_main_interp) {
670 if (!_PyFloat_Init()) {
671 return _PyStatus_ERR("can't init float");
672 }
Nick Coghland6009512014-11-20 21:39:37 +1000673
Victor Stinnere7e699e2019-11-20 12:08:13 +0100674 if (_PyStructSequence_Init() < 0) {
675 return _PyStatus_ERR("can't initialize structseq");
676 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100677 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200678
Victor Stinner331a6a52019-05-27 16:39:22 +0200679 status = _PyErr_Init();
680 if (_PyStatus_EXCEPTION(status)) {
681 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200682 }
683
Victor Stinnere7e699e2019-11-20 12:08:13 +0100684 if (is_main_interp) {
685 if (!_PyContext_Init()) {
686 return _PyStatus_ERR("can't init context");
687 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100688 }
689
Victor Stinneref75a622020-11-12 15:14:13 +0100690 if (_PyWarnings_InitState(tstate) < 0) {
691 return _PyStatus_ERR("can't initialize warnings");
692 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200693 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100694}
695
696
Victor Stinner331a6a52019-05-27 16:39:22 +0200697static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200698pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100699{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100700 assert(!_PyErr_Occurred(tstate));
701
Victor Stinnerb45d2592019-06-20 00:05:23 +0200702 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100703 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100704 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100705 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100706
Victor Stinner2582d462019-11-22 19:24:49 +0100707 PyInterpreterState *interp = tstate->interp;
708 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
709 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100710 }
Victor Stinner2582d462019-11-22 19:24:49 +0100711
712 PyObject *builtins_dict = PyModule_GetDict(bimod);
713 if (builtins_dict == NULL) {
714 goto error;
715 }
716 Py_INCREF(builtins_dict);
717 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100718
Victor Stinner331a6a52019-05-27 16:39:22 +0200719 PyStatus status = _PyBuiltins_AddExceptions(bimod);
720 if (_PyStatus_EXCEPTION(status)) {
721 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100722 }
Victor Stinner2582d462019-11-22 19:24:49 +0100723
724 interp->builtins_copy = PyDict_Copy(interp->builtins);
725 if (interp->builtins_copy == NULL) {
726 goto error;
727 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000728 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100729
Victor Stinner62230712020-11-18 23:18:29 +0100730 // Get the __import__ function
731 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
732 "__import__");
733 if (import_func == NULL) {
734 goto error;
735 }
736 interp->import_func = Py_NewRef(import_func);
737
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100738 assert(!_PyErr_Occurred(tstate));
739
Victor Stinner331a6a52019-05-27 16:39:22 +0200740 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100741
742error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000743 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100744 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100745}
746
747
Victor Stinner331a6a52019-05-27 16:39:22 +0200748static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100749pycore_interp_init(PyThreadState *tstate)
750{
751 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100752 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100753
754 status = pycore_init_types(tstate);
755 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100756 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100757 }
758
Victor Stinnerd863ade2019-12-06 03:37:07 +0100759 status = _PySys_Create(tstate, &sysmod);
760 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100761 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100762 }
763
764 status = pycore_init_builtins(tstate);
765 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100766 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100767 }
768
Victor Stinneref75a622020-11-12 15:14:13 +0100769 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
770 if (config->_install_importlib) {
771 /* This call sets up builtin and frozen import support */
772 if (init_importlib(tstate, sysmod) < 0) {
773 return _PyStatus_ERR("failed to initialize importlib");
774 }
775 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100776
777done:
778 /* sys.modules['sys'] contains a strong reference to the module */
779 Py_XDECREF(sysmod);
780 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100781}
782
783
784static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200785pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200786 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200787 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100788{
Victor Stinner331a6a52019-05-27 16:39:22 +0200789 PyStatus status = pycore_init_runtime(runtime, config);
790 if (_PyStatus_EXCEPTION(status)) {
791 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100792 }
793
Victor Stinnerb45d2592019-06-20 00:05:23 +0200794 PyThreadState *tstate;
795 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200796 if (_PyStatus_EXCEPTION(status)) {
797 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100798 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200799 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100800
Victor Stinnerd863ade2019-12-06 03:37:07 +0100801 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200802 if (_PyStatus_EXCEPTION(status)) {
803 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100804 }
Eric Snow1abcf672017-05-23 21:46:51 -0700805
806 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200807 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200808 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700809}
810
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100811
Victor Stinner331a6a52019-05-27 16:39:22 +0200812PyStatus
813_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100814{
Victor Stinner331a6a52019-05-27 16:39:22 +0200815 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100816
Victor Stinner6d1c4672019-05-20 11:02:00 +0200817 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200818 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200819 }
820
Victor Stinner331a6a52019-05-27 16:39:22 +0200821 status = _PyRuntime_Initialize();
822 if (_PyStatus_EXCEPTION(status)) {
823 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100824 }
Victor Stinner43125222019-04-24 18:23:53 +0200825 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100826
Victor Stinnerd3b90412019-09-17 23:59:51 +0200827 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100828 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200829 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100830 }
831
Victor Stinnerd3b90412019-09-17 23:59:51 +0200832 /* Note: preinitialized remains 1 on error, it is only set to 0
833 at exit on success. */
834 runtime->preinitializing = 1;
835
Victor Stinner331a6a52019-05-27 16:39:22 +0200836 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200837
838 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
839 if (_PyStatus_EXCEPTION(status)) {
840 return status;
841 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100842
Victor Stinner331a6a52019-05-27 16:39:22 +0200843 status = _PyPreConfig_Read(&config, args);
844 if (_PyStatus_EXCEPTION(status)) {
845 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100846 }
847
Victor Stinner331a6a52019-05-27 16:39:22 +0200848 status = _PyPreConfig_Write(&config);
849 if (_PyStatus_EXCEPTION(status)) {
850 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100851 }
852
Victor Stinnerd3b90412019-09-17 23:59:51 +0200853 runtime->preinitializing = 0;
854 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200855 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100856}
857
Victor Stinner70005ac2019-05-02 15:25:34 -0400858
Victor Stinner331a6a52019-05-27 16:39:22 +0200859PyStatus
860Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100861{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100862 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400863 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100864}
865
866
Victor Stinner331a6a52019-05-27 16:39:22 +0200867PyStatus
868Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100869{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100870 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400871 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100872}
873
874
Victor Stinner331a6a52019-05-27 16:39:22 +0200875PyStatus
876Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100877{
Victor Stinner70005ac2019-05-02 15:25:34 -0400878 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100879}
880
881
Victor Stinner331a6a52019-05-27 16:39:22 +0200882PyStatus
883_Py_PreInitializeFromConfig(const PyConfig *config,
884 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100885{
Victor Stinner331a6a52019-05-27 16:39:22 +0200886 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200887
Victor Stinner331a6a52019-05-27 16:39:22 +0200888 PyStatus status = _PyRuntime_Initialize();
889 if (_PyStatus_EXCEPTION(status)) {
890 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200891 }
892 _PyRuntimeState *runtime = &_PyRuntime;
893
Victor Stinnerd3b90412019-09-17 23:59:51 +0200894 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200895 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200896 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400897 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200898
Victor Stinner331a6a52019-05-27 16:39:22 +0200899 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200900
Victor Stinner3c30a762019-10-01 10:56:37 +0200901 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200902
Victor Stinner331a6a52019-05-27 16:39:22 +0200903 if (!config->parse_argv) {
904 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200905 }
906 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200907 _PyArgv config_args = {
908 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 .argc = config->argv.length,
910 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200911 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200912 }
913 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200914 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200915 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100916}
917
918
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100919/* Begin interpreter initialization
920 *
921 * On return, the first thread and interpreter state have been created,
922 * but the compiler, signal handling, multithreading and
923 * multiple interpreter support, and codec infrastructure are not yet
924 * available.
925 *
926 * The import system will support builtin and frozen modules only.
927 * The only supported io is writing to sys.stderr
928 *
929 * If any operation invoked by this function fails, a fatal error is
930 * issued and the function does not return.
931 *
932 * Any code invoked from this function should *not* assume it has access
933 * to the Python C API (unless the API is explicitly listed as being
934 * safe to call without calling Py_Initialize first)
935 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200936static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200937pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200938 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200939 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200940{
Victor Stinner331a6a52019-05-27 16:39:22 +0200941 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200942
Victor Stinner331a6a52019-05-27 16:39:22 +0200943 status = _Py_PreInitializeFromConfig(src_config, NULL);
944 if (_PyStatus_EXCEPTION(status)) {
945 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200946 }
947
Victor Stinner331a6a52019-05-27 16:39:22 +0200948 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100949 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200950
Victor Stinner331a6a52019-05-27 16:39:22 +0200951 status = _PyConfig_Copy(&config, src_config);
952 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200953 goto done;
954 }
955
Victor Stinner9e1b8282020-11-10 13:21:52 +0100956 // Read the configuration, but don't compute the path configuration
957 // (it is computed in the main init).
958 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200959 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200960 goto done;
961 }
962
963 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200964 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200965 }
966 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200967 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200968 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200969 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200970 goto done;
971 }
972
973done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200974 PyConfig_Clear(&config);
975 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200976}
977
Victor Stinner5ac27a52019-03-27 13:40:14 +0100978
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200979/* Py_Initialize() has already been called: update the main interpreter
980 configuration. Example of bpo-34008: Py_Main() called after
981 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200982static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100983pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200984{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100985 if (interpreter_update_config(tstate, 0) < 0) {
986 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200987 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200988 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200989}
990
Victor Stinnerb0051362019-11-22 17:52:42 +0100991
992static PyStatus
993init_interp_main(PyThreadState *tstate)
994{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100995 assert(!_PyErr_Occurred(tstate));
996
Victor Stinnerb0051362019-11-22 17:52:42 +0100997 PyStatus status;
998 int is_main_interp = _Py_IsMainInterpreter(tstate);
999 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001000 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001001
1002 if (!config->_install_importlib) {
1003 /* Special mode for freeze_importlib: run with no import system
1004 *
1005 * This means anything which needs support from extension modules
1006 * or pure Python code in the standard library won't work.
1007 */
1008 if (is_main_interp) {
1009 interp->runtime->initialized = 1;
1010 }
1011 return _PyStatus_OK();
1012 }
1013
Victor Stinner9e1b8282020-11-10 13:21:52 +01001014 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001015 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001016 if (_PyStatus_EXCEPTION(status)) {
1017 return status;
1018 }
1019
Victor Stinner9e1b8282020-11-10 13:21:52 +01001020 if (interpreter_update_config(tstate, 1) < 0) {
1021 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001022 }
1023
1024 status = init_importlib_external(tstate);
1025 if (_PyStatus_EXCEPTION(status)) {
1026 return status;
1027 }
1028
1029 if (is_main_interp) {
1030 /* initialize the faulthandler module */
1031 status = _PyFaulthandler_Init(config->faulthandler);
1032 if (_PyStatus_EXCEPTION(status)) {
1033 return status;
1034 }
1035 }
1036
1037 status = _PyUnicode_InitEncodings(tstate);
1038 if (_PyStatus_EXCEPTION(status)) {
1039 return status;
1040 }
1041
1042 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001043 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1044 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001045 }
1046
1047 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1048 return _PyStatus_ERR("can't initialize tracemalloc");
1049 }
1050 }
1051
1052 status = init_sys_streams(tstate);
1053 if (_PyStatus_EXCEPTION(status)) {
1054 return status;
1055 }
1056
Andy Lester75cd5bf2020-03-12 02:49:05 -05001057 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001058 if (_PyStatus_EXCEPTION(status)) {
1059 return status;
1060 }
1061
1062 status = add_main_module(interp);
1063 if (_PyStatus_EXCEPTION(status)) {
1064 return status;
1065 }
1066
1067 if (is_main_interp) {
1068 /* Initialize warnings. */
1069 PyObject *warnoptions = PySys_GetObject("warnoptions");
1070 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1071 {
1072 PyObject *warnings_module = PyImport_ImportModule("warnings");
1073 if (warnings_module == NULL) {
1074 fprintf(stderr, "'import warnings' failed; traceback:\n");
1075 _PyErr_Print(tstate);
1076 }
1077 Py_XDECREF(warnings_module);
1078 }
1079
1080 interp->runtime->initialized = 1;
1081 }
1082
1083 if (config->site_import) {
1084 status = init_import_site();
1085 if (_PyStatus_EXCEPTION(status)) {
1086 return status;
1087 }
1088 }
1089
1090 if (is_main_interp) {
1091#ifndef MS_WINDOWS
1092 emit_stderr_warning_for_legacy_locale(interp->runtime);
1093#endif
1094 }
1095
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001096 assert(!_PyErr_Occurred(tstate));
1097
Victor Stinnerb0051362019-11-22 17:52:42 +01001098 return _PyStatus_OK();
1099}
1100
1101
Eric Snowc7ec9982017-05-23 23:00:52 -07001102/* Update interpreter state based on supplied configuration settings
1103 *
1104 * After calling this function, most of the restrictions on the interpreter
1105 * are lifted. The only remaining incomplete settings are those related
1106 * to the main module (sys.argv[0], __main__ metadata)
1107 *
1108 * Calling this when the interpreter is not initializing, is already
1109 * initialized or without a valid current thread state is a fatal error.
1110 * Other errors should be reported as normal Python exceptions with a
1111 * non-zero return code.
1112 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001113static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001114pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001115{
Victor Stinnerb0051362019-11-22 17:52:42 +01001116 PyInterpreterState *interp = tstate->interp;
1117 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001118 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001119 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001120
Victor Stinnerb0051362019-11-22 17:52:42 +01001121 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001122 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001123 }
1124
Victor Stinnerb0051362019-11-22 17:52:42 +01001125 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001126 if (_PyStatus_EXCEPTION(status)) {
1127 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001128 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001129 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001130}
1131
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001132
Victor Stinner331a6a52019-05-27 16:39:22 +02001133PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001134Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001135{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001136 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001137 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001138 }
1139
Victor Stinner331a6a52019-05-27 16:39:22 +02001140 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001141
Victor Stinner331a6a52019-05-27 16:39:22 +02001142 status = _PyRuntime_Initialize();
1143 if (_PyStatus_EXCEPTION(status)) {
1144 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001145 }
1146 _PyRuntimeState *runtime = &_PyRuntime;
1147
Victor Stinnerb45d2592019-06-20 00:05:23 +02001148 PyThreadState *tstate = NULL;
1149 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001150 if (_PyStatus_EXCEPTION(status)) {
1151 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001152 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001153 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001154
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001155 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001156 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001157 if (_PyStatus_EXCEPTION(status)) {
1158 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001159 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001160 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001161
Victor Stinner331a6a52019-05-27 16:39:22 +02001162 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001163}
1164
1165
Eric Snow1abcf672017-05-23 21:46:51 -07001166void
Nick Coghland6009512014-11-20 21:39:37 +10001167Py_InitializeEx(int install_sigs)
1168{
Victor Stinner331a6a52019-05-27 16:39:22 +02001169 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001170
Victor Stinner331a6a52019-05-27 16:39:22 +02001171 status = _PyRuntime_Initialize();
1172 if (_PyStatus_EXCEPTION(status)) {
1173 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001174 }
1175 _PyRuntimeState *runtime = &_PyRuntime;
1176
1177 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001178 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1179 return;
1180 }
1181
Victor Stinner331a6a52019-05-27 16:39:22 +02001182 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001183 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001184
Victor Stinner1dc6e392018-07-25 02:49:17 +02001185 config.install_signal_handlers = install_sigs;
1186
Victor Stinner331a6a52019-05-27 16:39:22 +02001187 status = Py_InitializeFromConfig(&config);
1188 if (_PyStatus_EXCEPTION(status)) {
1189 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001190 }
Nick Coghland6009512014-11-20 21:39:37 +10001191}
1192
1193void
1194Py_Initialize(void)
1195{
1196 Py_InitializeEx(1);
1197}
1198
1199
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001200PyStatus
1201_Py_InitializeMain(void)
1202{
1203 PyStatus status = _PyRuntime_Initialize();
1204 if (_PyStatus_EXCEPTION(status)) {
1205 return status;
1206 }
1207 _PyRuntimeState *runtime = &_PyRuntime;
1208 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1209 return pyinit_main(tstate);
1210}
1211
1212
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001213static void
1214finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1215{
1216 // List of names to clear in sys
1217 static const char * const sys_deletes[] = {
1218 "path", "argv", "ps1", "ps2",
1219 "last_type", "last_value", "last_traceback",
1220 "path_hooks", "path_importer_cache", "meta_path",
1221 "__interactivehook__",
1222 NULL
1223 };
1224
1225 static const char * const sys_files[] = {
1226 "stdin", "__stdin__",
1227 "stdout", "__stdout__",
1228 "stderr", "__stderr__",
1229 NULL
1230 };
1231
1232 PyInterpreterState *interp = tstate->interp;
1233 if (verbose) {
1234 PySys_WriteStderr("# clear builtins._\n");
1235 }
1236 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1237 PyErr_WriteUnraisable(NULL);
1238 }
1239
1240 const char * const *p;
1241 for (p = sys_deletes; *p != NULL; p++) {
1242 if (verbose) {
1243 PySys_WriteStderr("# clear sys.%s\n", *p);
1244 }
1245 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1246 PyErr_WriteUnraisable(NULL);
1247 }
1248 }
1249 for (p = sys_files; *p != NULL; p+=2) {
1250 const char *name = p[0];
1251 const char *orig_name = p[1];
1252 if (verbose) {
1253 PySys_WriteStderr("# restore sys.%s\n", name);
1254 }
1255 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1256 orig_name);
1257 if (value == NULL) {
1258 if (_PyErr_Occurred(tstate)) {
1259 PyErr_WriteUnraisable(NULL);
1260 }
1261 value = Py_None;
1262 }
1263 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1264 PyErr_WriteUnraisable(NULL);
1265 }
1266 }
1267}
1268
1269
1270static PyObject*
1271finalize_remove_modules(PyObject *modules, int verbose)
1272{
1273 PyObject *weaklist = PyList_New(0);
1274 if (weaklist == NULL) {
1275 PyErr_WriteUnraisable(NULL);
1276 }
1277
1278#define STORE_MODULE_WEAKREF(name, mod) \
1279 if (weaklist != NULL) { \
1280 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1281 if (wr) { \
1282 PyObject *tup = PyTuple_Pack(2, name, wr); \
1283 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1284 PyErr_WriteUnraisable(NULL); \
1285 } \
1286 Py_XDECREF(tup); \
1287 Py_DECREF(wr); \
1288 } \
1289 else { \
1290 PyErr_WriteUnraisable(NULL); \
1291 } \
1292 }
1293
1294#define CLEAR_MODULE(name, mod) \
1295 if (PyModule_Check(mod)) { \
1296 if (verbose && PyUnicode_Check(name)) { \
1297 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1298 } \
1299 STORE_MODULE_WEAKREF(name, mod); \
1300 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1301 PyErr_WriteUnraisable(NULL); \
1302 } \
1303 }
1304
1305 if (PyDict_CheckExact(modules)) {
1306 Py_ssize_t pos = 0;
1307 PyObject *key, *value;
1308 while (PyDict_Next(modules, &pos, &key, &value)) {
1309 CLEAR_MODULE(key, value);
1310 }
1311 }
1312 else {
1313 PyObject *iterator = PyObject_GetIter(modules);
1314 if (iterator == NULL) {
1315 PyErr_WriteUnraisable(NULL);
1316 }
1317 else {
1318 PyObject *key;
1319 while ((key = PyIter_Next(iterator))) {
1320 PyObject *value = PyObject_GetItem(modules, key);
1321 if (value == NULL) {
1322 PyErr_WriteUnraisable(NULL);
1323 continue;
1324 }
1325 CLEAR_MODULE(key, value);
1326 Py_DECREF(value);
1327 Py_DECREF(key);
1328 }
1329 if (PyErr_Occurred()) {
1330 PyErr_WriteUnraisable(NULL);
1331 }
1332 Py_DECREF(iterator);
1333 }
1334 }
1335#undef CLEAR_MODULE
1336#undef STORE_MODULE_WEAKREF
1337
1338 return weaklist;
1339}
1340
1341
1342static void
1343finalize_clear_modules_dict(PyObject *modules)
1344{
1345 if (PyDict_CheckExact(modules)) {
1346 PyDict_Clear(modules);
1347 }
1348 else {
1349 _Py_IDENTIFIER(clear);
1350 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1351 PyErr_WriteUnraisable(NULL);
1352 }
1353 }
1354}
1355
1356
1357static void
1358finalize_restore_builtins(PyThreadState *tstate)
1359{
1360 PyInterpreterState *interp = tstate->interp;
1361 PyObject *dict = PyDict_Copy(interp->builtins);
1362 if (dict == NULL) {
1363 PyErr_WriteUnraisable(NULL);
1364 }
1365 PyDict_Clear(interp->builtins);
1366 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1367 _PyErr_Clear(tstate);
1368 }
1369 Py_XDECREF(dict);
1370}
1371
1372
1373static void
1374finalize_modules_clear_weaklist(PyInterpreterState *interp,
1375 PyObject *weaklist, int verbose)
1376{
1377 // First clear modules imported later
1378 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1379 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1380 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1381 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1382 if (mod == Py_None) {
1383 continue;
1384 }
1385 assert(PyModule_Check(mod));
1386 PyObject *dict = PyModule_GetDict(mod);
1387 if (dict == interp->builtins || dict == interp->sysdict) {
1388 continue;
1389 }
1390 Py_INCREF(mod);
1391 if (verbose && PyUnicode_Check(name)) {
1392 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1393 }
1394 _PyModule_Clear(mod);
1395 Py_DECREF(mod);
1396 }
1397}
1398
1399
1400static void
1401finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1402{
1403 // Clear sys dict
1404 if (verbose) {
1405 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1406 }
1407 _PyModule_ClearDict(interp->sysdict);
1408
1409 // Clear builtins dict
1410 if (verbose) {
1411 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1412 }
1413 _PyModule_ClearDict(interp->builtins);
1414}
1415
1416
1417/* Clear modules, as good as we can */
1418static void
1419finalize_modules(PyThreadState *tstate)
1420{
1421 PyInterpreterState *interp = tstate->interp;
1422 PyObject *modules = interp->modules;
1423 if (modules == NULL) {
1424 // Already done
1425 return;
1426 }
1427 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1428
1429 // Delete some special builtins._ and sys attributes first. These are
1430 // common places where user values hide and people complain when their
1431 // destructors fail. Since the modules containing them are
1432 // deleted *last* of all, they would come too late in the normal
1433 // destruction order. Sigh.
1434 //
1435 // XXX Perhaps these precautions are obsolete. Who knows?
1436 finalize_modules_delete_special(tstate, verbose);
1437
1438 // Remove all modules from sys.modules, hoping that garbage collection
1439 // can reclaim most of them: set all sys.modules values to None.
1440 //
1441 // We prepare a list which will receive (name, weakref) tuples of
1442 // modules when they are removed from sys.modules. The name is used
1443 // for diagnosis messages (in verbose mode), while the weakref helps
1444 // detect those modules which have been held alive.
1445 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1446
1447 // Clear the modules dict
1448 finalize_clear_modules_dict(modules);
1449
1450 // Restore the original builtins dict, to ensure that any
1451 // user data gets cleared.
1452 finalize_restore_builtins(tstate);
1453
1454 // Collect garbage
1455 _PyGC_CollectNoFail(tstate);
1456
1457 // Dump GC stats before it's too late, since it uses the warnings
1458 // machinery.
1459 _PyGC_DumpShutdownStats(tstate);
1460
1461 if (weaklist != NULL) {
1462 // Now, if there are any modules left alive, clear their globals to
1463 // minimize potential leaks. All C extension modules actually end
1464 // up here, since they are kept alive in the interpreter state.
1465 //
1466 // The special treatment of "builtins" here is because even
1467 // when it's not referenced as a module, its dictionary is
1468 // referenced by almost every module's __builtins__. Since
1469 // deleting a module clears its dictionary (even if there are
1470 // references left to it), we need to delete the "builtins"
1471 // module last. Likewise, we don't delete sys until the very
1472 // end because it is implicitly referenced (e.g. by print).
1473 //
1474 // Since dict is ordered in CPython 3.6+, modules are saved in
1475 // importing order. First clear modules imported later.
1476 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1477 Py_DECREF(weaklist);
1478 }
1479
1480 // Clear sys and builtins modules dict
1481 finalize_clear_sys_builtins_dict(interp, verbose);
1482
1483 // Clear module dict copies stored in the interpreter state:
1484 // clear PyInterpreterState.modules_by_index and
1485 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1486 // initialization API)
1487 _PyInterpreterState_ClearModules(interp);
1488
1489 // Clear and delete the modules directory. Actual modules will
1490 // still be there only if imported during the execution of some
1491 // destructor.
1492 Py_SETREF(interp->modules, NULL);
1493
1494 // Collect garbage once more
1495 _PyGC_CollectNoFail(tstate);
1496}
1497
1498
Nick Coghland6009512014-11-20 21:39:37 +10001499/* Flush stdout and stderr */
1500
1501static int
1502file_is_closed(PyObject *fobj)
1503{
1504 int r;
1505 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1506 if (tmp == NULL) {
1507 PyErr_Clear();
1508 return 0;
1509 }
1510 r = PyObject_IsTrue(tmp);
1511 Py_DECREF(tmp);
1512 if (r < 0)
1513 PyErr_Clear();
1514 return r > 0;
1515}
1516
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001517
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001518static int
Nick Coghland6009512014-11-20 21:39:37 +10001519flush_std_files(void)
1520{
1521 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1522 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1523 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001524 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001525
1526 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001527 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001528 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001529 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001530 status = -1;
1531 }
Nick Coghland6009512014-11-20 21:39:37 +10001532 else
1533 Py_DECREF(tmp);
1534 }
1535
1536 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001537 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001538 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001539 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001540 status = -1;
1541 }
Nick Coghland6009512014-11-20 21:39:37 +10001542 else
1543 Py_DECREF(tmp);
1544 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001545
1546 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001547}
1548
1549/* Undo the effect of Py_Initialize().
1550
1551 Beware: if multiple interpreter and/or thread states exist, these
1552 are not wiped out; only the current thread and interpreter state
1553 are deleted. But since everything else is deleted, those other
1554 interpreter and thread states should no longer be used.
1555
1556 (XXX We should do better, e.g. wipe out all interpreters and
1557 threads.)
1558
1559 Locking: as above.
1560
1561*/
1562
Victor Stinner7eee5be2019-11-20 10:38:34 +01001563
1564static void
Victor Stinner90db4652020-07-01 23:21:36 +02001565finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001566{
Victor Stinner281cce12020-06-23 22:55:46 +02001567 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001568 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001569 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001570 _PyContext_Fini(tstate);
Victor Stinner666ecfb2020-07-02 01:19:57 +02001571 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001572
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001573 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001574 _PyList_Fini(tstate);
1575 _PyTuple_Fini(tstate);
1576
1577 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001578
Victor Stinnerc41eed12020-06-23 15:54:35 +02001579 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001580 _PyUnicode_Fini(tstate);
1581 _PyFloat_Fini(tstate);
1582 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001583}
1584
1585
1586static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001587finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001588{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001589 int is_main_interp = _Py_IsMainInterpreter(tstate);
1590
Victor Stinner7eee5be2019-11-20 10:38:34 +01001591 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001592 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001593
Kongedaa0fe02020-07-04 05:06:46 +08001594 /* Clear all loghooks */
1595 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1596 Call _PySys_ClearAuditHooks when PyObject available. */
1597 if (is_main_interp) {
1598 _PySys_ClearAuditHooks(tstate);
1599 }
1600
Victor Stinner7907f8c2020-06-08 01:22:36 +02001601 if (is_main_interp) {
1602 _Py_HashRandomization_Fini();
1603 _PyArg_Fini();
1604 _Py_ClearFileSystemEncoding();
1605 }
1606
Victor Stinner90db4652020-07-01 23:21:36 +02001607 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001608}
1609
1610
1611static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001612finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001613{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001614 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001615 /* Cleanup auto-thread-state */
1616 _PyGILState_Fini(tstate);
1617 }
1618
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001619 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1620 fail when it is being awaited by another running daemon thread (see
1621 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1622 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1623 called multiple times. */
1624
Victor Stinner7eee5be2019-11-20 10:38:34 +01001625 PyInterpreterState_Delete(tstate->interp);
1626}
1627
1628
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001629int
1630Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001631{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001632 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001633
Victor Stinner8e91c242019-04-24 17:24:01 +02001634 _PyRuntimeState *runtime = &_PyRuntime;
1635 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001636 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001637 }
Nick Coghland6009512014-11-20 21:39:37 +10001638
Victor Stinnere225beb2019-06-03 18:14:24 +02001639 /* Get current thread state and interpreter pointer */
1640 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001641
Victor Stinnerb45d2592019-06-20 00:05:23 +02001642 // Wrap up existing "threading"-module-created, non-daemon threads.
1643 wait_for_thread_shutdown(tstate);
1644
1645 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001646 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001647
Nick Coghland6009512014-11-20 21:39:37 +10001648 /* The interpreter is still entirely intact at this point, and the
1649 * exit funcs may be relying on that. In particular, if some thread
1650 * or exit func is still waiting to do an import, the import machinery
1651 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001652 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001653 * Note that Threading.py uses an exit func to do a join on all the
1654 * threads created thru it, so this also protects pending imports in
1655 * the threads created via Threading.
1656 */
Nick Coghland6009512014-11-20 21:39:37 +10001657
Victor Stinnerb45d2592019-06-20 00:05:23 +02001658 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001659
Victor Stinnerda273412017-12-15 01:46:02 +01001660 /* Copy the core config, PyInterpreterState_Delete() free
1661 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001662#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001663 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001664#endif
1665#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001666 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001667#endif
1668#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001669 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001670#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001671
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001672 /* Remaining daemon threads will automatically exit
1673 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001674 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001675 runtime->initialized = 0;
1676 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001677
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001678 /* Destroy the state of all threads of the interpreter, except of the
1679 current thread. In practice, only daemon threads should still be alive,
1680 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1681 Clear frames of other threads to call objects destructors. Destructors
1682 will be called in the current Python thread. Since
1683 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1684 can take the GIL at this point: if they try, they will exit
1685 immediately. */
1686 _PyThreadState_DeleteExcept(runtime, tstate);
1687
Victor Stinnere0deff32015-03-24 13:46:18 +01001688 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001689 if (flush_std_files() < 0) {
1690 status = -1;
1691 }
Nick Coghland6009512014-11-20 21:39:37 +10001692
1693 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001694 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001695
1696 /* Collect garbage. This may call finalizers; it's nice to call these
1697 * before all modules are destroyed.
1698 * XXX If a __del__ or weakref callback is triggered here, and tries to
1699 * XXX import a module, bad things can happen, because Python no
1700 * XXX longer believes it's initialized.
1701 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1702 * XXX is easy to provoke that way. I've also seen, e.g.,
1703 * XXX Exception exceptions.ImportError: 'No module named sha'
1704 * XXX in <function callback at 0x008F5718> ignored
1705 * XXX but I'm unclear on exactly how that one happens. In any case,
1706 * XXX I haven't seen a real-life report of either of these.
1707 */
Victor Stinner8b341482020-10-30 17:00:00 +01001708 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001709
Nick Coghland6009512014-11-20 21:39:37 +10001710 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001711 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001712
Inada Naoki91234a12019-06-03 21:30:58 +09001713 /* Print debug stats if any */
1714 _PyEval_Fini();
1715
Victor Stinnere0deff32015-03-24 13:46:18 +01001716 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001717 if (flush_std_files() < 0) {
1718 status = -1;
1719 }
Nick Coghland6009512014-11-20 21:39:37 +10001720
1721 /* Collect final garbage. This disposes of cycles created by
1722 * class definitions, for example.
1723 * XXX This is disabled because it caused too many problems. If
1724 * XXX a __del__ or weakref callback triggers here, Python code has
1725 * XXX a hard time running, because even the sys module has been
1726 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1727 * XXX One symptom is a sequence of information-free messages
1728 * XXX coming from threads (if a __del__ or callback is invoked,
1729 * XXX other threads can execute too, and any exception they encounter
1730 * XXX triggers a comedy of errors as subsystem after subsystem
1731 * XXX fails to find what it *expects* to find in sys to help report
1732 * XXX the exception and consequent unexpected failures). I've also
1733 * XXX seen segfaults then, after adding print statements to the
1734 * XXX Python code getting called.
1735 */
1736#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001737 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001738#endif
1739
1740 /* Disable tracemalloc after all Python objects have been destroyed,
1741 so it is possible to use tracemalloc in objects destructor. */
1742 _PyTraceMalloc_Fini();
1743
1744 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1745 _PyImport_Fini();
1746
1747 /* Cleanup typeobject.c's internal caches. */
1748 _PyType_Fini();
1749
1750 /* unload faulthandler module */
1751 _PyFaulthandler_Fini();
1752
Nick Coghland6009512014-11-20 21:39:37 +10001753 /* dump hash stats */
1754 _PyHash_Fini();
1755
Eric Snowdae02762017-09-14 00:35:58 -07001756#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001757 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001758 _PyDebug_PrintTotalRefs();
1759 }
Eric Snowdae02762017-09-14 00:35:58 -07001760#endif
Nick Coghland6009512014-11-20 21:39:37 +10001761
1762#ifdef Py_TRACE_REFS
1763 /* Display all objects still alive -- this can invoke arbitrary
1764 * __repr__ overrides, so requires a mostly-intact interpreter.
1765 * Alas, a lot of stuff may still be alive now that will be cleaned
1766 * up later.
1767 */
Victor Stinnerda273412017-12-15 01:46:02 +01001768 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001769 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001770 }
Nick Coghland6009512014-11-20 21:39:37 +10001771#endif /* Py_TRACE_REFS */
1772
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001773 finalize_interp_clear(tstate);
1774 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001775
1776#ifdef Py_TRACE_REFS
1777 /* Display addresses (& refcnts) of all objects still alive.
1778 * An address can be used to find the repr of the object, printed
1779 * above by _Py_PrintReferences.
1780 */
Victor Stinnerda273412017-12-15 01:46:02 +01001781 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001782 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001783 }
Nick Coghland6009512014-11-20 21:39:37 +10001784#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001785#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001786 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001787 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001788 }
Nick Coghland6009512014-11-20 21:39:37 +10001789#endif
1790
Victor Stinner8e91c242019-04-24 17:24:01 +02001791 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001792
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001793 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001794 return status;
1795}
1796
1797void
1798Py_Finalize(void)
1799{
1800 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001801}
1802
Victor Stinnerb0051362019-11-22 17:52:42 +01001803
Nick Coghland6009512014-11-20 21:39:37 +10001804/* Create and initialize a new interpreter and thread, and return the
1805 new thread. This requires that Py_Initialize() has been called
1806 first.
1807
1808 Unsuccessful initialization yields a NULL pointer. Note that *no*
1809 exception information is available even in this case -- the
1810 exception information is held in the thread, and there is no
1811 thread.
1812
1813 Locking: as above.
1814
1815*/
1816
Victor Stinner331a6a52019-05-27 16:39:22 +02001817static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001818new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001819{
Victor Stinner331a6a52019-05-27 16:39:22 +02001820 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001821
Victor Stinner331a6a52019-05-27 16:39:22 +02001822 status = _PyRuntime_Initialize();
1823 if (_PyStatus_EXCEPTION(status)) {
1824 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001825 }
1826 _PyRuntimeState *runtime = &_PyRuntime;
1827
1828 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001829 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001830 }
Nick Coghland6009512014-11-20 21:39:37 +10001831
Victor Stinner8a1be612016-03-14 22:07:55 +01001832 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1833 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001834 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001835
Victor Stinner43125222019-04-24 18:23:53 +02001836 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001837 if (interp == NULL) {
1838 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001839 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001840 }
Nick Coghland6009512014-11-20 21:39:37 +10001841
Victor Stinner43125222019-04-24 18:23:53 +02001842 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001843 if (tstate == NULL) {
1844 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001845 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001846 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001847 }
1848
Victor Stinner43125222019-04-24 18:23:53 +02001849 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001850
Eric Snow1abcf672017-05-23 21:46:51 -07001851 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001852 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001853#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001854 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001855 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001856 }
1857 else
1858#endif
1859 {
Eric Snow1abcf672017-05-23 21:46:51 -07001860 /* No current thread state, copy from the main interpreter */
1861 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001862 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001863 }
1864
Victor Stinner048a3562020-11-05 00:45:56 +01001865
1866 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001867 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001868 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001869 }
Victor Stinner252346a2020-05-01 11:33:44 +02001870 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001871
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001872 status = init_interp_create_gil(tstate);
1873 if (_PyStatus_EXCEPTION(status)) {
1874 goto error;
1875 }
1876
Victor Stinnerd863ade2019-12-06 03:37:07 +01001877 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001878 if (_PyStatus_EXCEPTION(status)) {
1879 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001880 }
1881
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001882 status = init_interp_main(tstate);
1883 if (_PyStatus_EXCEPTION(status)) {
1884 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001885 }
Nick Coghland6009512014-11-20 21:39:37 +10001886
Victor Stinnera7368ac2017-11-15 18:11:45 -08001887 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001888 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001889
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001890error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001891 *tstate_p = NULL;
1892
1893 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001894 PyErr_PrintEx(0);
1895 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001896 PyThreadState_Delete(tstate);
1897 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001898 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001899
Victor Stinnerb0051362019-11-22 17:52:42 +01001900 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001901}
1902
1903PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001904_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001905{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001906 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001907 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001908 if (_PyStatus_EXCEPTION(status)) {
1909 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001910 }
1911 return tstate;
1912
Nick Coghland6009512014-11-20 21:39:37 +10001913}
1914
Victor Stinner252346a2020-05-01 11:33:44 +02001915PyThreadState *
1916Py_NewInterpreter(void)
1917{
1918 return _Py_NewInterpreter(0);
1919}
1920
Nick Coghland6009512014-11-20 21:39:37 +10001921/* Delete an interpreter and its last thread. This requires that the
1922 given thread state is current, that the thread has no remaining
1923 frames, and that it is its interpreter's only remaining thread.
1924 It is a fatal error to violate these constraints.
1925
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001926 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001927 everything, regardless.)
1928
1929 Locking: as above.
1930
1931*/
1932
1933void
1934Py_EndInterpreter(PyThreadState *tstate)
1935{
1936 PyInterpreterState *interp = tstate->interp;
1937
Victor Stinnerb45d2592019-06-20 00:05:23 +02001938 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001939 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001940 }
1941 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001942 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001943 }
Eric Snow5be45a62019-03-08 22:47:07 -07001944 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001945
Eric Snow842a2f02019-03-15 15:47:51 -06001946 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001947 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001948
Victor Stinnerb45d2592019-06-20 00:05:23 +02001949 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001950
Victor Stinnerb45d2592019-06-20 00:05:23 +02001951 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001952 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001953 }
Nick Coghland6009512014-11-20 21:39:37 +10001954
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001955 finalize_modules(tstate);
1956
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001957 finalize_interp_clear(tstate);
1958 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001959}
1960
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001961/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001962
Victor Stinner331a6a52019-05-27 16:39:22 +02001963static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001964add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001965{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001966 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001967 m = PyImport_AddModule("__main__");
1968 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001969 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001970
Nick Coghland6009512014-11-20 21:39:37 +10001971 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001972 ann_dict = PyDict_New();
1973 if ((ann_dict == NULL) ||
1974 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001975 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001976 }
1977 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001978
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001979 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1980 if (PyErr_Occurred()) {
1981 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1982 }
Nick Coghland6009512014-11-20 21:39:37 +10001983 PyObject *bimod = PyImport_ImportModule("builtins");
1984 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001985 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001986 }
1987 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001988 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001989 }
1990 Py_DECREF(bimod);
1991 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001992
Nick Coghland6009512014-11-20 21:39:37 +10001993 /* Main is a little special - imp.is_builtin("__main__") will return
1994 * False, but BuiltinImporter is still the most appropriate initial
1995 * setting for its __loader__ attribute. A more suitable value will
1996 * be set if __main__ gets further initialized later in the startup
1997 * process.
1998 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001999 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002000 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002001 if (PyErr_Occurred()) {
2002 return _PyStatus_ERR("Failed to test __main__.__loader__");
2003 }
Nick Coghland6009512014-11-20 21:39:37 +10002004 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2005 "BuiltinImporter");
2006 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002007 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002008 }
2009 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002010 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002011 }
2012 Py_DECREF(loader);
2013 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002014 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002015}
2016
Nick Coghland6009512014-11-20 21:39:37 +10002017/* Import the site module (not into __main__ though) */
2018
Victor Stinner331a6a52019-05-27 16:39:22 +02002019static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002020init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002021{
2022 PyObject *m;
2023 m = PyImport_ImportModule("site");
2024 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002025 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002026 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002027 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002028 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002029}
2030
Victor Stinner874dbe82015-09-04 17:29:57 +02002031/* Check if a file descriptor is valid or not.
2032 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2033static int
2034is_valid_fd(int fd)
2035{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002036/* dup() is faster than fstat(): fstat() can require input/output operations,
2037 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2038 startup. Problem: dup() doesn't check if the file descriptor is valid on
2039 some platforms.
2040
2041 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2042 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2043 EBADF. FreeBSD has similar issue (bpo-32849).
2044
2045 Only use dup() on platforms where dup() is enough to detect invalid FD in
2046 corner cases: on Linux and Windows (bpo-32849). */
2047#if defined(__linux__) || defined(MS_WINDOWS)
2048 if (fd < 0) {
2049 return 0;
2050 }
2051 int fd2;
2052
2053 _Py_BEGIN_SUPPRESS_IPH
2054 fd2 = dup(fd);
2055 if (fd2 >= 0) {
2056 close(fd2);
2057 }
2058 _Py_END_SUPPRESS_IPH
2059
2060 return (fd2 >= 0);
2061#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002062 struct stat st;
2063 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002064#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002065}
2066
2067/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002068static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002069create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002070 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002071 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002072{
2073 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2074 const char* mode;
2075 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002076 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002077 int buffering, isatty;
2078 _Py_IDENTIFIER(open);
2079 _Py_IDENTIFIER(isatty);
2080 _Py_IDENTIFIER(TextIOWrapper);
2081 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002082 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002083
Victor Stinner874dbe82015-09-04 17:29:57 +02002084 if (!is_valid_fd(fd))
2085 Py_RETURN_NONE;
2086
Nick Coghland6009512014-11-20 21:39:37 +10002087 /* stdin is always opened in buffered mode, first because it shouldn't
2088 make a difference in common use cases, second because TextIOWrapper
2089 depends on the presence of a read1() method which only exists on
2090 buffered streams.
2091 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002092 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002093 buffering = 0;
2094 else
2095 buffering = -1;
2096 if (write_mode)
2097 mode = "wb";
2098 else
2099 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002100 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002101 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002102 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002103 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002104 if (buf == NULL)
2105 goto error;
2106
2107 if (buffering) {
2108 _Py_IDENTIFIER(raw);
2109 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2110 if (raw == NULL)
2111 goto error;
2112 }
2113 else {
2114 raw = buf;
2115 Py_INCREF(raw);
2116 }
2117
Steve Dower39294992016-08-30 21:22:36 -07002118#ifdef MS_WINDOWS
2119 /* Windows console IO is always UTF-8 encoded */
2120 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002121 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002122#endif
2123
Nick Coghland6009512014-11-20 21:39:37 +10002124 text = PyUnicode_FromString(name);
2125 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2126 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002127 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002128 if (res == NULL)
2129 goto error;
2130 isatty = PyObject_IsTrue(res);
2131 Py_DECREF(res);
2132 if (isatty == -1)
2133 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002134 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002135 write_through = Py_True;
2136 else
2137 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002138 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002139 line_buffering = Py_True;
2140 else
2141 line_buffering = Py_False;
2142
2143 Py_CLEAR(raw);
2144 Py_CLEAR(text);
2145
2146#ifdef MS_WINDOWS
2147 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2148 newlines to "\n".
2149 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2150 newline = NULL;
2151#else
2152 /* sys.stdin: split lines at "\n".
2153 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2154 newline = "\n";
2155#endif
2156
Victor Stinner709d23d2019-05-02 14:56:30 -04002157 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2158 if (encoding_str == NULL) {
2159 Py_CLEAR(buf);
2160 goto error;
2161 }
2162
2163 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2164 if (errors_str == NULL) {
2165 Py_CLEAR(buf);
2166 Py_CLEAR(encoding_str);
2167 goto error;
2168 }
2169
2170 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2171 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002172 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002173 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002174 Py_CLEAR(encoding_str);
2175 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002176 if (stream == NULL)
2177 goto error;
2178
2179 if (write_mode)
2180 mode = "w";
2181 else
2182 mode = "r";
2183 text = PyUnicode_FromString(mode);
2184 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2185 goto error;
2186 Py_CLEAR(text);
2187 return stream;
2188
2189error:
2190 Py_XDECREF(buf);
2191 Py_XDECREF(stream);
2192 Py_XDECREF(text);
2193 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002194
Victor Stinner874dbe82015-09-04 17:29:57 +02002195 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2196 /* Issue #24891: the file descriptor was closed after the first
2197 is_valid_fd() check was called. Ignore the OSError and set the
2198 stream to None. */
2199 PyErr_Clear();
2200 Py_RETURN_NONE;
2201 }
2202 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002203}
2204
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002205/* Set builtins.open to io.OpenWrapper */
2206static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002207init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002208{
2209 PyObject *iomod = NULL, *wrapper;
2210 PyObject *bimod = NULL;
2211 PyStatus res = _PyStatus_OK();
2212
2213 if (!(iomod = PyImport_ImportModule("io"))) {
2214 goto error;
2215 }
2216
2217 if (!(bimod = PyImport_ImportModule("builtins"))) {
2218 goto error;
2219 }
2220
2221 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2222 goto error;
2223 }
2224
2225 /* Set builtins.open */
2226 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2227 Py_DECREF(wrapper);
2228 goto error;
2229 }
2230 Py_DECREF(wrapper);
2231 goto done;
2232
2233error:
2234 res = _PyStatus_ERR("can't initialize io.open");
2235
2236done:
2237 Py_XDECREF(bimod);
2238 Py_XDECREF(iomod);
2239 return res;
2240}
2241
2242
Nick Coghland6009512014-11-20 21:39:37 +10002243/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002244static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002245init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002246{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002247 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002248 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002249 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002250 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002251 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002252 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002253
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002254 /* Check that stdin is not a directory
2255 Using shell redirection, you can redirect stdin to a directory,
2256 crashing the Python interpreter. Catch this common mistake here
2257 and output a useful error message. Note that under MS Windows,
2258 the shell already prevents that. */
2259#ifndef MS_WINDOWS
2260 struct _Py_stat_struct sb;
2261 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2262 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002263 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002264 }
2265#endif
2266
Nick Coghland6009512014-11-20 21:39:37 +10002267 if (!(iomod = PyImport_ImportModule("io"))) {
2268 goto error;
2269 }
Nick Coghland6009512014-11-20 21:39:37 +10002270
Nick Coghland6009512014-11-20 21:39:37 +10002271 /* Set sys.stdin */
2272 fd = fileno(stdin);
2273 /* Under some conditions stdin, stdout and stderr may not be connected
2274 * and fileno() may point to an invalid file descriptor. For example
2275 * GUI apps don't have valid standard streams by default.
2276 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002277 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002278 config->stdio_encoding,
2279 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002280 if (std == NULL)
2281 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002282 PySys_SetObject("__stdin__", std);
2283 _PySys_SetObjectId(&PyId_stdin, std);
2284 Py_DECREF(std);
2285
2286 /* Set sys.stdout */
2287 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002288 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002289 config->stdio_encoding,
2290 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002291 if (std == NULL)
2292 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002293 PySys_SetObject("__stdout__", std);
2294 _PySys_SetObjectId(&PyId_stdout, std);
2295 Py_DECREF(std);
2296
2297#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2298 /* Set sys.stderr, replaces the preliminary stderr */
2299 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002300 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002301 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002302 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002303 if (std == NULL)
2304 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002305
2306 /* Same as hack above, pre-import stderr's codec to avoid recursion
2307 when import.c tries to write to stderr in verbose mode. */
2308 encoding_attr = PyObject_GetAttrString(std, "encoding");
2309 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002310 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002311 if (std_encoding != NULL) {
2312 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2313 Py_XDECREF(codec_info);
2314 }
2315 Py_DECREF(encoding_attr);
2316 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002317 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002318
2319 if (PySys_SetObject("__stderr__", std) < 0) {
2320 Py_DECREF(std);
2321 goto error;
2322 }
2323 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2324 Py_DECREF(std);
2325 goto error;
2326 }
2327 Py_DECREF(std);
2328#endif
2329
Victor Stinnera7368ac2017-11-15 18:11:45 -08002330 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002331
Victor Stinnera7368ac2017-11-15 18:11:45 -08002332error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002333 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002334
2335done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002336 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002337 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002338 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002339}
2340
2341
Victor Stinner10dc4842015-03-24 12:01:30 +01002342static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002343_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2344 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002345{
Victor Stinner10dc4842015-03-24 12:01:30 +01002346 fputc('\n', stderr);
2347 fflush(stderr);
2348
2349 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002350 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002351}
Victor Stinner791da1c2016-03-14 16:53:12 +01002352
2353/* Print the current exception (if an exception is set) with its traceback,
2354 or display the current Python stack.
2355
2356 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2357 called on catastrophic cases.
2358
2359 Return 1 if the traceback was displayed, 0 otherwise. */
2360
2361static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002362_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002363{
2364 PyObject *ferr, *res;
2365 PyObject *exception, *v, *tb;
2366 int has_tb;
2367
Victor Stinnerb45d2592019-06-20 00:05:23 +02002368 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002369 if (exception == NULL) {
2370 /* No current exception */
2371 return 0;
2372 }
2373
2374 ferr = _PySys_GetObjectId(&PyId_stderr);
2375 if (ferr == NULL || ferr == Py_None) {
2376 /* sys.stderr is not set yet or set to None,
2377 no need to try to display the exception */
2378 return 0;
2379 }
2380
Victor Stinnerb45d2592019-06-20 00:05:23 +02002381 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002382 if (tb == NULL) {
2383 tb = Py_None;
2384 Py_INCREF(tb);
2385 }
2386 PyException_SetTraceback(v, tb);
2387 if (exception == NULL) {
2388 /* PyErr_NormalizeException() failed */
2389 return 0;
2390 }
2391
2392 has_tb = (tb != Py_None);
2393 PyErr_Display(exception, v, tb);
2394 Py_XDECREF(exception);
2395 Py_XDECREF(v);
2396 Py_XDECREF(tb);
2397
2398 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002399 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002400 if (res == NULL) {
2401 _PyErr_Clear(tstate);
2402 }
2403 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002404 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002405 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002406
2407 return has_tb;
2408}
2409
Nick Coghland6009512014-11-20 21:39:37 +10002410/* Print fatal error message and abort */
2411
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002412#ifdef MS_WINDOWS
2413static void
2414fatal_output_debug(const char *msg)
2415{
2416 /* buffer of 256 bytes allocated on the stack */
2417 WCHAR buffer[256 / sizeof(WCHAR)];
2418 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2419 size_t msglen;
2420
2421 OutputDebugStringW(L"Fatal Python error: ");
2422
2423 msglen = strlen(msg);
2424 while (msglen) {
2425 size_t i;
2426
2427 if (buflen > msglen) {
2428 buflen = msglen;
2429 }
2430
2431 /* Convert the message to wchar_t. This uses a simple one-to-one
2432 conversion, assuming that the this error message actually uses
2433 ASCII only. If this ceases to be true, we will have to convert. */
2434 for (i=0; i < buflen; ++i) {
2435 buffer[i] = msg[i];
2436 }
2437 buffer[i] = L'\0';
2438 OutputDebugStringW(buffer);
2439
2440 msg += buflen;
2441 msglen -= buflen;
2442 }
2443 OutputDebugStringW(L"\n");
2444}
2445#endif
2446
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002447
2448static void
2449fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2450{
2451 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002452 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2453 if (finalizing) {
2454 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002455 }
2456 else if (runtime->initialized) {
2457 fprintf(stream, "initialized");
2458 }
2459 else if (runtime->core_initialized) {
2460 fprintf(stream, "core initialized");
2461 }
2462 else if (runtime->preinitialized) {
2463 fprintf(stream, "preinitialized");
2464 }
2465 else if (runtime->preinitializing) {
2466 fprintf(stream, "preinitializing");
2467 }
2468 else {
2469 fprintf(stream, "unknown");
2470 }
2471 fprintf(stream, "\n");
2472 fflush(stream);
2473}
2474
2475
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002476static inline void _Py_NO_RETURN
2477fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002478{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002479 if (status < 0) {
2480#if defined(MS_WINDOWS) && defined(_DEBUG)
2481 DebugBreak();
2482#endif
2483 abort();
2484 }
2485 else {
2486 exit(status);
2487 }
2488}
2489
2490
2491static void _Py_NO_RETURN
2492fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2493 int status)
2494{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002495 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002496 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002497
2498 if (reentrant) {
2499 /* Py_FatalError() caused a second fatal error.
2500 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002501 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002502 }
2503 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002504
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002505 if (header) {
2506 fprintf(stream, "Fatal Python error: ");
2507 if (prefix) {
2508 fputs(prefix, stream);
2509 fputs(": ", stream);
2510 }
2511 if (msg) {
2512 fputs(msg, stream);
2513 }
2514 else {
2515 fprintf(stream, "<message not set>");
2516 }
2517 fputs("\n", stream);
2518 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002519 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002520
2521 _PyRuntimeState *runtime = &_PyRuntime;
2522 fatal_error_dump_runtime(stream, runtime);
2523
2524 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2525 PyInterpreterState *interp = NULL;
2526 if (tstate != NULL) {
2527 interp = tstate->interp;
2528 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002529
Victor Stinner3a228ab2018-11-01 00:26:41 +01002530 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002531 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002532
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002533 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2534 has no Python thread state.
2535
2536 tss_tstate != tstate if the current Python thread does not hold the GIL.
2537 */
2538 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2539 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002540 if (has_tstate_and_gil) {
2541 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002542 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002543 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002544 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002545 }
2546 }
2547 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002548 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002549 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002550
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002551 /* The main purpose of faulthandler is to display the traceback.
2552 This function already did its best to display a traceback.
2553 Disable faulthandler to prevent writing a second traceback
2554 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002555 _PyFaulthandler_Fini();
2556
Victor Stinner791da1c2016-03-14 16:53:12 +01002557 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002558 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002559 /* Flush sys.stdout and sys.stderr */
2560 flush_std_files();
2561 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002562
Nick Coghland6009512014-11-20 21:39:37 +10002563#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002564 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002565#endif /* MS_WINDOWS */
2566
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002567 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002568}
2569
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002570
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002571#undef Py_FatalError
2572
Victor Stinner19760862017-12-20 01:41:59 +01002573void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002574Py_FatalError(const char *msg)
2575{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002576 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002577}
2578
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002579
Victor Stinner19760862017-12-20 01:41:59 +01002580void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002581_Py_FatalErrorFunc(const char *func, const char *msg)
2582{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002583 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002584}
2585
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002586
2587void _Py_NO_RETURN
2588_Py_FatalErrorFormat(const char *func, const char *format, ...)
2589{
2590 static int reentrant = 0;
2591 if (reentrant) {
2592 /* _Py_FatalErrorFormat() caused a second fatal error */
2593 fatal_error_exit(-1);
2594 }
2595 reentrant = 1;
2596
2597 FILE *stream = stderr;
2598 fprintf(stream, "Fatal Python error: ");
2599 if (func) {
2600 fputs(func, stream);
2601 fputs(": ", stream);
2602 }
2603 fflush(stream);
2604
2605 va_list vargs;
2606#ifdef HAVE_STDARG_PROTOTYPES
2607 va_start(vargs, format);
2608#else
2609 va_start(vargs);
2610#endif
2611 vfprintf(stream, format, vargs);
2612 va_end(vargs);
2613
2614 fputs("\n", stream);
2615 fflush(stream);
2616
2617 fatal_error(stream, 0, NULL, NULL, -1);
2618}
2619
2620
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002621void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002622Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002623{
Victor Stinner331a6a52019-05-27 16:39:22 +02002624 if (_PyStatus_IS_EXIT(status)) {
2625 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002626 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002627 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002628 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002629 }
2630 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002631 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002632 }
Nick Coghland6009512014-11-20 21:39:37 +10002633}
2634
2635/* Clean up and exit */
2636
Nick Coghland6009512014-11-20 21:39:37 +10002637/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002638void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002639{
Victor Stinner81a7be32020-04-14 15:14:01 +02002640 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002641
Antoine Pitroufc5db952017-12-13 02:29:07 +01002642 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002643 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2644
2645 is->pyexitfunc = func;
2646 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002647}
2648
2649static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002650call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002651{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002652 PyInterpreterState *interp = tstate->interp;
2653 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002654 return;
2655
Victor Stinnerb45d2592019-06-20 00:05:23 +02002656 (*interp->pyexitfunc)(interp->pyexitmodule);
2657 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002658}
2659
2660/* Wait until threading._shutdown completes, provided
2661 the threading module was imported in the first place.
2662 The shutdown routine will wait until all non-daemon
2663 "threading" threads have completed. */
2664static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002665wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002666{
Nick Coghland6009512014-11-20 21:39:37 +10002667 _Py_IDENTIFIER(_shutdown);
2668 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002669 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002670 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002671 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002672 PyErr_WriteUnraisable(NULL);
2673 }
2674 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002675 return;
2676 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002677 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002678 if (result == NULL) {
2679 PyErr_WriteUnraisable(threading);
2680 }
2681 else {
2682 Py_DECREF(result);
2683 }
2684 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002685}
2686
2687#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002688int Py_AtExit(void (*func)(void))
2689{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002690 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002691 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002692 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002693 return 0;
2694}
2695
2696static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002697call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002698{
Victor Stinner8e91c242019-04-24 17:24:01 +02002699 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002700 /* pop last function from the list */
2701 runtime->nexitfuncs--;
2702 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2703 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2704
2705 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002706 }
Nick Coghland6009512014-11-20 21:39:37 +10002707
2708 fflush(stdout);
2709 fflush(stderr);
2710}
2711
Victor Stinnercfc88312018-08-01 16:41:25 +02002712void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002713Py_Exit(int sts)
2714{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002715 if (Py_FinalizeEx() < 0) {
2716 sts = 120;
2717 }
Nick Coghland6009512014-11-20 21:39:37 +10002718
2719 exit(sts);
2720}
2721
Nick Coghland6009512014-11-20 21:39:37 +10002722
Nick Coghland6009512014-11-20 21:39:37 +10002723/*
2724 * The file descriptor fd is considered ``interactive'' if either
2725 * a) isatty(fd) is TRUE, or
2726 * b) the -i flag was given, and the filename associated with
2727 * the descriptor is NULL or "<stdin>" or "???".
2728 */
2729int
2730Py_FdIsInteractive(FILE *fp, const char *filename)
2731{
2732 if (isatty((int)fileno(fp)))
2733 return 1;
2734 if (!Py_InteractiveFlag)
2735 return 0;
2736 return (filename == NULL) ||
2737 (strcmp(filename, "<stdin>") == 0) ||
2738 (strcmp(filename, "???") == 0);
2739}
2740
2741
Victor Stinnera82f63f2020-12-09 22:37:27 +01002742int
2743_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2744{
2745 if (isatty((int)fileno(fp))) {
2746 return 1;
2747 }
2748 if (!Py_InteractiveFlag) {
2749 return 0;
2750 }
2751 return (filename == NULL) ||
2752 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2753 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2754}
2755
2756
Nick Coghland6009512014-11-20 21:39:37 +10002757/* Wrappers around sigaction() or signal(). */
2758
2759PyOS_sighandler_t
2760PyOS_getsig(int sig)
2761{
2762#ifdef HAVE_SIGACTION
2763 struct sigaction context;
2764 if (sigaction(sig, NULL, &context) == -1)
2765 return SIG_ERR;
2766 return context.sa_handler;
2767#else
2768 PyOS_sighandler_t handler;
2769/* Special signal handling for the secure CRT in Visual Studio 2005 */
2770#if defined(_MSC_VER) && _MSC_VER >= 1400
2771 switch (sig) {
2772 /* Only these signals are valid */
2773 case SIGINT:
2774 case SIGILL:
2775 case SIGFPE:
2776 case SIGSEGV:
2777 case SIGTERM:
2778 case SIGBREAK:
2779 case SIGABRT:
2780 break;
2781 /* Don't call signal() with other values or it will assert */
2782 default:
2783 return SIG_ERR;
2784 }
2785#endif /* _MSC_VER && _MSC_VER >= 1400 */
2786 handler = signal(sig, SIG_IGN);
2787 if (handler != SIG_ERR)
2788 signal(sig, handler);
2789 return handler;
2790#endif
2791}
2792
2793/*
2794 * All of the code in this function must only use async-signal-safe functions,
2795 * listed at `man 7 signal` or
2796 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2797 */
2798PyOS_sighandler_t
2799PyOS_setsig(int sig, PyOS_sighandler_t handler)
2800{
2801#ifdef HAVE_SIGACTION
2802 /* Some code in Modules/signalmodule.c depends on sigaction() being
2803 * used here if HAVE_SIGACTION is defined. Fix that if this code
2804 * changes to invalidate that assumption.
2805 */
2806 struct sigaction context, ocontext;
2807 context.sa_handler = handler;
2808 sigemptyset(&context.sa_mask);
2809 context.sa_flags = 0;
2810 if (sigaction(sig, &context, &ocontext) == -1)
2811 return SIG_ERR;
2812 return ocontext.sa_handler;
2813#else
2814 PyOS_sighandler_t oldhandler;
2815 oldhandler = signal(sig, handler);
2816#ifdef HAVE_SIGINTERRUPT
2817 siginterrupt(sig, 1);
2818#endif
2819 return oldhandler;
2820#endif
2821}
2822
2823#ifdef __cplusplus
2824}
2825#endif