blob: 9828dffad5c63009f34173c412e7bf65614d3da2 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +02007
8#include "pycore_ceval.h" // _PyEval_FiniGIL()
9#include "pycore_context.h" // _PyContext_Init()
10#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner62230712020-11-18 23:18:29 +010011#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner4f98f462020-04-15 04:01:58 +020012#include "pycore_initconfig.h" // _PyStatus_OK()
13#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
14#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
15#include "pycore_pyerrors.h" // _PyErr_Occurred()
16#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020017#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020018#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
19#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
20
Victor Stinner4f98f462020-04-15 04:01:58 +020021#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100022
23#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020024# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100025#endif
26
27#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020028# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100029#endif
30
31#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020032# undef BYTE
33# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070034
Victor Stinner4f98f462020-04-15 04:01:58 +020035 extern PyTypeObject PyWindowsConsoleIO_Type;
36# define PyWindowsConsoleIO_Check(op) \
37 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
Victor Stinner4f98f462020-04-15 04:01:58 +020040
Nick Coghland6009512014-11-20 21:39:37 +100041_Py_IDENTIFIER(flush);
42_Py_IDENTIFIER(name);
43_Py_IDENTIFIER(stdin);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060046_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100047
48#ifdef __cplusplus
49extern "C" {
50#endif
51
Nick Coghland6009512014-11-20 21:39:37 +100052
Victor Stinnerb45d2592019-06-20 00:05:23 +020053/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020054static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020055static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050056static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020057static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020058static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020059static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100060
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080061int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010063static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060064
Victor Stinner331a6a52019-05-27 16:39:22 +020065PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066_PyRuntime_Initialize(void)
67{
68 /* XXX We only initialize once in the process, which aligns with
69 the static initialization of the former globals now found in
70 _PyRuntime. However, _PyRuntime *should* be initialized with
71 every Py_Initialize() call, but doing so breaks the runtime.
72 This is because the runtime state is not properly finalized
73 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010074 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020075 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010077 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078
79 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080}
81
82void
83_PyRuntime_Finalize(void)
84{
85 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
88
89int
90_Py_IsFinalizing(void)
91{
Victor Stinner7b3c2522020-03-07 00:24:23 +010092 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060093}
94
Nick Coghland6009512014-11-20 21:39:37 +100095/* Hack to force loading of object files */
96int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
97 PyOS_mystrnicmp; /* Python/pystrcmp.o */
98
Eric Snowc7ec9982017-05-23 23:00:52 -070099
Eric Snow1abcf672017-05-23 21:46:51 -0700100/* APIs to access the initialization flags
101 *
102 * Can be called prior to Py_Initialize.
103 */
Nick Coghland6009512014-11-20 21:39:37 +1000104
Eric Snow1abcf672017-05-23 21:46:51 -0700105int
106_Py_IsCoreInitialized(void)
107{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600108 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700109}
Nick Coghland6009512014-11-20 21:39:37 +1000110
111int
112Py_IsInitialized(void)
113{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000115}
116
Nick Coghlan6ea41862017-06-11 13:16:15 +1000117
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000118/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
119 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000120 initializations fail, a fatal error is issued and the function does
121 not return. On return, the first thread and interpreter state have
122 been created.
123
124 Locking: you must hold the interpreter lock while calling this.
125 (If the lock has not yet been initialized, that's equivalent to
126 having the lock, but you cannot use multiple threads.)
127
128*/
Victor Stinneref75a622020-11-12 15:14:13 +0100129static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200130init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000131{
Victor Stinneref75a622020-11-12 15:14:13 +0100132 assert(!_PyErr_Occurred(tstate));
133
Victor Stinnerb45d2592019-06-20 00:05:23 +0200134 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200135 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000136
Victor Stinneref75a622020-11-12 15:14:13 +0100137 // Import _importlib through its frozen version, _frozen_importlib.
138 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000139 PySys_FormatStderr("import _frozen_importlib # frozen\n");
140 }
Victor Stinneref75a622020-11-12 15:14:13 +0100141 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
142 return -1;
143 }
144 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000145 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100146 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000147 }
Victor Stinneref75a622020-11-12 15:14:13 +0100148 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000149
Victor Stinneref75a622020-11-12 15:14:13 +0100150 // Import the _imp module
151 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200152 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000153 }
Victor Stinner62230712020-11-18 23:18:29 +0100154 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100155 if (imp_mod == NULL) {
156 return -1;
157 }
158 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
159 Py_DECREF(imp_mod);
160 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000161 }
162
Victor Stinneref75a622020-11-12 15:14:13 +0100163 // Install importlib as the implementation of import
164 PyObject *value = PyObject_CallMethod(importlib, "_install",
165 "OO", sysmod, imp_mod);
166 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000167 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100168 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000169 }
170 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000171
Victor Stinneref75a622020-11-12 15:14:13 +0100172 assert(!_PyErr_Occurred(tstate));
173 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000174}
175
Victor Stinneref75a622020-11-12 15:14:13 +0100176
Victor Stinner331a6a52019-05-27 16:39:22 +0200177static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200178init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700179{
180 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200181 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700182 "_install_external_importers", "");
183 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200184 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200185 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700186 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200187 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200188 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700189}
Nick Coghland6009512014-11-20 21:39:37 +1000190
Nick Coghlan6ea41862017-06-11 13:16:15 +1000191/* Helper functions to better handle the legacy C locale
192 *
193 * The legacy C locale assumes ASCII as the default text encoding, which
194 * causes problems not only for the CPython runtime, but also other
195 * components like GNU readline.
196 *
197 * Accordingly, when the CLI detects it, it attempts to coerce it to a
198 * more capable UTF-8 based alternative as follows:
199 *
200 * if (_Py_LegacyLocaleDetected()) {
201 * _Py_CoerceLegacyLocale();
202 * }
203 *
204 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
205 *
206 * Locale coercion also impacts the default error handler for the standard
207 * streams: while the usual default is "strict", the default for the legacy
208 * C locale and for any of the coercion target locales is "surrogateescape".
209 */
210
211int
Victor Stinner0f721472019-05-20 17:16:38 +0200212_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000213{
214#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200215 if (!warn) {
216 const char *locale_override = getenv("LC_ALL");
217 if (locale_override != NULL && *locale_override != '\0') {
218 /* Don't coerce C locale if the LC_ALL environment variable
219 is set */
220 return 0;
221 }
222 }
223
Nick Coghlan6ea41862017-06-11 13:16:15 +1000224 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000225 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
226 * the POSIX locale as a simple alias for the C locale, so
227 * we may also want to check for that explicitly.
228 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000229 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
230 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
231#else
232 /* Windows uses code pages instead of locales, so no locale is legacy */
233 return 0;
234#endif
235}
236
Victor Stinnerb0051362019-11-22 17:52:42 +0100237#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000238static const char *_C_LOCALE_WARNING =
239 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
240 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
241 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
242 "locales is recommended.\n";
243
Nick Coghlaneb817952017-06-18 12:29:42 +1000244static void
Victor Stinner43125222019-04-24 18:23:53 +0200245emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000246{
Victor Stinner331a6a52019-05-27 16:39:22 +0200247 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200248 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200249 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000250 }
251}
Victor Stinnerb0051362019-11-22 17:52:42 +0100252#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000253
Nick Coghlan6ea41862017-06-11 13:16:15 +1000254typedef struct _CandidateLocale {
255 const char *locale_name; /* The locale to try as a coercion target */
256} _LocaleCoercionTarget;
257
258static _LocaleCoercionTarget _TARGET_LOCALES[] = {
259 {"C.UTF-8"},
260 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000261 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000262 {NULL}
263};
264
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200265
266int
267_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000268{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200269 const _LocaleCoercionTarget *target = NULL;
270 for (target = _TARGET_LOCALES; target->locale_name; target++) {
271 if (strcmp(ctype_loc, target->locale_name) == 0) {
272 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000273 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200274 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200275 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276}
277
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200278
Nick Coghlan6ea41862017-06-11 13:16:15 +1000279#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100280static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000281 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
282 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
283
Victor Stinner0f721472019-05-20 17:16:38 +0200284static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200285_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000286{
287 const char *newloc = target->locale_name;
288
289 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100290 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291
292 /* Set the relevant locale environment variable */
293 if (setenv("LC_CTYPE", newloc, 1)) {
294 fprintf(stderr,
295 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200296 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200298 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100299 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000300 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301
302 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100303 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200304 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305}
306#endif
307
Victor Stinner0f721472019-05-20 17:16:38 +0200308int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200309_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310{
Victor Stinner0f721472019-05-20 17:16:38 +0200311 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200313 char *oldloc = NULL;
314
315 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
316 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200317 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200318 }
319
Victor Stinner94540602017-12-16 04:54:22 +0100320 const char *locale_override = getenv("LC_ALL");
321 if (locale_override == NULL || *locale_override == '\0') {
322 /* LC_ALL is also not set (or is set to an empty string) */
323 const _LocaleCoercionTarget *target = NULL;
324 for (target = _TARGET_LOCALES; target->locale_name; target++) {
325 const char *new_locale = setlocale(LC_CTYPE,
326 target->locale_name);
327 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400328#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100329 /* Also ensure that nl_langinfo works in this locale */
330 char *codeset = nl_langinfo(CODESET);
331 if (!codeset || *codeset == '\0') {
332 /* CODESET is not set or empty, so skip coercion */
333 new_locale = NULL;
334 _Py_SetLocaleFromEnv(LC_CTYPE);
335 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000336 }
Victor Stinner94540602017-12-16 04:54:22 +0100337#endif
338 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200339 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200340 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000341 }
342 }
343 }
344 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200345
346 setlocale(LC_CTYPE, oldloc);
347
348done:
349 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200351 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000352}
353
xdegaye1588be62017-11-12 12:45:59 +0100354/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
355 * isolate the idiosyncrasies of different libc implementations. It reads the
356 * appropriate environment variable and uses its value to select the locale for
357 * 'category'. */
358char *
359_Py_SetLocaleFromEnv(int category)
360{
Victor Stinner353933e2018-11-23 13:08:26 +0100361 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100362#ifdef __ANDROID__
363 const char *locale;
364 const char **pvar;
365#ifdef PY_COERCE_C_LOCALE
366 const char *coerce_c_locale;
367#endif
368 const char *utf8_locale = "C.UTF-8";
369 const char *env_var_set[] = {
370 "LC_ALL",
371 "LC_CTYPE",
372 "LANG",
373 NULL,
374 };
375
376 /* Android setlocale(category, "") doesn't check the environment variables
377 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
378 * check the environment variables listed in env_var_set. */
379 for (pvar=env_var_set; *pvar; pvar++) {
380 locale = getenv(*pvar);
381 if (locale != NULL && *locale != '\0') {
382 if (strcmp(locale, utf8_locale) == 0 ||
383 strcmp(locale, "en_US.UTF-8") == 0) {
384 return setlocale(category, utf8_locale);
385 }
386 return setlocale(category, "C");
387 }
388 }
389
390 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
391 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
392 * Quote from POSIX section "8.2 Internationalization Variables":
393 * "4. If the LANG environment variable is not set or is set to the empty
394 * string, the implementation-defined default locale shall be used." */
395
396#ifdef PY_COERCE_C_LOCALE
397 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
398 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
399 /* Some other ported code may check the environment variables (e.g. in
400 * extension modules), so we make sure that they match the locale
401 * configuration */
402 if (setenv("LC_CTYPE", utf8_locale, 1)) {
403 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
404 "environment variable to %s\n", utf8_locale);
405 }
406 }
407#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100408 res = setlocale(category, utf8_locale);
409#else /* !defined(__ANDROID__) */
410 res = setlocale(category, "");
411#endif
412 _Py_ResetForceASCII();
413 return res;
xdegaye1588be62017-11-12 12:45:59 +0100414}
415
Nick Coghlan6ea41862017-06-11 13:16:15 +1000416
Victor Stinner048a3562020-11-05 00:45:56 +0100417static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100418interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100419{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100420 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100421
Victor Stinner9e1b8282020-11-10 13:21:52 +0100422 if (!only_update_path_config) {
423 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
424 if (_PyStatus_EXCEPTION(status)) {
425 _PyErr_SetFromPyStatus(status);
426 return -1;
427 }
Victor Stinner048a3562020-11-05 00:45:56 +0100428 }
429
Victor Stinner9e1b8282020-11-10 13:21:52 +0100430 if (_Py_IsMainInterpreter(tstate)) {
431 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100432 if (_PyStatus_EXCEPTION(status)) {
433 _PyErr_SetFromPyStatus(status);
434 return -1;
435 }
436 }
437
438 // Update the sys module for the new configuration
439 if (_PySys_UpdateConfig(tstate) < 0) {
440 return -1;
441 }
442 return 0;
443}
444
445
446int
447_PyInterpreterState_SetConfig(const PyConfig *src_config)
448{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100449 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100450 int res = -1;
451
452 PyConfig config;
453 PyConfig_InitPythonConfig(&config);
454 PyStatus status = _PyConfig_Copy(&config, src_config);
455 if (_PyStatus_EXCEPTION(status)) {
456 _PyErr_SetFromPyStatus(status);
457 goto done;
458 }
459
460 status = PyConfig_Read(&config);
461 if (_PyStatus_EXCEPTION(status)) {
462 _PyErr_SetFromPyStatus(status);
463 goto done;
464 }
465
Victor Stinner9e1b8282020-11-10 13:21:52 +0100466 status = _PyConfig_Copy(&tstate->interp->config, &config);
467 if (_PyStatus_EXCEPTION(status)) {
468 _PyErr_SetFromPyStatus(status);
469 goto done;
470 }
471
472 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100473
474done:
475 PyConfig_Clear(&config);
476 return res;
477}
478
479
Eric Snow1abcf672017-05-23 21:46:51 -0700480/* Global initializations. Can be undone by Py_Finalize(). Don't
481 call this twice without an intervening Py_Finalize() call.
482
Victor Stinner331a6a52019-05-27 16:39:22 +0200483 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700484 must have a corresponding call to Py_Finalize.
485
486 Locking: you must hold the interpreter lock while calling these APIs.
487 (If the lock has not yet been initialized, that's equivalent to
488 having the lock, but you cannot use multiple threads.)
489
490*/
491
Victor Stinner331a6a52019-05-27 16:39:22 +0200492static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200493pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200494 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200495 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200496{
Victor Stinner331a6a52019-05-27 16:39:22 +0200497 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100498 PyThreadState *tstate = _PyThreadState_GET();
499 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200500 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100501 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200502 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100503
504 PyInterpreterState *interp = tstate->interp;
505 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200506 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100507 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100508
Victor Stinnere81f6e62020-06-08 18:12:59 +0200509 status = _PyConfig_Write(config, runtime);
510 if (_PyStatus_EXCEPTION(status)) {
511 return status;
512 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200513
Victor Stinner048a3562020-11-05 00:45:56 +0100514 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200515 if (_PyStatus_EXCEPTION(status)) {
516 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200517 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200518 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200519
Victor Stinner331a6a52019-05-27 16:39:22 +0200520 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200521 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200522 if (_PyStatus_EXCEPTION(status)) {
523 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200524 }
525 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200526 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527}
528
529
Victor Stinner331a6a52019-05-27 16:39:22 +0200530static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200531pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200532 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000533{
Victor Stinner43125222019-04-24 18:23:53 +0200534 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200536 }
Victor Stinnerda273412017-12-15 01:46:02 +0100537
Victor Stinnere81f6e62020-06-08 18:12:59 +0200538 PyStatus status = _PyConfig_Write(config, runtime);
539 if (_PyStatus_EXCEPTION(status)) {
540 return status;
541 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600542
Eric Snow1abcf672017-05-23 21:46:51 -0700543 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
544 * threads behave a little more gracefully at interpreter shutdown.
545 * We clobber it here so the new interpreter can start with a clean
546 * slate.
547 *
548 * However, this may still lead to misbehaviour if there are daemon
549 * threads still hanging around from a previous Py_Initialize/Finalize
550 * pair :(
551 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100552 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600553
Victor Stinnere81f6e62020-06-08 18:12:59 +0200554 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200555 if (_PyStatus_EXCEPTION(status)) {
556 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800557 }
558
Victor Stinner331a6a52019-05-27 16:39:22 +0200559 status = _PyInterpreterState_Enable(runtime);
560 if (_PyStatus_EXCEPTION(status)) {
561 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800562 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200563 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100564}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800565
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100566
Victor Stinner331a6a52019-05-27 16:39:22 +0200567static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200568init_interp_create_gil(PyThreadState *tstate)
569{
570 PyStatus status;
571
572 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
573 only called here. */
574 _PyEval_FiniGIL(tstate);
575
576 /* Auto-thread-state API */
577 status = _PyGILState_Init(tstate);
578 if (_PyStatus_EXCEPTION(status)) {
579 return status;
580 }
581
582 /* Create the GIL and take it */
583 status = _PyEval_InitGIL(tstate);
584 if (_PyStatus_EXCEPTION(status)) {
585 return status;
586 }
587
588 return _PyStatus_OK();
589}
590
591
592static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200593pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200594 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200595 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596{
597 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100598 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200599 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100600 }
601
Victor Stinner048a3562020-11-05 00:45:56 +0100602 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200603 if (_PyStatus_EXCEPTION(status)) {
604 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100605 }
Nick Coghland6009512014-11-20 21:39:37 +1000606
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200607 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200608 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200609 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200610 }
Nick Coghland6009512014-11-20 21:39:37 +1000611 (void) PyThreadState_Swap(tstate);
612
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200613 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100614 if (_PyStatus_EXCEPTION(status)) {
615 return status;
616 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100617
Victor Stinnerb45d2592019-06-20 00:05:23 +0200618 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200619 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100620}
Nick Coghland6009512014-11-20 21:39:37 +1000621
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100622
Victor Stinner331a6a52019-05-27 16:39:22 +0200623static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100624pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100625{
Victor Stinner444b39b2019-11-20 01:18:11 +0100626 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100627 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100628
Victor Stinner01b1cc12019-11-20 02:27:56 +0100629 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100630 if (_PyStatus_EXCEPTION(status)) {
631 return status;
632 }
633
Victor Stinner0430dfa2020-06-24 15:21:54 +0200634 // Create the empty tuple singleton. It must be created before the first
635 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
636 // for example.
637 status = _PyTuple_Init(tstate);
638 if (_PyStatus_EXCEPTION(status)) {
639 return status;
640 }
641
Victor Stinnere7e699e2019-11-20 12:08:13 +0100642 if (is_main_interp) {
643 status = _PyTypes_Init();
644 if (_PyStatus_EXCEPTION(status)) {
645 return status;
646 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100647 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100648
Victor Stinner630c8df2019-12-17 13:02:18 +0100649 if (!_PyLong_Init(tstate)) {
650 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100651 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100652
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200653 status = _PyUnicode_Init(tstate);
654 if (_PyStatus_EXCEPTION(status)) {
655 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100656 }
657
Victor Stinner91698d82020-06-25 14:07:40 +0200658 status = _PyBytes_Init(tstate);
659 if (_PyStatus_EXCEPTION(status)) {
660 return status;
661 }
662
Victor Stinner281cce12020-06-23 22:55:46 +0200663 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200664 if (_PyStatus_EXCEPTION(status)) {
665 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100666 }
667
Victor Stinnere7e699e2019-11-20 12:08:13 +0100668 if (is_main_interp) {
669 if (!_PyFloat_Init()) {
670 return _PyStatus_ERR("can't init float");
671 }
Nick Coghland6009512014-11-20 21:39:37 +1000672
Victor Stinnere7e699e2019-11-20 12:08:13 +0100673 if (_PyStructSequence_Init() < 0) {
674 return _PyStatus_ERR("can't initialize structseq");
675 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100676 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200677
Victor Stinner331a6a52019-05-27 16:39:22 +0200678 status = _PyErr_Init();
679 if (_PyStatus_EXCEPTION(status)) {
680 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200681 }
682
Victor Stinnere7e699e2019-11-20 12:08:13 +0100683 if (is_main_interp) {
684 if (!_PyContext_Init()) {
685 return _PyStatus_ERR("can't init context");
686 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100687 }
688
Victor Stinneref75a622020-11-12 15:14:13 +0100689 if (_PyWarnings_InitState(tstate) < 0) {
690 return _PyStatus_ERR("can't initialize warnings");
691 }
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100692
693 status = _PyAtExit_Init(tstate);
694 if (_PyStatus_EXCEPTION(status)) {
695 return status;
696 }
697
Victor Stinner331a6a52019-05-27 16:39:22 +0200698 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100699}
700
701
Victor Stinner331a6a52019-05-27 16:39:22 +0200702static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200703pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100704{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100705 assert(!_PyErr_Occurred(tstate));
706
Victor Stinnerb45d2592019-06-20 00:05:23 +0200707 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100708 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100709 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100710 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711
Victor Stinner2582d462019-11-22 19:24:49 +0100712 PyInterpreterState *interp = tstate->interp;
713 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
714 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100715 }
Victor Stinner2582d462019-11-22 19:24:49 +0100716
717 PyObject *builtins_dict = PyModule_GetDict(bimod);
718 if (builtins_dict == NULL) {
719 goto error;
720 }
721 Py_INCREF(builtins_dict);
722 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100723
Victor Stinner331a6a52019-05-27 16:39:22 +0200724 PyStatus status = _PyBuiltins_AddExceptions(bimod);
725 if (_PyStatus_EXCEPTION(status)) {
726 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100727 }
Victor Stinner2582d462019-11-22 19:24:49 +0100728
729 interp->builtins_copy = PyDict_Copy(interp->builtins);
730 if (interp->builtins_copy == NULL) {
731 goto error;
732 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000733 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100734
Victor Stinner62230712020-11-18 23:18:29 +0100735 // Get the __import__ function
736 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
737 "__import__");
738 if (import_func == NULL) {
739 goto error;
740 }
741 interp->import_func = Py_NewRef(import_func);
742
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100743 assert(!_PyErr_Occurred(tstate));
744
Victor Stinner331a6a52019-05-27 16:39:22 +0200745 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100746
747error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000748 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100749 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100750}
751
752
Victor Stinner331a6a52019-05-27 16:39:22 +0200753static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100754pycore_interp_init(PyThreadState *tstate)
755{
756 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100757 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100758
759 status = pycore_init_types(tstate);
760 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100761 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100762 }
763
Victor Stinnerd863ade2019-12-06 03:37:07 +0100764 status = _PySys_Create(tstate, &sysmod);
765 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100766 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100767 }
768
769 status = pycore_init_builtins(tstate);
770 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100771 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100772 }
773
Victor Stinneref75a622020-11-12 15:14:13 +0100774 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
775 if (config->_install_importlib) {
776 /* This call sets up builtin and frozen import support */
777 if (init_importlib(tstate, sysmod) < 0) {
778 return _PyStatus_ERR("failed to initialize importlib");
779 }
780 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100781
782done:
783 /* sys.modules['sys'] contains a strong reference to the module */
784 Py_XDECREF(sysmod);
785 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100786}
787
788
789static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200790pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200791 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200792 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100793{
Victor Stinner331a6a52019-05-27 16:39:22 +0200794 PyStatus status = pycore_init_runtime(runtime, config);
795 if (_PyStatus_EXCEPTION(status)) {
796 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100797 }
798
Victor Stinnerb45d2592019-06-20 00:05:23 +0200799 PyThreadState *tstate;
800 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200801 if (_PyStatus_EXCEPTION(status)) {
802 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100803 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200804 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100805
Victor Stinnerd863ade2019-12-06 03:37:07 +0100806 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200807 if (_PyStatus_EXCEPTION(status)) {
808 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100809 }
Eric Snow1abcf672017-05-23 21:46:51 -0700810
811 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200812 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200813 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700814}
815
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100816
Victor Stinner331a6a52019-05-27 16:39:22 +0200817PyStatus
818_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100819{
Victor Stinner331a6a52019-05-27 16:39:22 +0200820 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100821
Victor Stinner6d1c4672019-05-20 11:02:00 +0200822 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200823 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200824 }
825
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 status = _PyRuntime_Initialize();
827 if (_PyStatus_EXCEPTION(status)) {
828 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100829 }
Victor Stinner43125222019-04-24 18:23:53 +0200830 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100831
Victor Stinnerd3b90412019-09-17 23:59:51 +0200832 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100833 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200834 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100835 }
836
Victor Stinnerd3b90412019-09-17 23:59:51 +0200837 /* Note: preinitialized remains 1 on error, it is only set to 0
838 at exit on success. */
839 runtime->preinitializing = 1;
840
Victor Stinner331a6a52019-05-27 16:39:22 +0200841 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200842
843 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
844 if (_PyStatus_EXCEPTION(status)) {
845 return status;
846 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100847
Victor Stinner331a6a52019-05-27 16:39:22 +0200848 status = _PyPreConfig_Read(&config, args);
849 if (_PyStatus_EXCEPTION(status)) {
850 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100851 }
852
Victor Stinner331a6a52019-05-27 16:39:22 +0200853 status = _PyPreConfig_Write(&config);
854 if (_PyStatus_EXCEPTION(status)) {
855 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100856 }
857
Victor Stinnerd3b90412019-09-17 23:59:51 +0200858 runtime->preinitializing = 0;
859 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200860 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100861}
862
Victor Stinner70005ac2019-05-02 15:25:34 -0400863
Victor Stinner331a6a52019-05-27 16:39:22 +0200864PyStatus
865Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100866{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100867 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400868 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100869}
870
871
Victor Stinner331a6a52019-05-27 16:39:22 +0200872PyStatus
873Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100874{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100875 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400876 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100877}
878
879
Victor Stinner331a6a52019-05-27 16:39:22 +0200880PyStatus
881Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100882{
Victor Stinner70005ac2019-05-02 15:25:34 -0400883 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100884}
885
886
Victor Stinner331a6a52019-05-27 16:39:22 +0200887PyStatus
888_Py_PreInitializeFromConfig(const PyConfig *config,
889 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100890{
Victor Stinner331a6a52019-05-27 16:39:22 +0200891 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200892
Victor Stinner331a6a52019-05-27 16:39:22 +0200893 PyStatus status = _PyRuntime_Initialize();
894 if (_PyStatus_EXCEPTION(status)) {
895 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200896 }
897 _PyRuntimeState *runtime = &_PyRuntime;
898
Victor Stinnerd3b90412019-09-17 23:59:51 +0200899 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200900 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200901 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400902 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200903
Victor Stinner331a6a52019-05-27 16:39:22 +0200904 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200905
Victor Stinner3c30a762019-10-01 10:56:37 +0200906 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200907
Victor Stinner331a6a52019-05-27 16:39:22 +0200908 if (!config->parse_argv) {
909 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200910 }
911 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200912 _PyArgv config_args = {
913 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200914 .argc = config->argv.length,
915 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200916 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200917 }
918 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200919 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200920 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100921}
922
923
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100924/* Begin interpreter initialization
925 *
926 * On return, the first thread and interpreter state have been created,
927 * but the compiler, signal handling, multithreading and
928 * multiple interpreter support, and codec infrastructure are not yet
929 * available.
930 *
931 * The import system will support builtin and frozen modules only.
932 * The only supported io is writing to sys.stderr
933 *
934 * If any operation invoked by this function fails, a fatal error is
935 * issued and the function does not return.
936 *
937 * Any code invoked from this function should *not* assume it has access
938 * to the Python C API (unless the API is explicitly listed as being
939 * safe to call without calling Py_Initialize first)
940 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200941static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200942pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200943 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200944 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200945{
Victor Stinner331a6a52019-05-27 16:39:22 +0200946 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200947
Victor Stinner331a6a52019-05-27 16:39:22 +0200948 status = _Py_PreInitializeFromConfig(src_config, NULL);
949 if (_PyStatus_EXCEPTION(status)) {
950 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200951 }
952
Victor Stinner331a6a52019-05-27 16:39:22 +0200953 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100954 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200955
Victor Stinner331a6a52019-05-27 16:39:22 +0200956 status = _PyConfig_Copy(&config, src_config);
957 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200958 goto done;
959 }
960
Victor Stinner9e1b8282020-11-10 13:21:52 +0100961 // Read the configuration, but don't compute the path configuration
962 // (it is computed in the main init).
963 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200964 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200965 goto done;
966 }
967
968 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200969 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200970 }
971 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200972 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200973 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200974 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200975 goto done;
976 }
977
978done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200979 PyConfig_Clear(&config);
980 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200981}
982
Victor Stinner5ac27a52019-03-27 13:40:14 +0100983
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200984/* Py_Initialize() has already been called: update the main interpreter
985 configuration. Example of bpo-34008: Py_Main() called after
986 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200987static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100988pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200989{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100990 if (interpreter_update_config(tstate, 0) < 0) {
991 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200992 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200993 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200994}
995
Victor Stinnerb0051362019-11-22 17:52:42 +0100996
997static PyStatus
998init_interp_main(PyThreadState *tstate)
999{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001000 assert(!_PyErr_Occurred(tstate));
1001
Victor Stinnerb0051362019-11-22 17:52:42 +01001002 PyStatus status;
1003 int is_main_interp = _Py_IsMainInterpreter(tstate);
1004 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001005 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001006
1007 if (!config->_install_importlib) {
1008 /* Special mode for freeze_importlib: run with no import system
1009 *
1010 * This means anything which needs support from extension modules
1011 * or pure Python code in the standard library won't work.
1012 */
1013 if (is_main_interp) {
1014 interp->runtime->initialized = 1;
1015 }
1016 return _PyStatus_OK();
1017 }
1018
Victor Stinner9e1b8282020-11-10 13:21:52 +01001019 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001020 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001021 if (_PyStatus_EXCEPTION(status)) {
1022 return status;
1023 }
1024
Victor Stinner9e1b8282020-11-10 13:21:52 +01001025 if (interpreter_update_config(tstate, 1) < 0) {
1026 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001027 }
1028
1029 status = init_importlib_external(tstate);
1030 if (_PyStatus_EXCEPTION(status)) {
1031 return status;
1032 }
1033
1034 if (is_main_interp) {
1035 /* initialize the faulthandler module */
1036 status = _PyFaulthandler_Init(config->faulthandler);
1037 if (_PyStatus_EXCEPTION(status)) {
1038 return status;
1039 }
1040 }
1041
1042 status = _PyUnicode_InitEncodings(tstate);
1043 if (_PyStatus_EXCEPTION(status)) {
1044 return status;
1045 }
1046
1047 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001048 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1049 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001050 }
1051
1052 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1053 return _PyStatus_ERR("can't initialize tracemalloc");
1054 }
1055 }
1056
1057 status = init_sys_streams(tstate);
1058 if (_PyStatus_EXCEPTION(status)) {
1059 return status;
1060 }
1061
Andy Lester75cd5bf2020-03-12 02:49:05 -05001062 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001063 if (_PyStatus_EXCEPTION(status)) {
1064 return status;
1065 }
1066
1067 status = add_main_module(interp);
1068 if (_PyStatus_EXCEPTION(status)) {
1069 return status;
1070 }
1071
1072 if (is_main_interp) {
1073 /* Initialize warnings. */
1074 PyObject *warnoptions = PySys_GetObject("warnoptions");
1075 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1076 {
1077 PyObject *warnings_module = PyImport_ImportModule("warnings");
1078 if (warnings_module == NULL) {
1079 fprintf(stderr, "'import warnings' failed; traceback:\n");
1080 _PyErr_Print(tstate);
1081 }
1082 Py_XDECREF(warnings_module);
1083 }
1084
1085 interp->runtime->initialized = 1;
1086 }
1087
1088 if (config->site_import) {
1089 status = init_import_site();
1090 if (_PyStatus_EXCEPTION(status)) {
1091 return status;
1092 }
1093 }
1094
1095 if (is_main_interp) {
1096#ifndef MS_WINDOWS
1097 emit_stderr_warning_for_legacy_locale(interp->runtime);
1098#endif
1099 }
1100
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001101 assert(!_PyErr_Occurred(tstate));
1102
Victor Stinnerb0051362019-11-22 17:52:42 +01001103 return _PyStatus_OK();
1104}
1105
1106
Eric Snowc7ec9982017-05-23 23:00:52 -07001107/* Update interpreter state based on supplied configuration settings
1108 *
1109 * After calling this function, most of the restrictions on the interpreter
1110 * are lifted. The only remaining incomplete settings are those related
1111 * to the main module (sys.argv[0], __main__ metadata)
1112 *
1113 * Calling this when the interpreter is not initializing, is already
1114 * initialized or without a valid current thread state is a fatal error.
1115 * Other errors should be reported as normal Python exceptions with a
1116 * non-zero return code.
1117 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001118static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001119pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001120{
Victor Stinnerb0051362019-11-22 17:52:42 +01001121 PyInterpreterState *interp = tstate->interp;
1122 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001123 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001124 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001125
Victor Stinnerb0051362019-11-22 17:52:42 +01001126 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001127 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001128 }
1129
Victor Stinnerb0051362019-11-22 17:52:42 +01001130 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001131 if (_PyStatus_EXCEPTION(status)) {
1132 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001133 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001134 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001135}
1136
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001137
Victor Stinner331a6a52019-05-27 16:39:22 +02001138PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001139Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001140{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001141 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001142 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001143 }
1144
Victor Stinner331a6a52019-05-27 16:39:22 +02001145 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001146
Victor Stinner331a6a52019-05-27 16:39:22 +02001147 status = _PyRuntime_Initialize();
1148 if (_PyStatus_EXCEPTION(status)) {
1149 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001150 }
1151 _PyRuntimeState *runtime = &_PyRuntime;
1152
Victor Stinnerb45d2592019-06-20 00:05:23 +02001153 PyThreadState *tstate = NULL;
1154 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001155 if (_PyStatus_EXCEPTION(status)) {
1156 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001157 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001158 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001159
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001160 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001161 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001162 if (_PyStatus_EXCEPTION(status)) {
1163 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001164 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001165 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001166
Victor Stinner331a6a52019-05-27 16:39:22 +02001167 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001168}
1169
1170
Eric Snow1abcf672017-05-23 21:46:51 -07001171void
Nick Coghland6009512014-11-20 21:39:37 +10001172Py_InitializeEx(int install_sigs)
1173{
Victor Stinner331a6a52019-05-27 16:39:22 +02001174 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001175
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 status = _PyRuntime_Initialize();
1177 if (_PyStatus_EXCEPTION(status)) {
1178 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001179 }
1180 _PyRuntimeState *runtime = &_PyRuntime;
1181
1182 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001183 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1184 return;
1185 }
1186
Victor Stinner331a6a52019-05-27 16:39:22 +02001187 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001188 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001189
Victor Stinner1dc6e392018-07-25 02:49:17 +02001190 config.install_signal_handlers = install_sigs;
1191
Victor Stinner331a6a52019-05-27 16:39:22 +02001192 status = Py_InitializeFromConfig(&config);
1193 if (_PyStatus_EXCEPTION(status)) {
1194 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001195 }
Nick Coghland6009512014-11-20 21:39:37 +10001196}
1197
1198void
1199Py_Initialize(void)
1200{
1201 Py_InitializeEx(1);
1202}
1203
1204
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001205PyStatus
1206_Py_InitializeMain(void)
1207{
1208 PyStatus status = _PyRuntime_Initialize();
1209 if (_PyStatus_EXCEPTION(status)) {
1210 return status;
1211 }
1212 _PyRuntimeState *runtime = &_PyRuntime;
1213 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1214 return pyinit_main(tstate);
1215}
1216
1217
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001218static void
1219finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1220{
1221 // List of names to clear in sys
1222 static const char * const sys_deletes[] = {
1223 "path", "argv", "ps1", "ps2",
1224 "last_type", "last_value", "last_traceback",
1225 "path_hooks", "path_importer_cache", "meta_path",
1226 "__interactivehook__",
1227 NULL
1228 };
1229
1230 static const char * const sys_files[] = {
1231 "stdin", "__stdin__",
1232 "stdout", "__stdout__",
1233 "stderr", "__stderr__",
1234 NULL
1235 };
1236
1237 PyInterpreterState *interp = tstate->interp;
1238 if (verbose) {
1239 PySys_WriteStderr("# clear builtins._\n");
1240 }
1241 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1242 PyErr_WriteUnraisable(NULL);
1243 }
1244
1245 const char * const *p;
1246 for (p = sys_deletes; *p != NULL; p++) {
1247 if (verbose) {
1248 PySys_WriteStderr("# clear sys.%s\n", *p);
1249 }
1250 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1251 PyErr_WriteUnraisable(NULL);
1252 }
1253 }
1254 for (p = sys_files; *p != NULL; p+=2) {
1255 const char *name = p[0];
1256 const char *orig_name = p[1];
1257 if (verbose) {
1258 PySys_WriteStderr("# restore sys.%s\n", name);
1259 }
1260 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1261 orig_name);
1262 if (value == NULL) {
1263 if (_PyErr_Occurred(tstate)) {
1264 PyErr_WriteUnraisable(NULL);
1265 }
1266 value = Py_None;
1267 }
1268 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1269 PyErr_WriteUnraisable(NULL);
1270 }
1271 }
1272}
1273
1274
1275static PyObject*
1276finalize_remove_modules(PyObject *modules, int verbose)
1277{
1278 PyObject *weaklist = PyList_New(0);
1279 if (weaklist == NULL) {
1280 PyErr_WriteUnraisable(NULL);
1281 }
1282
1283#define STORE_MODULE_WEAKREF(name, mod) \
1284 if (weaklist != NULL) { \
1285 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1286 if (wr) { \
1287 PyObject *tup = PyTuple_Pack(2, name, wr); \
1288 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1289 PyErr_WriteUnraisable(NULL); \
1290 } \
1291 Py_XDECREF(tup); \
1292 Py_DECREF(wr); \
1293 } \
1294 else { \
1295 PyErr_WriteUnraisable(NULL); \
1296 } \
1297 }
1298
1299#define CLEAR_MODULE(name, mod) \
1300 if (PyModule_Check(mod)) { \
1301 if (verbose && PyUnicode_Check(name)) { \
1302 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1303 } \
1304 STORE_MODULE_WEAKREF(name, mod); \
1305 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1306 PyErr_WriteUnraisable(NULL); \
1307 } \
1308 }
1309
1310 if (PyDict_CheckExact(modules)) {
1311 Py_ssize_t pos = 0;
1312 PyObject *key, *value;
1313 while (PyDict_Next(modules, &pos, &key, &value)) {
1314 CLEAR_MODULE(key, value);
1315 }
1316 }
1317 else {
1318 PyObject *iterator = PyObject_GetIter(modules);
1319 if (iterator == NULL) {
1320 PyErr_WriteUnraisable(NULL);
1321 }
1322 else {
1323 PyObject *key;
1324 while ((key = PyIter_Next(iterator))) {
1325 PyObject *value = PyObject_GetItem(modules, key);
1326 if (value == NULL) {
1327 PyErr_WriteUnraisable(NULL);
1328 continue;
1329 }
1330 CLEAR_MODULE(key, value);
1331 Py_DECREF(value);
1332 Py_DECREF(key);
1333 }
1334 if (PyErr_Occurred()) {
1335 PyErr_WriteUnraisable(NULL);
1336 }
1337 Py_DECREF(iterator);
1338 }
1339 }
1340#undef CLEAR_MODULE
1341#undef STORE_MODULE_WEAKREF
1342
1343 return weaklist;
1344}
1345
1346
1347static void
1348finalize_clear_modules_dict(PyObject *modules)
1349{
1350 if (PyDict_CheckExact(modules)) {
1351 PyDict_Clear(modules);
1352 }
1353 else {
1354 _Py_IDENTIFIER(clear);
1355 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1356 PyErr_WriteUnraisable(NULL);
1357 }
1358 }
1359}
1360
1361
1362static void
1363finalize_restore_builtins(PyThreadState *tstate)
1364{
1365 PyInterpreterState *interp = tstate->interp;
1366 PyObject *dict = PyDict_Copy(interp->builtins);
1367 if (dict == NULL) {
1368 PyErr_WriteUnraisable(NULL);
1369 }
1370 PyDict_Clear(interp->builtins);
1371 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1372 _PyErr_Clear(tstate);
1373 }
1374 Py_XDECREF(dict);
1375}
1376
1377
1378static void
1379finalize_modules_clear_weaklist(PyInterpreterState *interp,
1380 PyObject *weaklist, int verbose)
1381{
1382 // First clear modules imported later
1383 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1384 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1385 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1386 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1387 if (mod == Py_None) {
1388 continue;
1389 }
1390 assert(PyModule_Check(mod));
1391 PyObject *dict = PyModule_GetDict(mod);
1392 if (dict == interp->builtins || dict == interp->sysdict) {
1393 continue;
1394 }
1395 Py_INCREF(mod);
1396 if (verbose && PyUnicode_Check(name)) {
1397 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1398 }
1399 _PyModule_Clear(mod);
1400 Py_DECREF(mod);
1401 }
1402}
1403
1404
1405static void
1406finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1407{
1408 // Clear sys dict
1409 if (verbose) {
1410 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1411 }
1412 _PyModule_ClearDict(interp->sysdict);
1413
1414 // Clear builtins dict
1415 if (verbose) {
1416 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1417 }
1418 _PyModule_ClearDict(interp->builtins);
1419}
1420
1421
1422/* Clear modules, as good as we can */
1423static void
1424finalize_modules(PyThreadState *tstate)
1425{
1426 PyInterpreterState *interp = tstate->interp;
1427 PyObject *modules = interp->modules;
1428 if (modules == NULL) {
1429 // Already done
1430 return;
1431 }
1432 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1433
1434 // Delete some special builtins._ and sys attributes first. These are
1435 // common places where user values hide and people complain when their
1436 // destructors fail. Since the modules containing them are
1437 // deleted *last* of all, they would come too late in the normal
1438 // destruction order. Sigh.
1439 //
1440 // XXX Perhaps these precautions are obsolete. Who knows?
1441 finalize_modules_delete_special(tstate, verbose);
1442
1443 // Remove all modules from sys.modules, hoping that garbage collection
1444 // can reclaim most of them: set all sys.modules values to None.
1445 //
1446 // We prepare a list which will receive (name, weakref) tuples of
1447 // modules when they are removed from sys.modules. The name is used
1448 // for diagnosis messages (in verbose mode), while the weakref helps
1449 // detect those modules which have been held alive.
1450 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1451
1452 // Clear the modules dict
1453 finalize_clear_modules_dict(modules);
1454
1455 // Restore the original builtins dict, to ensure that any
1456 // user data gets cleared.
1457 finalize_restore_builtins(tstate);
1458
1459 // Collect garbage
1460 _PyGC_CollectNoFail(tstate);
1461
1462 // Dump GC stats before it's too late, since it uses the warnings
1463 // machinery.
1464 _PyGC_DumpShutdownStats(tstate);
1465
1466 if (weaklist != NULL) {
1467 // Now, if there are any modules left alive, clear their globals to
1468 // minimize potential leaks. All C extension modules actually end
1469 // up here, since they are kept alive in the interpreter state.
1470 //
1471 // The special treatment of "builtins" here is because even
1472 // when it's not referenced as a module, its dictionary is
1473 // referenced by almost every module's __builtins__. Since
1474 // deleting a module clears its dictionary (even if there are
1475 // references left to it), we need to delete the "builtins"
1476 // module last. Likewise, we don't delete sys until the very
1477 // end because it is implicitly referenced (e.g. by print).
1478 //
1479 // Since dict is ordered in CPython 3.6+, modules are saved in
1480 // importing order. First clear modules imported later.
1481 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1482 Py_DECREF(weaklist);
1483 }
1484
1485 // Clear sys and builtins modules dict
1486 finalize_clear_sys_builtins_dict(interp, verbose);
1487
1488 // Clear module dict copies stored in the interpreter state:
1489 // clear PyInterpreterState.modules_by_index and
1490 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1491 // initialization API)
1492 _PyInterpreterState_ClearModules(interp);
1493
1494 // Clear and delete the modules directory. Actual modules will
1495 // still be there only if imported during the execution of some
1496 // destructor.
1497 Py_SETREF(interp->modules, NULL);
1498
1499 // Collect garbage once more
1500 _PyGC_CollectNoFail(tstate);
1501}
1502
1503
Nick Coghland6009512014-11-20 21:39:37 +10001504/* Flush stdout and stderr */
1505
1506static int
1507file_is_closed(PyObject *fobj)
1508{
1509 int r;
1510 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1511 if (tmp == NULL) {
1512 PyErr_Clear();
1513 return 0;
1514 }
1515 r = PyObject_IsTrue(tmp);
1516 Py_DECREF(tmp);
1517 if (r < 0)
1518 PyErr_Clear();
1519 return r > 0;
1520}
1521
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001522
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001523static int
Nick Coghland6009512014-11-20 21:39:37 +10001524flush_std_files(void)
1525{
1526 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1527 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1528 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001529 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001530
1531 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001532 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001533 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001534 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001535 status = -1;
1536 }
Nick Coghland6009512014-11-20 21:39:37 +10001537 else
1538 Py_DECREF(tmp);
1539 }
1540
1541 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001542 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001543 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001544 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001545 status = -1;
1546 }
Nick Coghland6009512014-11-20 21:39:37 +10001547 else
1548 Py_DECREF(tmp);
1549 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001550
1551 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001552}
1553
1554/* Undo the effect of Py_Initialize().
1555
1556 Beware: if multiple interpreter and/or thread states exist, these
1557 are not wiped out; only the current thread and interpreter state
1558 are deleted. But since everything else is deleted, those other
1559 interpreter and thread states should no longer be used.
1560
1561 (XXX We should do better, e.g. wipe out all interpreters and
1562 threads.)
1563
1564 Locking: as above.
1565
1566*/
1567
Victor Stinner7eee5be2019-11-20 10:38:34 +01001568
1569static void
Victor Stinner90db4652020-07-01 23:21:36 +02001570finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001571{
Victor Stinner281cce12020-06-23 22:55:46 +02001572 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001573 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001574 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001575 _PyContext_Fini(tstate);
Victor Stinnerf4507232020-12-26 20:26:08 +01001576 _PyType_Fini(tstate);
Victor Stinnerea251802020-12-26 02:58:33 +01001577 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1578 // a dict internally.
Victor Stinner666ecfb2020-07-02 01:19:57 +02001579 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001580
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001581 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001582 _PyList_Fini(tstate);
1583 _PyTuple_Fini(tstate);
1584
1585 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001586
Victor Stinnerc41eed12020-06-23 15:54:35 +02001587 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001588 _PyUnicode_Fini(tstate);
1589 _PyFloat_Fini(tstate);
1590 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001591}
1592
1593
1594static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001595finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001596{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001597 int is_main_interp = _Py_IsMainInterpreter(tstate);
1598
Victor Stinner7eee5be2019-11-20 10:38:34 +01001599 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001600 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001601
Kongedaa0fe02020-07-04 05:06:46 +08001602 /* Clear all loghooks */
1603 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1604 Call _PySys_ClearAuditHooks when PyObject available. */
1605 if (is_main_interp) {
1606 _PySys_ClearAuditHooks(tstate);
1607 }
1608
Victor Stinner7907f8c2020-06-08 01:22:36 +02001609 if (is_main_interp) {
1610 _Py_HashRandomization_Fini();
1611 _PyArg_Fini();
1612 _Py_ClearFileSystemEncoding();
1613 }
1614
Victor Stinner90db4652020-07-01 23:21:36 +02001615 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001616}
1617
1618
1619static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001620finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001621{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001622 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001623 /* Cleanup auto-thread-state */
1624 _PyGILState_Fini(tstate);
1625 }
1626
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001627 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1628 fail when it is being awaited by another running daemon thread (see
1629 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1630 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1631 called multiple times. */
1632
Victor Stinner7eee5be2019-11-20 10:38:34 +01001633 PyInterpreterState_Delete(tstate->interp);
1634}
1635
1636
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001637int
1638Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001639{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001640 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001641
Victor Stinner8e91c242019-04-24 17:24:01 +02001642 _PyRuntimeState *runtime = &_PyRuntime;
1643 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001644 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001645 }
Nick Coghland6009512014-11-20 21:39:37 +10001646
Victor Stinnere225beb2019-06-03 18:14:24 +02001647 /* Get current thread state and interpreter pointer */
1648 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001649
Victor Stinnerb45d2592019-06-20 00:05:23 +02001650 // Wrap up existing "threading"-module-created, non-daemon threads.
1651 wait_for_thread_shutdown(tstate);
1652
1653 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001654 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001655
Nick Coghland6009512014-11-20 21:39:37 +10001656 /* The interpreter is still entirely intact at this point, and the
1657 * exit funcs may be relying on that. In particular, if some thread
1658 * or exit func is still waiting to do an import, the import machinery
1659 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001660 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001661 * Note that Threading.py uses an exit func to do a join on all the
1662 * threads created thru it, so this also protects pending imports in
1663 * the threads created via Threading.
1664 */
Nick Coghland6009512014-11-20 21:39:37 +10001665
Victor Stinnerb8fa1352020-12-15 14:34:19 +01001666 _PyAtExit_Call(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001667
Victor Stinnerda273412017-12-15 01:46:02 +01001668 /* Copy the core config, PyInterpreterState_Delete() free
1669 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001670#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001671 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001672#endif
1673#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001674 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001675#endif
1676#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001677 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001678#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001679
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001680 /* Remaining daemon threads will automatically exit
1681 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001682 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001683 runtime->initialized = 0;
1684 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001685
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001686 /* Destroy the state of all threads of the interpreter, except of the
1687 current thread. In practice, only daemon threads should still be alive,
1688 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1689 Clear frames of other threads to call objects destructors. Destructors
1690 will be called in the current Python thread. Since
1691 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1692 can take the GIL at this point: if they try, they will exit
1693 immediately. */
1694 _PyThreadState_DeleteExcept(runtime, tstate);
1695
Victor Stinnere0deff32015-03-24 13:46:18 +01001696 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001697 if (flush_std_files() < 0) {
1698 status = -1;
1699 }
Nick Coghland6009512014-11-20 21:39:37 +10001700
1701 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001702 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001703
1704 /* Collect garbage. This may call finalizers; it's nice to call these
1705 * before all modules are destroyed.
1706 * XXX If a __del__ or weakref callback is triggered here, and tries to
1707 * XXX import a module, bad things can happen, because Python no
1708 * XXX longer believes it's initialized.
1709 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1710 * XXX is easy to provoke that way. I've also seen, e.g.,
1711 * XXX Exception exceptions.ImportError: 'No module named sha'
1712 * XXX in <function callback at 0x008F5718> ignored
1713 * XXX but I'm unclear on exactly how that one happens. In any case,
1714 * XXX I haven't seen a real-life report of either of these.
1715 */
Victor Stinner8b341482020-10-30 17:00:00 +01001716 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001717
Nick Coghland6009512014-11-20 21:39:37 +10001718 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001719 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001720
Inada Naoki91234a12019-06-03 21:30:58 +09001721 /* Print debug stats if any */
1722 _PyEval_Fini();
1723
Victor Stinnere0deff32015-03-24 13:46:18 +01001724 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001725 if (flush_std_files() < 0) {
1726 status = -1;
1727 }
Nick Coghland6009512014-11-20 21:39:37 +10001728
1729 /* Collect final garbage. This disposes of cycles created by
1730 * class definitions, for example.
1731 * XXX This is disabled because it caused too many problems. If
1732 * XXX a __del__ or weakref callback triggers here, Python code has
1733 * XXX a hard time running, because even the sys module has been
1734 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1735 * XXX One symptom is a sequence of information-free messages
1736 * XXX coming from threads (if a __del__ or callback is invoked,
1737 * XXX other threads can execute too, and any exception they encounter
1738 * XXX triggers a comedy of errors as subsystem after subsystem
1739 * XXX fails to find what it *expects* to find in sys to help report
1740 * XXX the exception and consequent unexpected failures). I've also
1741 * XXX seen segfaults then, after adding print statements to the
1742 * XXX Python code getting called.
1743 */
1744#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001745 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001746#endif
1747
1748 /* Disable tracemalloc after all Python objects have been destroyed,
1749 so it is possible to use tracemalloc in objects destructor. */
1750 _PyTraceMalloc_Fini();
1751
1752 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1753 _PyImport_Fini();
1754
Nick Coghland6009512014-11-20 21:39:37 +10001755 /* unload faulthandler module */
1756 _PyFaulthandler_Fini();
1757
Nick Coghland6009512014-11-20 21:39:37 +10001758 /* dump hash stats */
1759 _PyHash_Fini();
1760
Eric Snowdae02762017-09-14 00:35:58 -07001761#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001762 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001763 _PyDebug_PrintTotalRefs();
1764 }
Eric Snowdae02762017-09-14 00:35:58 -07001765#endif
Nick Coghland6009512014-11-20 21:39:37 +10001766
1767#ifdef Py_TRACE_REFS
1768 /* Display all objects still alive -- this can invoke arbitrary
1769 * __repr__ overrides, so requires a mostly-intact interpreter.
1770 * Alas, a lot of stuff may still be alive now that will be cleaned
1771 * up later.
1772 */
Victor Stinnerda273412017-12-15 01:46:02 +01001773 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001774 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001775 }
Nick Coghland6009512014-11-20 21:39:37 +10001776#endif /* Py_TRACE_REFS */
1777
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001778 finalize_interp_clear(tstate);
1779 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001780
1781#ifdef Py_TRACE_REFS
1782 /* Display addresses (& refcnts) of all objects still alive.
1783 * An address can be used to find the repr of the object, printed
1784 * above by _Py_PrintReferences.
1785 */
Victor Stinnerda273412017-12-15 01:46:02 +01001786 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001787 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001788 }
Nick Coghland6009512014-11-20 21:39:37 +10001789#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001790#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001791 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001792 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001793 }
Nick Coghland6009512014-11-20 21:39:37 +10001794#endif
1795
Victor Stinner8e91c242019-04-24 17:24:01 +02001796 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001797
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001798 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001799 return status;
1800}
1801
1802void
1803Py_Finalize(void)
1804{
1805 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001806}
1807
Victor Stinnerb0051362019-11-22 17:52:42 +01001808
Nick Coghland6009512014-11-20 21:39:37 +10001809/* Create and initialize a new interpreter and thread, and return the
1810 new thread. This requires that Py_Initialize() has been called
1811 first.
1812
1813 Unsuccessful initialization yields a NULL pointer. Note that *no*
1814 exception information is available even in this case -- the
1815 exception information is held in the thread, and there is no
1816 thread.
1817
1818 Locking: as above.
1819
1820*/
1821
Victor Stinner331a6a52019-05-27 16:39:22 +02001822static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001823new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001824{
Victor Stinner331a6a52019-05-27 16:39:22 +02001825 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001826
Victor Stinner331a6a52019-05-27 16:39:22 +02001827 status = _PyRuntime_Initialize();
1828 if (_PyStatus_EXCEPTION(status)) {
1829 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001830 }
1831 _PyRuntimeState *runtime = &_PyRuntime;
1832
1833 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001834 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001835 }
Nick Coghland6009512014-11-20 21:39:37 +10001836
Victor Stinner8a1be612016-03-14 22:07:55 +01001837 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1838 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001839 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001840
Victor Stinner43125222019-04-24 18:23:53 +02001841 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001842 if (interp == NULL) {
1843 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001844 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001845 }
Nick Coghland6009512014-11-20 21:39:37 +10001846
Victor Stinner43125222019-04-24 18:23:53 +02001847 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001848 if (tstate == NULL) {
1849 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001850 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001851 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001852 }
1853
Victor Stinner43125222019-04-24 18:23:53 +02001854 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001855
Eric Snow1abcf672017-05-23 21:46:51 -07001856 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001857 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001858#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001859 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001860 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001861 }
1862 else
1863#endif
1864 {
Eric Snow1abcf672017-05-23 21:46:51 -07001865 /* No current thread state, copy from the main interpreter */
1866 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001867 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001868 }
1869
Victor Stinner048a3562020-11-05 00:45:56 +01001870
1871 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001872 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001873 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001874 }
Victor Stinner252346a2020-05-01 11:33:44 +02001875 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001876
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001877 status = init_interp_create_gil(tstate);
1878 if (_PyStatus_EXCEPTION(status)) {
1879 goto error;
1880 }
1881
Victor Stinnerd863ade2019-12-06 03:37:07 +01001882 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001883 if (_PyStatus_EXCEPTION(status)) {
1884 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001885 }
1886
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001887 status = init_interp_main(tstate);
1888 if (_PyStatus_EXCEPTION(status)) {
1889 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001890 }
Nick Coghland6009512014-11-20 21:39:37 +10001891
Victor Stinnera7368ac2017-11-15 18:11:45 -08001892 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001893 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001894
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001895error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001896 *tstate_p = NULL;
1897
1898 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001899 PyErr_PrintEx(0);
1900 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001901 PyThreadState_Delete(tstate);
1902 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001903 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001904
Victor Stinnerb0051362019-11-22 17:52:42 +01001905 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001906}
1907
1908PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001909_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001910{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001911 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001912 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001913 if (_PyStatus_EXCEPTION(status)) {
1914 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001915 }
1916 return tstate;
1917
Nick Coghland6009512014-11-20 21:39:37 +10001918}
1919
Victor Stinner252346a2020-05-01 11:33:44 +02001920PyThreadState *
1921Py_NewInterpreter(void)
1922{
1923 return _Py_NewInterpreter(0);
1924}
1925
Nick Coghland6009512014-11-20 21:39:37 +10001926/* Delete an interpreter and its last thread. This requires that the
1927 given thread state is current, that the thread has no remaining
1928 frames, and that it is its interpreter's only remaining thread.
1929 It is a fatal error to violate these constraints.
1930
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001931 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001932 everything, regardless.)
1933
1934 Locking: as above.
1935
1936*/
1937
1938void
1939Py_EndInterpreter(PyThreadState *tstate)
1940{
1941 PyInterpreterState *interp = tstate->interp;
1942
Victor Stinnerb45d2592019-06-20 00:05:23 +02001943 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001944 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001945 }
1946 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001947 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001948 }
Eric Snow5be45a62019-03-08 22:47:07 -07001949 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001950
Eric Snow842a2f02019-03-15 15:47:51 -06001951 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001952 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001953
Victor Stinnerb8fa1352020-12-15 14:34:19 +01001954 _PyAtExit_Call(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001955
Victor Stinnerb45d2592019-06-20 00:05:23 +02001956 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001957 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001958 }
Nick Coghland6009512014-11-20 21:39:37 +10001959
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001960 finalize_modules(tstate);
1961
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001962 finalize_interp_clear(tstate);
1963 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001964}
1965
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001966/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001967
Victor Stinner331a6a52019-05-27 16:39:22 +02001968static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001969add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001970{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001971 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001972 m = PyImport_AddModule("__main__");
1973 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001974 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975
Nick Coghland6009512014-11-20 21:39:37 +10001976 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001977 ann_dict = PyDict_New();
1978 if ((ann_dict == NULL) ||
1979 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001980 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001981 }
1982 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001983
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001984 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1985 if (PyErr_Occurred()) {
1986 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1987 }
Nick Coghland6009512014-11-20 21:39:37 +10001988 PyObject *bimod = PyImport_ImportModule("builtins");
1989 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001990 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001991 }
1992 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001993 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001994 }
1995 Py_DECREF(bimod);
1996 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001997
Nick Coghland6009512014-11-20 21:39:37 +10001998 /* Main is a little special - imp.is_builtin("__main__") will return
1999 * False, but BuiltinImporter is still the most appropriate initial
2000 * setting for its __loader__ attribute. A more suitable value will
2001 * be set if __main__ gets further initialized later in the startup
2002 * process.
2003 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002004 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002005 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002006 if (PyErr_Occurred()) {
2007 return _PyStatus_ERR("Failed to test __main__.__loader__");
2008 }
Nick Coghland6009512014-11-20 21:39:37 +10002009 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2010 "BuiltinImporter");
2011 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002012 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002013 }
2014 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002015 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002016 }
2017 Py_DECREF(loader);
2018 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002019 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002020}
2021
Nick Coghland6009512014-11-20 21:39:37 +10002022/* Import the site module (not into __main__ though) */
2023
Victor Stinner331a6a52019-05-27 16:39:22 +02002024static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002025init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002026{
2027 PyObject *m;
2028 m = PyImport_ImportModule("site");
2029 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002030 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002031 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002032 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002033 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002034}
2035
Victor Stinner874dbe82015-09-04 17:29:57 +02002036/* Check if a file descriptor is valid or not.
2037 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2038static int
2039is_valid_fd(int fd)
2040{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002041/* dup() is faster than fstat(): fstat() can require input/output operations,
2042 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2043 startup. Problem: dup() doesn't check if the file descriptor is valid on
2044 some platforms.
2045
2046 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2047 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2048 EBADF. FreeBSD has similar issue (bpo-32849).
2049
2050 Only use dup() on platforms where dup() is enough to detect invalid FD in
2051 corner cases: on Linux and Windows (bpo-32849). */
2052#if defined(__linux__) || defined(MS_WINDOWS)
2053 if (fd < 0) {
2054 return 0;
2055 }
2056 int fd2;
2057
2058 _Py_BEGIN_SUPPRESS_IPH
2059 fd2 = dup(fd);
2060 if (fd2 >= 0) {
2061 close(fd2);
2062 }
2063 _Py_END_SUPPRESS_IPH
2064
2065 return (fd2 >= 0);
2066#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002067 struct stat st;
2068 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002069#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002070}
2071
2072/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002073static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002074create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002075 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002076 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002077{
2078 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2079 const char* mode;
2080 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002081 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002082 int buffering, isatty;
2083 _Py_IDENTIFIER(open);
2084 _Py_IDENTIFIER(isatty);
2085 _Py_IDENTIFIER(TextIOWrapper);
2086 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002087 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002088
Victor Stinner874dbe82015-09-04 17:29:57 +02002089 if (!is_valid_fd(fd))
2090 Py_RETURN_NONE;
2091
Nick Coghland6009512014-11-20 21:39:37 +10002092 /* stdin is always opened in buffered mode, first because it shouldn't
2093 make a difference in common use cases, second because TextIOWrapper
2094 depends on the presence of a read1() method which only exists on
2095 buffered streams.
2096 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002097 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002098 buffering = 0;
2099 else
2100 buffering = -1;
2101 if (write_mode)
2102 mode = "wb";
2103 else
2104 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002105 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002106 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002107 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002108 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002109 if (buf == NULL)
2110 goto error;
2111
2112 if (buffering) {
2113 _Py_IDENTIFIER(raw);
2114 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2115 if (raw == NULL)
2116 goto error;
2117 }
2118 else {
2119 raw = buf;
2120 Py_INCREF(raw);
2121 }
2122
Steve Dower39294992016-08-30 21:22:36 -07002123#ifdef MS_WINDOWS
2124 /* Windows console IO is always UTF-8 encoded */
2125 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002126 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002127#endif
2128
Nick Coghland6009512014-11-20 21:39:37 +10002129 text = PyUnicode_FromString(name);
2130 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2131 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002132 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002133 if (res == NULL)
2134 goto error;
2135 isatty = PyObject_IsTrue(res);
2136 Py_DECREF(res);
2137 if (isatty == -1)
2138 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002139 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002140 write_through = Py_True;
2141 else
2142 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002143 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002144 line_buffering = Py_True;
2145 else
2146 line_buffering = Py_False;
2147
2148 Py_CLEAR(raw);
2149 Py_CLEAR(text);
2150
2151#ifdef MS_WINDOWS
2152 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2153 newlines to "\n".
2154 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2155 newline = NULL;
2156#else
2157 /* sys.stdin: split lines at "\n".
2158 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2159 newline = "\n";
2160#endif
2161
Victor Stinner709d23d2019-05-02 14:56:30 -04002162 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2163 if (encoding_str == NULL) {
2164 Py_CLEAR(buf);
2165 goto error;
2166 }
2167
2168 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2169 if (errors_str == NULL) {
2170 Py_CLEAR(buf);
2171 Py_CLEAR(encoding_str);
2172 goto error;
2173 }
2174
2175 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2176 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002177 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002178 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002179 Py_CLEAR(encoding_str);
2180 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002181 if (stream == NULL)
2182 goto error;
2183
2184 if (write_mode)
2185 mode = "w";
2186 else
2187 mode = "r";
2188 text = PyUnicode_FromString(mode);
2189 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2190 goto error;
2191 Py_CLEAR(text);
2192 return stream;
2193
2194error:
2195 Py_XDECREF(buf);
2196 Py_XDECREF(stream);
2197 Py_XDECREF(text);
2198 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002199
Victor Stinner874dbe82015-09-04 17:29:57 +02002200 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2201 /* Issue #24891: the file descriptor was closed after the first
2202 is_valid_fd() check was called. Ignore the OSError and set the
2203 stream to None. */
2204 PyErr_Clear();
2205 Py_RETURN_NONE;
2206 }
2207 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002208}
2209
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002210/* Set builtins.open to io.OpenWrapper */
2211static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002212init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002213{
2214 PyObject *iomod = NULL, *wrapper;
2215 PyObject *bimod = NULL;
2216 PyStatus res = _PyStatus_OK();
2217
2218 if (!(iomod = PyImport_ImportModule("io"))) {
2219 goto error;
2220 }
2221
2222 if (!(bimod = PyImport_ImportModule("builtins"))) {
2223 goto error;
2224 }
2225
2226 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2227 goto error;
2228 }
2229
2230 /* Set builtins.open */
2231 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2232 Py_DECREF(wrapper);
2233 goto error;
2234 }
2235 Py_DECREF(wrapper);
2236 goto done;
2237
2238error:
2239 res = _PyStatus_ERR("can't initialize io.open");
2240
2241done:
2242 Py_XDECREF(bimod);
2243 Py_XDECREF(iomod);
2244 return res;
2245}
2246
2247
Nick Coghland6009512014-11-20 21:39:37 +10002248/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002249static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002250init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002251{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002252 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002253 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002254 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002255 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002256 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002257 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002258
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002259 /* Check that stdin is not a directory
2260 Using shell redirection, you can redirect stdin to a directory,
2261 crashing the Python interpreter. Catch this common mistake here
2262 and output a useful error message. Note that under MS Windows,
2263 the shell already prevents that. */
2264#ifndef MS_WINDOWS
2265 struct _Py_stat_struct sb;
2266 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2267 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002268 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002269 }
2270#endif
2271
Nick Coghland6009512014-11-20 21:39:37 +10002272 if (!(iomod = PyImport_ImportModule("io"))) {
2273 goto error;
2274 }
Nick Coghland6009512014-11-20 21:39:37 +10002275
Nick Coghland6009512014-11-20 21:39:37 +10002276 /* Set sys.stdin */
2277 fd = fileno(stdin);
2278 /* Under some conditions stdin, stdout and stderr may not be connected
2279 * and fileno() may point to an invalid file descriptor. For example
2280 * GUI apps don't have valid standard streams by default.
2281 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002282 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002283 config->stdio_encoding,
2284 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002285 if (std == NULL)
2286 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002287 PySys_SetObject("__stdin__", std);
2288 _PySys_SetObjectId(&PyId_stdin, std);
2289 Py_DECREF(std);
2290
2291 /* Set sys.stdout */
2292 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002293 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002294 config->stdio_encoding,
2295 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002296 if (std == NULL)
2297 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002298 PySys_SetObject("__stdout__", std);
2299 _PySys_SetObjectId(&PyId_stdout, std);
2300 Py_DECREF(std);
2301
2302#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2303 /* Set sys.stderr, replaces the preliminary stderr */
2304 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002305 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002306 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002307 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002308 if (std == NULL)
2309 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002310
2311 /* Same as hack above, pre-import stderr's codec to avoid recursion
2312 when import.c tries to write to stderr in verbose mode. */
2313 encoding_attr = PyObject_GetAttrString(std, "encoding");
2314 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002315 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002316 if (std_encoding != NULL) {
2317 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2318 Py_XDECREF(codec_info);
2319 }
2320 Py_DECREF(encoding_attr);
2321 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002322 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002323
2324 if (PySys_SetObject("__stderr__", std) < 0) {
2325 Py_DECREF(std);
2326 goto error;
2327 }
2328 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2329 Py_DECREF(std);
2330 goto error;
2331 }
2332 Py_DECREF(std);
2333#endif
2334
Victor Stinnera7368ac2017-11-15 18:11:45 -08002335 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002336
Victor Stinnera7368ac2017-11-15 18:11:45 -08002337error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002338 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002339
2340done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002341 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002342 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002343 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002344}
2345
2346
Victor Stinner10dc4842015-03-24 12:01:30 +01002347static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002348_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2349 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002350{
Victor Stinner10dc4842015-03-24 12:01:30 +01002351 fputc('\n', stderr);
2352 fflush(stderr);
2353
2354 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002355 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002356}
Victor Stinner791da1c2016-03-14 16:53:12 +01002357
2358/* Print the current exception (if an exception is set) with its traceback,
2359 or display the current Python stack.
2360
2361 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2362 called on catastrophic cases.
2363
2364 Return 1 if the traceback was displayed, 0 otherwise. */
2365
2366static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002367_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002368{
2369 PyObject *ferr, *res;
2370 PyObject *exception, *v, *tb;
2371 int has_tb;
2372
Victor Stinnerb45d2592019-06-20 00:05:23 +02002373 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002374 if (exception == NULL) {
2375 /* No current exception */
2376 return 0;
2377 }
2378
2379 ferr = _PySys_GetObjectId(&PyId_stderr);
2380 if (ferr == NULL || ferr == Py_None) {
2381 /* sys.stderr is not set yet or set to None,
2382 no need to try to display the exception */
2383 return 0;
2384 }
2385
Victor Stinnerb45d2592019-06-20 00:05:23 +02002386 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002387 if (tb == NULL) {
2388 tb = Py_None;
2389 Py_INCREF(tb);
2390 }
2391 PyException_SetTraceback(v, tb);
2392 if (exception == NULL) {
2393 /* PyErr_NormalizeException() failed */
2394 return 0;
2395 }
2396
2397 has_tb = (tb != Py_None);
2398 PyErr_Display(exception, v, tb);
2399 Py_XDECREF(exception);
2400 Py_XDECREF(v);
2401 Py_XDECREF(tb);
2402
2403 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002404 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002405 if (res == NULL) {
2406 _PyErr_Clear(tstate);
2407 }
2408 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002409 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002410 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002411
2412 return has_tb;
2413}
2414
Nick Coghland6009512014-11-20 21:39:37 +10002415/* Print fatal error message and abort */
2416
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002417#ifdef MS_WINDOWS
2418static void
2419fatal_output_debug(const char *msg)
2420{
2421 /* buffer of 256 bytes allocated on the stack */
2422 WCHAR buffer[256 / sizeof(WCHAR)];
2423 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2424 size_t msglen;
2425
2426 OutputDebugStringW(L"Fatal Python error: ");
2427
2428 msglen = strlen(msg);
2429 while (msglen) {
2430 size_t i;
2431
2432 if (buflen > msglen) {
2433 buflen = msglen;
2434 }
2435
2436 /* Convert the message to wchar_t. This uses a simple one-to-one
2437 conversion, assuming that the this error message actually uses
2438 ASCII only. If this ceases to be true, we will have to convert. */
2439 for (i=0; i < buflen; ++i) {
2440 buffer[i] = msg[i];
2441 }
2442 buffer[i] = L'\0';
2443 OutputDebugStringW(buffer);
2444
2445 msg += buflen;
2446 msglen -= buflen;
2447 }
2448 OutputDebugStringW(L"\n");
2449}
2450#endif
2451
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002452
2453static void
2454fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2455{
2456 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002457 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2458 if (finalizing) {
2459 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002460 }
2461 else if (runtime->initialized) {
2462 fprintf(stream, "initialized");
2463 }
2464 else if (runtime->core_initialized) {
2465 fprintf(stream, "core initialized");
2466 }
2467 else if (runtime->preinitialized) {
2468 fprintf(stream, "preinitialized");
2469 }
2470 else if (runtime->preinitializing) {
2471 fprintf(stream, "preinitializing");
2472 }
2473 else {
2474 fprintf(stream, "unknown");
2475 }
2476 fprintf(stream, "\n");
2477 fflush(stream);
2478}
2479
2480
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002481static inline void _Py_NO_RETURN
2482fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002483{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002484 if (status < 0) {
2485#if defined(MS_WINDOWS) && defined(_DEBUG)
2486 DebugBreak();
2487#endif
2488 abort();
2489 }
2490 else {
2491 exit(status);
2492 }
2493}
2494
2495
2496static void _Py_NO_RETURN
2497fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2498 int status)
2499{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002500 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002501 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002502
2503 if (reentrant) {
2504 /* Py_FatalError() caused a second fatal error.
2505 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002506 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002507 }
2508 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002509
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002510 if (header) {
2511 fprintf(stream, "Fatal Python error: ");
2512 if (prefix) {
2513 fputs(prefix, stream);
2514 fputs(": ", stream);
2515 }
2516 if (msg) {
2517 fputs(msg, stream);
2518 }
2519 else {
2520 fprintf(stream, "<message not set>");
2521 }
2522 fputs("\n", stream);
2523 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002524 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002525
2526 _PyRuntimeState *runtime = &_PyRuntime;
2527 fatal_error_dump_runtime(stream, runtime);
2528
2529 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2530 PyInterpreterState *interp = NULL;
2531 if (tstate != NULL) {
2532 interp = tstate->interp;
2533 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002534
Victor Stinner3a228ab2018-11-01 00:26:41 +01002535 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002536 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002537
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002538 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2539 has no Python thread state.
2540
2541 tss_tstate != tstate if the current Python thread does not hold the GIL.
2542 */
2543 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2544 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002545 if (has_tstate_and_gil) {
2546 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002547 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002548 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002549 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002550 }
2551 }
2552 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002553 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002554 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002555
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002556 /* The main purpose of faulthandler is to display the traceback.
2557 This function already did its best to display a traceback.
2558 Disable faulthandler to prevent writing a second traceback
2559 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002560 _PyFaulthandler_Fini();
2561
Victor Stinner791da1c2016-03-14 16:53:12 +01002562 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002563 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002564 /* Flush sys.stdout and sys.stderr */
2565 flush_std_files();
2566 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002567
Nick Coghland6009512014-11-20 21:39:37 +10002568#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002569 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002570#endif /* MS_WINDOWS */
2571
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002572 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002573}
2574
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002575
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002576#undef Py_FatalError
2577
Victor Stinner19760862017-12-20 01:41:59 +01002578void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002579Py_FatalError(const char *msg)
2580{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002581 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002582}
2583
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002584
Victor Stinner19760862017-12-20 01:41:59 +01002585void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002586_Py_FatalErrorFunc(const char *func, const char *msg)
2587{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002588 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002589}
2590
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002591
2592void _Py_NO_RETURN
2593_Py_FatalErrorFormat(const char *func, const char *format, ...)
2594{
2595 static int reentrant = 0;
2596 if (reentrant) {
2597 /* _Py_FatalErrorFormat() caused a second fatal error */
2598 fatal_error_exit(-1);
2599 }
2600 reentrant = 1;
2601
2602 FILE *stream = stderr;
2603 fprintf(stream, "Fatal Python error: ");
2604 if (func) {
2605 fputs(func, stream);
2606 fputs(": ", stream);
2607 }
2608 fflush(stream);
2609
2610 va_list vargs;
2611#ifdef HAVE_STDARG_PROTOTYPES
2612 va_start(vargs, format);
2613#else
2614 va_start(vargs);
2615#endif
2616 vfprintf(stream, format, vargs);
2617 va_end(vargs);
2618
2619 fputs("\n", stream);
2620 fflush(stream);
2621
2622 fatal_error(stream, 0, NULL, NULL, -1);
2623}
2624
2625
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002626void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002627Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002628{
Victor Stinner331a6a52019-05-27 16:39:22 +02002629 if (_PyStatus_IS_EXIT(status)) {
2630 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002631 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002632 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002633 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002634 }
2635 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002636 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002637 }
Nick Coghland6009512014-11-20 21:39:37 +10002638}
2639
Victor Stinner357704c2020-12-14 23:07:54 +01002640
Nick Coghland6009512014-11-20 21:39:37 +10002641/* Wait until threading._shutdown completes, provided
2642 the threading module was imported in the first place.
2643 The shutdown routine will wait until all non-daemon
2644 "threading" threads have completed. */
2645static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002646wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002647{
Nick Coghland6009512014-11-20 21:39:37 +10002648 _Py_IDENTIFIER(_shutdown);
2649 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002650 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002651 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002652 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002653 PyErr_WriteUnraisable(NULL);
2654 }
2655 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002656 return;
2657 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002658 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002659 if (result == NULL) {
2660 PyErr_WriteUnraisable(threading);
2661 }
2662 else {
2663 Py_DECREF(result);
2664 }
2665 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002666}
2667
2668#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002669int Py_AtExit(void (*func)(void))
2670{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002671 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002672 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002673 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002674 return 0;
2675}
2676
2677static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002678call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002679{
Victor Stinner8e91c242019-04-24 17:24:01 +02002680 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002681 /* pop last function from the list */
2682 runtime->nexitfuncs--;
2683 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2684 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2685
2686 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002687 }
Nick Coghland6009512014-11-20 21:39:37 +10002688
2689 fflush(stdout);
2690 fflush(stderr);
2691}
2692
Victor Stinnercfc88312018-08-01 16:41:25 +02002693void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002694Py_Exit(int sts)
2695{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002696 if (Py_FinalizeEx() < 0) {
2697 sts = 120;
2698 }
Nick Coghland6009512014-11-20 21:39:37 +10002699
2700 exit(sts);
2701}
2702
Nick Coghland6009512014-11-20 21:39:37 +10002703
Nick Coghland6009512014-11-20 21:39:37 +10002704/*
2705 * The file descriptor fd is considered ``interactive'' if either
2706 * a) isatty(fd) is TRUE, or
2707 * b) the -i flag was given, and the filename associated with
2708 * the descriptor is NULL or "<stdin>" or "???".
2709 */
2710int
2711Py_FdIsInteractive(FILE *fp, const char *filename)
2712{
2713 if (isatty((int)fileno(fp)))
2714 return 1;
2715 if (!Py_InteractiveFlag)
2716 return 0;
2717 return (filename == NULL) ||
2718 (strcmp(filename, "<stdin>") == 0) ||
2719 (strcmp(filename, "???") == 0);
2720}
2721
2722
Victor Stinnera82f63f2020-12-09 22:37:27 +01002723int
2724_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2725{
2726 if (isatty((int)fileno(fp))) {
2727 return 1;
2728 }
2729 if (!Py_InteractiveFlag) {
2730 return 0;
2731 }
2732 return (filename == NULL) ||
2733 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2734 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2735}
2736
2737
Nick Coghland6009512014-11-20 21:39:37 +10002738/* Wrappers around sigaction() or signal(). */
2739
2740PyOS_sighandler_t
2741PyOS_getsig(int sig)
2742{
2743#ifdef HAVE_SIGACTION
2744 struct sigaction context;
2745 if (sigaction(sig, NULL, &context) == -1)
2746 return SIG_ERR;
2747 return context.sa_handler;
2748#else
2749 PyOS_sighandler_t handler;
2750/* Special signal handling for the secure CRT in Visual Studio 2005 */
2751#if defined(_MSC_VER) && _MSC_VER >= 1400
2752 switch (sig) {
2753 /* Only these signals are valid */
2754 case SIGINT:
2755 case SIGILL:
2756 case SIGFPE:
2757 case SIGSEGV:
2758 case SIGTERM:
2759 case SIGBREAK:
2760 case SIGABRT:
2761 break;
2762 /* Don't call signal() with other values or it will assert */
2763 default:
2764 return SIG_ERR;
2765 }
2766#endif /* _MSC_VER && _MSC_VER >= 1400 */
2767 handler = signal(sig, SIG_IGN);
2768 if (handler != SIG_ERR)
2769 signal(sig, handler);
2770 return handler;
2771#endif
2772}
2773
2774/*
2775 * All of the code in this function must only use async-signal-safe functions,
2776 * listed at `man 7 signal` or
2777 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2778 */
2779PyOS_sighandler_t
2780PyOS_setsig(int sig, PyOS_sighandler_t handler)
2781{
2782#ifdef HAVE_SIGACTION
2783 /* Some code in Modules/signalmodule.c depends on sigaction() being
2784 * used here if HAVE_SIGACTION is defined. Fix that if this code
2785 * changes to invalidate that assumption.
2786 */
2787 struct sigaction context, ocontext;
2788 context.sa_handler = handler;
2789 sigemptyset(&context.sa_mask);
2790 context.sa_flags = 0;
2791 if (sigaction(sig, &context, &ocontext) == -1)
2792 return SIG_ERR;
2793 return ocontext.sa_handler;
2794#else
2795 PyOS_sighandler_t oldhandler;
2796 oldhandler = signal(sig, handler);
2797#ifdef HAVE_SIGINTERRUPT
2798 siginterrupt(sig, 1);
2799#endif
2800 return oldhandler;
2801#endif
2802}
2803
2804#ifdef __cplusplus
2805}
2806#endif