blob: ff58c1b9153bd0a668a1e1cf90eec494a36fd2d1 [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 Stinner4f98f462020-04-15 04:01:58 +020011#include "pycore_initconfig.h" // _PyStatus_OK()
12#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
13#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
14#include "pycore_pyerrors.h" // _PyErr_Occurred()
15#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020016#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020017#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
18#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
19
Victor Stinner4f98f462020-04-15 04:01:58 +020020#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100021
22#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020023# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100024#endif
25
26#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020027# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100028#endif
29
30#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020031# undef BYTE
32# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070033
Victor Stinner4f98f462020-04-15 04:01:58 +020034 extern PyTypeObject PyWindowsConsoleIO_Type;
35# define PyWindowsConsoleIO_Check(op) \
36 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
Victor Stinner4f98f462020-04-15 04:01:58 +020039
Nick Coghland6009512014-11-20 21:39:37 +100040_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
Nick Coghland6009512014-11-20 21:39:37 +100051
Victor Stinnerb45d2592019-06-20 00:05:23 +020052/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020053static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020054static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050055static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020056static PyStatus init_sys_streams(PyThreadState *tstate);
57static PyStatus init_signals(PyThreadState *tstate);
58static void call_py_exitfuncs(PyThreadState *tstate);
59static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020060static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100061
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080062int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010064static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065
Victor Stinner331a6a52019-05-27 16:39:22 +020066PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067_PyRuntime_Initialize(void)
68{
69 /* XXX We only initialize once in the process, which aligns with
70 the static initialization of the former globals now found in
71 _PyRuntime. However, _PyRuntime *should* be initialized with
72 every Py_Initialize() call, but doing so breaks the runtime.
73 This is because the runtime state is not properly finalized
74 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010075 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020076 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010078 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079
80 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081}
82
83void
84_PyRuntime_Finalize(void)
85{
86 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010087 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
89
90int
91_Py_IsFinalizing(void)
92{
Victor Stinner7b3c2522020-03-07 00:24:23 +010093 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
Nick Coghland6009512014-11-20 21:39:37 +100096/* Hack to force loading of object files */
97int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
98 PyOS_mystrnicmp; /* Python/pystrcmp.o */
99
100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
104{
105 return PyImport_ImportModule("warnings");
106}
107
Eric Snowc7ec9982017-05-23 23:00:52 -0700108
Eric Snow1abcf672017-05-23 21:46:51 -0700109/* APIs to access the initialization flags
110 *
111 * Can be called prior to Py_Initialize.
112 */
Nick Coghland6009512014-11-20 21:39:37 +1000113
Eric Snow1abcf672017-05-23 21:46:51 -0700114int
115_Py_IsCoreInitialized(void)
116{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700118}
Nick Coghland6009512014-11-20 21:39:37 +1000119
120int
121Py_IsInitialized(void)
122{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600123 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000124}
125
Nick Coghlan6ea41862017-06-11 13:16:15 +1000126
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000127/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
128 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000129 initializations fail, a fatal error is issued and the function does
130 not return. On return, the first thread and interpreter state have
131 been created.
132
133 Locking: you must hold the interpreter lock while calling this.
134 (If the lock has not yet been initialized, that's equivalent to
135 having the lock, but you cannot use multiple threads.)
136
137*/
138
Victor Stinner331a6a52019-05-27 16:39:22 +0200139static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200140init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000141{
142 PyObject *importlib;
143 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000144 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200145 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200146 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000147
148 /* Import _importlib through its frozen version, _frozen_importlib. */
149 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200150 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000151 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200152 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000153 PySys_FormatStderr("import _frozen_importlib # frozen\n");
154 }
155 importlib = PyImport_AddModule("_frozen_importlib");
156 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200157 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000158 }
159 interp->importlib = importlib;
160 Py_INCREF(interp->importlib);
161
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200162 interp->import_func = _PyDict_GetItemStringWithError(interp->builtins, "__import__");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300163 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200164 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300165 Py_INCREF(interp->import_func);
166
Victor Stinnercd6e6942015-09-18 09:11:57 +0200167 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800168 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000169 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200170 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000171 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200172 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200173 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000174 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600175 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200176 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000177 }
178
Victor Stinnercd6e6942015-09-18 09:11:57 +0200179 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000180 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
181 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200182 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200183 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000184 }
185 Py_DECREF(value);
186 Py_DECREF(impmod);
187
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000189}
190
Victor Stinner331a6a52019-05-27 16:39:22 +0200191static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200192init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700193{
194 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200195 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700196 "_install_external_importers", "");
197 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200198 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200199 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700200 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200201 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200202 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700203}
Nick Coghland6009512014-11-20 21:39:37 +1000204
Nick Coghlan6ea41862017-06-11 13:16:15 +1000205/* Helper functions to better handle the legacy C locale
206 *
207 * The legacy C locale assumes ASCII as the default text encoding, which
208 * causes problems not only for the CPython runtime, but also other
209 * components like GNU readline.
210 *
211 * Accordingly, when the CLI detects it, it attempts to coerce it to a
212 * more capable UTF-8 based alternative as follows:
213 *
214 * if (_Py_LegacyLocaleDetected()) {
215 * _Py_CoerceLegacyLocale();
216 * }
217 *
218 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
219 *
220 * Locale coercion also impacts the default error handler for the standard
221 * streams: while the usual default is "strict", the default for the legacy
222 * C locale and for any of the coercion target locales is "surrogateescape".
223 */
224
225int
Victor Stinner0f721472019-05-20 17:16:38 +0200226_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000227{
228#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200229 if (!warn) {
230 const char *locale_override = getenv("LC_ALL");
231 if (locale_override != NULL && *locale_override != '\0') {
232 /* Don't coerce C locale if the LC_ALL environment variable
233 is set */
234 return 0;
235 }
236 }
237
Nick Coghlan6ea41862017-06-11 13:16:15 +1000238 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000239 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
240 * the POSIX locale as a simple alias for the C locale, so
241 * we may also want to check for that explicitly.
242 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000243 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
244 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
245#else
246 /* Windows uses code pages instead of locales, so no locale is legacy */
247 return 0;
248#endif
249}
250
Victor Stinnerb0051362019-11-22 17:52:42 +0100251#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000252static const char *_C_LOCALE_WARNING =
253 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
254 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
255 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
256 "locales is recommended.\n";
257
Nick Coghlaneb817952017-06-18 12:29:42 +1000258static void
Victor Stinner43125222019-04-24 18:23:53 +0200259emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000260{
Victor Stinner331a6a52019-05-27 16:39:22 +0200261 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200262 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200263 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000264 }
265}
Victor Stinnerb0051362019-11-22 17:52:42 +0100266#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000267
Nick Coghlan6ea41862017-06-11 13:16:15 +1000268typedef struct _CandidateLocale {
269 const char *locale_name; /* The locale to try as a coercion target */
270} _LocaleCoercionTarget;
271
272static _LocaleCoercionTarget _TARGET_LOCALES[] = {
273 {"C.UTF-8"},
274 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000275 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276 {NULL}
277};
278
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200279
280int
281_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200283 const _LocaleCoercionTarget *target = NULL;
284 for (target = _TARGET_LOCALES; target->locale_name; target++) {
285 if (strcmp(ctype_loc, target->locale_name) == 0) {
286 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000287 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200288 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200289 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000290}
291
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200292
Nick Coghlan6ea41862017-06-11 13:16:15 +1000293#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100294static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
296 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
297
Victor Stinner0f721472019-05-20 17:16:38 +0200298static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200299_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300{
301 const char *newloc = target->locale_name;
302
303 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100304 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305
306 /* Set the relevant locale environment variable */
307 if (setenv("LC_CTYPE", newloc, 1)) {
308 fprintf(stderr,
309 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200310 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200312 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100313 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000314 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315
316 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100317 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200318 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319}
320#endif
321
Victor Stinner0f721472019-05-20 17:16:38 +0200322int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200323_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000324{
Victor Stinner0f721472019-05-20 17:16:38 +0200325 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200327 char *oldloc = NULL;
328
329 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
330 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200331 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200332 }
333
Victor Stinner94540602017-12-16 04:54:22 +0100334 const char *locale_override = getenv("LC_ALL");
335 if (locale_override == NULL || *locale_override == '\0') {
336 /* LC_ALL is also not set (or is set to an empty string) */
337 const _LocaleCoercionTarget *target = NULL;
338 for (target = _TARGET_LOCALES; target->locale_name; target++) {
339 const char *new_locale = setlocale(LC_CTYPE,
340 target->locale_name);
341 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400342#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100343 /* Also ensure that nl_langinfo works in this locale */
344 char *codeset = nl_langinfo(CODESET);
345 if (!codeset || *codeset == '\0') {
346 /* CODESET is not set or empty, so skip coercion */
347 new_locale = NULL;
348 _Py_SetLocaleFromEnv(LC_CTYPE);
349 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350 }
Victor Stinner94540602017-12-16 04:54:22 +0100351#endif
352 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200353 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200354 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000355 }
356 }
357 }
358 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200359
360 setlocale(LC_CTYPE, oldloc);
361
362done:
363 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000364#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200365 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000366}
367
xdegaye1588be62017-11-12 12:45:59 +0100368/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
369 * isolate the idiosyncrasies of different libc implementations. It reads the
370 * appropriate environment variable and uses its value to select the locale for
371 * 'category'. */
372char *
373_Py_SetLocaleFromEnv(int category)
374{
Victor Stinner353933e2018-11-23 13:08:26 +0100375 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100376#ifdef __ANDROID__
377 const char *locale;
378 const char **pvar;
379#ifdef PY_COERCE_C_LOCALE
380 const char *coerce_c_locale;
381#endif
382 const char *utf8_locale = "C.UTF-8";
383 const char *env_var_set[] = {
384 "LC_ALL",
385 "LC_CTYPE",
386 "LANG",
387 NULL,
388 };
389
390 /* Android setlocale(category, "") doesn't check the environment variables
391 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
392 * check the environment variables listed in env_var_set. */
393 for (pvar=env_var_set; *pvar; pvar++) {
394 locale = getenv(*pvar);
395 if (locale != NULL && *locale != '\0') {
396 if (strcmp(locale, utf8_locale) == 0 ||
397 strcmp(locale, "en_US.UTF-8") == 0) {
398 return setlocale(category, utf8_locale);
399 }
400 return setlocale(category, "C");
401 }
402 }
403
404 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
405 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
406 * Quote from POSIX section "8.2 Internationalization Variables":
407 * "4. If the LANG environment variable is not set or is set to the empty
408 * string, the implementation-defined default locale shall be used." */
409
410#ifdef PY_COERCE_C_LOCALE
411 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
412 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
413 /* Some other ported code may check the environment variables (e.g. in
414 * extension modules), so we make sure that they match the locale
415 * configuration */
416 if (setenv("LC_CTYPE", utf8_locale, 1)) {
417 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
418 "environment variable to %s\n", utf8_locale);
419 }
420 }
421#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100422 res = setlocale(category, utf8_locale);
423#else /* !defined(__ANDROID__) */
424 res = setlocale(category, "");
425#endif
426 _Py_ResetForceASCII();
427 return res;
xdegaye1588be62017-11-12 12:45:59 +0100428}
429
Nick Coghlan6ea41862017-06-11 13:16:15 +1000430
Eric Snow1abcf672017-05-23 21:46:51 -0700431/* Global initializations. Can be undone by Py_Finalize(). Don't
432 call this twice without an intervening Py_Finalize() call.
433
Victor Stinner331a6a52019-05-27 16:39:22 +0200434 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700435 must have a corresponding call to Py_Finalize.
436
437 Locking: you must hold the interpreter lock while calling these APIs.
438 (If the lock has not yet been initialized, that's equivalent to
439 having the lock, but you cannot use multiple threads.)
440
441*/
442
Victor Stinner331a6a52019-05-27 16:39:22 +0200443static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200444pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200445 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200446 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200447{
Victor Stinner331a6a52019-05-27 16:39:22 +0200448 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100449 PyThreadState *tstate = _PyThreadState_GET();
450 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200451 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100452 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200453 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100454
455 PyInterpreterState *interp = tstate->interp;
456 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200457 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100458 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100459
Victor Stinnere81f6e62020-06-08 18:12:59 +0200460 status = _PyConfig_Write(config, runtime);
461 if (_PyStatus_EXCEPTION(status)) {
462 return status;
463 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200464
Victor Stinnerda7933e2020-04-13 03:04:28 +0200465 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200466 if (_PyStatus_EXCEPTION(status)) {
467 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200468 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200469 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470
Victor Stinner331a6a52019-05-27 16:39:22 +0200471 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200472 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200473 if (_PyStatus_EXCEPTION(status)) {
474 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200475 }
476 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200477 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200478}
479
480
Victor Stinner331a6a52019-05-27 16:39:22 +0200481static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200482pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200483 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000484{
Victor Stinner43125222019-04-24 18:23:53 +0200485 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200486 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200487 }
Victor Stinnerda273412017-12-15 01:46:02 +0100488
Victor Stinnere81f6e62020-06-08 18:12:59 +0200489 PyStatus status = _PyConfig_Write(config, runtime);
490 if (_PyStatus_EXCEPTION(status)) {
491 return status;
492 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600493
Eric Snow1abcf672017-05-23 21:46:51 -0700494 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
495 * threads behave a little more gracefully at interpreter shutdown.
496 * We clobber it here so the new interpreter can start with a clean
497 * slate.
498 *
499 * However, this may still lead to misbehaviour if there are daemon
500 * threads still hanging around from a previous Py_Initialize/Finalize
501 * pair :(
502 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100503 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600504
Victor Stinnere81f6e62020-06-08 18:12:59 +0200505 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200506 if (_PyStatus_EXCEPTION(status)) {
507 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800508 }
509
Victor Stinner331a6a52019-05-27 16:39:22 +0200510 status = _PyInterpreterState_Enable(runtime);
511 if (_PyStatus_EXCEPTION(status)) {
512 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800513 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200514 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100515}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800516
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517
Victor Stinner331a6a52019-05-27 16:39:22 +0200518static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200519init_interp_create_gil(PyThreadState *tstate)
520{
521 PyStatus status;
522
523 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
524 only called here. */
525 _PyEval_FiniGIL(tstate);
526
527 /* Auto-thread-state API */
528 status = _PyGILState_Init(tstate);
529 if (_PyStatus_EXCEPTION(status)) {
530 return status;
531 }
532
533 /* Create the GIL and take it */
534 status = _PyEval_InitGIL(tstate);
535 if (_PyStatus_EXCEPTION(status)) {
536 return status;
537 }
538
539 return _PyStatus_OK();
540}
541
542
543static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200544pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200545 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200546 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100547{
548 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100549 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200550 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100551 }
552
Victor Stinnerda7933e2020-04-13 03:04:28 +0200553 PyStatus status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200554 if (_PyStatus_EXCEPTION(status)) {
555 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100556 }
Nick Coghland6009512014-11-20 21:39:37 +1000557
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200558 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200559 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200560 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200561 }
Nick Coghland6009512014-11-20 21:39:37 +1000562 (void) PyThreadState_Swap(tstate);
563
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200564 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100565 if (_PyStatus_EXCEPTION(status)) {
566 return status;
567 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100568
Victor Stinnerb45d2592019-06-20 00:05:23 +0200569 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200570 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100571}
Nick Coghland6009512014-11-20 21:39:37 +1000572
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573
Victor Stinner331a6a52019-05-27 16:39:22 +0200574static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100575pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100576{
Victor Stinner444b39b2019-11-20 01:18:11 +0100577 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100578 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100579
Victor Stinner01b1cc12019-11-20 02:27:56 +0100580 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100581 if (_PyStatus_EXCEPTION(status)) {
582 return status;
583 }
584
Victor Stinner0430dfa2020-06-24 15:21:54 +0200585 // Create the empty tuple singleton. It must be created before the first
586 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
587 // for example.
588 status = _PyTuple_Init(tstate);
589 if (_PyStatus_EXCEPTION(status)) {
590 return status;
591 }
592
Victor Stinnere7e699e2019-11-20 12:08:13 +0100593 if (is_main_interp) {
594 status = _PyTypes_Init();
595 if (_PyStatus_EXCEPTION(status)) {
596 return status;
597 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100598 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100599
Victor Stinner630c8df2019-12-17 13:02:18 +0100600 if (!_PyLong_Init(tstate)) {
601 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100602 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100603
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200604 status = _PyUnicode_Init(tstate);
605 if (_PyStatus_EXCEPTION(status)) {
606 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100607 }
608
Victor Stinner91698d82020-06-25 14:07:40 +0200609 status = _PyBytes_Init(tstate);
610 if (_PyStatus_EXCEPTION(status)) {
611 return status;
612 }
613
Victor Stinner281cce12020-06-23 22:55:46 +0200614 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 if (_PyStatus_EXCEPTION(status)) {
616 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100617 }
618
Victor Stinnere7e699e2019-11-20 12:08:13 +0100619 if (is_main_interp) {
620 if (!_PyFloat_Init()) {
621 return _PyStatus_ERR("can't init float");
622 }
Nick Coghland6009512014-11-20 21:39:37 +1000623
Victor Stinnere7e699e2019-11-20 12:08:13 +0100624 if (_PyStructSequence_Init() < 0) {
625 return _PyStatus_ERR("can't initialize structseq");
626 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100627 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200628
Victor Stinner331a6a52019-05-27 16:39:22 +0200629 status = _PyErr_Init();
630 if (_PyStatus_EXCEPTION(status)) {
631 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200632 }
633
Victor Stinnere7e699e2019-11-20 12:08:13 +0100634 if (is_main_interp) {
635 if (!_PyContext_Init()) {
636 return _PyStatus_ERR("can't init context");
637 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100638 }
639
Victor Stinner331a6a52019-05-27 16:39:22 +0200640 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641}
642
643
Victor Stinner331a6a52019-05-27 16:39:22 +0200644static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200645pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100646{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100647 assert(!_PyErr_Occurred(tstate));
648
Victor Stinnerb45d2592019-06-20 00:05:23 +0200649 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100650 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100651 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100652 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100653
Victor Stinner2582d462019-11-22 19:24:49 +0100654 PyInterpreterState *interp = tstate->interp;
655 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
656 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100657 }
Victor Stinner2582d462019-11-22 19:24:49 +0100658
659 PyObject *builtins_dict = PyModule_GetDict(bimod);
660 if (builtins_dict == NULL) {
661 goto error;
662 }
663 Py_INCREF(builtins_dict);
664 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100665
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 PyStatus status = _PyBuiltins_AddExceptions(bimod);
667 if (_PyStatus_EXCEPTION(status)) {
668 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 }
Victor Stinner2582d462019-11-22 19:24:49 +0100670
671 interp->builtins_copy = PyDict_Copy(interp->builtins);
672 if (interp->builtins_copy == NULL) {
673 goto error;
674 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000675 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100676
677 assert(!_PyErr_Occurred(tstate));
678
Victor Stinner331a6a52019-05-27 16:39:22 +0200679 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100680
681error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000682 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100683 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100684}
685
686
Victor Stinner331a6a52019-05-27 16:39:22 +0200687static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200688pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100689{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100690 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200691
Victor Stinner2582d462019-11-22 19:24:49 +0100692 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200693 if (_PyStatus_EXCEPTION(status)) {
694 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800695 }
Nick Coghland6009512014-11-20 21:39:37 +1000696
Victor Stinner30a89332020-06-23 15:55:45 +0200697 /* Initialize _warnings. */
698 status = _PyWarnings_InitState(tstate);
699 if (_PyStatus_EXCEPTION(status)) {
700 return status;
701 }
Nick Coghland6009512014-11-20 21:39:37 +1000702
Victor Stinner30a89332020-06-23 15:55:45 +0200703 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
704 if (config->_install_importlib) {
705 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100706 status = _PyConfig_WritePathConfig(config);
707 if (_PyStatus_EXCEPTION(status)) {
708 return status;
709 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200710 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200711
Victor Stinner30a89332020-06-23 15:55:45 +0200712 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200713 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200714 if (_PyStatus_EXCEPTION(status)) {
715 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 }
Eric Snow1abcf672017-05-23 21:46:51 -0700717 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100718
719 assert(!_PyErr_Occurred(tstate));
720
Victor Stinner331a6a52019-05-27 16:39:22 +0200721 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100722}
723
724
Victor Stinner331a6a52019-05-27 16:39:22 +0200725static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100726pycore_interp_init(PyThreadState *tstate)
727{
728 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100729 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100730
731 status = pycore_init_types(tstate);
732 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100733 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100734 }
735
Victor Stinnerd863ade2019-12-06 03:37:07 +0100736 status = _PySys_Create(tstate, &sysmod);
737 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100738 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100739 }
740
741 status = pycore_init_builtins(tstate);
742 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100743 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100744 }
745
Victor Stinner080ee5a2019-12-08 21:55:58 +0100746 status = pycore_init_import_warnings(tstate, sysmod);
747
748done:
749 /* sys.modules['sys'] contains a strong reference to the module */
750 Py_XDECREF(sysmod);
751 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100752}
753
754
755static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200756pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200757 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200758 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100759{
Victor Stinner331a6a52019-05-27 16:39:22 +0200760 PyStatus status = pycore_init_runtime(runtime, config);
761 if (_PyStatus_EXCEPTION(status)) {
762 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100763 }
764
Victor Stinnerb45d2592019-06-20 00:05:23 +0200765 PyThreadState *tstate;
766 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200767 if (_PyStatus_EXCEPTION(status)) {
768 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100769 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200770 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100771
Victor Stinnerd863ade2019-12-06 03:37:07 +0100772 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200773 if (_PyStatus_EXCEPTION(status)) {
774 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100775 }
Eric Snow1abcf672017-05-23 21:46:51 -0700776
777 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200778 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200779 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700780}
781
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100782
Victor Stinner331a6a52019-05-27 16:39:22 +0200783PyStatus
784_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100785{
Victor Stinner331a6a52019-05-27 16:39:22 +0200786 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100787
Victor Stinner6d1c4672019-05-20 11:02:00 +0200788 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200789 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200790 }
791
Victor Stinner331a6a52019-05-27 16:39:22 +0200792 status = _PyRuntime_Initialize();
793 if (_PyStatus_EXCEPTION(status)) {
794 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100795 }
Victor Stinner43125222019-04-24 18:23:53 +0200796 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100797
Victor Stinnerd3b90412019-09-17 23:59:51 +0200798 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100799 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200800 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100801 }
802
Victor Stinnerd3b90412019-09-17 23:59:51 +0200803 /* Note: preinitialized remains 1 on error, it is only set to 0
804 at exit on success. */
805 runtime->preinitializing = 1;
806
Victor Stinner331a6a52019-05-27 16:39:22 +0200807 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200808
809 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
810 if (_PyStatus_EXCEPTION(status)) {
811 return status;
812 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100813
Victor Stinner331a6a52019-05-27 16:39:22 +0200814 status = _PyPreConfig_Read(&config, args);
815 if (_PyStatus_EXCEPTION(status)) {
816 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100817 }
818
Victor Stinner331a6a52019-05-27 16:39:22 +0200819 status = _PyPreConfig_Write(&config);
820 if (_PyStatus_EXCEPTION(status)) {
821 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100822 }
823
Victor Stinnerd3b90412019-09-17 23:59:51 +0200824 runtime->preinitializing = 0;
825 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100827}
828
Victor Stinner70005ac2019-05-02 15:25:34 -0400829
Victor Stinner331a6a52019-05-27 16:39:22 +0200830PyStatus
831Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100832{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100833 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400834 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100835}
836
837
Victor Stinner331a6a52019-05-27 16:39:22 +0200838PyStatus
839Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100840{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100841 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400842 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100843}
844
845
Victor Stinner331a6a52019-05-27 16:39:22 +0200846PyStatus
847Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100848{
Victor Stinner70005ac2019-05-02 15:25:34 -0400849 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100850}
851
852
Victor Stinner331a6a52019-05-27 16:39:22 +0200853PyStatus
854_Py_PreInitializeFromConfig(const PyConfig *config,
855 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100856{
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200858
Victor Stinner331a6a52019-05-27 16:39:22 +0200859 PyStatus status = _PyRuntime_Initialize();
860 if (_PyStatus_EXCEPTION(status)) {
861 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200862 }
863 _PyRuntimeState *runtime = &_PyRuntime;
864
Victor Stinnerd3b90412019-09-17 23:59:51 +0200865 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200866 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200867 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400868 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200869
Victor Stinner331a6a52019-05-27 16:39:22 +0200870 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200871
Victor Stinner3c30a762019-10-01 10:56:37 +0200872 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200873
Victor Stinner331a6a52019-05-27 16:39:22 +0200874 if (!config->parse_argv) {
875 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200876 }
877 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200878 _PyArgv config_args = {
879 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200880 .argc = config->argv.length,
881 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200882 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200883 }
884 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200885 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200886 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100887}
888
889
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100890/* Begin interpreter initialization
891 *
892 * On return, the first thread and interpreter state have been created,
893 * but the compiler, signal handling, multithreading and
894 * multiple interpreter support, and codec infrastructure are not yet
895 * available.
896 *
897 * The import system will support builtin and frozen modules only.
898 * The only supported io is writing to sys.stderr
899 *
900 * If any operation invoked by this function fails, a fatal error is
901 * issued and the function does not return.
902 *
903 * Any code invoked from this function should *not* assume it has access
904 * to the Python C API (unless the API is explicitly listed as being
905 * safe to call without calling Py_Initialize first)
906 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200907static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200908pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200910 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200911{
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200913
Victor Stinner331a6a52019-05-27 16:39:22 +0200914 status = _Py_PreInitializeFromConfig(src_config, NULL);
915 if (_PyStatus_EXCEPTION(status)) {
916 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200917 }
918
Victor Stinner331a6a52019-05-27 16:39:22 +0200919 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200920 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200921
Victor Stinner331a6a52019-05-27 16:39:22 +0200922 status = _PyConfig_Copy(&config, src_config);
923 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200924 goto done;
925 }
926
Victor Stinner331a6a52019-05-27 16:39:22 +0200927 status = PyConfig_Read(&config);
928 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200929 goto done;
930 }
931
932 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200933 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200934 }
935 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200936 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200937 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200938 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200939 goto done;
940 }
941
942done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200943 PyConfig_Clear(&config);
944 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200945}
946
Victor Stinner5ac27a52019-03-27 13:40:14 +0100947
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200948/* Py_Initialize() has already been called: update the main interpreter
949 configuration. Example of bpo-34008: Py_Main() called after
950 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200951static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100952_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200953{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200954 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100955
Victor Stinner331a6a52019-05-27 16:39:22 +0200956 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100957 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200958 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100959 }
960
Victor Stinnerb0051362019-11-22 17:52:42 +0100961 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100962 Py_DECREF(argv);
963 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200964 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200965 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200967}
968
Victor Stinnerb0051362019-11-22 17:52:42 +0100969
970static PyStatus
971init_interp_main(PyThreadState *tstate)
972{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100973 assert(!_PyErr_Occurred(tstate));
974
Victor Stinnerb0051362019-11-22 17:52:42 +0100975 PyStatus status;
976 int is_main_interp = _Py_IsMainInterpreter(tstate);
977 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200978 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +0100979
980 if (!config->_install_importlib) {
981 /* Special mode for freeze_importlib: run with no import system
982 *
983 * This means anything which needs support from extension modules
984 * or pure Python code in the standard library won't work.
985 */
986 if (is_main_interp) {
987 interp->runtime->initialized = 1;
988 }
989 return _PyStatus_OK();
990 }
991
992 if (is_main_interp) {
993 if (_PyTime_Init() < 0) {
994 return _PyStatus_ERR("can't initialize time");
995 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100996 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100997
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100998 if (_PySys_InitMain(tstate) < 0) {
999 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +01001000 }
1001
1002 status = init_importlib_external(tstate);
1003 if (_PyStatus_EXCEPTION(status)) {
1004 return status;
1005 }
1006
1007 if (is_main_interp) {
1008 /* initialize the faulthandler module */
1009 status = _PyFaulthandler_Init(config->faulthandler);
1010 if (_PyStatus_EXCEPTION(status)) {
1011 return status;
1012 }
1013 }
1014
1015 status = _PyUnicode_InitEncodings(tstate);
1016 if (_PyStatus_EXCEPTION(status)) {
1017 return status;
1018 }
1019
1020 if (is_main_interp) {
1021 if (config->install_signal_handlers) {
1022 status = init_signals(tstate);
1023 if (_PyStatus_EXCEPTION(status)) {
1024 return status;
1025 }
1026 }
1027
1028 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1029 return _PyStatus_ERR("can't initialize tracemalloc");
1030 }
1031 }
1032
1033 status = init_sys_streams(tstate);
1034 if (_PyStatus_EXCEPTION(status)) {
1035 return status;
1036 }
1037
Andy Lester75cd5bf2020-03-12 02:49:05 -05001038 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001039 if (_PyStatus_EXCEPTION(status)) {
1040 return status;
1041 }
1042
1043 status = add_main_module(interp);
1044 if (_PyStatus_EXCEPTION(status)) {
1045 return status;
1046 }
1047
1048 if (is_main_interp) {
1049 /* Initialize warnings. */
1050 PyObject *warnoptions = PySys_GetObject("warnoptions");
1051 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1052 {
1053 PyObject *warnings_module = PyImport_ImportModule("warnings");
1054 if (warnings_module == NULL) {
1055 fprintf(stderr, "'import warnings' failed; traceback:\n");
1056 _PyErr_Print(tstate);
1057 }
1058 Py_XDECREF(warnings_module);
1059 }
1060
1061 interp->runtime->initialized = 1;
1062 }
1063
1064 if (config->site_import) {
1065 status = init_import_site();
1066 if (_PyStatus_EXCEPTION(status)) {
1067 return status;
1068 }
1069 }
1070
1071 if (is_main_interp) {
1072#ifndef MS_WINDOWS
1073 emit_stderr_warning_for_legacy_locale(interp->runtime);
1074#endif
1075 }
1076
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001077 assert(!_PyErr_Occurred(tstate));
1078
Victor Stinnerb0051362019-11-22 17:52:42 +01001079 return _PyStatus_OK();
1080}
1081
1082
Eric Snowc7ec9982017-05-23 23:00:52 -07001083/* Update interpreter state based on supplied configuration settings
1084 *
1085 * After calling this function, most of the restrictions on the interpreter
1086 * are lifted. The only remaining incomplete settings are those related
1087 * to the main module (sys.argv[0], __main__ metadata)
1088 *
1089 * Calling this when the interpreter is not initializing, is already
1090 * initialized or without a valid current thread state is a fatal error.
1091 * Other errors should be reported as normal Python exceptions with a
1092 * non-zero return code.
1093 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001094static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001095pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001096{
Victor Stinnerb0051362019-11-22 17:52:42 +01001097 PyInterpreterState *interp = tstate->interp;
1098 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001099 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001100 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001101
Victor Stinnerb0051362019-11-22 17:52:42 +01001102 if (interp->runtime->initialized) {
1103 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001104 }
1105
Victor Stinnerb0051362019-11-22 17:52:42 +01001106 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001107 if (_PyStatus_EXCEPTION(status)) {
1108 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001109 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001110 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001111}
1112
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001113
Victor Stinner331a6a52019-05-27 16:39:22 +02001114PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001115_Py_InitializeMain(void)
1116{
Victor Stinner331a6a52019-05-27 16:39:22 +02001117 PyStatus status = _PyRuntime_Initialize();
1118 if (_PyStatus_EXCEPTION(status)) {
1119 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001120 }
1121 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001122 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001123 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001124}
1125
1126
Victor Stinner331a6a52019-05-27 16:39:22 +02001127PyStatus
1128Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001129{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001130 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001131 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001132 }
1133
Victor Stinner331a6a52019-05-27 16:39:22 +02001134 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001135
Victor Stinner331a6a52019-05-27 16:39:22 +02001136 status = _PyRuntime_Initialize();
1137 if (_PyStatus_EXCEPTION(status)) {
1138 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001139 }
1140 _PyRuntimeState *runtime = &_PyRuntime;
1141
Victor Stinnerb45d2592019-06-20 00:05:23 +02001142 PyThreadState *tstate = NULL;
1143 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001144 if (_PyStatus_EXCEPTION(status)) {
1145 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001146 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001147 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001148
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001149 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001150 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001151 if (_PyStatus_EXCEPTION(status)) {
1152 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001153 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001154 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001155
Victor Stinner331a6a52019-05-27 16:39:22 +02001156 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001157}
1158
1159
Eric Snow1abcf672017-05-23 21:46:51 -07001160void
Nick Coghland6009512014-11-20 21:39:37 +10001161Py_InitializeEx(int install_sigs)
1162{
Victor Stinner331a6a52019-05-27 16:39:22 +02001163 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001164
Victor Stinner331a6a52019-05-27 16:39:22 +02001165 status = _PyRuntime_Initialize();
1166 if (_PyStatus_EXCEPTION(status)) {
1167 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001168 }
1169 _PyRuntimeState *runtime = &_PyRuntime;
1170
1171 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001172 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1173 return;
1174 }
1175
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001177 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001178
Victor Stinner1dc6e392018-07-25 02:49:17 +02001179 config.install_signal_handlers = install_sigs;
1180
Victor Stinner331a6a52019-05-27 16:39:22 +02001181 status = Py_InitializeFromConfig(&config);
1182 if (_PyStatus_EXCEPTION(status)) {
1183 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001184 }
Nick Coghland6009512014-11-20 21:39:37 +10001185}
1186
1187void
1188Py_Initialize(void)
1189{
1190 Py_InitializeEx(1);
1191}
1192
1193
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001194static void
1195finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1196{
1197 // List of names to clear in sys
1198 static const char * const sys_deletes[] = {
1199 "path", "argv", "ps1", "ps2",
1200 "last_type", "last_value", "last_traceback",
1201 "path_hooks", "path_importer_cache", "meta_path",
1202 "__interactivehook__",
1203 NULL
1204 };
1205
1206 static const char * const sys_files[] = {
1207 "stdin", "__stdin__",
1208 "stdout", "__stdout__",
1209 "stderr", "__stderr__",
1210 NULL
1211 };
1212
1213 PyInterpreterState *interp = tstate->interp;
1214 if (verbose) {
1215 PySys_WriteStderr("# clear builtins._\n");
1216 }
1217 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1218 PyErr_WriteUnraisable(NULL);
1219 }
1220
1221 const char * const *p;
1222 for (p = sys_deletes; *p != NULL; p++) {
1223 if (verbose) {
1224 PySys_WriteStderr("# clear sys.%s\n", *p);
1225 }
1226 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1227 PyErr_WriteUnraisable(NULL);
1228 }
1229 }
1230 for (p = sys_files; *p != NULL; p+=2) {
1231 const char *name = p[0];
1232 const char *orig_name = p[1];
1233 if (verbose) {
1234 PySys_WriteStderr("# restore sys.%s\n", name);
1235 }
1236 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1237 orig_name);
1238 if (value == NULL) {
1239 if (_PyErr_Occurred(tstate)) {
1240 PyErr_WriteUnraisable(NULL);
1241 }
1242 value = Py_None;
1243 }
1244 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1245 PyErr_WriteUnraisable(NULL);
1246 }
1247 }
1248}
1249
1250
1251static PyObject*
1252finalize_remove_modules(PyObject *modules, int verbose)
1253{
1254 PyObject *weaklist = PyList_New(0);
1255 if (weaklist == NULL) {
1256 PyErr_WriteUnraisable(NULL);
1257 }
1258
1259#define STORE_MODULE_WEAKREF(name, mod) \
1260 if (weaklist != NULL) { \
1261 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1262 if (wr) { \
1263 PyObject *tup = PyTuple_Pack(2, name, wr); \
1264 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1265 PyErr_WriteUnraisable(NULL); \
1266 } \
1267 Py_XDECREF(tup); \
1268 Py_DECREF(wr); \
1269 } \
1270 else { \
1271 PyErr_WriteUnraisable(NULL); \
1272 } \
1273 }
1274
1275#define CLEAR_MODULE(name, mod) \
1276 if (PyModule_Check(mod)) { \
1277 if (verbose && PyUnicode_Check(name)) { \
1278 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1279 } \
1280 STORE_MODULE_WEAKREF(name, mod); \
1281 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1282 PyErr_WriteUnraisable(NULL); \
1283 } \
1284 }
1285
1286 if (PyDict_CheckExact(modules)) {
1287 Py_ssize_t pos = 0;
1288 PyObject *key, *value;
1289 while (PyDict_Next(modules, &pos, &key, &value)) {
1290 CLEAR_MODULE(key, value);
1291 }
1292 }
1293 else {
1294 PyObject *iterator = PyObject_GetIter(modules);
1295 if (iterator == NULL) {
1296 PyErr_WriteUnraisable(NULL);
1297 }
1298 else {
1299 PyObject *key;
1300 while ((key = PyIter_Next(iterator))) {
1301 PyObject *value = PyObject_GetItem(modules, key);
1302 if (value == NULL) {
1303 PyErr_WriteUnraisable(NULL);
1304 continue;
1305 }
1306 CLEAR_MODULE(key, value);
1307 Py_DECREF(value);
1308 Py_DECREF(key);
1309 }
1310 if (PyErr_Occurred()) {
1311 PyErr_WriteUnraisable(NULL);
1312 }
1313 Py_DECREF(iterator);
1314 }
1315 }
1316#undef CLEAR_MODULE
1317#undef STORE_MODULE_WEAKREF
1318
1319 return weaklist;
1320}
1321
1322
1323static void
1324finalize_clear_modules_dict(PyObject *modules)
1325{
1326 if (PyDict_CheckExact(modules)) {
1327 PyDict_Clear(modules);
1328 }
1329 else {
1330 _Py_IDENTIFIER(clear);
1331 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1332 PyErr_WriteUnraisable(NULL);
1333 }
1334 }
1335}
1336
1337
1338static void
1339finalize_restore_builtins(PyThreadState *tstate)
1340{
1341 PyInterpreterState *interp = tstate->interp;
1342 PyObject *dict = PyDict_Copy(interp->builtins);
1343 if (dict == NULL) {
1344 PyErr_WriteUnraisable(NULL);
1345 }
1346 PyDict_Clear(interp->builtins);
1347 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1348 _PyErr_Clear(tstate);
1349 }
1350 Py_XDECREF(dict);
1351}
1352
1353
1354static void
1355finalize_modules_clear_weaklist(PyInterpreterState *interp,
1356 PyObject *weaklist, int verbose)
1357{
1358 // First clear modules imported later
1359 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1360 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1361 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1362 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1363 if (mod == Py_None) {
1364 continue;
1365 }
1366 assert(PyModule_Check(mod));
1367 PyObject *dict = PyModule_GetDict(mod);
1368 if (dict == interp->builtins || dict == interp->sysdict) {
1369 continue;
1370 }
1371 Py_INCREF(mod);
1372 if (verbose && PyUnicode_Check(name)) {
1373 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1374 }
1375 _PyModule_Clear(mod);
1376 Py_DECREF(mod);
1377 }
1378}
1379
1380
1381static void
1382finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1383{
1384 // Clear sys dict
1385 if (verbose) {
1386 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1387 }
1388 _PyModule_ClearDict(interp->sysdict);
1389
1390 // Clear builtins dict
1391 if (verbose) {
1392 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1393 }
1394 _PyModule_ClearDict(interp->builtins);
1395}
1396
1397
1398/* Clear modules, as good as we can */
1399static void
1400finalize_modules(PyThreadState *tstate)
1401{
1402 PyInterpreterState *interp = tstate->interp;
1403 PyObject *modules = interp->modules;
1404 if (modules == NULL) {
1405 // Already done
1406 return;
1407 }
1408 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1409
1410 // Delete some special builtins._ and sys attributes first. These are
1411 // common places where user values hide and people complain when their
1412 // destructors fail. Since the modules containing them are
1413 // deleted *last* of all, they would come too late in the normal
1414 // destruction order. Sigh.
1415 //
1416 // XXX Perhaps these precautions are obsolete. Who knows?
1417 finalize_modules_delete_special(tstate, verbose);
1418
1419 // Remove all modules from sys.modules, hoping that garbage collection
1420 // can reclaim most of them: set all sys.modules values to None.
1421 //
1422 // We prepare a list which will receive (name, weakref) tuples of
1423 // modules when they are removed from sys.modules. The name is used
1424 // for diagnosis messages (in verbose mode), while the weakref helps
1425 // detect those modules which have been held alive.
1426 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1427
1428 // Clear the modules dict
1429 finalize_clear_modules_dict(modules);
1430
1431 // Restore the original builtins dict, to ensure that any
1432 // user data gets cleared.
1433 finalize_restore_builtins(tstate);
1434
1435 // Collect garbage
1436 _PyGC_CollectNoFail(tstate);
1437
1438 // Dump GC stats before it's too late, since it uses the warnings
1439 // machinery.
1440 _PyGC_DumpShutdownStats(tstate);
1441
1442 if (weaklist != NULL) {
1443 // Now, if there are any modules left alive, clear their globals to
1444 // minimize potential leaks. All C extension modules actually end
1445 // up here, since they are kept alive in the interpreter state.
1446 //
1447 // The special treatment of "builtins" here is because even
1448 // when it's not referenced as a module, its dictionary is
1449 // referenced by almost every module's __builtins__. Since
1450 // deleting a module clears its dictionary (even if there are
1451 // references left to it), we need to delete the "builtins"
1452 // module last. Likewise, we don't delete sys until the very
1453 // end because it is implicitly referenced (e.g. by print).
1454 //
1455 // Since dict is ordered in CPython 3.6+, modules are saved in
1456 // importing order. First clear modules imported later.
1457 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1458 Py_DECREF(weaklist);
1459 }
1460
1461 // Clear sys and builtins modules dict
1462 finalize_clear_sys_builtins_dict(interp, verbose);
1463
1464 // Clear module dict copies stored in the interpreter state:
1465 // clear PyInterpreterState.modules_by_index and
1466 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1467 // initialization API)
1468 _PyInterpreterState_ClearModules(interp);
1469
1470 // Clear and delete the modules directory. Actual modules will
1471 // still be there only if imported during the execution of some
1472 // destructor.
1473 Py_SETREF(interp->modules, NULL);
1474
1475 // Collect garbage once more
1476 _PyGC_CollectNoFail(tstate);
1477}
1478
1479
Nick Coghland6009512014-11-20 21:39:37 +10001480/* Flush stdout and stderr */
1481
1482static int
1483file_is_closed(PyObject *fobj)
1484{
1485 int r;
1486 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1487 if (tmp == NULL) {
1488 PyErr_Clear();
1489 return 0;
1490 }
1491 r = PyObject_IsTrue(tmp);
1492 Py_DECREF(tmp);
1493 if (r < 0)
1494 PyErr_Clear();
1495 return r > 0;
1496}
1497
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001498
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001499static int
Nick Coghland6009512014-11-20 21:39:37 +10001500flush_std_files(void)
1501{
1502 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1503 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1504 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001505 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001506
1507 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001508 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001509 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001510 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001511 status = -1;
1512 }
Nick Coghland6009512014-11-20 21:39:37 +10001513 else
1514 Py_DECREF(tmp);
1515 }
1516
1517 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001518 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001519 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001520 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001521 status = -1;
1522 }
Nick Coghland6009512014-11-20 21:39:37 +10001523 else
1524 Py_DECREF(tmp);
1525 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001526
1527 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001528}
1529
1530/* Undo the effect of Py_Initialize().
1531
1532 Beware: if multiple interpreter and/or thread states exist, these
1533 are not wiped out; only the current thread and interpreter state
1534 are deleted. But since everything else is deleted, those other
1535 interpreter and thread states should no longer be used.
1536
1537 (XXX We should do better, e.g. wipe out all interpreters and
1538 threads.)
1539
1540 Locking: as above.
1541
1542*/
1543
Victor Stinner7eee5be2019-11-20 10:38:34 +01001544
1545static void
Victor Stinner90db4652020-07-01 23:21:36 +02001546finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001547{
Victor Stinnere5fbe0c2020-09-15 18:03:34 +02001548 // The _ast module state is shared by all interpreters.
1549 // The state must only be cleared by the main interpreter.
1550 if (_Py_IsMainInterpreter(tstate)) {
1551 _PyAST_Fini(tstate);
1552 }
1553
Victor Stinner281cce12020-06-23 22:55:46 +02001554 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001555 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001556 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001557 _PyContext_Fini(tstate);
Victor Stinner666ecfb2020-07-02 01:19:57 +02001558 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001559
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001560 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001561 _PyList_Fini(tstate);
1562 _PyTuple_Fini(tstate);
1563
1564 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001565
Victor Stinnerc41eed12020-06-23 15:54:35 +02001566 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001567 _PyUnicode_Fini(tstate);
1568 _PyFloat_Fini(tstate);
1569 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001570}
1571
1572
1573static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001574finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001575{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001576 int is_main_interp = _Py_IsMainInterpreter(tstate);
1577
Victor Stinner7eee5be2019-11-20 10:38:34 +01001578 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001579 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001580
Kongedaa0fe02020-07-04 05:06:46 +08001581 /* Clear all loghooks */
1582 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1583 Call _PySys_ClearAuditHooks when PyObject available. */
1584 if (is_main_interp) {
1585 _PySys_ClearAuditHooks(tstate);
1586 }
1587
Victor Stinner7907f8c2020-06-08 01:22:36 +02001588 if (is_main_interp) {
1589 _Py_HashRandomization_Fini();
1590 _PyArg_Fini();
1591 _Py_ClearFileSystemEncoding();
1592 }
1593
1594 _PyWarnings_Fini(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001595
Victor Stinner90db4652020-07-01 23:21:36 +02001596 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001597}
1598
1599
1600static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001601finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001602{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001603 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001604 /* Cleanup auto-thread-state */
1605 _PyGILState_Fini(tstate);
1606 }
1607
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001608 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1609 fail when it is being awaited by another running daemon thread (see
1610 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1611 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1612 called multiple times. */
1613
Victor Stinner7eee5be2019-11-20 10:38:34 +01001614 PyInterpreterState_Delete(tstate->interp);
1615}
1616
1617
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001618int
1619Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001620{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001621 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001622
Victor Stinner8e91c242019-04-24 17:24:01 +02001623 _PyRuntimeState *runtime = &_PyRuntime;
1624 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001625 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001626 }
Nick Coghland6009512014-11-20 21:39:37 +10001627
Victor Stinnere225beb2019-06-03 18:14:24 +02001628 /* Get current thread state and interpreter pointer */
1629 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1630 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001631
Victor Stinnerb45d2592019-06-20 00:05:23 +02001632 // Wrap up existing "threading"-module-created, non-daemon threads.
1633 wait_for_thread_shutdown(tstate);
1634
1635 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001636 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001637
Nick Coghland6009512014-11-20 21:39:37 +10001638 /* The interpreter is still entirely intact at this point, and the
1639 * exit funcs may be relying on that. In particular, if some thread
1640 * or exit func is still waiting to do an import, the import machinery
1641 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001642 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001643 * Note that Threading.py uses an exit func to do a join on all the
1644 * threads created thru it, so this also protects pending imports in
1645 * the threads created via Threading.
1646 */
Nick Coghland6009512014-11-20 21:39:37 +10001647
Victor Stinnerb45d2592019-06-20 00:05:23 +02001648 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001649
Victor Stinnerda273412017-12-15 01:46:02 +01001650 /* Copy the core config, PyInterpreterState_Delete() free
1651 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001652#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001653 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001654#endif
1655#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001656 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001657#endif
1658#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001659 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001660#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001661
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001662 /* Remaining daemon threads will automatically exit
1663 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001664 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001665 runtime->initialized = 0;
1666 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001667
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001668 /* Destroy the state of all threads of the interpreter, except of the
1669 current thread. In practice, only daemon threads should still be alive,
1670 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1671 Clear frames of other threads to call objects destructors. Destructors
1672 will be called in the current Python thread. Since
1673 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1674 can take the GIL at this point: if they try, they will exit
1675 immediately. */
1676 _PyThreadState_DeleteExcept(runtime, tstate);
1677
Victor Stinnere0deff32015-03-24 13:46:18 +01001678 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001679 if (flush_std_files() < 0) {
1680 status = -1;
1681 }
Nick Coghland6009512014-11-20 21:39:37 +10001682
1683 /* Disable signal handling */
1684 PyOS_FiniInterrupts();
1685
1686 /* Collect garbage. This may call finalizers; it's nice to call these
1687 * before all modules are destroyed.
1688 * XXX If a __del__ or weakref callback is triggered here, and tries to
1689 * XXX import a module, bad things can happen, because Python no
1690 * XXX longer believes it's initialized.
1691 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1692 * XXX is easy to provoke that way. I've also seen, e.g.,
1693 * XXX Exception exceptions.ImportError: 'No module named sha'
1694 * XXX in <function callback at 0x008F5718> ignored
1695 * XXX but I'm unclear on exactly how that one happens. In any case,
1696 * XXX I haven't seen a real-life report of either of these.
1697 */
Victor Stinner8b341482020-10-30 17:00:00 +01001698 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001699
Nick Coghland6009512014-11-20 21:39:37 +10001700 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001701 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001702
Inada Naoki91234a12019-06-03 21:30:58 +09001703 /* Print debug stats if any */
1704 _PyEval_Fini();
1705
Victor Stinnere0deff32015-03-24 13:46:18 +01001706 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001707 if (flush_std_files() < 0) {
1708 status = -1;
1709 }
Nick Coghland6009512014-11-20 21:39:37 +10001710
1711 /* Collect final garbage. This disposes of cycles created by
1712 * class definitions, for example.
1713 * XXX This is disabled because it caused too many problems. If
1714 * XXX a __del__ or weakref callback triggers here, Python code has
1715 * XXX a hard time running, because even the sys module has been
1716 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1717 * XXX One symptom is a sequence of information-free messages
1718 * XXX coming from threads (if a __del__ or callback is invoked,
1719 * XXX other threads can execute too, and any exception they encounter
1720 * XXX triggers a comedy of errors as subsystem after subsystem
1721 * XXX fails to find what it *expects* to find in sys to help report
1722 * XXX the exception and consequent unexpected failures). I've also
1723 * XXX seen segfaults then, after adding print statements to the
1724 * XXX Python code getting called.
1725 */
1726#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001727 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001728#endif
1729
1730 /* Disable tracemalloc after all Python objects have been destroyed,
1731 so it is possible to use tracemalloc in objects destructor. */
1732 _PyTraceMalloc_Fini();
1733
1734 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1735 _PyImport_Fini();
1736
1737 /* Cleanup typeobject.c's internal caches. */
1738 _PyType_Fini();
1739
1740 /* unload faulthandler module */
1741 _PyFaulthandler_Fini();
1742
Nick Coghland6009512014-11-20 21:39:37 +10001743 /* dump hash stats */
1744 _PyHash_Fini();
1745
Eric Snowdae02762017-09-14 00:35:58 -07001746#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001747 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001748 _PyDebug_PrintTotalRefs();
1749 }
Eric Snowdae02762017-09-14 00:35:58 -07001750#endif
Nick Coghland6009512014-11-20 21:39:37 +10001751
1752#ifdef Py_TRACE_REFS
1753 /* Display all objects still alive -- this can invoke arbitrary
1754 * __repr__ overrides, so requires a mostly-intact interpreter.
1755 * Alas, a lot of stuff may still be alive now that will be cleaned
1756 * up later.
1757 */
Victor Stinnerda273412017-12-15 01:46:02 +01001758 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001759 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001760 }
Nick Coghland6009512014-11-20 21:39:37 +10001761#endif /* Py_TRACE_REFS */
1762
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001763 finalize_interp_clear(tstate);
1764 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001765
1766#ifdef Py_TRACE_REFS
1767 /* Display addresses (& refcnts) of all objects still alive.
1768 * An address can be used to find the repr of the object, printed
1769 * above by _Py_PrintReferences.
1770 */
Victor Stinnerda273412017-12-15 01:46:02 +01001771 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001772 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001773 }
Nick Coghland6009512014-11-20 21:39:37 +10001774#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001775#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001776 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001777 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001778 }
Nick Coghland6009512014-11-20 21:39:37 +10001779#endif
1780
Victor Stinner8e91c242019-04-24 17:24:01 +02001781 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001782
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001783 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001784 return status;
1785}
1786
1787void
1788Py_Finalize(void)
1789{
1790 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001791}
1792
Victor Stinnerb0051362019-11-22 17:52:42 +01001793
Nick Coghland6009512014-11-20 21:39:37 +10001794/* Create and initialize a new interpreter and thread, and return the
1795 new thread. This requires that Py_Initialize() has been called
1796 first.
1797
1798 Unsuccessful initialization yields a NULL pointer. Note that *no*
1799 exception information is available even in this case -- the
1800 exception information is held in the thread, and there is no
1801 thread.
1802
1803 Locking: as above.
1804
1805*/
1806
Victor Stinner331a6a52019-05-27 16:39:22 +02001807static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001808new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001809{
Victor Stinner331a6a52019-05-27 16:39:22 +02001810 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001811
Victor Stinner331a6a52019-05-27 16:39:22 +02001812 status = _PyRuntime_Initialize();
1813 if (_PyStatus_EXCEPTION(status)) {
1814 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001815 }
1816 _PyRuntimeState *runtime = &_PyRuntime;
1817
1818 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001819 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001820 }
Nick Coghland6009512014-11-20 21:39:37 +10001821
Victor Stinner8a1be612016-03-14 22:07:55 +01001822 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1823 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001824 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001825
Victor Stinner43125222019-04-24 18:23:53 +02001826 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001827 if (interp == NULL) {
1828 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001829 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001830 }
Nick Coghland6009512014-11-20 21:39:37 +10001831
Victor Stinner43125222019-04-24 18:23:53 +02001832 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001833 if (tstate == NULL) {
1834 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001835 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001836 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001837 }
1838
Victor Stinner43125222019-04-24 18:23:53 +02001839 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001840
Eric Snow1abcf672017-05-23 21:46:51 -07001841 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001842 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001843#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001844 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001845 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001846 }
1847 else
1848#endif
1849 {
Eric Snow1abcf672017-05-23 21:46:51 -07001850 /* No current thread state, copy from the main interpreter */
1851 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001852 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001853 }
1854
Victor Stinnerda7933e2020-04-13 03:04:28 +02001855 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001856 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001857 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001858 }
Victor Stinner252346a2020-05-01 11:33:44 +02001859 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001860
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001861 status = init_interp_create_gil(tstate);
1862 if (_PyStatus_EXCEPTION(status)) {
1863 goto error;
1864 }
1865
Victor Stinnerd863ade2019-12-06 03:37:07 +01001866 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001867 if (_PyStatus_EXCEPTION(status)) {
1868 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001869 }
1870
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001871 status = init_interp_main(tstate);
1872 if (_PyStatus_EXCEPTION(status)) {
1873 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001874 }
Nick Coghland6009512014-11-20 21:39:37 +10001875
Victor Stinnera7368ac2017-11-15 18:11:45 -08001876 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001877 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001878
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001879error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001880 *tstate_p = NULL;
1881
1882 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001883 PyErr_PrintEx(0);
1884 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001885 PyThreadState_Delete(tstate);
1886 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001887 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001888
Victor Stinnerb0051362019-11-22 17:52:42 +01001889 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001890}
1891
1892PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001893_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001894{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001895 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001896 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001897 if (_PyStatus_EXCEPTION(status)) {
1898 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001899 }
1900 return tstate;
1901
Nick Coghland6009512014-11-20 21:39:37 +10001902}
1903
Victor Stinner252346a2020-05-01 11:33:44 +02001904PyThreadState *
1905Py_NewInterpreter(void)
1906{
1907 return _Py_NewInterpreter(0);
1908}
1909
Nick Coghland6009512014-11-20 21:39:37 +10001910/* Delete an interpreter and its last thread. This requires that the
1911 given thread state is current, that the thread has no remaining
1912 frames, and that it is its interpreter's only remaining thread.
1913 It is a fatal error to violate these constraints.
1914
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001915 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001916 everything, regardless.)
1917
1918 Locking: as above.
1919
1920*/
1921
1922void
1923Py_EndInterpreter(PyThreadState *tstate)
1924{
1925 PyInterpreterState *interp = tstate->interp;
1926
Victor Stinnerb45d2592019-06-20 00:05:23 +02001927 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001928 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001929 }
1930 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001931 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001932 }
Eric Snow5be45a62019-03-08 22:47:07 -07001933 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001934
Eric Snow842a2f02019-03-15 15:47:51 -06001935 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001936 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001937
Victor Stinnerb45d2592019-06-20 00:05:23 +02001938 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001939
Victor Stinnerb45d2592019-06-20 00:05:23 +02001940 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001941 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001942 }
Nick Coghland6009512014-11-20 21:39:37 +10001943
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001944 finalize_modules(tstate);
1945
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001946 finalize_interp_clear(tstate);
1947 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001948}
1949
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001950/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001951
Victor Stinner331a6a52019-05-27 16:39:22 +02001952static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001953add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001954{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001955 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001956 m = PyImport_AddModule("__main__");
1957 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001958 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001959
Nick Coghland6009512014-11-20 21:39:37 +10001960 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001961 ann_dict = PyDict_New();
1962 if ((ann_dict == NULL) ||
1963 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001964 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001965 }
1966 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001967
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001968 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1969 if (PyErr_Occurred()) {
1970 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1971 }
Nick Coghland6009512014-11-20 21:39:37 +10001972 PyObject *bimod = PyImport_ImportModule("builtins");
1973 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001974 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001975 }
1976 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001977 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001978 }
1979 Py_DECREF(bimod);
1980 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001981
Nick Coghland6009512014-11-20 21:39:37 +10001982 /* Main is a little special - imp.is_builtin("__main__") will return
1983 * False, but BuiltinImporter is still the most appropriate initial
1984 * setting for its __loader__ attribute. A more suitable value will
1985 * be set if __main__ gets further initialized later in the startup
1986 * process.
1987 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001988 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001989 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001990 if (PyErr_Occurred()) {
1991 return _PyStatus_ERR("Failed to test __main__.__loader__");
1992 }
Nick Coghland6009512014-11-20 21:39:37 +10001993 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1994 "BuiltinImporter");
1995 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001996 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001997 }
1998 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001999 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002000 }
2001 Py_DECREF(loader);
2002 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002003 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002004}
2005
Nick Coghland6009512014-11-20 21:39:37 +10002006/* Import the site module (not into __main__ though) */
2007
Victor Stinner331a6a52019-05-27 16:39:22 +02002008static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002009init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002010{
2011 PyObject *m;
2012 m = PyImport_ImportModule("site");
2013 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002014 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002015 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002016 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002017 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002018}
2019
Victor Stinner874dbe82015-09-04 17:29:57 +02002020/* Check if a file descriptor is valid or not.
2021 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2022static int
2023is_valid_fd(int fd)
2024{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002025/* dup() is faster than fstat(): fstat() can require input/output operations,
2026 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2027 startup. Problem: dup() doesn't check if the file descriptor is valid on
2028 some platforms.
2029
2030 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2031 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2032 EBADF. FreeBSD has similar issue (bpo-32849).
2033
2034 Only use dup() on platforms where dup() is enough to detect invalid FD in
2035 corner cases: on Linux and Windows (bpo-32849). */
2036#if defined(__linux__) || defined(MS_WINDOWS)
2037 if (fd < 0) {
2038 return 0;
2039 }
2040 int fd2;
2041
2042 _Py_BEGIN_SUPPRESS_IPH
2043 fd2 = dup(fd);
2044 if (fd2 >= 0) {
2045 close(fd2);
2046 }
2047 _Py_END_SUPPRESS_IPH
2048
2049 return (fd2 >= 0);
2050#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002051 struct stat st;
2052 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002053#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002054}
2055
2056/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002057static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002058create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002059 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002060 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002061{
2062 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2063 const char* mode;
2064 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002065 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002066 int buffering, isatty;
2067 _Py_IDENTIFIER(open);
2068 _Py_IDENTIFIER(isatty);
2069 _Py_IDENTIFIER(TextIOWrapper);
2070 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002071 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002072
Victor Stinner874dbe82015-09-04 17:29:57 +02002073 if (!is_valid_fd(fd))
2074 Py_RETURN_NONE;
2075
Nick Coghland6009512014-11-20 21:39:37 +10002076 /* stdin is always opened in buffered mode, first because it shouldn't
2077 make a difference in common use cases, second because TextIOWrapper
2078 depends on the presence of a read1() method which only exists on
2079 buffered streams.
2080 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002081 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002082 buffering = 0;
2083 else
2084 buffering = -1;
2085 if (write_mode)
2086 mode = "wb";
2087 else
2088 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002089 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002090 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002091 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002092 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002093 if (buf == NULL)
2094 goto error;
2095
2096 if (buffering) {
2097 _Py_IDENTIFIER(raw);
2098 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2099 if (raw == NULL)
2100 goto error;
2101 }
2102 else {
2103 raw = buf;
2104 Py_INCREF(raw);
2105 }
2106
Steve Dower39294992016-08-30 21:22:36 -07002107#ifdef MS_WINDOWS
2108 /* Windows console IO is always UTF-8 encoded */
2109 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002110 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002111#endif
2112
Nick Coghland6009512014-11-20 21:39:37 +10002113 text = PyUnicode_FromString(name);
2114 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2115 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002116 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002117 if (res == NULL)
2118 goto error;
2119 isatty = PyObject_IsTrue(res);
2120 Py_DECREF(res);
2121 if (isatty == -1)
2122 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002123 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002124 write_through = Py_True;
2125 else
2126 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002127 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002128 line_buffering = Py_True;
2129 else
2130 line_buffering = Py_False;
2131
2132 Py_CLEAR(raw);
2133 Py_CLEAR(text);
2134
2135#ifdef MS_WINDOWS
2136 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2137 newlines to "\n".
2138 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2139 newline = NULL;
2140#else
2141 /* sys.stdin: split lines at "\n".
2142 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2143 newline = "\n";
2144#endif
2145
Victor Stinner709d23d2019-05-02 14:56:30 -04002146 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2147 if (encoding_str == NULL) {
2148 Py_CLEAR(buf);
2149 goto error;
2150 }
2151
2152 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2153 if (errors_str == NULL) {
2154 Py_CLEAR(buf);
2155 Py_CLEAR(encoding_str);
2156 goto error;
2157 }
2158
2159 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2160 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002161 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002162 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002163 Py_CLEAR(encoding_str);
2164 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002165 if (stream == NULL)
2166 goto error;
2167
2168 if (write_mode)
2169 mode = "w";
2170 else
2171 mode = "r";
2172 text = PyUnicode_FromString(mode);
2173 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2174 goto error;
2175 Py_CLEAR(text);
2176 return stream;
2177
2178error:
2179 Py_XDECREF(buf);
2180 Py_XDECREF(stream);
2181 Py_XDECREF(text);
2182 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002183
Victor Stinner874dbe82015-09-04 17:29:57 +02002184 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2185 /* Issue #24891: the file descriptor was closed after the first
2186 is_valid_fd() check was called. Ignore the OSError and set the
2187 stream to None. */
2188 PyErr_Clear();
2189 Py_RETURN_NONE;
2190 }
2191 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002192}
2193
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002194/* Set builtins.open to io.OpenWrapper */
2195static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002196init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002197{
2198 PyObject *iomod = NULL, *wrapper;
2199 PyObject *bimod = NULL;
2200 PyStatus res = _PyStatus_OK();
2201
2202 if (!(iomod = PyImport_ImportModule("io"))) {
2203 goto error;
2204 }
2205
2206 if (!(bimod = PyImport_ImportModule("builtins"))) {
2207 goto error;
2208 }
2209
2210 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2211 goto error;
2212 }
2213
2214 /* Set builtins.open */
2215 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2216 Py_DECREF(wrapper);
2217 goto error;
2218 }
2219 Py_DECREF(wrapper);
2220 goto done;
2221
2222error:
2223 res = _PyStatus_ERR("can't initialize io.open");
2224
2225done:
2226 Py_XDECREF(bimod);
2227 Py_XDECREF(iomod);
2228 return res;
2229}
2230
2231
Nick Coghland6009512014-11-20 21:39:37 +10002232/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002233static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002234init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002235{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002236 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002237 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002238 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002239 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002240 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002241 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002242
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002243 /* Check that stdin is not a directory
2244 Using shell redirection, you can redirect stdin to a directory,
2245 crashing the Python interpreter. Catch this common mistake here
2246 and output a useful error message. Note that under MS Windows,
2247 the shell already prevents that. */
2248#ifndef MS_WINDOWS
2249 struct _Py_stat_struct sb;
2250 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2251 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002252 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002253 }
2254#endif
2255
Nick Coghland6009512014-11-20 21:39:37 +10002256 if (!(iomod = PyImport_ImportModule("io"))) {
2257 goto error;
2258 }
Nick Coghland6009512014-11-20 21:39:37 +10002259
Nick Coghland6009512014-11-20 21:39:37 +10002260 /* Set sys.stdin */
2261 fd = fileno(stdin);
2262 /* Under some conditions stdin, stdout and stderr may not be connected
2263 * and fileno() may point to an invalid file descriptor. For example
2264 * GUI apps don't have valid standard streams by default.
2265 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002266 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002267 config->stdio_encoding,
2268 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002269 if (std == NULL)
2270 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002271 PySys_SetObject("__stdin__", std);
2272 _PySys_SetObjectId(&PyId_stdin, std);
2273 Py_DECREF(std);
2274
2275 /* Set sys.stdout */
2276 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002277 std = create_stdio(config, iomod, fd, 1, "<stdout>",
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("__stdout__", std);
2283 _PySys_SetObjectId(&PyId_stdout, std);
2284 Py_DECREF(std);
2285
2286#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2287 /* Set sys.stderr, replaces the preliminary stderr */
2288 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002289 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002290 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002291 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002292 if (std == NULL)
2293 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002294
2295 /* Same as hack above, pre-import stderr's codec to avoid recursion
2296 when import.c tries to write to stderr in verbose mode. */
2297 encoding_attr = PyObject_GetAttrString(std, "encoding");
2298 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002299 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002300 if (std_encoding != NULL) {
2301 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2302 Py_XDECREF(codec_info);
2303 }
2304 Py_DECREF(encoding_attr);
2305 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002306 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002307
2308 if (PySys_SetObject("__stderr__", std) < 0) {
2309 Py_DECREF(std);
2310 goto error;
2311 }
2312 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2313 Py_DECREF(std);
2314 goto error;
2315 }
2316 Py_DECREF(std);
2317#endif
2318
Victor Stinnera7368ac2017-11-15 18:11:45 -08002319 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002320
Victor Stinnera7368ac2017-11-15 18:11:45 -08002321error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002322 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002323
2324done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002325 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002326 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002327 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002328}
2329
2330
Victor Stinner10dc4842015-03-24 12:01:30 +01002331static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002332_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2333 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002334{
Victor Stinner10dc4842015-03-24 12:01:30 +01002335 fputc('\n', stderr);
2336 fflush(stderr);
2337
2338 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002339 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002340}
Victor Stinner791da1c2016-03-14 16:53:12 +01002341
2342/* Print the current exception (if an exception is set) with its traceback,
2343 or display the current Python stack.
2344
2345 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2346 called on catastrophic cases.
2347
2348 Return 1 if the traceback was displayed, 0 otherwise. */
2349
2350static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002351_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002352{
2353 PyObject *ferr, *res;
2354 PyObject *exception, *v, *tb;
2355 int has_tb;
2356
Victor Stinnerb45d2592019-06-20 00:05:23 +02002357 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002358 if (exception == NULL) {
2359 /* No current exception */
2360 return 0;
2361 }
2362
2363 ferr = _PySys_GetObjectId(&PyId_stderr);
2364 if (ferr == NULL || ferr == Py_None) {
2365 /* sys.stderr is not set yet or set to None,
2366 no need to try to display the exception */
2367 return 0;
2368 }
2369
Victor Stinnerb45d2592019-06-20 00:05:23 +02002370 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002371 if (tb == NULL) {
2372 tb = Py_None;
2373 Py_INCREF(tb);
2374 }
2375 PyException_SetTraceback(v, tb);
2376 if (exception == NULL) {
2377 /* PyErr_NormalizeException() failed */
2378 return 0;
2379 }
2380
2381 has_tb = (tb != Py_None);
2382 PyErr_Display(exception, v, tb);
2383 Py_XDECREF(exception);
2384 Py_XDECREF(v);
2385 Py_XDECREF(tb);
2386
2387 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002388 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002389 if (res == NULL) {
2390 _PyErr_Clear(tstate);
2391 }
2392 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002393 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002394 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002395
2396 return has_tb;
2397}
2398
Nick Coghland6009512014-11-20 21:39:37 +10002399/* Print fatal error message and abort */
2400
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002401#ifdef MS_WINDOWS
2402static void
2403fatal_output_debug(const char *msg)
2404{
2405 /* buffer of 256 bytes allocated on the stack */
2406 WCHAR buffer[256 / sizeof(WCHAR)];
2407 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2408 size_t msglen;
2409
2410 OutputDebugStringW(L"Fatal Python error: ");
2411
2412 msglen = strlen(msg);
2413 while (msglen) {
2414 size_t i;
2415
2416 if (buflen > msglen) {
2417 buflen = msglen;
2418 }
2419
2420 /* Convert the message to wchar_t. This uses a simple one-to-one
2421 conversion, assuming that the this error message actually uses
2422 ASCII only. If this ceases to be true, we will have to convert. */
2423 for (i=0; i < buflen; ++i) {
2424 buffer[i] = msg[i];
2425 }
2426 buffer[i] = L'\0';
2427 OutputDebugStringW(buffer);
2428
2429 msg += buflen;
2430 msglen -= buflen;
2431 }
2432 OutputDebugStringW(L"\n");
2433}
2434#endif
2435
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002436
2437static void
2438fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2439{
2440 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002441 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2442 if (finalizing) {
2443 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002444 }
2445 else if (runtime->initialized) {
2446 fprintf(stream, "initialized");
2447 }
2448 else if (runtime->core_initialized) {
2449 fprintf(stream, "core initialized");
2450 }
2451 else if (runtime->preinitialized) {
2452 fprintf(stream, "preinitialized");
2453 }
2454 else if (runtime->preinitializing) {
2455 fprintf(stream, "preinitializing");
2456 }
2457 else {
2458 fprintf(stream, "unknown");
2459 }
2460 fprintf(stream, "\n");
2461 fflush(stream);
2462}
2463
2464
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002465static inline void _Py_NO_RETURN
2466fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002467{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002468 if (status < 0) {
2469#if defined(MS_WINDOWS) && defined(_DEBUG)
2470 DebugBreak();
2471#endif
2472 abort();
2473 }
2474 else {
2475 exit(status);
2476 }
2477}
2478
2479
2480static void _Py_NO_RETURN
2481fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2482 int status)
2483{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002484 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002485 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002486
2487 if (reentrant) {
2488 /* Py_FatalError() caused a second fatal error.
2489 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002490 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002491 }
2492 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002493
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002494 if (header) {
2495 fprintf(stream, "Fatal Python error: ");
2496 if (prefix) {
2497 fputs(prefix, stream);
2498 fputs(": ", stream);
2499 }
2500 if (msg) {
2501 fputs(msg, stream);
2502 }
2503 else {
2504 fprintf(stream, "<message not set>");
2505 }
2506 fputs("\n", stream);
2507 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002508 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002509
2510 _PyRuntimeState *runtime = &_PyRuntime;
2511 fatal_error_dump_runtime(stream, runtime);
2512
2513 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2514 PyInterpreterState *interp = NULL;
2515 if (tstate != NULL) {
2516 interp = tstate->interp;
2517 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002518
Victor Stinner3a228ab2018-11-01 00:26:41 +01002519 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002520 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002521
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002522 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2523 has no Python thread state.
2524
2525 tss_tstate != tstate if the current Python thread does not hold the GIL.
2526 */
2527 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2528 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002529 if (has_tstate_and_gil) {
2530 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002531 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002532 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002533 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002534 }
2535 }
2536 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002537 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002538 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002539
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002540 /* The main purpose of faulthandler is to display the traceback.
2541 This function already did its best to display a traceback.
2542 Disable faulthandler to prevent writing a second traceback
2543 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002544 _PyFaulthandler_Fini();
2545
Victor Stinner791da1c2016-03-14 16:53:12 +01002546 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002547 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002548 /* Flush sys.stdout and sys.stderr */
2549 flush_std_files();
2550 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002551
Nick Coghland6009512014-11-20 21:39:37 +10002552#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002553 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002554#endif /* MS_WINDOWS */
2555
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002556 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002557}
2558
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002559
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002560#undef Py_FatalError
2561
Victor Stinner19760862017-12-20 01:41:59 +01002562void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002563Py_FatalError(const char *msg)
2564{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002565 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002566}
2567
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002568
Victor Stinner19760862017-12-20 01:41:59 +01002569void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002570_Py_FatalErrorFunc(const char *func, const char *msg)
2571{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002572 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002573}
2574
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002575
2576void _Py_NO_RETURN
2577_Py_FatalErrorFormat(const char *func, const char *format, ...)
2578{
2579 static int reentrant = 0;
2580 if (reentrant) {
2581 /* _Py_FatalErrorFormat() caused a second fatal error */
2582 fatal_error_exit(-1);
2583 }
2584 reentrant = 1;
2585
2586 FILE *stream = stderr;
2587 fprintf(stream, "Fatal Python error: ");
2588 if (func) {
2589 fputs(func, stream);
2590 fputs(": ", stream);
2591 }
2592 fflush(stream);
2593
2594 va_list vargs;
2595#ifdef HAVE_STDARG_PROTOTYPES
2596 va_start(vargs, format);
2597#else
2598 va_start(vargs);
2599#endif
2600 vfprintf(stream, format, vargs);
2601 va_end(vargs);
2602
2603 fputs("\n", stream);
2604 fflush(stream);
2605
2606 fatal_error(stream, 0, NULL, NULL, -1);
2607}
2608
2609
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002610void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002611Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002612{
Victor Stinner331a6a52019-05-27 16:39:22 +02002613 if (_PyStatus_IS_EXIT(status)) {
2614 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002615 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002616 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002617 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002618 }
2619 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002620 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002621 }
Nick Coghland6009512014-11-20 21:39:37 +10002622}
2623
2624/* Clean up and exit */
2625
Nick Coghland6009512014-11-20 21:39:37 +10002626/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002627void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002628{
Victor Stinner81a7be32020-04-14 15:14:01 +02002629 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002630
Antoine Pitroufc5db952017-12-13 02:29:07 +01002631 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002632 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2633
2634 is->pyexitfunc = func;
2635 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002636}
2637
2638static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002639call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002640{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002641 PyInterpreterState *interp = tstate->interp;
2642 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002643 return;
2644
Victor Stinnerb45d2592019-06-20 00:05:23 +02002645 (*interp->pyexitfunc)(interp->pyexitmodule);
2646 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002647}
2648
2649/* Wait until threading._shutdown completes, provided
2650 the threading module was imported in the first place.
2651 The shutdown routine will wait until all non-daemon
2652 "threading" threads have completed. */
2653static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002654wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002655{
Nick Coghland6009512014-11-20 21:39:37 +10002656 _Py_IDENTIFIER(_shutdown);
2657 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002658 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002659 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002660 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002661 PyErr_WriteUnraisable(NULL);
2662 }
2663 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002664 return;
2665 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002666 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002667 if (result == NULL) {
2668 PyErr_WriteUnraisable(threading);
2669 }
2670 else {
2671 Py_DECREF(result);
2672 }
2673 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002674}
2675
2676#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002677int Py_AtExit(void (*func)(void))
2678{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002679 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002680 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002681 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002682 return 0;
2683}
2684
2685static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002686call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002687{
Victor Stinner8e91c242019-04-24 17:24:01 +02002688 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002689 /* pop last function from the list */
2690 runtime->nexitfuncs--;
2691 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2692 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2693
2694 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002695 }
Nick Coghland6009512014-11-20 21:39:37 +10002696
2697 fflush(stdout);
2698 fflush(stderr);
2699}
2700
Victor Stinnercfc88312018-08-01 16:41:25 +02002701void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002702Py_Exit(int sts)
2703{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002704 if (Py_FinalizeEx() < 0) {
2705 sts = 120;
2706 }
Nick Coghland6009512014-11-20 21:39:37 +10002707
2708 exit(sts);
2709}
2710
Victor Stinner331a6a52019-05-27 16:39:22 +02002711static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002712init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002713{
2714#ifdef SIGPIPE
2715 PyOS_setsig(SIGPIPE, SIG_IGN);
2716#endif
2717#ifdef SIGXFZ
2718 PyOS_setsig(SIGXFZ, SIG_IGN);
2719#endif
2720#ifdef SIGXFSZ
2721 PyOS_setsig(SIGXFSZ, SIG_IGN);
2722#endif
Victor Stinner400e1db2020-03-31 19:13:10 +02002723 PyOS_InitInterrupts(); /* May imply init_signals() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002724 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002725 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002726 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002727 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002728}
2729
2730
2731/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2732 *
2733 * All of the code in this function must only use async-signal-safe functions,
2734 * listed at `man 7 signal` or
2735 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002736 *
2737 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002738 */
2739void
2740_Py_RestoreSignals(void)
2741{
2742#ifdef SIGPIPE
2743 PyOS_setsig(SIGPIPE, SIG_DFL);
2744#endif
2745#ifdef SIGXFZ
2746 PyOS_setsig(SIGXFZ, SIG_DFL);
2747#endif
2748#ifdef SIGXFSZ
2749 PyOS_setsig(SIGXFSZ, SIG_DFL);
2750#endif
2751}
2752
2753
2754/*
2755 * The file descriptor fd is considered ``interactive'' if either
2756 * a) isatty(fd) is TRUE, or
2757 * b) the -i flag was given, and the filename associated with
2758 * the descriptor is NULL or "<stdin>" or "???".
2759 */
2760int
2761Py_FdIsInteractive(FILE *fp, const char *filename)
2762{
2763 if (isatty((int)fileno(fp)))
2764 return 1;
2765 if (!Py_InteractiveFlag)
2766 return 0;
2767 return (filename == NULL) ||
2768 (strcmp(filename, "<stdin>") == 0) ||
2769 (strcmp(filename, "???") == 0);
2770}
2771
2772
Nick Coghland6009512014-11-20 21:39:37 +10002773/* Wrappers around sigaction() or signal(). */
2774
2775PyOS_sighandler_t
2776PyOS_getsig(int sig)
2777{
2778#ifdef HAVE_SIGACTION
2779 struct sigaction context;
2780 if (sigaction(sig, NULL, &context) == -1)
2781 return SIG_ERR;
2782 return context.sa_handler;
2783#else
2784 PyOS_sighandler_t handler;
2785/* Special signal handling for the secure CRT in Visual Studio 2005 */
2786#if defined(_MSC_VER) && _MSC_VER >= 1400
2787 switch (sig) {
2788 /* Only these signals are valid */
2789 case SIGINT:
2790 case SIGILL:
2791 case SIGFPE:
2792 case SIGSEGV:
2793 case SIGTERM:
2794 case SIGBREAK:
2795 case SIGABRT:
2796 break;
2797 /* Don't call signal() with other values or it will assert */
2798 default:
2799 return SIG_ERR;
2800 }
2801#endif /* _MSC_VER && _MSC_VER >= 1400 */
2802 handler = signal(sig, SIG_IGN);
2803 if (handler != SIG_ERR)
2804 signal(sig, handler);
2805 return handler;
2806#endif
2807}
2808
2809/*
2810 * All of the code in this function must only use async-signal-safe functions,
2811 * listed at `man 7 signal` or
2812 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2813 */
2814PyOS_sighandler_t
2815PyOS_setsig(int sig, PyOS_sighandler_t handler)
2816{
2817#ifdef HAVE_SIGACTION
2818 /* Some code in Modules/signalmodule.c depends on sigaction() being
2819 * used here if HAVE_SIGACTION is defined. Fix that if this code
2820 * changes to invalidate that assumption.
2821 */
2822 struct sigaction context, ocontext;
2823 context.sa_handler = handler;
2824 sigemptyset(&context.sa_mask);
2825 context.sa_flags = 0;
2826 if (sigaction(sig, &context, &ocontext) == -1)
2827 return SIG_ERR;
2828 return ocontext.sa_handler;
2829#else
2830 PyOS_sighandler_t oldhandler;
2831 oldhandler = signal(sig, handler);
2832#ifdef HAVE_SIGINTERRUPT
2833 siginterrupt(sig, 1);
2834#endif
2835 return oldhandler;
2836#endif
2837}
2838
2839#ifdef __cplusplus
2840}
2841#endif