blob: 77a18e17e07eadbab06883ee7661970636526d1e [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +02007
8#include "pycore_ceval.h" // _PyEval_FiniGIL()
9#include "pycore_context.h" // _PyContext_Init()
10#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner4f98f462020-04-15 04:01:58 +020011#include "pycore_initconfig.h" // _PyStatus_OK()
12#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
13#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
14#include "pycore_pyerrors.h" // _PyErr_Occurred()
15#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020016#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020017#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
18#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
19
Victor Stinner4f98f462020-04-15 04:01:58 +020020#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100021
22#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020023# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100024#endif
25
26#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020027# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100028#endif
29
30#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020031# undef BYTE
32# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070033
Victor Stinner4f98f462020-04-15 04:01:58 +020034 extern PyTypeObject PyWindowsConsoleIO_Type;
35# define PyWindowsConsoleIO_Check(op) \
36 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
Victor Stinner4f98f462020-04-15 04:01:58 +020039
Nick Coghland6009512014-11-20 21:39:37 +100040_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
Nick Coghland6009512014-11-20 21:39:37 +100051
Victor Stinnerb45d2592019-06-20 00:05:23 +020052/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020053static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020054static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050055static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020056static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020057static void call_py_exitfuncs(PyThreadState *tstate);
58static 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
99/* PyModule_GetWarningsModule is no longer necessary as of 2.6
100since _warnings is builtin. This API should not be used. */
101PyObject *
102PyModule_GetWarningsModule(void)
103{
104 return PyImport_ImportModule("warnings");
105}
106
Eric Snowc7ec9982017-05-23 23:00:52 -0700107
Eric Snow1abcf672017-05-23 21:46:51 -0700108/* APIs to access the initialization flags
109 *
110 * Can be called prior to Py_Initialize.
111 */
Nick Coghland6009512014-11-20 21:39:37 +1000112
Eric Snow1abcf672017-05-23 21:46:51 -0700113int
114_Py_IsCoreInitialized(void)
115{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600116 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700117}
Nick Coghland6009512014-11-20 21:39:37 +1000118
119int
120Py_IsInitialized(void)
121{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000123}
124
Nick Coghlan6ea41862017-06-11 13:16:15 +1000125
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000126/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
127 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000128 initializations fail, a fatal error is issued and the function does
129 not return. On return, the first thread and interpreter state have
130 been created.
131
132 Locking: you must hold the interpreter lock while calling this.
133 (If the lock has not yet been initialized, that's equivalent to
134 having the lock, but you cannot use multiple threads.)
135
136*/
Victor Stinneref75a622020-11-12 15:14:13 +0100137static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200138init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000139{
Victor Stinneref75a622020-11-12 15:14:13 +0100140 assert(!_PyErr_Occurred(tstate));
141
Victor Stinnerb45d2592019-06-20 00:05:23 +0200142 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200143 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000144
Victor Stinneref75a622020-11-12 15:14:13 +0100145 // Import _importlib through its frozen version, _frozen_importlib.
146 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000147 PySys_FormatStderr("import _frozen_importlib # frozen\n");
148 }
Victor Stinneref75a622020-11-12 15:14:13 +0100149 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
150 return -1;
151 }
152 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000153 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100154 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000155 }
Victor Stinneref75a622020-11-12 15:14:13 +0100156 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000157
Victor Stinneref75a622020-11-12 15:14:13 +0100158 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
159 "__import__");
160 if (import_func == NULL) {
161 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000162 }
Victor Stinneref75a622020-11-12 15:14:13 +0100163 interp->import_func = Py_NewRef(import_func);
164
165 // Import the _imp module
166 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200167 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000168 }
Victor Stinneref75a622020-11-12 15:14:13 +0100169 PyObject *imp_mod = PyInit__imp();
170 if (imp_mod == NULL) {
171 return -1;
172 }
173 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
174 Py_DECREF(imp_mod);
175 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000176 }
177
Victor Stinneref75a622020-11-12 15:14:13 +0100178 // Install importlib as the implementation of import
179 PyObject *value = PyObject_CallMethod(importlib, "_install",
180 "OO", sysmod, imp_mod);
181 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000182 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100183 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000184 }
185 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000186
Victor Stinneref75a622020-11-12 15:14:13 +0100187 assert(!_PyErr_Occurred(tstate));
188 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000189}
190
Victor Stinneref75a622020-11-12 15:14:13 +0100191
Victor Stinner331a6a52019-05-27 16:39:22 +0200192static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200193init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700194{
195 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200196 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700197 "_install_external_importers", "");
198 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200199 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200200 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700201 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200202 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200203 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700204}
Nick Coghland6009512014-11-20 21:39:37 +1000205
Nick Coghlan6ea41862017-06-11 13:16:15 +1000206/* Helper functions to better handle the legacy C locale
207 *
208 * The legacy C locale assumes ASCII as the default text encoding, which
209 * causes problems not only for the CPython runtime, but also other
210 * components like GNU readline.
211 *
212 * Accordingly, when the CLI detects it, it attempts to coerce it to a
213 * more capable UTF-8 based alternative as follows:
214 *
215 * if (_Py_LegacyLocaleDetected()) {
216 * _Py_CoerceLegacyLocale();
217 * }
218 *
219 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
220 *
221 * Locale coercion also impacts the default error handler for the standard
222 * streams: while the usual default is "strict", the default for the legacy
223 * C locale and for any of the coercion target locales is "surrogateescape".
224 */
225
226int
Victor Stinner0f721472019-05-20 17:16:38 +0200227_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000228{
229#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200230 if (!warn) {
231 const char *locale_override = getenv("LC_ALL");
232 if (locale_override != NULL && *locale_override != '\0') {
233 /* Don't coerce C locale if the LC_ALL environment variable
234 is set */
235 return 0;
236 }
237 }
238
Nick Coghlan6ea41862017-06-11 13:16:15 +1000239 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000240 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
241 * the POSIX locale as a simple alias for the C locale, so
242 * we may also want to check for that explicitly.
243 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000244 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
245 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
246#else
247 /* Windows uses code pages instead of locales, so no locale is legacy */
248 return 0;
249#endif
250}
251
Victor Stinnerb0051362019-11-22 17:52:42 +0100252#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000253static const char *_C_LOCALE_WARNING =
254 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
255 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
256 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
257 "locales is recommended.\n";
258
Nick Coghlaneb817952017-06-18 12:29:42 +1000259static void
Victor Stinner43125222019-04-24 18:23:53 +0200260emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000261{
Victor Stinner331a6a52019-05-27 16:39:22 +0200262 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200263 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200264 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000265 }
266}
Victor Stinnerb0051362019-11-22 17:52:42 +0100267#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000268
Nick Coghlan6ea41862017-06-11 13:16:15 +1000269typedef struct _CandidateLocale {
270 const char *locale_name; /* The locale to try as a coercion target */
271} _LocaleCoercionTarget;
272
273static _LocaleCoercionTarget _TARGET_LOCALES[] = {
274 {"C.UTF-8"},
275 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000276 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000277 {NULL}
278};
279
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200280
281int
282_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000283{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200284 const _LocaleCoercionTarget *target = NULL;
285 for (target = _TARGET_LOCALES; target->locale_name; target++) {
286 if (strcmp(ctype_loc, target->locale_name) == 0) {
287 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000288 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200289 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200290 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291}
292
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200293
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100295static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
297 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
298
Victor Stinner0f721472019-05-20 17:16:38 +0200299static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200300_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301{
302 const char *newloc = target->locale_name;
303
304 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100305 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000306
307 /* Set the relevant locale environment variable */
308 if (setenv("LC_CTYPE", newloc, 1)) {
309 fprintf(stderr,
310 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200311 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200313 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100314 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000315 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000316
317 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100318 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200319 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000320}
321#endif
322
Victor Stinner0f721472019-05-20 17:16:38 +0200323int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200324_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000325{
Victor Stinner0f721472019-05-20 17:16:38 +0200326 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000327#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200328 char *oldloc = NULL;
329
330 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
331 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200332 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200333 }
334
Victor Stinner94540602017-12-16 04:54:22 +0100335 const char *locale_override = getenv("LC_ALL");
336 if (locale_override == NULL || *locale_override == '\0') {
337 /* LC_ALL is also not set (or is set to an empty string) */
338 const _LocaleCoercionTarget *target = NULL;
339 for (target = _TARGET_LOCALES; target->locale_name; target++) {
340 const char *new_locale = setlocale(LC_CTYPE,
341 target->locale_name);
342 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400343#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100344 /* Also ensure that nl_langinfo works in this locale */
345 char *codeset = nl_langinfo(CODESET);
346 if (!codeset || *codeset == '\0') {
347 /* CODESET is not set or empty, so skip coercion */
348 new_locale = NULL;
349 _Py_SetLocaleFromEnv(LC_CTYPE);
350 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000351 }
Victor Stinner94540602017-12-16 04:54:22 +0100352#endif
353 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200354 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200355 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000356 }
357 }
358 }
359 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200360
361 setlocale(LC_CTYPE, oldloc);
362
363done:
364 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000365#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200366 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000367}
368
xdegaye1588be62017-11-12 12:45:59 +0100369/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
370 * isolate the idiosyncrasies of different libc implementations. It reads the
371 * appropriate environment variable and uses its value to select the locale for
372 * 'category'. */
373char *
374_Py_SetLocaleFromEnv(int category)
375{
Victor Stinner353933e2018-11-23 13:08:26 +0100376 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100377#ifdef __ANDROID__
378 const char *locale;
379 const char **pvar;
380#ifdef PY_COERCE_C_LOCALE
381 const char *coerce_c_locale;
382#endif
383 const char *utf8_locale = "C.UTF-8";
384 const char *env_var_set[] = {
385 "LC_ALL",
386 "LC_CTYPE",
387 "LANG",
388 NULL,
389 };
390
391 /* Android setlocale(category, "") doesn't check the environment variables
392 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
393 * check the environment variables listed in env_var_set. */
394 for (pvar=env_var_set; *pvar; pvar++) {
395 locale = getenv(*pvar);
396 if (locale != NULL && *locale != '\0') {
397 if (strcmp(locale, utf8_locale) == 0 ||
398 strcmp(locale, "en_US.UTF-8") == 0) {
399 return setlocale(category, utf8_locale);
400 }
401 return setlocale(category, "C");
402 }
403 }
404
405 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
406 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
407 * Quote from POSIX section "8.2 Internationalization Variables":
408 * "4. If the LANG environment variable is not set or is set to the empty
409 * string, the implementation-defined default locale shall be used." */
410
411#ifdef PY_COERCE_C_LOCALE
412 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
413 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
414 /* Some other ported code may check the environment variables (e.g. in
415 * extension modules), so we make sure that they match the locale
416 * configuration */
417 if (setenv("LC_CTYPE", utf8_locale, 1)) {
418 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
419 "environment variable to %s\n", utf8_locale);
420 }
421 }
422#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100423 res = setlocale(category, utf8_locale);
424#else /* !defined(__ANDROID__) */
425 res = setlocale(category, "");
426#endif
427 _Py_ResetForceASCII();
428 return res;
xdegaye1588be62017-11-12 12:45:59 +0100429}
430
Nick Coghlan6ea41862017-06-11 13:16:15 +1000431
Victor Stinner048a3562020-11-05 00:45:56 +0100432static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100433interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100434{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100435 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100436
Victor Stinner9e1b8282020-11-10 13:21:52 +0100437 if (!only_update_path_config) {
438 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
439 if (_PyStatus_EXCEPTION(status)) {
440 _PyErr_SetFromPyStatus(status);
441 return -1;
442 }
Victor Stinner048a3562020-11-05 00:45:56 +0100443 }
444
Victor Stinner9e1b8282020-11-10 13:21:52 +0100445 if (_Py_IsMainInterpreter(tstate)) {
446 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100447 if (_PyStatus_EXCEPTION(status)) {
448 _PyErr_SetFromPyStatus(status);
449 return -1;
450 }
451 }
452
453 // Update the sys module for the new configuration
454 if (_PySys_UpdateConfig(tstate) < 0) {
455 return -1;
456 }
457 return 0;
458}
459
460
461int
462_PyInterpreterState_SetConfig(const PyConfig *src_config)
463{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100464 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100465 int res = -1;
466
467 PyConfig config;
468 PyConfig_InitPythonConfig(&config);
469 PyStatus status = _PyConfig_Copy(&config, src_config);
470 if (_PyStatus_EXCEPTION(status)) {
471 _PyErr_SetFromPyStatus(status);
472 goto done;
473 }
474
475 status = PyConfig_Read(&config);
476 if (_PyStatus_EXCEPTION(status)) {
477 _PyErr_SetFromPyStatus(status);
478 goto done;
479 }
480
Victor Stinner9e1b8282020-11-10 13:21:52 +0100481 status = _PyConfig_Copy(&tstate->interp->config, &config);
482 if (_PyStatus_EXCEPTION(status)) {
483 _PyErr_SetFromPyStatus(status);
484 goto done;
485 }
486
487 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100488
489done:
490 PyConfig_Clear(&config);
491 return res;
492}
493
494
Eric Snow1abcf672017-05-23 21:46:51 -0700495/* Global initializations. Can be undone by Py_Finalize(). Don't
496 call this twice without an intervening Py_Finalize() call.
497
Victor Stinner331a6a52019-05-27 16:39:22 +0200498 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700499 must have a corresponding call to Py_Finalize.
500
501 Locking: you must hold the interpreter lock while calling these APIs.
502 (If the lock has not yet been initialized, that's equivalent to
503 having the lock, but you cannot use multiple threads.)
504
505*/
506
Victor Stinner331a6a52019-05-27 16:39:22 +0200507static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200508pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200509 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200510 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200511{
Victor Stinner331a6a52019-05-27 16:39:22 +0200512 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100513 PyThreadState *tstate = _PyThreadState_GET();
514 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200515 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100516 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200517 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100518
519 PyInterpreterState *interp = tstate->interp;
520 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200521 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100522 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100523
Victor Stinnere81f6e62020-06-08 18:12:59 +0200524 status = _PyConfig_Write(config, runtime);
525 if (_PyStatus_EXCEPTION(status)) {
526 return status;
527 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200528
Victor Stinner048a3562020-11-05 00:45:56 +0100529 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200530 if (_PyStatus_EXCEPTION(status)) {
531 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200532 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200533 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200534
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200536 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200537 if (_PyStatus_EXCEPTION(status)) {
538 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200539 }
540 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200541 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200542}
543
544
Victor Stinner331a6a52019-05-27 16:39:22 +0200545static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200546pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200547 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000548{
Victor Stinner43125222019-04-24 18:23:53 +0200549 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200550 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200551 }
Victor Stinnerda273412017-12-15 01:46:02 +0100552
Victor Stinnere81f6e62020-06-08 18:12:59 +0200553 PyStatus status = _PyConfig_Write(config, runtime);
554 if (_PyStatus_EXCEPTION(status)) {
555 return status;
556 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600557
Eric Snow1abcf672017-05-23 21:46:51 -0700558 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
559 * threads behave a little more gracefully at interpreter shutdown.
560 * We clobber it here so the new interpreter can start with a clean
561 * slate.
562 *
563 * However, this may still lead to misbehaviour if there are daemon
564 * threads still hanging around from a previous Py_Initialize/Finalize
565 * pair :(
566 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100567 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600568
Victor Stinnere81f6e62020-06-08 18:12:59 +0200569 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200570 if (_PyStatus_EXCEPTION(status)) {
571 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800572 }
573
Victor Stinner331a6a52019-05-27 16:39:22 +0200574 status = _PyInterpreterState_Enable(runtime);
575 if (_PyStatus_EXCEPTION(status)) {
576 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800577 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200578 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100579}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800580
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100581
Victor Stinner331a6a52019-05-27 16:39:22 +0200582static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200583init_interp_create_gil(PyThreadState *tstate)
584{
585 PyStatus status;
586
587 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
588 only called here. */
589 _PyEval_FiniGIL(tstate);
590
591 /* Auto-thread-state API */
592 status = _PyGILState_Init(tstate);
593 if (_PyStatus_EXCEPTION(status)) {
594 return status;
595 }
596
597 /* Create the GIL and take it */
598 status = _PyEval_InitGIL(tstate);
599 if (_PyStatus_EXCEPTION(status)) {
600 return status;
601 }
602
603 return _PyStatus_OK();
604}
605
606
607static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200608pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200609 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200610 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100611{
612 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100613 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200614 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100615 }
616
Victor Stinner048a3562020-11-05 00:45:56 +0100617 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200618 if (_PyStatus_EXCEPTION(status)) {
619 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100620 }
Nick Coghland6009512014-11-20 21:39:37 +1000621
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200622 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200623 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200624 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200625 }
Nick Coghland6009512014-11-20 21:39:37 +1000626 (void) PyThreadState_Swap(tstate);
627
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200628 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100629 if (_PyStatus_EXCEPTION(status)) {
630 return status;
631 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100632
Victor Stinnerb45d2592019-06-20 00:05:23 +0200633 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200634 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100635}
Nick Coghland6009512014-11-20 21:39:37 +1000636
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100637
Victor Stinner331a6a52019-05-27 16:39:22 +0200638static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100639pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100640{
Victor Stinner444b39b2019-11-20 01:18:11 +0100641 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100642 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100643
Victor Stinner01b1cc12019-11-20 02:27:56 +0100644 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100645 if (_PyStatus_EXCEPTION(status)) {
646 return status;
647 }
648
Victor Stinner0430dfa2020-06-24 15:21:54 +0200649 // Create the empty tuple singleton. It must be created before the first
650 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
651 // for example.
652 status = _PyTuple_Init(tstate);
653 if (_PyStatus_EXCEPTION(status)) {
654 return status;
655 }
656
Victor Stinnere7e699e2019-11-20 12:08:13 +0100657 if (is_main_interp) {
658 status = _PyTypes_Init();
659 if (_PyStatus_EXCEPTION(status)) {
660 return status;
661 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100662 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100663
Victor Stinner630c8df2019-12-17 13:02:18 +0100664 if (!_PyLong_Init(tstate)) {
665 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100666 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100667
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200668 status = _PyUnicode_Init(tstate);
669 if (_PyStatus_EXCEPTION(status)) {
670 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100671 }
672
Victor Stinner91698d82020-06-25 14:07:40 +0200673 status = _PyBytes_Init(tstate);
674 if (_PyStatus_EXCEPTION(status)) {
675 return status;
676 }
677
Victor Stinner281cce12020-06-23 22:55:46 +0200678 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200679 if (_PyStatus_EXCEPTION(status)) {
680 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100681 }
682
Victor Stinnere7e699e2019-11-20 12:08:13 +0100683 if (is_main_interp) {
684 if (!_PyFloat_Init()) {
685 return _PyStatus_ERR("can't init float");
686 }
Nick Coghland6009512014-11-20 21:39:37 +1000687
Victor Stinnere7e699e2019-11-20 12:08:13 +0100688 if (_PyStructSequence_Init() < 0) {
689 return _PyStatus_ERR("can't initialize structseq");
690 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100691 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200692
Victor Stinner331a6a52019-05-27 16:39:22 +0200693 status = _PyErr_Init();
694 if (_PyStatus_EXCEPTION(status)) {
695 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200696 }
697
Victor Stinnere7e699e2019-11-20 12:08:13 +0100698 if (is_main_interp) {
699 if (!_PyContext_Init()) {
700 return _PyStatus_ERR("can't init context");
701 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100702 }
703
Victor Stinneref75a622020-11-12 15:14:13 +0100704 if (_PyWarnings_InitState(tstate) < 0) {
705 return _PyStatus_ERR("can't initialize warnings");
706 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200707 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100708}
709
710
Victor Stinner331a6a52019-05-27 16:39:22 +0200711static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200712pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100713{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100714 assert(!_PyErr_Occurred(tstate));
715
Victor Stinnerb45d2592019-06-20 00:05:23 +0200716 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100717 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100718 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100719 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100720
Victor Stinner2582d462019-11-22 19:24:49 +0100721 PyInterpreterState *interp = tstate->interp;
722 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
723 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100724 }
Victor Stinner2582d462019-11-22 19:24:49 +0100725
726 PyObject *builtins_dict = PyModule_GetDict(bimod);
727 if (builtins_dict == NULL) {
728 goto error;
729 }
730 Py_INCREF(builtins_dict);
731 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100732
Victor Stinner331a6a52019-05-27 16:39:22 +0200733 PyStatus status = _PyBuiltins_AddExceptions(bimod);
734 if (_PyStatus_EXCEPTION(status)) {
735 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100736 }
Victor Stinner2582d462019-11-22 19:24:49 +0100737
738 interp->builtins_copy = PyDict_Copy(interp->builtins);
739 if (interp->builtins_copy == NULL) {
740 goto error;
741 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000742 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100743
744 assert(!_PyErr_Occurred(tstate));
745
Victor Stinner331a6a52019-05-27 16:39:22 +0200746 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100747
748error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000749 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100750 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100751}
752
753
Victor Stinner331a6a52019-05-27 16:39:22 +0200754static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100755pycore_interp_init(PyThreadState *tstate)
756{
757 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100758 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100759
760 status = pycore_init_types(tstate);
761 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100762 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100763 }
764
Victor Stinnerd863ade2019-12-06 03:37:07 +0100765 status = _PySys_Create(tstate, &sysmod);
766 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100767 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100768 }
769
770 status = pycore_init_builtins(tstate);
771 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100772 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100773 }
774
Victor Stinneref75a622020-11-12 15:14:13 +0100775 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
776 if (config->_install_importlib) {
777 /* This call sets up builtin and frozen import support */
778 if (init_importlib(tstate, sysmod) < 0) {
779 return _PyStatus_ERR("failed to initialize importlib");
780 }
781 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100782
783done:
784 /* sys.modules['sys'] contains a strong reference to the module */
785 Py_XDECREF(sysmod);
786 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100787}
788
789
790static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200791pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200792 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200793 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100794{
Victor Stinner331a6a52019-05-27 16:39:22 +0200795 PyStatus status = pycore_init_runtime(runtime, config);
796 if (_PyStatus_EXCEPTION(status)) {
797 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100798 }
799
Victor Stinnerb45d2592019-06-20 00:05:23 +0200800 PyThreadState *tstate;
801 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200802 if (_PyStatus_EXCEPTION(status)) {
803 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100804 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200805 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100806
Victor Stinnerd863ade2019-12-06 03:37:07 +0100807 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200808 if (_PyStatus_EXCEPTION(status)) {
809 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100810 }
Eric Snow1abcf672017-05-23 21:46:51 -0700811
812 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200813 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200814 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700815}
816
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100817
Victor Stinner331a6a52019-05-27 16:39:22 +0200818PyStatus
819_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100820{
Victor Stinner331a6a52019-05-27 16:39:22 +0200821 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100822
Victor Stinner6d1c4672019-05-20 11:02:00 +0200823 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200824 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200825 }
826
Victor Stinner331a6a52019-05-27 16:39:22 +0200827 status = _PyRuntime_Initialize();
828 if (_PyStatus_EXCEPTION(status)) {
829 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100830 }
Victor Stinner43125222019-04-24 18:23:53 +0200831 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100832
Victor Stinnerd3b90412019-09-17 23:59:51 +0200833 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100834 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200835 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100836 }
837
Victor Stinnerd3b90412019-09-17 23:59:51 +0200838 /* Note: preinitialized remains 1 on error, it is only set to 0
839 at exit on success. */
840 runtime->preinitializing = 1;
841
Victor Stinner331a6a52019-05-27 16:39:22 +0200842 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200843
844 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
845 if (_PyStatus_EXCEPTION(status)) {
846 return status;
847 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100848
Victor Stinner331a6a52019-05-27 16:39:22 +0200849 status = _PyPreConfig_Read(&config, args);
850 if (_PyStatus_EXCEPTION(status)) {
851 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100852 }
853
Victor Stinner331a6a52019-05-27 16:39:22 +0200854 status = _PyPreConfig_Write(&config);
855 if (_PyStatus_EXCEPTION(status)) {
856 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100857 }
858
Victor Stinnerd3b90412019-09-17 23:59:51 +0200859 runtime->preinitializing = 0;
860 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200861 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100862}
863
Victor Stinner70005ac2019-05-02 15:25:34 -0400864
Victor Stinner331a6a52019-05-27 16:39:22 +0200865PyStatus
866Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100867{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100868 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400869 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100870}
871
872
Victor Stinner331a6a52019-05-27 16:39:22 +0200873PyStatus
874Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100875{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100876 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400877 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100878}
879
880
Victor Stinner331a6a52019-05-27 16:39:22 +0200881PyStatus
882Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100883{
Victor Stinner70005ac2019-05-02 15:25:34 -0400884 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100885}
886
887
Victor Stinner331a6a52019-05-27 16:39:22 +0200888PyStatus
889_Py_PreInitializeFromConfig(const PyConfig *config,
890 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100891{
Victor Stinner331a6a52019-05-27 16:39:22 +0200892 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200893
Victor Stinner331a6a52019-05-27 16:39:22 +0200894 PyStatus status = _PyRuntime_Initialize();
895 if (_PyStatus_EXCEPTION(status)) {
896 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200897 }
898 _PyRuntimeState *runtime = &_PyRuntime;
899
Victor Stinnerd3b90412019-09-17 23:59:51 +0200900 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200901 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200902 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400903 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200904
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200906
Victor Stinner3c30a762019-10-01 10:56:37 +0200907 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200908
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 if (!config->parse_argv) {
910 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200911 }
912 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200913 _PyArgv config_args = {
914 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200915 .argc = config->argv.length,
916 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200917 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200918 }
919 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200920 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200921 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100922}
923
924
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100925/* Begin interpreter initialization
926 *
927 * On return, the first thread and interpreter state have been created,
928 * but the compiler, signal handling, multithreading and
929 * multiple interpreter support, and codec infrastructure are not yet
930 * available.
931 *
932 * The import system will support builtin and frozen modules only.
933 * The only supported io is writing to sys.stderr
934 *
935 * If any operation invoked by this function fails, a fatal error is
936 * issued and the function does not return.
937 *
938 * Any code invoked from this function should *not* assume it has access
939 * to the Python C API (unless the API is explicitly listed as being
940 * safe to call without calling Py_Initialize first)
941 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200942static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200943pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200944 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200945 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200946{
Victor Stinner331a6a52019-05-27 16:39:22 +0200947 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200948
Victor Stinner331a6a52019-05-27 16:39:22 +0200949 status = _Py_PreInitializeFromConfig(src_config, NULL);
950 if (_PyStatus_EXCEPTION(status)) {
951 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200952 }
953
Victor Stinner331a6a52019-05-27 16:39:22 +0200954 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100955 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200956
Victor Stinner331a6a52019-05-27 16:39:22 +0200957 status = _PyConfig_Copy(&config, src_config);
958 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200959 goto done;
960 }
961
Victor Stinner9e1b8282020-11-10 13:21:52 +0100962 // Read the configuration, but don't compute the path configuration
963 // (it is computed in the main init).
964 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200965 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200966 goto done;
967 }
968
969 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200970 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200971 }
972 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200973 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200974 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200975 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200976 goto done;
977 }
978
979done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200980 PyConfig_Clear(&config);
981 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200982}
983
Victor Stinner5ac27a52019-03-27 13:40:14 +0100984
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200985/* Py_Initialize() has already been called: update the main interpreter
986 configuration. Example of bpo-34008: Py_Main() called after
987 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200988static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100989pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200990{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100991 if (interpreter_update_config(tstate, 0) < 0) {
992 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200993 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200994 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200995}
996
Victor Stinnerb0051362019-11-22 17:52:42 +0100997
998static PyStatus
999init_interp_main(PyThreadState *tstate)
1000{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001001 assert(!_PyErr_Occurred(tstate));
1002
Victor Stinnerb0051362019-11-22 17:52:42 +01001003 PyStatus status;
1004 int is_main_interp = _Py_IsMainInterpreter(tstate);
1005 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001006 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001007
1008 if (!config->_install_importlib) {
1009 /* Special mode for freeze_importlib: run with no import system
1010 *
1011 * This means anything which needs support from extension modules
1012 * or pure Python code in the standard library won't work.
1013 */
1014 if (is_main_interp) {
1015 interp->runtime->initialized = 1;
1016 }
1017 return _PyStatus_OK();
1018 }
1019
Victor Stinner9e1b8282020-11-10 13:21:52 +01001020 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001021 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001022 if (_PyStatus_EXCEPTION(status)) {
1023 return status;
1024 }
1025
Victor Stinner9e1b8282020-11-10 13:21:52 +01001026 if (interpreter_update_config(tstate, 1) < 0) {
1027 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001028 }
1029
1030 status = init_importlib_external(tstate);
1031 if (_PyStatus_EXCEPTION(status)) {
1032 return status;
1033 }
1034
1035 if (is_main_interp) {
1036 /* initialize the faulthandler module */
1037 status = _PyFaulthandler_Init(config->faulthandler);
1038 if (_PyStatus_EXCEPTION(status)) {
1039 return status;
1040 }
1041 }
1042
1043 status = _PyUnicode_InitEncodings(tstate);
1044 if (_PyStatus_EXCEPTION(status)) {
1045 return status;
1046 }
1047
1048 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001049 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1050 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001051 }
1052
1053 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1054 return _PyStatus_ERR("can't initialize tracemalloc");
1055 }
1056 }
1057
1058 status = init_sys_streams(tstate);
1059 if (_PyStatus_EXCEPTION(status)) {
1060 return status;
1061 }
1062
Andy Lester75cd5bf2020-03-12 02:49:05 -05001063 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001064 if (_PyStatus_EXCEPTION(status)) {
1065 return status;
1066 }
1067
1068 status = add_main_module(interp);
1069 if (_PyStatus_EXCEPTION(status)) {
1070 return status;
1071 }
1072
1073 if (is_main_interp) {
1074 /* Initialize warnings. */
1075 PyObject *warnoptions = PySys_GetObject("warnoptions");
1076 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1077 {
1078 PyObject *warnings_module = PyImport_ImportModule("warnings");
1079 if (warnings_module == NULL) {
1080 fprintf(stderr, "'import warnings' failed; traceback:\n");
1081 _PyErr_Print(tstate);
1082 }
1083 Py_XDECREF(warnings_module);
1084 }
1085
1086 interp->runtime->initialized = 1;
1087 }
1088
1089 if (config->site_import) {
1090 status = init_import_site();
1091 if (_PyStatus_EXCEPTION(status)) {
1092 return status;
1093 }
1094 }
1095
1096 if (is_main_interp) {
1097#ifndef MS_WINDOWS
1098 emit_stderr_warning_for_legacy_locale(interp->runtime);
1099#endif
1100 }
1101
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001102 assert(!_PyErr_Occurred(tstate));
1103
Victor Stinnerb0051362019-11-22 17:52:42 +01001104 return _PyStatus_OK();
1105}
1106
1107
Eric Snowc7ec9982017-05-23 23:00:52 -07001108/* Update interpreter state based on supplied configuration settings
1109 *
1110 * After calling this function, most of the restrictions on the interpreter
1111 * are lifted. The only remaining incomplete settings are those related
1112 * to the main module (sys.argv[0], __main__ metadata)
1113 *
1114 * Calling this when the interpreter is not initializing, is already
1115 * initialized or without a valid current thread state is a fatal error.
1116 * Other errors should be reported as normal Python exceptions with a
1117 * non-zero return code.
1118 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001119static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001120pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001121{
Victor Stinnerb0051362019-11-22 17:52:42 +01001122 PyInterpreterState *interp = tstate->interp;
1123 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001124 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001125 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001126
Victor Stinnerb0051362019-11-22 17:52:42 +01001127 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001128 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001129 }
1130
Victor Stinnerb0051362019-11-22 17:52:42 +01001131 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001132 if (_PyStatus_EXCEPTION(status)) {
1133 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001134 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001135 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001136}
1137
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001138
Victor Stinner331a6a52019-05-27 16:39:22 +02001139PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001140Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001141{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001142 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001143 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001144 }
1145
Victor Stinner331a6a52019-05-27 16:39:22 +02001146 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001147
Victor Stinner331a6a52019-05-27 16:39:22 +02001148 status = _PyRuntime_Initialize();
1149 if (_PyStatus_EXCEPTION(status)) {
1150 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001151 }
1152 _PyRuntimeState *runtime = &_PyRuntime;
1153
Victor Stinnerb45d2592019-06-20 00:05:23 +02001154 PyThreadState *tstate = NULL;
1155 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001156 if (_PyStatus_EXCEPTION(status)) {
1157 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001158 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001159 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001160
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001161 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001162 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001163 if (_PyStatus_EXCEPTION(status)) {
1164 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001165 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001166 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001167
Victor Stinner331a6a52019-05-27 16:39:22 +02001168 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001169}
1170
1171
Eric Snow1abcf672017-05-23 21:46:51 -07001172void
Nick Coghland6009512014-11-20 21:39:37 +10001173Py_InitializeEx(int install_sigs)
1174{
Victor Stinner331a6a52019-05-27 16:39:22 +02001175 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001176
Victor Stinner331a6a52019-05-27 16:39:22 +02001177 status = _PyRuntime_Initialize();
1178 if (_PyStatus_EXCEPTION(status)) {
1179 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001180 }
1181 _PyRuntimeState *runtime = &_PyRuntime;
1182
1183 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001184 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1185 return;
1186 }
1187
Victor Stinner331a6a52019-05-27 16:39:22 +02001188 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001189 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001190
Victor Stinner1dc6e392018-07-25 02:49:17 +02001191 config.install_signal_handlers = install_sigs;
1192
Victor Stinner331a6a52019-05-27 16:39:22 +02001193 status = Py_InitializeFromConfig(&config);
1194 if (_PyStatus_EXCEPTION(status)) {
1195 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001196 }
Nick Coghland6009512014-11-20 21:39:37 +10001197}
1198
1199void
1200Py_Initialize(void)
1201{
1202 Py_InitializeEx(1);
1203}
1204
1205
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001206PyStatus
1207_Py_InitializeMain(void)
1208{
1209 PyStatus status = _PyRuntime_Initialize();
1210 if (_PyStatus_EXCEPTION(status)) {
1211 return status;
1212 }
1213 _PyRuntimeState *runtime = &_PyRuntime;
1214 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1215 return pyinit_main(tstate);
1216}
1217
1218
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001219static void
1220finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1221{
1222 // List of names to clear in sys
1223 static const char * const sys_deletes[] = {
1224 "path", "argv", "ps1", "ps2",
1225 "last_type", "last_value", "last_traceback",
1226 "path_hooks", "path_importer_cache", "meta_path",
1227 "__interactivehook__",
1228 NULL
1229 };
1230
1231 static const char * const sys_files[] = {
1232 "stdin", "__stdin__",
1233 "stdout", "__stdout__",
1234 "stderr", "__stderr__",
1235 NULL
1236 };
1237
1238 PyInterpreterState *interp = tstate->interp;
1239 if (verbose) {
1240 PySys_WriteStderr("# clear builtins._\n");
1241 }
1242 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1243 PyErr_WriteUnraisable(NULL);
1244 }
1245
1246 const char * const *p;
1247 for (p = sys_deletes; *p != NULL; p++) {
1248 if (verbose) {
1249 PySys_WriteStderr("# clear sys.%s\n", *p);
1250 }
1251 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1252 PyErr_WriteUnraisable(NULL);
1253 }
1254 }
1255 for (p = sys_files; *p != NULL; p+=2) {
1256 const char *name = p[0];
1257 const char *orig_name = p[1];
1258 if (verbose) {
1259 PySys_WriteStderr("# restore sys.%s\n", name);
1260 }
1261 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1262 orig_name);
1263 if (value == NULL) {
1264 if (_PyErr_Occurred(tstate)) {
1265 PyErr_WriteUnraisable(NULL);
1266 }
1267 value = Py_None;
1268 }
1269 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1270 PyErr_WriteUnraisable(NULL);
1271 }
1272 }
1273}
1274
1275
1276static PyObject*
1277finalize_remove_modules(PyObject *modules, int verbose)
1278{
1279 PyObject *weaklist = PyList_New(0);
1280 if (weaklist == NULL) {
1281 PyErr_WriteUnraisable(NULL);
1282 }
1283
1284#define STORE_MODULE_WEAKREF(name, mod) \
1285 if (weaklist != NULL) { \
1286 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1287 if (wr) { \
1288 PyObject *tup = PyTuple_Pack(2, name, wr); \
1289 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1290 PyErr_WriteUnraisable(NULL); \
1291 } \
1292 Py_XDECREF(tup); \
1293 Py_DECREF(wr); \
1294 } \
1295 else { \
1296 PyErr_WriteUnraisable(NULL); \
1297 } \
1298 }
1299
1300#define CLEAR_MODULE(name, mod) \
1301 if (PyModule_Check(mod)) { \
1302 if (verbose && PyUnicode_Check(name)) { \
1303 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1304 } \
1305 STORE_MODULE_WEAKREF(name, mod); \
1306 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1307 PyErr_WriteUnraisable(NULL); \
1308 } \
1309 }
1310
1311 if (PyDict_CheckExact(modules)) {
1312 Py_ssize_t pos = 0;
1313 PyObject *key, *value;
1314 while (PyDict_Next(modules, &pos, &key, &value)) {
1315 CLEAR_MODULE(key, value);
1316 }
1317 }
1318 else {
1319 PyObject *iterator = PyObject_GetIter(modules);
1320 if (iterator == NULL) {
1321 PyErr_WriteUnraisable(NULL);
1322 }
1323 else {
1324 PyObject *key;
1325 while ((key = PyIter_Next(iterator))) {
1326 PyObject *value = PyObject_GetItem(modules, key);
1327 if (value == NULL) {
1328 PyErr_WriteUnraisable(NULL);
1329 continue;
1330 }
1331 CLEAR_MODULE(key, value);
1332 Py_DECREF(value);
1333 Py_DECREF(key);
1334 }
1335 if (PyErr_Occurred()) {
1336 PyErr_WriteUnraisable(NULL);
1337 }
1338 Py_DECREF(iterator);
1339 }
1340 }
1341#undef CLEAR_MODULE
1342#undef STORE_MODULE_WEAKREF
1343
1344 return weaklist;
1345}
1346
1347
1348static void
1349finalize_clear_modules_dict(PyObject *modules)
1350{
1351 if (PyDict_CheckExact(modules)) {
1352 PyDict_Clear(modules);
1353 }
1354 else {
1355 _Py_IDENTIFIER(clear);
1356 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1357 PyErr_WriteUnraisable(NULL);
1358 }
1359 }
1360}
1361
1362
1363static void
1364finalize_restore_builtins(PyThreadState *tstate)
1365{
1366 PyInterpreterState *interp = tstate->interp;
1367 PyObject *dict = PyDict_Copy(interp->builtins);
1368 if (dict == NULL) {
1369 PyErr_WriteUnraisable(NULL);
1370 }
1371 PyDict_Clear(interp->builtins);
1372 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1373 _PyErr_Clear(tstate);
1374 }
1375 Py_XDECREF(dict);
1376}
1377
1378
1379static void
1380finalize_modules_clear_weaklist(PyInterpreterState *interp,
1381 PyObject *weaklist, int verbose)
1382{
1383 // First clear modules imported later
1384 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1385 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1386 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1387 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1388 if (mod == Py_None) {
1389 continue;
1390 }
1391 assert(PyModule_Check(mod));
1392 PyObject *dict = PyModule_GetDict(mod);
1393 if (dict == interp->builtins || dict == interp->sysdict) {
1394 continue;
1395 }
1396 Py_INCREF(mod);
1397 if (verbose && PyUnicode_Check(name)) {
1398 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1399 }
1400 _PyModule_Clear(mod);
1401 Py_DECREF(mod);
1402 }
1403}
1404
1405
1406static void
1407finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1408{
1409 // Clear sys dict
1410 if (verbose) {
1411 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1412 }
1413 _PyModule_ClearDict(interp->sysdict);
1414
1415 // Clear builtins dict
1416 if (verbose) {
1417 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1418 }
1419 _PyModule_ClearDict(interp->builtins);
1420}
1421
1422
1423/* Clear modules, as good as we can */
1424static void
1425finalize_modules(PyThreadState *tstate)
1426{
1427 PyInterpreterState *interp = tstate->interp;
1428 PyObject *modules = interp->modules;
1429 if (modules == NULL) {
1430 // Already done
1431 return;
1432 }
1433 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1434
1435 // Delete some special builtins._ and sys attributes first. These are
1436 // common places where user values hide and people complain when their
1437 // destructors fail. Since the modules containing them are
1438 // deleted *last* of all, they would come too late in the normal
1439 // destruction order. Sigh.
1440 //
1441 // XXX Perhaps these precautions are obsolete. Who knows?
1442 finalize_modules_delete_special(tstate, verbose);
1443
1444 // Remove all modules from sys.modules, hoping that garbage collection
1445 // can reclaim most of them: set all sys.modules values to None.
1446 //
1447 // We prepare a list which will receive (name, weakref) tuples of
1448 // modules when they are removed from sys.modules. The name is used
1449 // for diagnosis messages (in verbose mode), while the weakref helps
1450 // detect those modules which have been held alive.
1451 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1452
1453 // Clear the modules dict
1454 finalize_clear_modules_dict(modules);
1455
1456 // Restore the original builtins dict, to ensure that any
1457 // user data gets cleared.
1458 finalize_restore_builtins(tstate);
1459
1460 // Collect garbage
1461 _PyGC_CollectNoFail(tstate);
1462
1463 // Dump GC stats before it's too late, since it uses the warnings
1464 // machinery.
1465 _PyGC_DumpShutdownStats(tstate);
1466
1467 if (weaklist != NULL) {
1468 // Now, if there are any modules left alive, clear their globals to
1469 // minimize potential leaks. All C extension modules actually end
1470 // up here, since they are kept alive in the interpreter state.
1471 //
1472 // The special treatment of "builtins" here is because even
1473 // when it's not referenced as a module, its dictionary is
1474 // referenced by almost every module's __builtins__. Since
1475 // deleting a module clears its dictionary (even if there are
1476 // references left to it), we need to delete the "builtins"
1477 // module last. Likewise, we don't delete sys until the very
1478 // end because it is implicitly referenced (e.g. by print).
1479 //
1480 // Since dict is ordered in CPython 3.6+, modules are saved in
1481 // importing order. First clear modules imported later.
1482 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1483 Py_DECREF(weaklist);
1484 }
1485
1486 // Clear sys and builtins modules dict
1487 finalize_clear_sys_builtins_dict(interp, verbose);
1488
1489 // Clear module dict copies stored in the interpreter state:
1490 // clear PyInterpreterState.modules_by_index and
1491 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1492 // initialization API)
1493 _PyInterpreterState_ClearModules(interp);
1494
1495 // Clear and delete the modules directory. Actual modules will
1496 // still be there only if imported during the execution of some
1497 // destructor.
1498 Py_SETREF(interp->modules, NULL);
1499
1500 // Collect garbage once more
1501 _PyGC_CollectNoFail(tstate);
1502}
1503
1504
Nick Coghland6009512014-11-20 21:39:37 +10001505/* Flush stdout and stderr */
1506
1507static int
1508file_is_closed(PyObject *fobj)
1509{
1510 int r;
1511 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1512 if (tmp == NULL) {
1513 PyErr_Clear();
1514 return 0;
1515 }
1516 r = PyObject_IsTrue(tmp);
1517 Py_DECREF(tmp);
1518 if (r < 0)
1519 PyErr_Clear();
1520 return r > 0;
1521}
1522
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001523
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001524static int
Nick Coghland6009512014-11-20 21:39:37 +10001525flush_std_files(void)
1526{
1527 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1528 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1529 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001530 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001531
1532 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001533 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001534 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001535 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001536 status = -1;
1537 }
Nick Coghland6009512014-11-20 21:39:37 +10001538 else
1539 Py_DECREF(tmp);
1540 }
1541
1542 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001543 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001544 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001545 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001546 status = -1;
1547 }
Nick Coghland6009512014-11-20 21:39:37 +10001548 else
1549 Py_DECREF(tmp);
1550 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001551
1552 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001553}
1554
1555/* Undo the effect of Py_Initialize().
1556
1557 Beware: if multiple interpreter and/or thread states exist, these
1558 are not wiped out; only the current thread and interpreter state
1559 are deleted. But since everything else is deleted, those other
1560 interpreter and thread states should no longer be used.
1561
1562 (XXX We should do better, e.g. wipe out all interpreters and
1563 threads.)
1564
1565 Locking: as above.
1566
1567*/
1568
Victor Stinner7eee5be2019-11-20 10:38:34 +01001569
1570static void
Victor Stinner90db4652020-07-01 23:21:36 +02001571finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001572{
Victor Stinner281cce12020-06-23 22:55:46 +02001573 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001574 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001575 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001576 _PyContext_Fini(tstate);
Victor Stinner666ecfb2020-07-02 01:19:57 +02001577 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001578
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001579 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001580 _PyList_Fini(tstate);
1581 _PyTuple_Fini(tstate);
1582
1583 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001584
Victor Stinnerc41eed12020-06-23 15:54:35 +02001585 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001586 _PyUnicode_Fini(tstate);
1587 _PyFloat_Fini(tstate);
1588 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001589}
1590
1591
1592static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001593finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001594{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001595 int is_main_interp = _Py_IsMainInterpreter(tstate);
1596
Victor Stinner7eee5be2019-11-20 10:38:34 +01001597 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001598 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001599
Kongedaa0fe02020-07-04 05:06:46 +08001600 /* Clear all loghooks */
1601 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1602 Call _PySys_ClearAuditHooks when PyObject available. */
1603 if (is_main_interp) {
1604 _PySys_ClearAuditHooks(tstate);
1605 }
1606
Victor Stinner7907f8c2020-06-08 01:22:36 +02001607 if (is_main_interp) {
1608 _Py_HashRandomization_Fini();
1609 _PyArg_Fini();
1610 _Py_ClearFileSystemEncoding();
1611 }
1612
Victor Stinner90db4652020-07-01 23:21:36 +02001613 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001614}
1615
1616
1617static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001618finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001619{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001620 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001621 /* Cleanup auto-thread-state */
1622 _PyGILState_Fini(tstate);
1623 }
1624
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001625 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1626 fail when it is being awaited by another running daemon thread (see
1627 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1628 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1629 called multiple times. */
1630
Victor Stinner7eee5be2019-11-20 10:38:34 +01001631 PyInterpreterState_Delete(tstate->interp);
1632}
1633
1634
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001635int
1636Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001637{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001638 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001639
Victor Stinner8e91c242019-04-24 17:24:01 +02001640 _PyRuntimeState *runtime = &_PyRuntime;
1641 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001642 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001643 }
Nick Coghland6009512014-11-20 21:39:37 +10001644
Victor Stinnere225beb2019-06-03 18:14:24 +02001645 /* Get current thread state and interpreter pointer */
1646 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1647 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001648
Victor Stinnerb45d2592019-06-20 00:05:23 +02001649 // Wrap up existing "threading"-module-created, non-daemon threads.
1650 wait_for_thread_shutdown(tstate);
1651
1652 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001653 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001654
Nick Coghland6009512014-11-20 21:39:37 +10001655 /* The interpreter is still entirely intact at this point, and the
1656 * exit funcs may be relying on that. In particular, if some thread
1657 * or exit func is still waiting to do an import, the import machinery
1658 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001659 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001660 * Note that Threading.py uses an exit func to do a join on all the
1661 * threads created thru it, so this also protects pending imports in
1662 * the threads created via Threading.
1663 */
Nick Coghland6009512014-11-20 21:39:37 +10001664
Victor Stinnerb45d2592019-06-20 00:05:23 +02001665 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001666
Victor Stinnerda273412017-12-15 01:46:02 +01001667 /* Copy the core config, PyInterpreterState_Delete() free
1668 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001669#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001670 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001671#endif
1672#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001673 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001674#endif
1675#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001676 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001677#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001678
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001679 /* Remaining daemon threads will automatically exit
1680 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001681 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001682 runtime->initialized = 0;
1683 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001684
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001685 /* Destroy the state of all threads of the interpreter, except of the
1686 current thread. In practice, only daemon threads should still be alive,
1687 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1688 Clear frames of other threads to call objects destructors. Destructors
1689 will be called in the current Python thread. Since
1690 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1691 can take the GIL at this point: if they try, they will exit
1692 immediately. */
1693 _PyThreadState_DeleteExcept(runtime, tstate);
1694
Victor Stinnere0deff32015-03-24 13:46:18 +01001695 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001696 if (flush_std_files() < 0) {
1697 status = -1;
1698 }
Nick Coghland6009512014-11-20 21:39:37 +10001699
1700 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001701 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001702
1703 /* Collect garbage. This may call finalizers; it's nice to call these
1704 * before all modules are destroyed.
1705 * XXX If a __del__ or weakref callback is triggered here, and tries to
1706 * XXX import a module, bad things can happen, because Python no
1707 * XXX longer believes it's initialized.
1708 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1709 * XXX is easy to provoke that way. I've also seen, e.g.,
1710 * XXX Exception exceptions.ImportError: 'No module named sha'
1711 * XXX in <function callback at 0x008F5718> ignored
1712 * XXX but I'm unclear on exactly how that one happens. In any case,
1713 * XXX I haven't seen a real-life report of either of these.
1714 */
Victor Stinner8b341482020-10-30 17:00:00 +01001715 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001716
Nick Coghland6009512014-11-20 21:39:37 +10001717 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001718 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001719
Inada Naoki91234a12019-06-03 21:30:58 +09001720 /* Print debug stats if any */
1721 _PyEval_Fini();
1722
Victor Stinnere0deff32015-03-24 13:46:18 +01001723 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001724 if (flush_std_files() < 0) {
1725 status = -1;
1726 }
Nick Coghland6009512014-11-20 21:39:37 +10001727
1728 /* Collect final garbage. This disposes of cycles created by
1729 * class definitions, for example.
1730 * XXX This is disabled because it caused too many problems. If
1731 * XXX a __del__ or weakref callback triggers here, Python code has
1732 * XXX a hard time running, because even the sys module has been
1733 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1734 * XXX One symptom is a sequence of information-free messages
1735 * XXX coming from threads (if a __del__ or callback is invoked,
1736 * XXX other threads can execute too, and any exception they encounter
1737 * XXX triggers a comedy of errors as subsystem after subsystem
1738 * XXX fails to find what it *expects* to find in sys to help report
1739 * XXX the exception and consequent unexpected failures). I've also
1740 * XXX seen segfaults then, after adding print statements to the
1741 * XXX Python code getting called.
1742 */
1743#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001744 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001745#endif
1746
1747 /* Disable tracemalloc after all Python objects have been destroyed,
1748 so it is possible to use tracemalloc in objects destructor. */
1749 _PyTraceMalloc_Fini();
1750
1751 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1752 _PyImport_Fini();
1753
1754 /* Cleanup typeobject.c's internal caches. */
1755 _PyType_Fini();
1756
1757 /* unload faulthandler module */
1758 _PyFaulthandler_Fini();
1759
Nick Coghland6009512014-11-20 21:39:37 +10001760 /* dump hash stats */
1761 _PyHash_Fini();
1762
Eric Snowdae02762017-09-14 00:35:58 -07001763#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001764 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001765 _PyDebug_PrintTotalRefs();
1766 }
Eric Snowdae02762017-09-14 00:35:58 -07001767#endif
Nick Coghland6009512014-11-20 21:39:37 +10001768
1769#ifdef Py_TRACE_REFS
1770 /* Display all objects still alive -- this can invoke arbitrary
1771 * __repr__ overrides, so requires a mostly-intact interpreter.
1772 * Alas, a lot of stuff may still be alive now that will be cleaned
1773 * up later.
1774 */
Victor Stinnerda273412017-12-15 01:46:02 +01001775 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001776 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001777 }
Nick Coghland6009512014-11-20 21:39:37 +10001778#endif /* Py_TRACE_REFS */
1779
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001780 finalize_interp_clear(tstate);
1781 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001782
1783#ifdef Py_TRACE_REFS
1784 /* Display addresses (& refcnts) of all objects still alive.
1785 * An address can be used to find the repr of the object, printed
1786 * above by _Py_PrintReferences.
1787 */
Victor Stinnerda273412017-12-15 01:46:02 +01001788 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001789 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001790 }
Nick Coghland6009512014-11-20 21:39:37 +10001791#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001792#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001793 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001794 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001795 }
Nick Coghland6009512014-11-20 21:39:37 +10001796#endif
1797
Victor Stinner8e91c242019-04-24 17:24:01 +02001798 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001799
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001800 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001801 return status;
1802}
1803
1804void
1805Py_Finalize(void)
1806{
1807 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001808}
1809
Victor Stinnerb0051362019-11-22 17:52:42 +01001810
Nick Coghland6009512014-11-20 21:39:37 +10001811/* Create and initialize a new interpreter and thread, and return the
1812 new thread. This requires that Py_Initialize() has been called
1813 first.
1814
1815 Unsuccessful initialization yields a NULL pointer. Note that *no*
1816 exception information is available even in this case -- the
1817 exception information is held in the thread, and there is no
1818 thread.
1819
1820 Locking: as above.
1821
1822*/
1823
Victor Stinner331a6a52019-05-27 16:39:22 +02001824static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001825new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001826{
Victor Stinner331a6a52019-05-27 16:39:22 +02001827 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001828
Victor Stinner331a6a52019-05-27 16:39:22 +02001829 status = _PyRuntime_Initialize();
1830 if (_PyStatus_EXCEPTION(status)) {
1831 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001832 }
1833 _PyRuntimeState *runtime = &_PyRuntime;
1834
1835 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001836 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001837 }
Nick Coghland6009512014-11-20 21:39:37 +10001838
Victor Stinner8a1be612016-03-14 22:07:55 +01001839 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1840 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001841 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001842
Victor Stinner43125222019-04-24 18:23:53 +02001843 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001844 if (interp == NULL) {
1845 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001846 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001847 }
Nick Coghland6009512014-11-20 21:39:37 +10001848
Victor Stinner43125222019-04-24 18:23:53 +02001849 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001850 if (tstate == NULL) {
1851 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001852 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001853 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001854 }
1855
Victor Stinner43125222019-04-24 18:23:53 +02001856 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001857
Eric Snow1abcf672017-05-23 21:46:51 -07001858 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001859 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001860#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001861 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001862 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001863 }
1864 else
1865#endif
1866 {
Eric Snow1abcf672017-05-23 21:46:51 -07001867 /* No current thread state, copy from the main interpreter */
1868 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001869 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001870 }
1871
Victor Stinner048a3562020-11-05 00:45:56 +01001872
1873 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001874 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001875 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001876 }
Victor Stinner252346a2020-05-01 11:33:44 +02001877 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001878
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001879 status = init_interp_create_gil(tstate);
1880 if (_PyStatus_EXCEPTION(status)) {
1881 goto error;
1882 }
1883
Victor Stinnerd863ade2019-12-06 03:37:07 +01001884 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001885 if (_PyStatus_EXCEPTION(status)) {
1886 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001887 }
1888
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001889 status = init_interp_main(tstate);
1890 if (_PyStatus_EXCEPTION(status)) {
1891 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001892 }
Nick Coghland6009512014-11-20 21:39:37 +10001893
Victor Stinnera7368ac2017-11-15 18:11:45 -08001894 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001895 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001896
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001897error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001898 *tstate_p = NULL;
1899
1900 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001901 PyErr_PrintEx(0);
1902 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001903 PyThreadState_Delete(tstate);
1904 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001905 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001906
Victor Stinnerb0051362019-11-22 17:52:42 +01001907 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001908}
1909
1910PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001911_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001912{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001913 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001914 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001915 if (_PyStatus_EXCEPTION(status)) {
1916 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001917 }
1918 return tstate;
1919
Nick Coghland6009512014-11-20 21:39:37 +10001920}
1921
Victor Stinner252346a2020-05-01 11:33:44 +02001922PyThreadState *
1923Py_NewInterpreter(void)
1924{
1925 return _Py_NewInterpreter(0);
1926}
1927
Nick Coghland6009512014-11-20 21:39:37 +10001928/* Delete an interpreter and its last thread. This requires that the
1929 given thread state is current, that the thread has no remaining
1930 frames, and that it is its interpreter's only remaining thread.
1931 It is a fatal error to violate these constraints.
1932
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001933 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001934 everything, regardless.)
1935
1936 Locking: as above.
1937
1938*/
1939
1940void
1941Py_EndInterpreter(PyThreadState *tstate)
1942{
1943 PyInterpreterState *interp = tstate->interp;
1944
Victor Stinnerb45d2592019-06-20 00:05:23 +02001945 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001946 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001947 }
1948 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001949 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001950 }
Eric Snow5be45a62019-03-08 22:47:07 -07001951 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001952
Eric Snow842a2f02019-03-15 15:47:51 -06001953 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001954 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001955
Victor Stinnerb45d2592019-06-20 00:05:23 +02001956 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001957
Victor Stinnerb45d2592019-06-20 00:05:23 +02001958 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001959 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001960 }
Nick Coghland6009512014-11-20 21:39:37 +10001961
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001962 finalize_modules(tstate);
1963
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001964 finalize_interp_clear(tstate);
1965 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001966}
1967
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001968/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001969
Victor Stinner331a6a52019-05-27 16:39:22 +02001970static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001971add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001972{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001973 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001974 m = PyImport_AddModule("__main__");
1975 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001976 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001977
Nick Coghland6009512014-11-20 21:39:37 +10001978 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001979 ann_dict = PyDict_New();
1980 if ((ann_dict == NULL) ||
1981 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001982 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001983 }
1984 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001985
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001986 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1987 if (PyErr_Occurred()) {
1988 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1989 }
Nick Coghland6009512014-11-20 21:39:37 +10001990 PyObject *bimod = PyImport_ImportModule("builtins");
1991 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001992 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001993 }
1994 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001995 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001996 }
1997 Py_DECREF(bimod);
1998 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001999
Nick Coghland6009512014-11-20 21:39:37 +10002000 /* Main is a little special - imp.is_builtin("__main__") will return
2001 * False, but BuiltinImporter is still the most appropriate initial
2002 * setting for its __loader__ attribute. A more suitable value will
2003 * be set if __main__ gets further initialized later in the startup
2004 * process.
2005 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002006 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002007 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002008 if (PyErr_Occurred()) {
2009 return _PyStatus_ERR("Failed to test __main__.__loader__");
2010 }
Nick Coghland6009512014-11-20 21:39:37 +10002011 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2012 "BuiltinImporter");
2013 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002014 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002015 }
2016 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002017 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002018 }
2019 Py_DECREF(loader);
2020 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002021 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002022}
2023
Nick Coghland6009512014-11-20 21:39:37 +10002024/* Import the site module (not into __main__ though) */
2025
Victor Stinner331a6a52019-05-27 16:39:22 +02002026static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002027init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002028{
2029 PyObject *m;
2030 m = PyImport_ImportModule("site");
2031 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002032 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002033 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002034 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002035 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002036}
2037
Victor Stinner874dbe82015-09-04 17:29:57 +02002038/* Check if a file descriptor is valid or not.
2039 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2040static int
2041is_valid_fd(int fd)
2042{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002043/* dup() is faster than fstat(): fstat() can require input/output operations,
2044 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2045 startup. Problem: dup() doesn't check if the file descriptor is valid on
2046 some platforms.
2047
2048 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2049 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2050 EBADF. FreeBSD has similar issue (bpo-32849).
2051
2052 Only use dup() on platforms where dup() is enough to detect invalid FD in
2053 corner cases: on Linux and Windows (bpo-32849). */
2054#if defined(__linux__) || defined(MS_WINDOWS)
2055 if (fd < 0) {
2056 return 0;
2057 }
2058 int fd2;
2059
2060 _Py_BEGIN_SUPPRESS_IPH
2061 fd2 = dup(fd);
2062 if (fd2 >= 0) {
2063 close(fd2);
2064 }
2065 _Py_END_SUPPRESS_IPH
2066
2067 return (fd2 >= 0);
2068#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002069 struct stat st;
2070 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002071#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002072}
2073
2074/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002075static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002076create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002077 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002078 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002079{
2080 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2081 const char* mode;
2082 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002083 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002084 int buffering, isatty;
2085 _Py_IDENTIFIER(open);
2086 _Py_IDENTIFIER(isatty);
2087 _Py_IDENTIFIER(TextIOWrapper);
2088 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002089 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002090
Victor Stinner874dbe82015-09-04 17:29:57 +02002091 if (!is_valid_fd(fd))
2092 Py_RETURN_NONE;
2093
Nick Coghland6009512014-11-20 21:39:37 +10002094 /* stdin is always opened in buffered mode, first because it shouldn't
2095 make a difference in common use cases, second because TextIOWrapper
2096 depends on the presence of a read1() method which only exists on
2097 buffered streams.
2098 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002099 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002100 buffering = 0;
2101 else
2102 buffering = -1;
2103 if (write_mode)
2104 mode = "wb";
2105 else
2106 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002107 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002108 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002109 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002110 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002111 if (buf == NULL)
2112 goto error;
2113
2114 if (buffering) {
2115 _Py_IDENTIFIER(raw);
2116 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2117 if (raw == NULL)
2118 goto error;
2119 }
2120 else {
2121 raw = buf;
2122 Py_INCREF(raw);
2123 }
2124
Steve Dower39294992016-08-30 21:22:36 -07002125#ifdef MS_WINDOWS
2126 /* Windows console IO is always UTF-8 encoded */
2127 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002128 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002129#endif
2130
Nick Coghland6009512014-11-20 21:39:37 +10002131 text = PyUnicode_FromString(name);
2132 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2133 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002134 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002135 if (res == NULL)
2136 goto error;
2137 isatty = PyObject_IsTrue(res);
2138 Py_DECREF(res);
2139 if (isatty == -1)
2140 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002141 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002142 write_through = Py_True;
2143 else
2144 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002145 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002146 line_buffering = Py_True;
2147 else
2148 line_buffering = Py_False;
2149
2150 Py_CLEAR(raw);
2151 Py_CLEAR(text);
2152
2153#ifdef MS_WINDOWS
2154 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2155 newlines to "\n".
2156 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2157 newline = NULL;
2158#else
2159 /* sys.stdin: split lines at "\n".
2160 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2161 newline = "\n";
2162#endif
2163
Victor Stinner709d23d2019-05-02 14:56:30 -04002164 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2165 if (encoding_str == NULL) {
2166 Py_CLEAR(buf);
2167 goto error;
2168 }
2169
2170 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2171 if (errors_str == NULL) {
2172 Py_CLEAR(buf);
2173 Py_CLEAR(encoding_str);
2174 goto error;
2175 }
2176
2177 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2178 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002179 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002180 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002181 Py_CLEAR(encoding_str);
2182 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002183 if (stream == NULL)
2184 goto error;
2185
2186 if (write_mode)
2187 mode = "w";
2188 else
2189 mode = "r";
2190 text = PyUnicode_FromString(mode);
2191 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2192 goto error;
2193 Py_CLEAR(text);
2194 return stream;
2195
2196error:
2197 Py_XDECREF(buf);
2198 Py_XDECREF(stream);
2199 Py_XDECREF(text);
2200 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002201
Victor Stinner874dbe82015-09-04 17:29:57 +02002202 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2203 /* Issue #24891: the file descriptor was closed after the first
2204 is_valid_fd() check was called. Ignore the OSError and set the
2205 stream to None. */
2206 PyErr_Clear();
2207 Py_RETURN_NONE;
2208 }
2209 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002210}
2211
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002212/* Set builtins.open to io.OpenWrapper */
2213static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002214init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002215{
2216 PyObject *iomod = NULL, *wrapper;
2217 PyObject *bimod = NULL;
2218 PyStatus res = _PyStatus_OK();
2219
2220 if (!(iomod = PyImport_ImportModule("io"))) {
2221 goto error;
2222 }
2223
2224 if (!(bimod = PyImport_ImportModule("builtins"))) {
2225 goto error;
2226 }
2227
2228 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2229 goto error;
2230 }
2231
2232 /* Set builtins.open */
2233 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2234 Py_DECREF(wrapper);
2235 goto error;
2236 }
2237 Py_DECREF(wrapper);
2238 goto done;
2239
2240error:
2241 res = _PyStatus_ERR("can't initialize io.open");
2242
2243done:
2244 Py_XDECREF(bimod);
2245 Py_XDECREF(iomod);
2246 return res;
2247}
2248
2249
Nick Coghland6009512014-11-20 21:39:37 +10002250/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002251static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002252init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002253{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002254 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002255 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002256 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002257 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002258 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002259 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002260
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002261 /* Check that stdin is not a directory
2262 Using shell redirection, you can redirect stdin to a directory,
2263 crashing the Python interpreter. Catch this common mistake here
2264 and output a useful error message. Note that under MS Windows,
2265 the shell already prevents that. */
2266#ifndef MS_WINDOWS
2267 struct _Py_stat_struct sb;
2268 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2269 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002270 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002271 }
2272#endif
2273
Nick Coghland6009512014-11-20 21:39:37 +10002274 if (!(iomod = PyImport_ImportModule("io"))) {
2275 goto error;
2276 }
Nick Coghland6009512014-11-20 21:39:37 +10002277
Nick Coghland6009512014-11-20 21:39:37 +10002278 /* Set sys.stdin */
2279 fd = fileno(stdin);
2280 /* Under some conditions stdin, stdout and stderr may not be connected
2281 * and fileno() may point to an invalid file descriptor. For example
2282 * GUI apps don't have valid standard streams by default.
2283 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002284 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002285 config->stdio_encoding,
2286 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002287 if (std == NULL)
2288 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002289 PySys_SetObject("__stdin__", std);
2290 _PySys_SetObjectId(&PyId_stdin, std);
2291 Py_DECREF(std);
2292
2293 /* Set sys.stdout */
2294 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002295 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002296 config->stdio_encoding,
2297 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002298 if (std == NULL)
2299 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002300 PySys_SetObject("__stdout__", std);
2301 _PySys_SetObjectId(&PyId_stdout, std);
2302 Py_DECREF(std);
2303
2304#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2305 /* Set sys.stderr, replaces the preliminary stderr */
2306 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002307 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002308 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002309 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002310 if (std == NULL)
2311 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002312
2313 /* Same as hack above, pre-import stderr's codec to avoid recursion
2314 when import.c tries to write to stderr in verbose mode. */
2315 encoding_attr = PyObject_GetAttrString(std, "encoding");
2316 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002317 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002318 if (std_encoding != NULL) {
2319 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2320 Py_XDECREF(codec_info);
2321 }
2322 Py_DECREF(encoding_attr);
2323 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002324 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002325
2326 if (PySys_SetObject("__stderr__", std) < 0) {
2327 Py_DECREF(std);
2328 goto error;
2329 }
2330 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2331 Py_DECREF(std);
2332 goto error;
2333 }
2334 Py_DECREF(std);
2335#endif
2336
Victor Stinnera7368ac2017-11-15 18:11:45 -08002337 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002338
Victor Stinnera7368ac2017-11-15 18:11:45 -08002339error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002340 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002341
2342done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002343 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002344 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002345 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002346}
2347
2348
Victor Stinner10dc4842015-03-24 12:01:30 +01002349static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002350_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2351 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002352{
Victor Stinner10dc4842015-03-24 12:01:30 +01002353 fputc('\n', stderr);
2354 fflush(stderr);
2355
2356 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002357 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002358}
Victor Stinner791da1c2016-03-14 16:53:12 +01002359
2360/* Print the current exception (if an exception is set) with its traceback,
2361 or display the current Python stack.
2362
2363 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2364 called on catastrophic cases.
2365
2366 Return 1 if the traceback was displayed, 0 otherwise. */
2367
2368static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002369_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002370{
2371 PyObject *ferr, *res;
2372 PyObject *exception, *v, *tb;
2373 int has_tb;
2374
Victor Stinnerb45d2592019-06-20 00:05:23 +02002375 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002376 if (exception == NULL) {
2377 /* No current exception */
2378 return 0;
2379 }
2380
2381 ferr = _PySys_GetObjectId(&PyId_stderr);
2382 if (ferr == NULL || ferr == Py_None) {
2383 /* sys.stderr is not set yet or set to None,
2384 no need to try to display the exception */
2385 return 0;
2386 }
2387
Victor Stinnerb45d2592019-06-20 00:05:23 +02002388 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002389 if (tb == NULL) {
2390 tb = Py_None;
2391 Py_INCREF(tb);
2392 }
2393 PyException_SetTraceback(v, tb);
2394 if (exception == NULL) {
2395 /* PyErr_NormalizeException() failed */
2396 return 0;
2397 }
2398
2399 has_tb = (tb != Py_None);
2400 PyErr_Display(exception, v, tb);
2401 Py_XDECREF(exception);
2402 Py_XDECREF(v);
2403 Py_XDECREF(tb);
2404
2405 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002406 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002407 if (res == NULL) {
2408 _PyErr_Clear(tstate);
2409 }
2410 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002411 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002412 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002413
2414 return has_tb;
2415}
2416
Nick Coghland6009512014-11-20 21:39:37 +10002417/* Print fatal error message and abort */
2418
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002419#ifdef MS_WINDOWS
2420static void
2421fatal_output_debug(const char *msg)
2422{
2423 /* buffer of 256 bytes allocated on the stack */
2424 WCHAR buffer[256 / sizeof(WCHAR)];
2425 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2426 size_t msglen;
2427
2428 OutputDebugStringW(L"Fatal Python error: ");
2429
2430 msglen = strlen(msg);
2431 while (msglen) {
2432 size_t i;
2433
2434 if (buflen > msglen) {
2435 buflen = msglen;
2436 }
2437
2438 /* Convert the message to wchar_t. This uses a simple one-to-one
2439 conversion, assuming that the this error message actually uses
2440 ASCII only. If this ceases to be true, we will have to convert. */
2441 for (i=0; i < buflen; ++i) {
2442 buffer[i] = msg[i];
2443 }
2444 buffer[i] = L'\0';
2445 OutputDebugStringW(buffer);
2446
2447 msg += buflen;
2448 msglen -= buflen;
2449 }
2450 OutputDebugStringW(L"\n");
2451}
2452#endif
2453
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002454
2455static void
2456fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2457{
2458 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002459 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2460 if (finalizing) {
2461 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002462 }
2463 else if (runtime->initialized) {
2464 fprintf(stream, "initialized");
2465 }
2466 else if (runtime->core_initialized) {
2467 fprintf(stream, "core initialized");
2468 }
2469 else if (runtime->preinitialized) {
2470 fprintf(stream, "preinitialized");
2471 }
2472 else if (runtime->preinitializing) {
2473 fprintf(stream, "preinitializing");
2474 }
2475 else {
2476 fprintf(stream, "unknown");
2477 }
2478 fprintf(stream, "\n");
2479 fflush(stream);
2480}
2481
2482
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002483static inline void _Py_NO_RETURN
2484fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002485{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002486 if (status < 0) {
2487#if defined(MS_WINDOWS) && defined(_DEBUG)
2488 DebugBreak();
2489#endif
2490 abort();
2491 }
2492 else {
2493 exit(status);
2494 }
2495}
2496
2497
2498static void _Py_NO_RETURN
2499fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2500 int status)
2501{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002502 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002503 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002504
2505 if (reentrant) {
2506 /* Py_FatalError() caused a second fatal error.
2507 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002508 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002509 }
2510 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002511
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002512 if (header) {
2513 fprintf(stream, "Fatal Python error: ");
2514 if (prefix) {
2515 fputs(prefix, stream);
2516 fputs(": ", stream);
2517 }
2518 if (msg) {
2519 fputs(msg, stream);
2520 }
2521 else {
2522 fprintf(stream, "<message not set>");
2523 }
2524 fputs("\n", stream);
2525 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002526 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002527
2528 _PyRuntimeState *runtime = &_PyRuntime;
2529 fatal_error_dump_runtime(stream, runtime);
2530
2531 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2532 PyInterpreterState *interp = NULL;
2533 if (tstate != NULL) {
2534 interp = tstate->interp;
2535 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002536
Victor Stinner3a228ab2018-11-01 00:26:41 +01002537 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002538 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002539
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002540 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2541 has no Python thread state.
2542
2543 tss_tstate != tstate if the current Python thread does not hold the GIL.
2544 */
2545 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2546 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002547 if (has_tstate_and_gil) {
2548 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002549 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002550 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002551 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002552 }
2553 }
2554 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002555 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002556 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002557
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002558 /* The main purpose of faulthandler is to display the traceback.
2559 This function already did its best to display a traceback.
2560 Disable faulthandler to prevent writing a second traceback
2561 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002562 _PyFaulthandler_Fini();
2563
Victor Stinner791da1c2016-03-14 16:53:12 +01002564 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002565 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002566 /* Flush sys.stdout and sys.stderr */
2567 flush_std_files();
2568 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002569
Nick Coghland6009512014-11-20 21:39:37 +10002570#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002571 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002572#endif /* MS_WINDOWS */
2573
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002574 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002575}
2576
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002577
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002578#undef Py_FatalError
2579
Victor Stinner19760862017-12-20 01:41:59 +01002580void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002581Py_FatalError(const char *msg)
2582{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002583 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002584}
2585
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002586
Victor Stinner19760862017-12-20 01:41:59 +01002587void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002588_Py_FatalErrorFunc(const char *func, const char *msg)
2589{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002590 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002591}
2592
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002593
2594void _Py_NO_RETURN
2595_Py_FatalErrorFormat(const char *func, const char *format, ...)
2596{
2597 static int reentrant = 0;
2598 if (reentrant) {
2599 /* _Py_FatalErrorFormat() caused a second fatal error */
2600 fatal_error_exit(-1);
2601 }
2602 reentrant = 1;
2603
2604 FILE *stream = stderr;
2605 fprintf(stream, "Fatal Python error: ");
2606 if (func) {
2607 fputs(func, stream);
2608 fputs(": ", stream);
2609 }
2610 fflush(stream);
2611
2612 va_list vargs;
2613#ifdef HAVE_STDARG_PROTOTYPES
2614 va_start(vargs, format);
2615#else
2616 va_start(vargs);
2617#endif
2618 vfprintf(stream, format, vargs);
2619 va_end(vargs);
2620
2621 fputs("\n", stream);
2622 fflush(stream);
2623
2624 fatal_error(stream, 0, NULL, NULL, -1);
2625}
2626
2627
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002628void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002629Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002630{
Victor Stinner331a6a52019-05-27 16:39:22 +02002631 if (_PyStatus_IS_EXIT(status)) {
2632 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002633 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002634 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002635 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002636 }
2637 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002638 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002639 }
Nick Coghland6009512014-11-20 21:39:37 +10002640}
2641
2642/* Clean up and exit */
2643
Nick Coghland6009512014-11-20 21:39:37 +10002644/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002645void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002646{
Victor Stinner81a7be32020-04-14 15:14:01 +02002647 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002648
Antoine Pitroufc5db952017-12-13 02:29:07 +01002649 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002650 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2651
2652 is->pyexitfunc = func;
2653 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002654}
2655
2656static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002657call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002658{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002659 PyInterpreterState *interp = tstate->interp;
2660 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002661 return;
2662
Victor Stinnerb45d2592019-06-20 00:05:23 +02002663 (*interp->pyexitfunc)(interp->pyexitmodule);
2664 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002665}
2666
2667/* Wait until threading._shutdown completes, provided
2668 the threading module was imported in the first place.
2669 The shutdown routine will wait until all non-daemon
2670 "threading" threads have completed. */
2671static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002672wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002673{
Nick Coghland6009512014-11-20 21:39:37 +10002674 _Py_IDENTIFIER(_shutdown);
2675 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002676 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002677 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002678 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002679 PyErr_WriteUnraisable(NULL);
2680 }
2681 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002682 return;
2683 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002684 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002685 if (result == NULL) {
2686 PyErr_WriteUnraisable(threading);
2687 }
2688 else {
2689 Py_DECREF(result);
2690 }
2691 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002692}
2693
2694#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002695int Py_AtExit(void (*func)(void))
2696{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002697 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002698 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002699 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002700 return 0;
2701}
2702
2703static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002704call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002705{
Victor Stinner8e91c242019-04-24 17:24:01 +02002706 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002707 /* pop last function from the list */
2708 runtime->nexitfuncs--;
2709 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2710 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2711
2712 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002713 }
Nick Coghland6009512014-11-20 21:39:37 +10002714
2715 fflush(stdout);
2716 fflush(stderr);
2717}
2718
Victor Stinnercfc88312018-08-01 16:41:25 +02002719void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002720Py_Exit(int sts)
2721{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002722 if (Py_FinalizeEx() < 0) {
2723 sts = 120;
2724 }
Nick Coghland6009512014-11-20 21:39:37 +10002725
2726 exit(sts);
2727}
2728
Nick Coghland6009512014-11-20 21:39:37 +10002729
2730/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2731 *
2732 * All of the code in this function must only use async-signal-safe functions,
2733 * listed at `man 7 signal` or
2734 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002735 *
2736 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002737 */
2738void
2739_Py_RestoreSignals(void)
2740{
2741#ifdef SIGPIPE
2742 PyOS_setsig(SIGPIPE, SIG_DFL);
2743#endif
2744#ifdef SIGXFZ
2745 PyOS_setsig(SIGXFZ, SIG_DFL);
2746#endif
2747#ifdef SIGXFSZ
2748 PyOS_setsig(SIGXFSZ, SIG_DFL);
2749#endif
2750}
2751
2752
2753/*
2754 * The file descriptor fd is considered ``interactive'' if either
2755 * a) isatty(fd) is TRUE, or
2756 * b) the -i flag was given, and the filename associated with
2757 * the descriptor is NULL or "<stdin>" or "???".
2758 */
2759int
2760Py_FdIsInteractive(FILE *fp, const char *filename)
2761{
2762 if (isatty((int)fileno(fp)))
2763 return 1;
2764 if (!Py_InteractiveFlag)
2765 return 0;
2766 return (filename == NULL) ||
2767 (strcmp(filename, "<stdin>") == 0) ||
2768 (strcmp(filename, "???") == 0);
2769}
2770
2771
Nick Coghland6009512014-11-20 21:39:37 +10002772/* Wrappers around sigaction() or signal(). */
2773
2774PyOS_sighandler_t
2775PyOS_getsig(int sig)
2776{
2777#ifdef HAVE_SIGACTION
2778 struct sigaction context;
2779 if (sigaction(sig, NULL, &context) == -1)
2780 return SIG_ERR;
2781 return context.sa_handler;
2782#else
2783 PyOS_sighandler_t handler;
2784/* Special signal handling for the secure CRT in Visual Studio 2005 */
2785#if defined(_MSC_VER) && _MSC_VER >= 1400
2786 switch (sig) {
2787 /* Only these signals are valid */
2788 case SIGINT:
2789 case SIGILL:
2790 case SIGFPE:
2791 case SIGSEGV:
2792 case SIGTERM:
2793 case SIGBREAK:
2794 case SIGABRT:
2795 break;
2796 /* Don't call signal() with other values or it will assert */
2797 default:
2798 return SIG_ERR;
2799 }
2800#endif /* _MSC_VER && _MSC_VER >= 1400 */
2801 handler = signal(sig, SIG_IGN);
2802 if (handler != SIG_ERR)
2803 signal(sig, handler);
2804 return handler;
2805#endif
2806}
2807
2808/*
2809 * All of the code in this function must only use async-signal-safe functions,
2810 * listed at `man 7 signal` or
2811 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2812 */
2813PyOS_sighandler_t
2814PyOS_setsig(int sig, PyOS_sighandler_t handler)
2815{
2816#ifdef HAVE_SIGACTION
2817 /* Some code in Modules/signalmodule.c depends on sigaction() being
2818 * used here if HAVE_SIGACTION is defined. Fix that if this code
2819 * changes to invalidate that assumption.
2820 */
2821 struct sigaction context, ocontext;
2822 context.sa_handler = handler;
2823 sigemptyset(&context.sa_mask);
2824 context.sa_flags = 0;
2825 if (sigaction(sig, &context, &ocontext) == -1)
2826 return SIG_ERR;
2827 return ocontext.sa_handler;
2828#else
2829 PyOS_sighandler_t oldhandler;
2830 oldhandler = signal(sig, handler);
2831#ifdef HAVE_SIGINTERRUPT
2832 siginterrupt(sig, 1);
2833#endif
2834 return oldhandler;
2835#endif
2836}
2837
2838#ifdef __cplusplus
2839}
2840#endif