blob: 33deafbc0a215fe8f9ae18400bb6301842d5ffaf [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*/
Victor Stinneref75a622020-11-12 15:14:13 +0100138static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200139init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000140{
Victor Stinneref75a622020-11-12 15:14:13 +0100141 assert(!_PyErr_Occurred(tstate));
142
Victor Stinnerb45d2592019-06-20 00:05:23 +0200143 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200144 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000145
Victor Stinneref75a622020-11-12 15:14:13 +0100146 // Import _importlib through its frozen version, _frozen_importlib.
147 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000148 PySys_FormatStderr("import _frozen_importlib # frozen\n");
149 }
Victor Stinneref75a622020-11-12 15:14:13 +0100150 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
151 return -1;
152 }
153 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000154 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100155 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000156 }
Victor Stinneref75a622020-11-12 15:14:13 +0100157 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000158
Victor Stinneref75a622020-11-12 15:14:13 +0100159 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
160 "__import__");
161 if (import_func == NULL) {
162 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000163 }
Victor Stinneref75a622020-11-12 15:14:13 +0100164 interp->import_func = Py_NewRef(import_func);
165
166 // Import the _imp module
167 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200168 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000169 }
Victor Stinneref75a622020-11-12 15:14:13 +0100170 PyObject *imp_mod = PyInit__imp();
171 if (imp_mod == NULL) {
172 return -1;
173 }
174 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
175 Py_DECREF(imp_mod);
176 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000177 }
178
Victor Stinneref75a622020-11-12 15:14:13 +0100179 // Install importlib as the implementation of import
180 PyObject *value = PyObject_CallMethod(importlib, "_install",
181 "OO", sysmod, imp_mod);
182 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000183 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100184 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000185 }
186 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000187
Victor Stinneref75a622020-11-12 15:14:13 +0100188 assert(!_PyErr_Occurred(tstate));
189 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000190}
191
Victor Stinneref75a622020-11-12 15:14:13 +0100192
Victor Stinner331a6a52019-05-27 16:39:22 +0200193static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200194init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700195{
196 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200197 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700198 "_install_external_importers", "");
199 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200200 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200201 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700202 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200203 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200204 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700205}
Nick Coghland6009512014-11-20 21:39:37 +1000206
Nick Coghlan6ea41862017-06-11 13:16:15 +1000207/* Helper functions to better handle the legacy C locale
208 *
209 * The legacy C locale assumes ASCII as the default text encoding, which
210 * causes problems not only for the CPython runtime, but also other
211 * components like GNU readline.
212 *
213 * Accordingly, when the CLI detects it, it attempts to coerce it to a
214 * more capable UTF-8 based alternative as follows:
215 *
216 * if (_Py_LegacyLocaleDetected()) {
217 * _Py_CoerceLegacyLocale();
218 * }
219 *
220 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
221 *
222 * Locale coercion also impacts the default error handler for the standard
223 * streams: while the usual default is "strict", the default for the legacy
224 * C locale and for any of the coercion target locales is "surrogateescape".
225 */
226
227int
Victor Stinner0f721472019-05-20 17:16:38 +0200228_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000229{
230#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200231 if (!warn) {
232 const char *locale_override = getenv("LC_ALL");
233 if (locale_override != NULL && *locale_override != '\0') {
234 /* Don't coerce C locale if the LC_ALL environment variable
235 is set */
236 return 0;
237 }
238 }
239
Nick Coghlan6ea41862017-06-11 13:16:15 +1000240 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000241 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
242 * the POSIX locale as a simple alias for the C locale, so
243 * we may also want to check for that explicitly.
244 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000245 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
246 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
247#else
248 /* Windows uses code pages instead of locales, so no locale is legacy */
249 return 0;
250#endif
251}
252
Victor Stinnerb0051362019-11-22 17:52:42 +0100253#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000254static const char *_C_LOCALE_WARNING =
255 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
256 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
257 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
258 "locales is recommended.\n";
259
Nick Coghlaneb817952017-06-18 12:29:42 +1000260static void
Victor Stinner43125222019-04-24 18:23:53 +0200261emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000262{
Victor Stinner331a6a52019-05-27 16:39:22 +0200263 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200264 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200265 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000266 }
267}
Victor Stinnerb0051362019-11-22 17:52:42 +0100268#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000269
Nick Coghlan6ea41862017-06-11 13:16:15 +1000270typedef struct _CandidateLocale {
271 const char *locale_name; /* The locale to try as a coercion target */
272} _LocaleCoercionTarget;
273
274static _LocaleCoercionTarget _TARGET_LOCALES[] = {
275 {"C.UTF-8"},
276 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000277 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000278 {NULL}
279};
280
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200281
282int
283_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000284{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200285 const _LocaleCoercionTarget *target = NULL;
286 for (target = _TARGET_LOCALES; target->locale_name; target++) {
287 if (strcmp(ctype_loc, target->locale_name) == 0) {
288 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200290 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200291 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000292}
293
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200294
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100296static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
298 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
299
Victor Stinner0f721472019-05-20 17:16:38 +0200300static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200301_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302{
303 const char *newloc = target->locale_name;
304
305 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100306 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307
308 /* Set the relevant locale environment variable */
309 if (setenv("LC_CTYPE", newloc, 1)) {
310 fprintf(stderr,
311 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200312 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200314 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100315 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000316 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317
318 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100319 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200320 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000321}
322#endif
323
Victor Stinner0f721472019-05-20 17:16:38 +0200324int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200325_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326{
Victor Stinner0f721472019-05-20 17:16:38 +0200327 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200329 char *oldloc = NULL;
330
331 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
332 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200333 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200334 }
335
Victor Stinner94540602017-12-16 04:54:22 +0100336 const char *locale_override = getenv("LC_ALL");
337 if (locale_override == NULL || *locale_override == '\0') {
338 /* LC_ALL is also not set (or is set to an empty string) */
339 const _LocaleCoercionTarget *target = NULL;
340 for (target = _TARGET_LOCALES; target->locale_name; target++) {
341 const char *new_locale = setlocale(LC_CTYPE,
342 target->locale_name);
343 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400344#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100345 /* Also ensure that nl_langinfo works in this locale */
346 char *codeset = nl_langinfo(CODESET);
347 if (!codeset || *codeset == '\0') {
348 /* CODESET is not set or empty, so skip coercion */
349 new_locale = NULL;
350 _Py_SetLocaleFromEnv(LC_CTYPE);
351 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000352 }
Victor Stinner94540602017-12-16 04:54:22 +0100353#endif
354 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200355 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200356 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357 }
358 }
359 }
360 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200361
362 setlocale(LC_CTYPE, oldloc);
363
364done:
365 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000366#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200367 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000368}
369
xdegaye1588be62017-11-12 12:45:59 +0100370/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
371 * isolate the idiosyncrasies of different libc implementations. It reads the
372 * appropriate environment variable and uses its value to select the locale for
373 * 'category'. */
374char *
375_Py_SetLocaleFromEnv(int category)
376{
Victor Stinner353933e2018-11-23 13:08:26 +0100377 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100378#ifdef __ANDROID__
379 const char *locale;
380 const char **pvar;
381#ifdef PY_COERCE_C_LOCALE
382 const char *coerce_c_locale;
383#endif
384 const char *utf8_locale = "C.UTF-8";
385 const char *env_var_set[] = {
386 "LC_ALL",
387 "LC_CTYPE",
388 "LANG",
389 NULL,
390 };
391
392 /* Android setlocale(category, "") doesn't check the environment variables
393 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
394 * check the environment variables listed in env_var_set. */
395 for (pvar=env_var_set; *pvar; pvar++) {
396 locale = getenv(*pvar);
397 if (locale != NULL && *locale != '\0') {
398 if (strcmp(locale, utf8_locale) == 0 ||
399 strcmp(locale, "en_US.UTF-8") == 0) {
400 return setlocale(category, utf8_locale);
401 }
402 return setlocale(category, "C");
403 }
404 }
405
406 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
407 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
408 * Quote from POSIX section "8.2 Internationalization Variables":
409 * "4. If the LANG environment variable is not set or is set to the empty
410 * string, the implementation-defined default locale shall be used." */
411
412#ifdef PY_COERCE_C_LOCALE
413 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
414 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
415 /* Some other ported code may check the environment variables (e.g. in
416 * extension modules), so we make sure that they match the locale
417 * configuration */
418 if (setenv("LC_CTYPE", utf8_locale, 1)) {
419 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
420 "environment variable to %s\n", utf8_locale);
421 }
422 }
423#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100424 res = setlocale(category, utf8_locale);
425#else /* !defined(__ANDROID__) */
426 res = setlocale(category, "");
427#endif
428 _Py_ResetForceASCII();
429 return res;
xdegaye1588be62017-11-12 12:45:59 +0100430}
431
Nick Coghlan6ea41862017-06-11 13:16:15 +1000432
Victor Stinner048a3562020-11-05 00:45:56 +0100433static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100434interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100435{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100436 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100437
Victor Stinner9e1b8282020-11-10 13:21:52 +0100438 if (!only_update_path_config) {
439 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
440 if (_PyStatus_EXCEPTION(status)) {
441 _PyErr_SetFromPyStatus(status);
442 return -1;
443 }
Victor Stinner048a3562020-11-05 00:45:56 +0100444 }
445
Victor Stinner9e1b8282020-11-10 13:21:52 +0100446 if (_Py_IsMainInterpreter(tstate)) {
447 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100448 if (_PyStatus_EXCEPTION(status)) {
449 _PyErr_SetFromPyStatus(status);
450 return -1;
451 }
452 }
453
454 // Update the sys module for the new configuration
455 if (_PySys_UpdateConfig(tstate) < 0) {
456 return -1;
457 }
458 return 0;
459}
460
461
462int
463_PyInterpreterState_SetConfig(const PyConfig *src_config)
464{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100465 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100466 int res = -1;
467
468 PyConfig config;
469 PyConfig_InitPythonConfig(&config);
470 PyStatus status = _PyConfig_Copy(&config, src_config);
471 if (_PyStatus_EXCEPTION(status)) {
472 _PyErr_SetFromPyStatus(status);
473 goto done;
474 }
475
476 status = PyConfig_Read(&config);
477 if (_PyStatus_EXCEPTION(status)) {
478 _PyErr_SetFromPyStatus(status);
479 goto done;
480 }
481
Victor Stinner9e1b8282020-11-10 13:21:52 +0100482 status = _PyConfig_Copy(&tstate->interp->config, &config);
483 if (_PyStatus_EXCEPTION(status)) {
484 _PyErr_SetFromPyStatus(status);
485 goto done;
486 }
487
488 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100489
490done:
491 PyConfig_Clear(&config);
492 return res;
493}
494
495
Eric Snow1abcf672017-05-23 21:46:51 -0700496/* Global initializations. Can be undone by Py_Finalize(). Don't
497 call this twice without an intervening Py_Finalize() call.
498
Victor Stinner331a6a52019-05-27 16:39:22 +0200499 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700500 must have a corresponding call to Py_Finalize.
501
502 Locking: you must hold the interpreter lock while calling these APIs.
503 (If the lock has not yet been initialized, that's equivalent to
504 having the lock, but you cannot use multiple threads.)
505
506*/
507
Victor Stinner331a6a52019-05-27 16:39:22 +0200508static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200509pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200510 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200511 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200512{
Victor Stinner331a6a52019-05-27 16:39:22 +0200513 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100514 PyThreadState *tstate = _PyThreadState_GET();
515 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200516 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200518 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100519
520 PyInterpreterState *interp = tstate->interp;
521 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200522 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100523 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100524
Victor Stinnere81f6e62020-06-08 18:12:59 +0200525 status = _PyConfig_Write(config, runtime);
526 if (_PyStatus_EXCEPTION(status)) {
527 return status;
528 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200529
Victor Stinner048a3562020-11-05 00:45:56 +0100530 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200531 if (_PyStatus_EXCEPTION(status)) {
532 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200533 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200534 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200535
Victor Stinner331a6a52019-05-27 16:39:22 +0200536 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200537 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200538 if (_PyStatus_EXCEPTION(status)) {
539 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200540 }
541 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200542 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200543}
544
545
Victor Stinner331a6a52019-05-27 16:39:22 +0200546static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200547pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200548 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000549{
Victor Stinner43125222019-04-24 18:23:53 +0200550 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200551 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200552 }
Victor Stinnerda273412017-12-15 01:46:02 +0100553
Victor Stinnere81f6e62020-06-08 18:12:59 +0200554 PyStatus status = _PyConfig_Write(config, runtime);
555 if (_PyStatus_EXCEPTION(status)) {
556 return status;
557 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600558
Eric Snow1abcf672017-05-23 21:46:51 -0700559 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
560 * threads behave a little more gracefully at interpreter shutdown.
561 * We clobber it here so the new interpreter can start with a clean
562 * slate.
563 *
564 * However, this may still lead to misbehaviour if there are daemon
565 * threads still hanging around from a previous Py_Initialize/Finalize
566 * pair :(
567 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100568 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600569
Victor Stinnere81f6e62020-06-08 18:12:59 +0200570 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200571 if (_PyStatus_EXCEPTION(status)) {
572 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800573 }
574
Victor Stinner331a6a52019-05-27 16:39:22 +0200575 status = _PyInterpreterState_Enable(runtime);
576 if (_PyStatus_EXCEPTION(status)) {
577 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800578 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200579 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100580}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800581
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100582
Victor Stinner331a6a52019-05-27 16:39:22 +0200583static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200584init_interp_create_gil(PyThreadState *tstate)
585{
586 PyStatus status;
587
588 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
589 only called here. */
590 _PyEval_FiniGIL(tstate);
591
592 /* Auto-thread-state API */
593 status = _PyGILState_Init(tstate);
594 if (_PyStatus_EXCEPTION(status)) {
595 return status;
596 }
597
598 /* Create the GIL and take it */
599 status = _PyEval_InitGIL(tstate);
600 if (_PyStatus_EXCEPTION(status)) {
601 return status;
602 }
603
604 return _PyStatus_OK();
605}
606
607
608static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200609pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200610 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200611 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100612{
613 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100614 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100616 }
617
Victor Stinner048a3562020-11-05 00:45:56 +0100618 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200619 if (_PyStatus_EXCEPTION(status)) {
620 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100621 }
Nick Coghland6009512014-11-20 21:39:37 +1000622
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200623 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200624 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200625 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200626 }
Nick Coghland6009512014-11-20 21:39:37 +1000627 (void) PyThreadState_Swap(tstate);
628
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200629 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100630 if (_PyStatus_EXCEPTION(status)) {
631 return status;
632 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100633
Victor Stinnerb45d2592019-06-20 00:05:23 +0200634 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200635 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100636}
Nick Coghland6009512014-11-20 21:39:37 +1000637
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100638
Victor Stinner331a6a52019-05-27 16:39:22 +0200639static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100640pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641{
Victor Stinner444b39b2019-11-20 01:18:11 +0100642 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100643 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100644
Victor Stinner01b1cc12019-11-20 02:27:56 +0100645 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100646 if (_PyStatus_EXCEPTION(status)) {
647 return status;
648 }
649
Victor Stinner0430dfa2020-06-24 15:21:54 +0200650 // Create the empty tuple singleton. It must be created before the first
651 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
652 // for example.
653 status = _PyTuple_Init(tstate);
654 if (_PyStatus_EXCEPTION(status)) {
655 return status;
656 }
657
Victor Stinnere7e699e2019-11-20 12:08:13 +0100658 if (is_main_interp) {
659 status = _PyTypes_Init();
660 if (_PyStatus_EXCEPTION(status)) {
661 return status;
662 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100663 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100664
Victor Stinner630c8df2019-12-17 13:02:18 +0100665 if (!_PyLong_Init(tstate)) {
666 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100667 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100668
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200669 status = _PyUnicode_Init(tstate);
670 if (_PyStatus_EXCEPTION(status)) {
671 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100672 }
673
Victor Stinner91698d82020-06-25 14:07:40 +0200674 status = _PyBytes_Init(tstate);
675 if (_PyStatus_EXCEPTION(status)) {
676 return status;
677 }
678
Victor Stinner281cce12020-06-23 22:55:46 +0200679 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200680 if (_PyStatus_EXCEPTION(status)) {
681 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100682 }
683
Victor Stinnere7e699e2019-11-20 12:08:13 +0100684 if (is_main_interp) {
685 if (!_PyFloat_Init()) {
686 return _PyStatus_ERR("can't init float");
687 }
Nick Coghland6009512014-11-20 21:39:37 +1000688
Victor Stinnere7e699e2019-11-20 12:08:13 +0100689 if (_PyStructSequence_Init() < 0) {
690 return _PyStatus_ERR("can't initialize structseq");
691 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100692 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200693
Victor Stinner331a6a52019-05-27 16:39:22 +0200694 status = _PyErr_Init();
695 if (_PyStatus_EXCEPTION(status)) {
696 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200697 }
698
Victor Stinnere7e699e2019-11-20 12:08:13 +0100699 if (is_main_interp) {
700 if (!_PyContext_Init()) {
701 return _PyStatus_ERR("can't init context");
702 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100703 }
704
Victor Stinneref75a622020-11-12 15:14:13 +0100705 if (_PyWarnings_InitState(tstate) < 0) {
706 return _PyStatus_ERR("can't initialize warnings");
707 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200708 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100709}
710
711
Victor Stinner331a6a52019-05-27 16:39:22 +0200712static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200713pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100714{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100715 assert(!_PyErr_Occurred(tstate));
716
Victor Stinnerb45d2592019-06-20 00:05:23 +0200717 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100718 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100719 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100720 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100721
Victor Stinner2582d462019-11-22 19:24:49 +0100722 PyInterpreterState *interp = tstate->interp;
723 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
724 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100725 }
Victor Stinner2582d462019-11-22 19:24:49 +0100726
727 PyObject *builtins_dict = PyModule_GetDict(bimod);
728 if (builtins_dict == NULL) {
729 goto error;
730 }
731 Py_INCREF(builtins_dict);
732 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100733
Victor Stinner331a6a52019-05-27 16:39:22 +0200734 PyStatus status = _PyBuiltins_AddExceptions(bimod);
735 if (_PyStatus_EXCEPTION(status)) {
736 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100737 }
Victor Stinner2582d462019-11-22 19:24:49 +0100738
739 interp->builtins_copy = PyDict_Copy(interp->builtins);
740 if (interp->builtins_copy == NULL) {
741 goto error;
742 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000743 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100744
745 assert(!_PyErr_Occurred(tstate));
746
Victor Stinner331a6a52019-05-27 16:39:22 +0200747 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100748
749error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000750 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100751 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100752}
753
754
Victor Stinner331a6a52019-05-27 16:39:22 +0200755static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100756pycore_interp_init(PyThreadState *tstate)
757{
758 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100759 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100760
761 status = pycore_init_types(tstate);
762 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100763 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100764 }
765
Victor Stinnerd863ade2019-12-06 03:37:07 +0100766 status = _PySys_Create(tstate, &sysmod);
767 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100768 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100769 }
770
771 status = pycore_init_builtins(tstate);
772 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100773 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100774 }
775
Victor Stinneref75a622020-11-12 15:14:13 +0100776 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
777 if (config->_install_importlib) {
778 /* This call sets up builtin and frozen import support */
779 if (init_importlib(tstate, sysmod) < 0) {
780 return _PyStatus_ERR("failed to initialize importlib");
781 }
782 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100783
784done:
785 /* sys.modules['sys'] contains a strong reference to the module */
786 Py_XDECREF(sysmod);
787 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100788}
789
790
791static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200792pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200793 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200794 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100795{
Victor Stinner331a6a52019-05-27 16:39:22 +0200796 PyStatus status = pycore_init_runtime(runtime, config);
797 if (_PyStatus_EXCEPTION(status)) {
798 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100799 }
800
Victor Stinnerb45d2592019-06-20 00:05:23 +0200801 PyThreadState *tstate;
802 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200803 if (_PyStatus_EXCEPTION(status)) {
804 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100805 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200806 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100807
Victor Stinnerd863ade2019-12-06 03:37:07 +0100808 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200809 if (_PyStatus_EXCEPTION(status)) {
810 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100811 }
Eric Snow1abcf672017-05-23 21:46:51 -0700812
813 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200814 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200815 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700816}
817
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100818
Victor Stinner331a6a52019-05-27 16:39:22 +0200819PyStatus
820_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100821{
Victor Stinner331a6a52019-05-27 16:39:22 +0200822 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100823
Victor Stinner6d1c4672019-05-20 11:02:00 +0200824 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200825 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200826 }
827
Victor Stinner331a6a52019-05-27 16:39:22 +0200828 status = _PyRuntime_Initialize();
829 if (_PyStatus_EXCEPTION(status)) {
830 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100831 }
Victor Stinner43125222019-04-24 18:23:53 +0200832 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100833
Victor Stinnerd3b90412019-09-17 23:59:51 +0200834 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100835 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200836 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100837 }
838
Victor Stinnerd3b90412019-09-17 23:59:51 +0200839 /* Note: preinitialized remains 1 on error, it is only set to 0
840 at exit on success. */
841 runtime->preinitializing = 1;
842
Victor Stinner331a6a52019-05-27 16:39:22 +0200843 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200844
845 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
846 if (_PyStatus_EXCEPTION(status)) {
847 return status;
848 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100849
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 status = _PyPreConfig_Read(&config, args);
851 if (_PyStatus_EXCEPTION(status)) {
852 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100853 }
854
Victor Stinner331a6a52019-05-27 16:39:22 +0200855 status = _PyPreConfig_Write(&config);
856 if (_PyStatus_EXCEPTION(status)) {
857 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100858 }
859
Victor Stinnerd3b90412019-09-17 23:59:51 +0200860 runtime->preinitializing = 0;
861 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200862 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100863}
864
Victor Stinner70005ac2019-05-02 15:25:34 -0400865
Victor Stinner331a6a52019-05-27 16:39:22 +0200866PyStatus
867Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100868{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100869 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400870 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100871}
872
873
Victor Stinner331a6a52019-05-27 16:39:22 +0200874PyStatus
875Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100876{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100877 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400878 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100879}
880
881
Victor Stinner331a6a52019-05-27 16:39:22 +0200882PyStatus
883Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100884{
Victor Stinner70005ac2019-05-02 15:25:34 -0400885 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100886}
887
888
Victor Stinner331a6a52019-05-27 16:39:22 +0200889PyStatus
890_Py_PreInitializeFromConfig(const PyConfig *config,
891 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100892{
Victor Stinner331a6a52019-05-27 16:39:22 +0200893 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200894
Victor Stinner331a6a52019-05-27 16:39:22 +0200895 PyStatus status = _PyRuntime_Initialize();
896 if (_PyStatus_EXCEPTION(status)) {
897 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200898 }
899 _PyRuntimeState *runtime = &_PyRuntime;
900
Victor Stinnerd3b90412019-09-17 23:59:51 +0200901 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200902 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200903 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400904 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200905
Victor Stinner331a6a52019-05-27 16:39:22 +0200906 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200907
Victor Stinner3c30a762019-10-01 10:56:37 +0200908 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200909
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 if (!config->parse_argv) {
911 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200912 }
913 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200914 _PyArgv config_args = {
915 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200916 .argc = config->argv.length,
917 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200918 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200919 }
920 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200921 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200922 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100923}
924
925
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100926/* Begin interpreter initialization
927 *
928 * On return, the first thread and interpreter state have been created,
929 * but the compiler, signal handling, multithreading and
930 * multiple interpreter support, and codec infrastructure are not yet
931 * available.
932 *
933 * The import system will support builtin and frozen modules only.
934 * The only supported io is writing to sys.stderr
935 *
936 * If any operation invoked by this function fails, a fatal error is
937 * issued and the function does not return.
938 *
939 * Any code invoked from this function should *not* assume it has access
940 * to the Python C API (unless the API is explicitly listed as being
941 * safe to call without calling Py_Initialize first)
942 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200943static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200944pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200945 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200946 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200947{
Victor Stinner331a6a52019-05-27 16:39:22 +0200948 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200949
Victor Stinner331a6a52019-05-27 16:39:22 +0200950 status = _Py_PreInitializeFromConfig(src_config, NULL);
951 if (_PyStatus_EXCEPTION(status)) {
952 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200953 }
954
Victor Stinner331a6a52019-05-27 16:39:22 +0200955 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100956 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200957
Victor Stinner331a6a52019-05-27 16:39:22 +0200958 status = _PyConfig_Copy(&config, src_config);
959 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200960 goto done;
961 }
962
Victor Stinner9e1b8282020-11-10 13:21:52 +0100963 // Read the configuration, but don't compute the path configuration
964 // (it is computed in the main init).
965 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200967 goto done;
968 }
969
970 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200971 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200972 }
973 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200974 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200975 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200976 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200977 goto done;
978 }
979
980done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200981 PyConfig_Clear(&config);
982 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200983}
984
Victor Stinner5ac27a52019-03-27 13:40:14 +0100985
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200986/* Py_Initialize() has already been called: update the main interpreter
987 configuration. Example of bpo-34008: Py_Main() called after
988 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200989static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100990pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200991{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100992 if (interpreter_update_config(tstate, 0) < 0) {
993 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200994 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200995 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200996}
997
Victor Stinnerb0051362019-11-22 17:52:42 +0100998
999static PyStatus
1000init_interp_main(PyThreadState *tstate)
1001{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001002 assert(!_PyErr_Occurred(tstate));
1003
Victor Stinnerb0051362019-11-22 17:52:42 +01001004 PyStatus status;
1005 int is_main_interp = _Py_IsMainInterpreter(tstate);
1006 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001007 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001008
1009 if (!config->_install_importlib) {
1010 /* Special mode for freeze_importlib: run with no import system
1011 *
1012 * This means anything which needs support from extension modules
1013 * or pure Python code in the standard library won't work.
1014 */
1015 if (is_main_interp) {
1016 interp->runtime->initialized = 1;
1017 }
1018 return _PyStatus_OK();
1019 }
1020
Victor Stinner9e1b8282020-11-10 13:21:52 +01001021 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001022 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001023 if (_PyStatus_EXCEPTION(status)) {
1024 return status;
1025 }
1026
Victor Stinner9e1b8282020-11-10 13:21:52 +01001027 if (interpreter_update_config(tstate, 1) < 0) {
1028 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001029 }
1030
1031 status = init_importlib_external(tstate);
1032 if (_PyStatus_EXCEPTION(status)) {
1033 return status;
1034 }
1035
1036 if (is_main_interp) {
1037 /* initialize the faulthandler module */
1038 status = _PyFaulthandler_Init(config->faulthandler);
1039 if (_PyStatus_EXCEPTION(status)) {
1040 return status;
1041 }
1042 }
1043
1044 status = _PyUnicode_InitEncodings(tstate);
1045 if (_PyStatus_EXCEPTION(status)) {
1046 return status;
1047 }
1048
1049 if (is_main_interp) {
1050 if (config->install_signal_handlers) {
1051 status = init_signals(tstate);
1052 if (_PyStatus_EXCEPTION(status)) {
1053 return status;
1054 }
1055 }
1056
1057 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1058 return _PyStatus_ERR("can't initialize tracemalloc");
1059 }
1060 }
1061
1062 status = init_sys_streams(tstate);
1063 if (_PyStatus_EXCEPTION(status)) {
1064 return status;
1065 }
1066
Andy Lester75cd5bf2020-03-12 02:49:05 -05001067 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001068 if (_PyStatus_EXCEPTION(status)) {
1069 return status;
1070 }
1071
1072 status = add_main_module(interp);
1073 if (_PyStatus_EXCEPTION(status)) {
1074 return status;
1075 }
1076
1077 if (is_main_interp) {
1078 /* Initialize warnings. */
1079 PyObject *warnoptions = PySys_GetObject("warnoptions");
1080 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1081 {
1082 PyObject *warnings_module = PyImport_ImportModule("warnings");
1083 if (warnings_module == NULL) {
1084 fprintf(stderr, "'import warnings' failed; traceback:\n");
1085 _PyErr_Print(tstate);
1086 }
1087 Py_XDECREF(warnings_module);
1088 }
1089
1090 interp->runtime->initialized = 1;
1091 }
1092
1093 if (config->site_import) {
1094 status = init_import_site();
1095 if (_PyStatus_EXCEPTION(status)) {
1096 return status;
1097 }
1098 }
1099
1100 if (is_main_interp) {
1101#ifndef MS_WINDOWS
1102 emit_stderr_warning_for_legacy_locale(interp->runtime);
1103#endif
1104 }
1105
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001106 assert(!_PyErr_Occurred(tstate));
1107
Victor Stinnerb0051362019-11-22 17:52:42 +01001108 return _PyStatus_OK();
1109}
1110
1111
Eric Snowc7ec9982017-05-23 23:00:52 -07001112/* Update interpreter state based on supplied configuration settings
1113 *
1114 * After calling this function, most of the restrictions on the interpreter
1115 * are lifted. The only remaining incomplete settings are those related
1116 * to the main module (sys.argv[0], __main__ metadata)
1117 *
1118 * Calling this when the interpreter is not initializing, is already
1119 * initialized or without a valid current thread state is a fatal error.
1120 * Other errors should be reported as normal Python exceptions with a
1121 * non-zero return code.
1122 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001123static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001124pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001125{
Victor Stinnerb0051362019-11-22 17:52:42 +01001126 PyInterpreterState *interp = tstate->interp;
1127 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001128 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001129 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001130
Victor Stinnerb0051362019-11-22 17:52:42 +01001131 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001132 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001133 }
1134
Victor Stinnerb0051362019-11-22 17:52:42 +01001135 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001136 if (_PyStatus_EXCEPTION(status)) {
1137 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001138 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001139 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001140}
1141
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001142
Victor Stinner331a6a52019-05-27 16:39:22 +02001143PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001144Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001145{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001146 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001147 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001148 }
1149
Victor Stinner331a6a52019-05-27 16:39:22 +02001150 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001151
Victor Stinner331a6a52019-05-27 16:39:22 +02001152 status = _PyRuntime_Initialize();
1153 if (_PyStatus_EXCEPTION(status)) {
1154 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001155 }
1156 _PyRuntimeState *runtime = &_PyRuntime;
1157
Victor Stinnerb45d2592019-06-20 00:05:23 +02001158 PyThreadState *tstate = NULL;
1159 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001160 if (_PyStatus_EXCEPTION(status)) {
1161 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001162 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001163 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001164
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001165 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001166 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001167 if (_PyStatus_EXCEPTION(status)) {
1168 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001169 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001170 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001171
Victor Stinner331a6a52019-05-27 16:39:22 +02001172 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001173}
1174
1175
Eric Snow1abcf672017-05-23 21:46:51 -07001176void
Nick Coghland6009512014-11-20 21:39:37 +10001177Py_InitializeEx(int install_sigs)
1178{
Victor Stinner331a6a52019-05-27 16:39:22 +02001179 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001180
Victor Stinner331a6a52019-05-27 16:39:22 +02001181 status = _PyRuntime_Initialize();
1182 if (_PyStatus_EXCEPTION(status)) {
1183 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001184 }
1185 _PyRuntimeState *runtime = &_PyRuntime;
1186
1187 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001188 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1189 return;
1190 }
1191
Victor Stinner331a6a52019-05-27 16:39:22 +02001192 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001193 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001194
Victor Stinner1dc6e392018-07-25 02:49:17 +02001195 config.install_signal_handlers = install_sigs;
1196
Victor Stinner331a6a52019-05-27 16:39:22 +02001197 status = Py_InitializeFromConfig(&config);
1198 if (_PyStatus_EXCEPTION(status)) {
1199 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001200 }
Nick Coghland6009512014-11-20 21:39:37 +10001201}
1202
1203void
1204Py_Initialize(void)
1205{
1206 Py_InitializeEx(1);
1207}
1208
1209
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001210PyStatus
1211_Py_InitializeMain(void)
1212{
1213 PyStatus status = _PyRuntime_Initialize();
1214 if (_PyStatus_EXCEPTION(status)) {
1215 return status;
1216 }
1217 _PyRuntimeState *runtime = &_PyRuntime;
1218 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1219 return pyinit_main(tstate);
1220}
1221
1222
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001223static void
1224finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1225{
1226 // List of names to clear in sys
1227 static const char * const sys_deletes[] = {
1228 "path", "argv", "ps1", "ps2",
1229 "last_type", "last_value", "last_traceback",
1230 "path_hooks", "path_importer_cache", "meta_path",
1231 "__interactivehook__",
1232 NULL
1233 };
1234
1235 static const char * const sys_files[] = {
1236 "stdin", "__stdin__",
1237 "stdout", "__stdout__",
1238 "stderr", "__stderr__",
1239 NULL
1240 };
1241
1242 PyInterpreterState *interp = tstate->interp;
1243 if (verbose) {
1244 PySys_WriteStderr("# clear builtins._\n");
1245 }
1246 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1247 PyErr_WriteUnraisable(NULL);
1248 }
1249
1250 const char * const *p;
1251 for (p = sys_deletes; *p != NULL; p++) {
1252 if (verbose) {
1253 PySys_WriteStderr("# clear sys.%s\n", *p);
1254 }
1255 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1256 PyErr_WriteUnraisable(NULL);
1257 }
1258 }
1259 for (p = sys_files; *p != NULL; p+=2) {
1260 const char *name = p[0];
1261 const char *orig_name = p[1];
1262 if (verbose) {
1263 PySys_WriteStderr("# restore sys.%s\n", name);
1264 }
1265 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1266 orig_name);
1267 if (value == NULL) {
1268 if (_PyErr_Occurred(tstate)) {
1269 PyErr_WriteUnraisable(NULL);
1270 }
1271 value = Py_None;
1272 }
1273 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1274 PyErr_WriteUnraisable(NULL);
1275 }
1276 }
1277}
1278
1279
1280static PyObject*
1281finalize_remove_modules(PyObject *modules, int verbose)
1282{
1283 PyObject *weaklist = PyList_New(0);
1284 if (weaklist == NULL) {
1285 PyErr_WriteUnraisable(NULL);
1286 }
1287
1288#define STORE_MODULE_WEAKREF(name, mod) \
1289 if (weaklist != NULL) { \
1290 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1291 if (wr) { \
1292 PyObject *tup = PyTuple_Pack(2, name, wr); \
1293 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1294 PyErr_WriteUnraisable(NULL); \
1295 } \
1296 Py_XDECREF(tup); \
1297 Py_DECREF(wr); \
1298 } \
1299 else { \
1300 PyErr_WriteUnraisable(NULL); \
1301 } \
1302 }
1303
1304#define CLEAR_MODULE(name, mod) \
1305 if (PyModule_Check(mod)) { \
1306 if (verbose && PyUnicode_Check(name)) { \
1307 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1308 } \
1309 STORE_MODULE_WEAKREF(name, mod); \
1310 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1311 PyErr_WriteUnraisable(NULL); \
1312 } \
1313 }
1314
1315 if (PyDict_CheckExact(modules)) {
1316 Py_ssize_t pos = 0;
1317 PyObject *key, *value;
1318 while (PyDict_Next(modules, &pos, &key, &value)) {
1319 CLEAR_MODULE(key, value);
1320 }
1321 }
1322 else {
1323 PyObject *iterator = PyObject_GetIter(modules);
1324 if (iterator == NULL) {
1325 PyErr_WriteUnraisable(NULL);
1326 }
1327 else {
1328 PyObject *key;
1329 while ((key = PyIter_Next(iterator))) {
1330 PyObject *value = PyObject_GetItem(modules, key);
1331 if (value == NULL) {
1332 PyErr_WriteUnraisable(NULL);
1333 continue;
1334 }
1335 CLEAR_MODULE(key, value);
1336 Py_DECREF(value);
1337 Py_DECREF(key);
1338 }
1339 if (PyErr_Occurred()) {
1340 PyErr_WriteUnraisable(NULL);
1341 }
1342 Py_DECREF(iterator);
1343 }
1344 }
1345#undef CLEAR_MODULE
1346#undef STORE_MODULE_WEAKREF
1347
1348 return weaklist;
1349}
1350
1351
1352static void
1353finalize_clear_modules_dict(PyObject *modules)
1354{
1355 if (PyDict_CheckExact(modules)) {
1356 PyDict_Clear(modules);
1357 }
1358 else {
1359 _Py_IDENTIFIER(clear);
1360 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1361 PyErr_WriteUnraisable(NULL);
1362 }
1363 }
1364}
1365
1366
1367static void
1368finalize_restore_builtins(PyThreadState *tstate)
1369{
1370 PyInterpreterState *interp = tstate->interp;
1371 PyObject *dict = PyDict_Copy(interp->builtins);
1372 if (dict == NULL) {
1373 PyErr_WriteUnraisable(NULL);
1374 }
1375 PyDict_Clear(interp->builtins);
1376 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1377 _PyErr_Clear(tstate);
1378 }
1379 Py_XDECREF(dict);
1380}
1381
1382
1383static void
1384finalize_modules_clear_weaklist(PyInterpreterState *interp,
1385 PyObject *weaklist, int verbose)
1386{
1387 // First clear modules imported later
1388 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1389 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1390 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1391 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1392 if (mod == Py_None) {
1393 continue;
1394 }
1395 assert(PyModule_Check(mod));
1396 PyObject *dict = PyModule_GetDict(mod);
1397 if (dict == interp->builtins || dict == interp->sysdict) {
1398 continue;
1399 }
1400 Py_INCREF(mod);
1401 if (verbose && PyUnicode_Check(name)) {
1402 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1403 }
1404 _PyModule_Clear(mod);
1405 Py_DECREF(mod);
1406 }
1407}
1408
1409
1410static void
1411finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1412{
1413 // Clear sys dict
1414 if (verbose) {
1415 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1416 }
1417 _PyModule_ClearDict(interp->sysdict);
1418
1419 // Clear builtins dict
1420 if (verbose) {
1421 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1422 }
1423 _PyModule_ClearDict(interp->builtins);
1424}
1425
1426
1427/* Clear modules, as good as we can */
1428static void
1429finalize_modules(PyThreadState *tstate)
1430{
1431 PyInterpreterState *interp = tstate->interp;
1432 PyObject *modules = interp->modules;
1433 if (modules == NULL) {
1434 // Already done
1435 return;
1436 }
1437 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1438
1439 // Delete some special builtins._ and sys attributes first. These are
1440 // common places where user values hide and people complain when their
1441 // destructors fail. Since the modules containing them are
1442 // deleted *last* of all, they would come too late in the normal
1443 // destruction order. Sigh.
1444 //
1445 // XXX Perhaps these precautions are obsolete. Who knows?
1446 finalize_modules_delete_special(tstate, verbose);
1447
1448 // Remove all modules from sys.modules, hoping that garbage collection
1449 // can reclaim most of them: set all sys.modules values to None.
1450 //
1451 // We prepare a list which will receive (name, weakref) tuples of
1452 // modules when they are removed from sys.modules. The name is used
1453 // for diagnosis messages (in verbose mode), while the weakref helps
1454 // detect those modules which have been held alive.
1455 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1456
1457 // Clear the modules dict
1458 finalize_clear_modules_dict(modules);
1459
1460 // Restore the original builtins dict, to ensure that any
1461 // user data gets cleared.
1462 finalize_restore_builtins(tstate);
1463
1464 // Collect garbage
1465 _PyGC_CollectNoFail(tstate);
1466
1467 // Dump GC stats before it's too late, since it uses the warnings
1468 // machinery.
1469 _PyGC_DumpShutdownStats(tstate);
1470
1471 if (weaklist != NULL) {
1472 // Now, if there are any modules left alive, clear their globals to
1473 // minimize potential leaks. All C extension modules actually end
1474 // up here, since they are kept alive in the interpreter state.
1475 //
1476 // The special treatment of "builtins" here is because even
1477 // when it's not referenced as a module, its dictionary is
1478 // referenced by almost every module's __builtins__. Since
1479 // deleting a module clears its dictionary (even if there are
1480 // references left to it), we need to delete the "builtins"
1481 // module last. Likewise, we don't delete sys until the very
1482 // end because it is implicitly referenced (e.g. by print).
1483 //
1484 // Since dict is ordered in CPython 3.6+, modules are saved in
1485 // importing order. First clear modules imported later.
1486 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1487 Py_DECREF(weaklist);
1488 }
1489
1490 // Clear sys and builtins modules dict
1491 finalize_clear_sys_builtins_dict(interp, verbose);
1492
1493 // Clear module dict copies stored in the interpreter state:
1494 // clear PyInterpreterState.modules_by_index and
1495 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1496 // initialization API)
1497 _PyInterpreterState_ClearModules(interp);
1498
1499 // Clear and delete the modules directory. Actual modules will
1500 // still be there only if imported during the execution of some
1501 // destructor.
1502 Py_SETREF(interp->modules, NULL);
1503
1504 // Collect garbage once more
1505 _PyGC_CollectNoFail(tstate);
1506}
1507
1508
Nick Coghland6009512014-11-20 21:39:37 +10001509/* Flush stdout and stderr */
1510
1511static int
1512file_is_closed(PyObject *fobj)
1513{
1514 int r;
1515 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1516 if (tmp == NULL) {
1517 PyErr_Clear();
1518 return 0;
1519 }
1520 r = PyObject_IsTrue(tmp);
1521 Py_DECREF(tmp);
1522 if (r < 0)
1523 PyErr_Clear();
1524 return r > 0;
1525}
1526
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001527
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001528static int
Nick Coghland6009512014-11-20 21:39:37 +10001529flush_std_files(void)
1530{
1531 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1532 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1533 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001534 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001535
1536 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001537 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001538 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001539 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001540 status = -1;
1541 }
Nick Coghland6009512014-11-20 21:39:37 +10001542 else
1543 Py_DECREF(tmp);
1544 }
1545
1546 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001547 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001548 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001549 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001550 status = -1;
1551 }
Nick Coghland6009512014-11-20 21:39:37 +10001552 else
1553 Py_DECREF(tmp);
1554 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001555
1556 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001557}
1558
1559/* Undo the effect of Py_Initialize().
1560
1561 Beware: if multiple interpreter and/or thread states exist, these
1562 are not wiped out; only the current thread and interpreter state
1563 are deleted. But since everything else is deleted, those other
1564 interpreter and thread states should no longer be used.
1565
1566 (XXX We should do better, e.g. wipe out all interpreters and
1567 threads.)
1568
1569 Locking: as above.
1570
1571*/
1572
Victor Stinner7eee5be2019-11-20 10:38:34 +01001573
1574static void
Victor Stinner90db4652020-07-01 23:21:36 +02001575finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001576{
Victor Stinner281cce12020-06-23 22:55:46 +02001577 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001578 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001579 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001580 _PyContext_Fini(tstate);
Victor Stinner666ecfb2020-07-02 01:19:57 +02001581 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001582
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001583 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001584 _PyList_Fini(tstate);
1585 _PyTuple_Fini(tstate);
1586
1587 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001588
Victor Stinnerc41eed12020-06-23 15:54:35 +02001589 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001590 _PyUnicode_Fini(tstate);
1591 _PyFloat_Fini(tstate);
1592 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001593}
1594
1595
1596static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001597finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001598{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001599 int is_main_interp = _Py_IsMainInterpreter(tstate);
1600
Victor Stinner7eee5be2019-11-20 10:38:34 +01001601 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001602 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001603
Kongedaa0fe02020-07-04 05:06:46 +08001604 /* Clear all loghooks */
1605 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1606 Call _PySys_ClearAuditHooks when PyObject available. */
1607 if (is_main_interp) {
1608 _PySys_ClearAuditHooks(tstate);
1609 }
1610
Victor Stinner7907f8c2020-06-08 01:22:36 +02001611 if (is_main_interp) {
1612 _Py_HashRandomization_Fini();
1613 _PyArg_Fini();
1614 _Py_ClearFileSystemEncoding();
1615 }
1616
Victor Stinner90db4652020-07-01 23:21:36 +02001617 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001618}
1619
1620
1621static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001622finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001623{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001624 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001625 /* Cleanup auto-thread-state */
1626 _PyGILState_Fini(tstate);
1627 }
1628
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001629 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1630 fail when it is being awaited by another running daemon thread (see
1631 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1632 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1633 called multiple times. */
1634
Victor Stinner7eee5be2019-11-20 10:38:34 +01001635 PyInterpreterState_Delete(tstate->interp);
1636}
1637
1638
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001639int
1640Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001641{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001642 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001643
Victor Stinner8e91c242019-04-24 17:24:01 +02001644 _PyRuntimeState *runtime = &_PyRuntime;
1645 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001646 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001647 }
Nick Coghland6009512014-11-20 21:39:37 +10001648
Victor Stinnere225beb2019-06-03 18:14:24 +02001649 /* Get current thread state and interpreter pointer */
1650 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1651 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001652
Victor Stinnerb45d2592019-06-20 00:05:23 +02001653 // Wrap up existing "threading"-module-created, non-daemon threads.
1654 wait_for_thread_shutdown(tstate);
1655
1656 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001657 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001658
Nick Coghland6009512014-11-20 21:39:37 +10001659 /* The interpreter is still entirely intact at this point, and the
1660 * exit funcs may be relying on that. In particular, if some thread
1661 * or exit func is still waiting to do an import, the import machinery
1662 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001663 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001664 * Note that Threading.py uses an exit func to do a join on all the
1665 * threads created thru it, so this also protects pending imports in
1666 * the threads created via Threading.
1667 */
Nick Coghland6009512014-11-20 21:39:37 +10001668
Victor Stinnerb45d2592019-06-20 00:05:23 +02001669 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001670
Victor Stinnerda273412017-12-15 01:46:02 +01001671 /* Copy the core config, PyInterpreterState_Delete() free
1672 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001673#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001674 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001675#endif
1676#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001677 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001678#endif
1679#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001680 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001681#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001682
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001683 /* Remaining daemon threads will automatically exit
1684 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001685 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001686 runtime->initialized = 0;
1687 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001688
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001689 /* Destroy the state of all threads of the interpreter, except of the
1690 current thread. In practice, only daemon threads should still be alive,
1691 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1692 Clear frames of other threads to call objects destructors. Destructors
1693 will be called in the current Python thread. Since
1694 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1695 can take the GIL at this point: if they try, they will exit
1696 immediately. */
1697 _PyThreadState_DeleteExcept(runtime, tstate);
1698
Victor Stinnere0deff32015-03-24 13:46:18 +01001699 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001700 if (flush_std_files() < 0) {
1701 status = -1;
1702 }
Nick Coghland6009512014-11-20 21:39:37 +10001703
1704 /* Disable signal handling */
1705 PyOS_FiniInterrupts();
1706
1707 /* Collect garbage. This may call finalizers; it's nice to call these
1708 * before all modules are destroyed.
1709 * XXX If a __del__ or weakref callback is triggered here, and tries to
1710 * XXX import a module, bad things can happen, because Python no
1711 * XXX longer believes it's initialized.
1712 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1713 * XXX is easy to provoke that way. I've also seen, e.g.,
1714 * XXX Exception exceptions.ImportError: 'No module named sha'
1715 * XXX in <function callback at 0x008F5718> ignored
1716 * XXX but I'm unclear on exactly how that one happens. In any case,
1717 * XXX I haven't seen a real-life report of either of these.
1718 */
Victor Stinner8b341482020-10-30 17:00:00 +01001719 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001720
Nick Coghland6009512014-11-20 21:39:37 +10001721 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001722 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001723
Inada Naoki91234a12019-06-03 21:30:58 +09001724 /* Print debug stats if any */
1725 _PyEval_Fini();
1726
Victor Stinnere0deff32015-03-24 13:46:18 +01001727 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001728 if (flush_std_files() < 0) {
1729 status = -1;
1730 }
Nick Coghland6009512014-11-20 21:39:37 +10001731
1732 /* Collect final garbage. This disposes of cycles created by
1733 * class definitions, for example.
1734 * XXX This is disabled because it caused too many problems. If
1735 * XXX a __del__ or weakref callback triggers here, Python code has
1736 * XXX a hard time running, because even the sys module has been
1737 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1738 * XXX One symptom is a sequence of information-free messages
1739 * XXX coming from threads (if a __del__ or callback is invoked,
1740 * XXX other threads can execute too, and any exception they encounter
1741 * XXX triggers a comedy of errors as subsystem after subsystem
1742 * XXX fails to find what it *expects* to find in sys to help report
1743 * XXX the exception and consequent unexpected failures). I've also
1744 * XXX seen segfaults then, after adding print statements to the
1745 * XXX Python code getting called.
1746 */
1747#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001748 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001749#endif
1750
1751 /* Disable tracemalloc after all Python objects have been destroyed,
1752 so it is possible to use tracemalloc in objects destructor. */
1753 _PyTraceMalloc_Fini();
1754
1755 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1756 _PyImport_Fini();
1757
1758 /* Cleanup typeobject.c's internal caches. */
1759 _PyType_Fini();
1760
1761 /* unload faulthandler module */
1762 _PyFaulthandler_Fini();
1763
Nick Coghland6009512014-11-20 21:39:37 +10001764 /* dump hash stats */
1765 _PyHash_Fini();
1766
Eric Snowdae02762017-09-14 00:35:58 -07001767#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001768 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001769 _PyDebug_PrintTotalRefs();
1770 }
Eric Snowdae02762017-09-14 00:35:58 -07001771#endif
Nick Coghland6009512014-11-20 21:39:37 +10001772
1773#ifdef Py_TRACE_REFS
1774 /* Display all objects still alive -- this can invoke arbitrary
1775 * __repr__ overrides, so requires a mostly-intact interpreter.
1776 * Alas, a lot of stuff may still be alive now that will be cleaned
1777 * up later.
1778 */
Victor Stinnerda273412017-12-15 01:46:02 +01001779 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001780 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001781 }
Nick Coghland6009512014-11-20 21:39:37 +10001782#endif /* Py_TRACE_REFS */
1783
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001784 finalize_interp_clear(tstate);
1785 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001786
1787#ifdef Py_TRACE_REFS
1788 /* Display addresses (& refcnts) of all objects still alive.
1789 * An address can be used to find the repr of the object, printed
1790 * above by _Py_PrintReferences.
1791 */
Victor Stinnerda273412017-12-15 01:46:02 +01001792 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001793 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001794 }
Nick Coghland6009512014-11-20 21:39:37 +10001795#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001796#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001797 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001798 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001799 }
Nick Coghland6009512014-11-20 21:39:37 +10001800#endif
1801
Victor Stinner8e91c242019-04-24 17:24:01 +02001802 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001803
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001804 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001805 return status;
1806}
1807
1808void
1809Py_Finalize(void)
1810{
1811 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001812}
1813
Victor Stinnerb0051362019-11-22 17:52:42 +01001814
Nick Coghland6009512014-11-20 21:39:37 +10001815/* Create and initialize a new interpreter and thread, and return the
1816 new thread. This requires that Py_Initialize() has been called
1817 first.
1818
1819 Unsuccessful initialization yields a NULL pointer. Note that *no*
1820 exception information is available even in this case -- the
1821 exception information is held in the thread, and there is no
1822 thread.
1823
1824 Locking: as above.
1825
1826*/
1827
Victor Stinner331a6a52019-05-27 16:39:22 +02001828static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001829new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001830{
Victor Stinner331a6a52019-05-27 16:39:22 +02001831 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001832
Victor Stinner331a6a52019-05-27 16:39:22 +02001833 status = _PyRuntime_Initialize();
1834 if (_PyStatus_EXCEPTION(status)) {
1835 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001836 }
1837 _PyRuntimeState *runtime = &_PyRuntime;
1838
1839 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001840 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001841 }
Nick Coghland6009512014-11-20 21:39:37 +10001842
Victor Stinner8a1be612016-03-14 22:07:55 +01001843 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1844 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001845 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001846
Victor Stinner43125222019-04-24 18:23:53 +02001847 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001848 if (interp == NULL) {
1849 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001850 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001851 }
Nick Coghland6009512014-11-20 21:39:37 +10001852
Victor Stinner43125222019-04-24 18:23:53 +02001853 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001854 if (tstate == NULL) {
1855 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001856 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001857 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001858 }
1859
Victor Stinner43125222019-04-24 18:23:53 +02001860 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001861
Eric Snow1abcf672017-05-23 21:46:51 -07001862 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001863 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001864#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001865 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001866 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001867 }
1868 else
1869#endif
1870 {
Eric Snow1abcf672017-05-23 21:46:51 -07001871 /* No current thread state, copy from the main interpreter */
1872 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001873 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001874 }
1875
Victor Stinner048a3562020-11-05 00:45:56 +01001876
1877 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001878 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001879 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001880 }
Victor Stinner252346a2020-05-01 11:33:44 +02001881 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001882
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001883 status = init_interp_create_gil(tstate);
1884 if (_PyStatus_EXCEPTION(status)) {
1885 goto error;
1886 }
1887
Victor Stinnerd863ade2019-12-06 03:37:07 +01001888 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001889 if (_PyStatus_EXCEPTION(status)) {
1890 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001891 }
1892
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001893 status = init_interp_main(tstate);
1894 if (_PyStatus_EXCEPTION(status)) {
1895 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001896 }
Nick Coghland6009512014-11-20 21:39:37 +10001897
Victor Stinnera7368ac2017-11-15 18:11:45 -08001898 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001899 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001900
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001901error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001902 *tstate_p = NULL;
1903
1904 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001905 PyErr_PrintEx(0);
1906 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001907 PyThreadState_Delete(tstate);
1908 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001909 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001910
Victor Stinnerb0051362019-11-22 17:52:42 +01001911 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001912}
1913
1914PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001915_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001916{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001917 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001918 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001919 if (_PyStatus_EXCEPTION(status)) {
1920 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001921 }
1922 return tstate;
1923
Nick Coghland6009512014-11-20 21:39:37 +10001924}
1925
Victor Stinner252346a2020-05-01 11:33:44 +02001926PyThreadState *
1927Py_NewInterpreter(void)
1928{
1929 return _Py_NewInterpreter(0);
1930}
1931
Nick Coghland6009512014-11-20 21:39:37 +10001932/* Delete an interpreter and its last thread. This requires that the
1933 given thread state is current, that the thread has no remaining
1934 frames, and that it is its interpreter's only remaining thread.
1935 It is a fatal error to violate these constraints.
1936
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001937 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001938 everything, regardless.)
1939
1940 Locking: as above.
1941
1942*/
1943
1944void
1945Py_EndInterpreter(PyThreadState *tstate)
1946{
1947 PyInterpreterState *interp = tstate->interp;
1948
Victor Stinnerb45d2592019-06-20 00:05:23 +02001949 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001950 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001951 }
1952 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001953 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001954 }
Eric Snow5be45a62019-03-08 22:47:07 -07001955 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001956
Eric Snow842a2f02019-03-15 15:47:51 -06001957 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001958 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001959
Victor Stinnerb45d2592019-06-20 00:05:23 +02001960 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001961
Victor Stinnerb45d2592019-06-20 00:05:23 +02001962 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001963 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001964 }
Nick Coghland6009512014-11-20 21:39:37 +10001965
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001966 finalize_modules(tstate);
1967
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001968 finalize_interp_clear(tstate);
1969 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001970}
1971
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001972/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001973
Victor Stinner331a6a52019-05-27 16:39:22 +02001974static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001976{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001977 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001978 m = PyImport_AddModule("__main__");
1979 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001980 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001981
Nick Coghland6009512014-11-20 21:39:37 +10001982 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001983 ann_dict = PyDict_New();
1984 if ((ann_dict == NULL) ||
1985 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001986 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001987 }
1988 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001989
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001990 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1991 if (PyErr_Occurred()) {
1992 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1993 }
Nick Coghland6009512014-11-20 21:39:37 +10001994 PyObject *bimod = PyImport_ImportModule("builtins");
1995 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001996 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001997 }
1998 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001999 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10002000 }
2001 Py_DECREF(bimod);
2002 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002003
Nick Coghland6009512014-11-20 21:39:37 +10002004 /* Main is a little special - imp.is_builtin("__main__") will return
2005 * False, but BuiltinImporter is still the most appropriate initial
2006 * setting for its __loader__ attribute. A more suitable value will
2007 * be set if __main__ gets further initialized later in the startup
2008 * process.
2009 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002010 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002011 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002012 if (PyErr_Occurred()) {
2013 return _PyStatus_ERR("Failed to test __main__.__loader__");
2014 }
Nick Coghland6009512014-11-20 21:39:37 +10002015 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2016 "BuiltinImporter");
2017 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002018 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002019 }
2020 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002021 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002022 }
2023 Py_DECREF(loader);
2024 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002025 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002026}
2027
Nick Coghland6009512014-11-20 21:39:37 +10002028/* Import the site module (not into __main__ though) */
2029
Victor Stinner331a6a52019-05-27 16:39:22 +02002030static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002031init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002032{
2033 PyObject *m;
2034 m = PyImport_ImportModule("site");
2035 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002036 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002037 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002038 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002039 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002040}
2041
Victor Stinner874dbe82015-09-04 17:29:57 +02002042/* Check if a file descriptor is valid or not.
2043 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2044static int
2045is_valid_fd(int fd)
2046{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002047/* dup() is faster than fstat(): fstat() can require input/output operations,
2048 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2049 startup. Problem: dup() doesn't check if the file descriptor is valid on
2050 some platforms.
2051
2052 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2053 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2054 EBADF. FreeBSD has similar issue (bpo-32849).
2055
2056 Only use dup() on platforms where dup() is enough to detect invalid FD in
2057 corner cases: on Linux and Windows (bpo-32849). */
2058#if defined(__linux__) || defined(MS_WINDOWS)
2059 if (fd < 0) {
2060 return 0;
2061 }
2062 int fd2;
2063
2064 _Py_BEGIN_SUPPRESS_IPH
2065 fd2 = dup(fd);
2066 if (fd2 >= 0) {
2067 close(fd2);
2068 }
2069 _Py_END_SUPPRESS_IPH
2070
2071 return (fd2 >= 0);
2072#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002073 struct stat st;
2074 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002075#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002076}
2077
2078/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002079static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002080create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002081 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002082 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002083{
2084 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2085 const char* mode;
2086 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002087 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002088 int buffering, isatty;
2089 _Py_IDENTIFIER(open);
2090 _Py_IDENTIFIER(isatty);
2091 _Py_IDENTIFIER(TextIOWrapper);
2092 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002093 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002094
Victor Stinner874dbe82015-09-04 17:29:57 +02002095 if (!is_valid_fd(fd))
2096 Py_RETURN_NONE;
2097
Nick Coghland6009512014-11-20 21:39:37 +10002098 /* stdin is always opened in buffered mode, first because it shouldn't
2099 make a difference in common use cases, second because TextIOWrapper
2100 depends on the presence of a read1() method which only exists on
2101 buffered streams.
2102 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002103 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002104 buffering = 0;
2105 else
2106 buffering = -1;
2107 if (write_mode)
2108 mode = "wb";
2109 else
2110 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002111 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002112 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002113 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002114 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002115 if (buf == NULL)
2116 goto error;
2117
2118 if (buffering) {
2119 _Py_IDENTIFIER(raw);
2120 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2121 if (raw == NULL)
2122 goto error;
2123 }
2124 else {
2125 raw = buf;
2126 Py_INCREF(raw);
2127 }
2128
Steve Dower39294992016-08-30 21:22:36 -07002129#ifdef MS_WINDOWS
2130 /* Windows console IO is always UTF-8 encoded */
2131 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002132 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002133#endif
2134
Nick Coghland6009512014-11-20 21:39:37 +10002135 text = PyUnicode_FromString(name);
2136 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2137 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002138 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002139 if (res == NULL)
2140 goto error;
2141 isatty = PyObject_IsTrue(res);
2142 Py_DECREF(res);
2143 if (isatty == -1)
2144 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002145 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002146 write_through = Py_True;
2147 else
2148 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002149 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002150 line_buffering = Py_True;
2151 else
2152 line_buffering = Py_False;
2153
2154 Py_CLEAR(raw);
2155 Py_CLEAR(text);
2156
2157#ifdef MS_WINDOWS
2158 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2159 newlines to "\n".
2160 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2161 newline = NULL;
2162#else
2163 /* sys.stdin: split lines at "\n".
2164 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2165 newline = "\n";
2166#endif
2167
Victor Stinner709d23d2019-05-02 14:56:30 -04002168 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2169 if (encoding_str == NULL) {
2170 Py_CLEAR(buf);
2171 goto error;
2172 }
2173
2174 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2175 if (errors_str == NULL) {
2176 Py_CLEAR(buf);
2177 Py_CLEAR(encoding_str);
2178 goto error;
2179 }
2180
2181 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2182 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002183 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002184 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002185 Py_CLEAR(encoding_str);
2186 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002187 if (stream == NULL)
2188 goto error;
2189
2190 if (write_mode)
2191 mode = "w";
2192 else
2193 mode = "r";
2194 text = PyUnicode_FromString(mode);
2195 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2196 goto error;
2197 Py_CLEAR(text);
2198 return stream;
2199
2200error:
2201 Py_XDECREF(buf);
2202 Py_XDECREF(stream);
2203 Py_XDECREF(text);
2204 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002205
Victor Stinner874dbe82015-09-04 17:29:57 +02002206 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2207 /* Issue #24891: the file descriptor was closed after the first
2208 is_valid_fd() check was called. Ignore the OSError and set the
2209 stream to None. */
2210 PyErr_Clear();
2211 Py_RETURN_NONE;
2212 }
2213 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002214}
2215
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002216/* Set builtins.open to io.OpenWrapper */
2217static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002218init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002219{
2220 PyObject *iomod = NULL, *wrapper;
2221 PyObject *bimod = NULL;
2222 PyStatus res = _PyStatus_OK();
2223
2224 if (!(iomod = PyImport_ImportModule("io"))) {
2225 goto error;
2226 }
2227
2228 if (!(bimod = PyImport_ImportModule("builtins"))) {
2229 goto error;
2230 }
2231
2232 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2233 goto error;
2234 }
2235
2236 /* Set builtins.open */
2237 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2238 Py_DECREF(wrapper);
2239 goto error;
2240 }
2241 Py_DECREF(wrapper);
2242 goto done;
2243
2244error:
2245 res = _PyStatus_ERR("can't initialize io.open");
2246
2247done:
2248 Py_XDECREF(bimod);
2249 Py_XDECREF(iomod);
2250 return res;
2251}
2252
2253
Nick Coghland6009512014-11-20 21:39:37 +10002254/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002255static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002256init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002257{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002258 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002259 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002260 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002261 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002262 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002263 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002264
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002265 /* Check that stdin is not a directory
2266 Using shell redirection, you can redirect stdin to a directory,
2267 crashing the Python interpreter. Catch this common mistake here
2268 and output a useful error message. Note that under MS Windows,
2269 the shell already prevents that. */
2270#ifndef MS_WINDOWS
2271 struct _Py_stat_struct sb;
2272 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2273 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002274 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002275 }
2276#endif
2277
Nick Coghland6009512014-11-20 21:39:37 +10002278 if (!(iomod = PyImport_ImportModule("io"))) {
2279 goto error;
2280 }
Nick Coghland6009512014-11-20 21:39:37 +10002281
Nick Coghland6009512014-11-20 21:39:37 +10002282 /* Set sys.stdin */
2283 fd = fileno(stdin);
2284 /* Under some conditions stdin, stdout and stderr may not be connected
2285 * and fileno() may point to an invalid file descriptor. For example
2286 * GUI apps don't have valid standard streams by default.
2287 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002288 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002289 config->stdio_encoding,
2290 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002291 if (std == NULL)
2292 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002293 PySys_SetObject("__stdin__", std);
2294 _PySys_SetObjectId(&PyId_stdin, std);
2295 Py_DECREF(std);
2296
2297 /* Set sys.stdout */
2298 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002299 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002300 config->stdio_encoding,
2301 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002302 if (std == NULL)
2303 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002304 PySys_SetObject("__stdout__", std);
2305 _PySys_SetObjectId(&PyId_stdout, std);
2306 Py_DECREF(std);
2307
2308#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2309 /* Set sys.stderr, replaces the preliminary stderr */
2310 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002311 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002312 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002313 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002314 if (std == NULL)
2315 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002316
2317 /* Same as hack above, pre-import stderr's codec to avoid recursion
2318 when import.c tries to write to stderr in verbose mode. */
2319 encoding_attr = PyObject_GetAttrString(std, "encoding");
2320 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002321 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002322 if (std_encoding != NULL) {
2323 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2324 Py_XDECREF(codec_info);
2325 }
2326 Py_DECREF(encoding_attr);
2327 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002328 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002329
2330 if (PySys_SetObject("__stderr__", std) < 0) {
2331 Py_DECREF(std);
2332 goto error;
2333 }
2334 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2335 Py_DECREF(std);
2336 goto error;
2337 }
2338 Py_DECREF(std);
2339#endif
2340
Victor Stinnera7368ac2017-11-15 18:11:45 -08002341 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002342
Victor Stinnera7368ac2017-11-15 18:11:45 -08002343error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002344 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002345
2346done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002347 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002348 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002349 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002350}
2351
2352
Victor Stinner10dc4842015-03-24 12:01:30 +01002353static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002354_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2355 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002356{
Victor Stinner10dc4842015-03-24 12:01:30 +01002357 fputc('\n', stderr);
2358 fflush(stderr);
2359
2360 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002361 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002362}
Victor Stinner791da1c2016-03-14 16:53:12 +01002363
2364/* Print the current exception (if an exception is set) with its traceback,
2365 or display the current Python stack.
2366
2367 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2368 called on catastrophic cases.
2369
2370 Return 1 if the traceback was displayed, 0 otherwise. */
2371
2372static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002373_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002374{
2375 PyObject *ferr, *res;
2376 PyObject *exception, *v, *tb;
2377 int has_tb;
2378
Victor Stinnerb45d2592019-06-20 00:05:23 +02002379 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002380 if (exception == NULL) {
2381 /* No current exception */
2382 return 0;
2383 }
2384
2385 ferr = _PySys_GetObjectId(&PyId_stderr);
2386 if (ferr == NULL || ferr == Py_None) {
2387 /* sys.stderr is not set yet or set to None,
2388 no need to try to display the exception */
2389 return 0;
2390 }
2391
Victor Stinnerb45d2592019-06-20 00:05:23 +02002392 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002393 if (tb == NULL) {
2394 tb = Py_None;
2395 Py_INCREF(tb);
2396 }
2397 PyException_SetTraceback(v, tb);
2398 if (exception == NULL) {
2399 /* PyErr_NormalizeException() failed */
2400 return 0;
2401 }
2402
2403 has_tb = (tb != Py_None);
2404 PyErr_Display(exception, v, tb);
2405 Py_XDECREF(exception);
2406 Py_XDECREF(v);
2407 Py_XDECREF(tb);
2408
2409 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002410 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002411 if (res == NULL) {
2412 _PyErr_Clear(tstate);
2413 }
2414 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002415 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002416 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002417
2418 return has_tb;
2419}
2420
Nick Coghland6009512014-11-20 21:39:37 +10002421/* Print fatal error message and abort */
2422
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002423#ifdef MS_WINDOWS
2424static void
2425fatal_output_debug(const char *msg)
2426{
2427 /* buffer of 256 bytes allocated on the stack */
2428 WCHAR buffer[256 / sizeof(WCHAR)];
2429 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2430 size_t msglen;
2431
2432 OutputDebugStringW(L"Fatal Python error: ");
2433
2434 msglen = strlen(msg);
2435 while (msglen) {
2436 size_t i;
2437
2438 if (buflen > msglen) {
2439 buflen = msglen;
2440 }
2441
2442 /* Convert the message to wchar_t. This uses a simple one-to-one
2443 conversion, assuming that the this error message actually uses
2444 ASCII only. If this ceases to be true, we will have to convert. */
2445 for (i=0; i < buflen; ++i) {
2446 buffer[i] = msg[i];
2447 }
2448 buffer[i] = L'\0';
2449 OutputDebugStringW(buffer);
2450
2451 msg += buflen;
2452 msglen -= buflen;
2453 }
2454 OutputDebugStringW(L"\n");
2455}
2456#endif
2457
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002458
2459static void
2460fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2461{
2462 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002463 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2464 if (finalizing) {
2465 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002466 }
2467 else if (runtime->initialized) {
2468 fprintf(stream, "initialized");
2469 }
2470 else if (runtime->core_initialized) {
2471 fprintf(stream, "core initialized");
2472 }
2473 else if (runtime->preinitialized) {
2474 fprintf(stream, "preinitialized");
2475 }
2476 else if (runtime->preinitializing) {
2477 fprintf(stream, "preinitializing");
2478 }
2479 else {
2480 fprintf(stream, "unknown");
2481 }
2482 fprintf(stream, "\n");
2483 fflush(stream);
2484}
2485
2486
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002487static inline void _Py_NO_RETURN
2488fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002489{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002490 if (status < 0) {
2491#if defined(MS_WINDOWS) && defined(_DEBUG)
2492 DebugBreak();
2493#endif
2494 abort();
2495 }
2496 else {
2497 exit(status);
2498 }
2499}
2500
2501
2502static void _Py_NO_RETURN
2503fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2504 int status)
2505{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002506 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002507 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002508
2509 if (reentrant) {
2510 /* Py_FatalError() caused a second fatal error.
2511 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002512 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002513 }
2514 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002515
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002516 if (header) {
2517 fprintf(stream, "Fatal Python error: ");
2518 if (prefix) {
2519 fputs(prefix, stream);
2520 fputs(": ", stream);
2521 }
2522 if (msg) {
2523 fputs(msg, stream);
2524 }
2525 else {
2526 fprintf(stream, "<message not set>");
2527 }
2528 fputs("\n", stream);
2529 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002530 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002531
2532 _PyRuntimeState *runtime = &_PyRuntime;
2533 fatal_error_dump_runtime(stream, runtime);
2534
2535 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2536 PyInterpreterState *interp = NULL;
2537 if (tstate != NULL) {
2538 interp = tstate->interp;
2539 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002540
Victor Stinner3a228ab2018-11-01 00:26:41 +01002541 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002542 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002543
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002544 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2545 has no Python thread state.
2546
2547 tss_tstate != tstate if the current Python thread does not hold the GIL.
2548 */
2549 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2550 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002551 if (has_tstate_and_gil) {
2552 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002553 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002554 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002555 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002556 }
2557 }
2558 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002559 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002560 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002561
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002562 /* The main purpose of faulthandler is to display the traceback.
2563 This function already did its best to display a traceback.
2564 Disable faulthandler to prevent writing a second traceback
2565 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002566 _PyFaulthandler_Fini();
2567
Victor Stinner791da1c2016-03-14 16:53:12 +01002568 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002569 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002570 /* Flush sys.stdout and sys.stderr */
2571 flush_std_files();
2572 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002573
Nick Coghland6009512014-11-20 21:39:37 +10002574#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002575 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002576#endif /* MS_WINDOWS */
2577
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002578 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002579}
2580
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002581
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002582#undef Py_FatalError
2583
Victor Stinner19760862017-12-20 01:41:59 +01002584void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002585Py_FatalError(const char *msg)
2586{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002587 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002588}
2589
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002590
Victor Stinner19760862017-12-20 01:41:59 +01002591void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002592_Py_FatalErrorFunc(const char *func, const char *msg)
2593{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002594 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002595}
2596
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002597
2598void _Py_NO_RETURN
2599_Py_FatalErrorFormat(const char *func, const char *format, ...)
2600{
2601 static int reentrant = 0;
2602 if (reentrant) {
2603 /* _Py_FatalErrorFormat() caused a second fatal error */
2604 fatal_error_exit(-1);
2605 }
2606 reentrant = 1;
2607
2608 FILE *stream = stderr;
2609 fprintf(stream, "Fatal Python error: ");
2610 if (func) {
2611 fputs(func, stream);
2612 fputs(": ", stream);
2613 }
2614 fflush(stream);
2615
2616 va_list vargs;
2617#ifdef HAVE_STDARG_PROTOTYPES
2618 va_start(vargs, format);
2619#else
2620 va_start(vargs);
2621#endif
2622 vfprintf(stream, format, vargs);
2623 va_end(vargs);
2624
2625 fputs("\n", stream);
2626 fflush(stream);
2627
2628 fatal_error(stream, 0, NULL, NULL, -1);
2629}
2630
2631
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002632void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002633Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002634{
Victor Stinner331a6a52019-05-27 16:39:22 +02002635 if (_PyStatus_IS_EXIT(status)) {
2636 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002637 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002638 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002639 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002640 }
2641 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002642 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002643 }
Nick Coghland6009512014-11-20 21:39:37 +10002644}
2645
2646/* Clean up and exit */
2647
Nick Coghland6009512014-11-20 21:39:37 +10002648/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002649void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002650{
Victor Stinner81a7be32020-04-14 15:14:01 +02002651 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002652
Antoine Pitroufc5db952017-12-13 02:29:07 +01002653 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002654 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2655
2656 is->pyexitfunc = func;
2657 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002658}
2659
2660static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002661call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002662{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002663 PyInterpreterState *interp = tstate->interp;
2664 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002665 return;
2666
Victor Stinnerb45d2592019-06-20 00:05:23 +02002667 (*interp->pyexitfunc)(interp->pyexitmodule);
2668 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002669}
2670
2671/* Wait until threading._shutdown completes, provided
2672 the threading module was imported in the first place.
2673 The shutdown routine will wait until all non-daemon
2674 "threading" threads have completed. */
2675static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002676wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002677{
Nick Coghland6009512014-11-20 21:39:37 +10002678 _Py_IDENTIFIER(_shutdown);
2679 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002680 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002681 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002682 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002683 PyErr_WriteUnraisable(NULL);
2684 }
2685 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002686 return;
2687 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002688 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002689 if (result == NULL) {
2690 PyErr_WriteUnraisable(threading);
2691 }
2692 else {
2693 Py_DECREF(result);
2694 }
2695 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002696}
2697
2698#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002699int Py_AtExit(void (*func)(void))
2700{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002701 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002702 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002703 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002704 return 0;
2705}
2706
2707static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002708call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002709{
Victor Stinner8e91c242019-04-24 17:24:01 +02002710 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002711 /* pop last function from the list */
2712 runtime->nexitfuncs--;
2713 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2714 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2715
2716 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002717 }
Nick Coghland6009512014-11-20 21:39:37 +10002718
2719 fflush(stdout);
2720 fflush(stderr);
2721}
2722
Victor Stinnercfc88312018-08-01 16:41:25 +02002723void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002724Py_Exit(int sts)
2725{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002726 if (Py_FinalizeEx() < 0) {
2727 sts = 120;
2728 }
Nick Coghland6009512014-11-20 21:39:37 +10002729
2730 exit(sts);
2731}
2732
Victor Stinner331a6a52019-05-27 16:39:22 +02002733static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002734init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002735{
2736#ifdef SIGPIPE
2737 PyOS_setsig(SIGPIPE, SIG_IGN);
2738#endif
2739#ifdef SIGXFZ
2740 PyOS_setsig(SIGXFZ, SIG_IGN);
2741#endif
2742#ifdef SIGXFSZ
2743 PyOS_setsig(SIGXFSZ, SIG_IGN);
2744#endif
Victor Stinner400e1db2020-03-31 19:13:10 +02002745 PyOS_InitInterrupts(); /* May imply init_signals() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002746 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002747 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002748 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002749 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002750}
2751
2752
2753/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2754 *
2755 * All of the code in this function must only use async-signal-safe functions,
2756 * listed at `man 7 signal` or
2757 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002758 *
2759 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002760 */
2761void
2762_Py_RestoreSignals(void)
2763{
2764#ifdef SIGPIPE
2765 PyOS_setsig(SIGPIPE, SIG_DFL);
2766#endif
2767#ifdef SIGXFZ
2768 PyOS_setsig(SIGXFZ, SIG_DFL);
2769#endif
2770#ifdef SIGXFSZ
2771 PyOS_setsig(SIGXFSZ, SIG_DFL);
2772#endif
2773}
2774
2775
2776/*
2777 * The file descriptor fd is considered ``interactive'' if either
2778 * a) isatty(fd) is TRUE, or
2779 * b) the -i flag was given, and the filename associated with
2780 * the descriptor is NULL or "<stdin>" or "???".
2781 */
2782int
2783Py_FdIsInteractive(FILE *fp, const char *filename)
2784{
2785 if (isatty((int)fileno(fp)))
2786 return 1;
2787 if (!Py_InteractiveFlag)
2788 return 0;
2789 return (filename == NULL) ||
2790 (strcmp(filename, "<stdin>") == 0) ||
2791 (strcmp(filename, "???") == 0);
2792}
2793
2794
Nick Coghland6009512014-11-20 21:39:37 +10002795/* Wrappers around sigaction() or signal(). */
2796
2797PyOS_sighandler_t
2798PyOS_getsig(int sig)
2799{
2800#ifdef HAVE_SIGACTION
2801 struct sigaction context;
2802 if (sigaction(sig, NULL, &context) == -1)
2803 return SIG_ERR;
2804 return context.sa_handler;
2805#else
2806 PyOS_sighandler_t handler;
2807/* Special signal handling for the secure CRT in Visual Studio 2005 */
2808#if defined(_MSC_VER) && _MSC_VER >= 1400
2809 switch (sig) {
2810 /* Only these signals are valid */
2811 case SIGINT:
2812 case SIGILL:
2813 case SIGFPE:
2814 case SIGSEGV:
2815 case SIGTERM:
2816 case SIGBREAK:
2817 case SIGABRT:
2818 break;
2819 /* Don't call signal() with other values or it will assert */
2820 default:
2821 return SIG_ERR;
2822 }
2823#endif /* _MSC_VER && _MSC_VER >= 1400 */
2824 handler = signal(sig, SIG_IGN);
2825 if (handler != SIG_ERR)
2826 signal(sig, handler);
2827 return handler;
2828#endif
2829}
2830
2831/*
2832 * All of the code in this function must only use async-signal-safe functions,
2833 * listed at `man 7 signal` or
2834 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2835 */
2836PyOS_sighandler_t
2837PyOS_setsig(int sig, PyOS_sighandler_t handler)
2838{
2839#ifdef HAVE_SIGACTION
2840 /* Some code in Modules/signalmodule.c depends on sigaction() being
2841 * used here if HAVE_SIGACTION is defined. Fix that if this code
2842 * changes to invalidate that assumption.
2843 */
2844 struct sigaction context, ocontext;
2845 context.sa_handler = handler;
2846 sigemptyset(&context.sa_mask);
2847 context.sa_flags = 0;
2848 if (sigaction(sig, &context, &ocontext) == -1)
2849 return SIG_ERR;
2850 return ocontext.sa_handler;
2851#else
2852 PyOS_sighandler_t oldhandler;
2853 oldhandler = signal(sig, handler);
2854#ifdef HAVE_SIGINTERRUPT
2855 siginterrupt(sig, 1);
2856#endif
2857 return oldhandler;
2858#endif
2859}
2860
2861#ifdef __cplusplus
2862}
2863#endif