blob: cad0fa7026bfd5ffb6f6ca7a978d5d9a614d1479 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +02007
8#include "pycore_ceval.h" // _PyEval_FiniGIL()
9#include "pycore_context.h" // _PyContext_Init()
10#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner4f98f462020-04-15 04:01:58 +020011#include "pycore_initconfig.h" // _PyStatus_OK()
12#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
13#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
14#include "pycore_pyerrors.h" // _PyErr_Occurred()
15#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020016#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020017#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
18#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
19
Victor Stinner4f98f462020-04-15 04:01:58 +020020#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100021
22#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020023# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100024#endif
25
26#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020027# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100028#endif
29
30#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020031# undef BYTE
32# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070033
Victor Stinner4f98f462020-04-15 04:01:58 +020034 extern PyTypeObject PyWindowsConsoleIO_Type;
35# define PyWindowsConsoleIO_Check(op) \
36 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
Victor Stinner4f98f462020-04-15 04:01:58 +020039
Nick Coghland6009512014-11-20 21:39:37 +100040_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
Nick Coghland6009512014-11-20 21:39:37 +100051
Victor Stinnerb45d2592019-06-20 00:05:23 +020052/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020053static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020054static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050055static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020056static PyStatus init_sys_streams(PyThreadState *tstate);
57static PyStatus init_signals(PyThreadState *tstate);
58static void call_py_exitfuncs(PyThreadState *tstate);
59static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020060static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100061
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080062int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010064static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065
Victor Stinner331a6a52019-05-27 16:39:22 +020066PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067_PyRuntime_Initialize(void)
68{
69 /* XXX We only initialize once in the process, which aligns with
70 the static initialization of the former globals now found in
71 _PyRuntime. However, _PyRuntime *should* be initialized with
72 every Py_Initialize() call, but doing so breaks the runtime.
73 This is because the runtime state is not properly finalized
74 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010075 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020076 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010078 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079
80 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081}
82
83void
84_PyRuntime_Finalize(void)
85{
86 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010087 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
89
90int
91_Py_IsFinalizing(void)
92{
Victor Stinner7b3c2522020-03-07 00:24:23 +010093 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
Nick Coghland6009512014-11-20 21:39:37 +100096/* Hack to force loading of object files */
97int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
98 PyOS_mystrnicmp; /* Python/pystrcmp.o */
99
100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
104{
105 return PyImport_ImportModule("warnings");
106}
107
Eric Snowc7ec9982017-05-23 23:00:52 -0700108
Eric Snow1abcf672017-05-23 21:46:51 -0700109/* APIs to access the initialization flags
110 *
111 * Can be called prior to Py_Initialize.
112 */
Nick Coghland6009512014-11-20 21:39:37 +1000113
Eric Snow1abcf672017-05-23 21:46:51 -0700114int
115_Py_IsCoreInitialized(void)
116{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700118}
Nick Coghland6009512014-11-20 21:39:37 +1000119
120int
121Py_IsInitialized(void)
122{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600123 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000124}
125
Nick Coghlan6ea41862017-06-11 13:16:15 +1000126
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000127/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
128 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000129 initializations fail, a fatal error is issued and the function does
130 not return. On return, the first thread and interpreter state have
131 been created.
132
133 Locking: you must hold the interpreter lock while calling this.
134 (If the lock has not yet been initialized, that's equivalent to
135 having the lock, but you cannot use multiple threads.)
136
137*/
138
Victor Stinner331a6a52019-05-27 16:39:22 +0200139static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200140init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000141{
142 PyObject *importlib;
143 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000144 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200145 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200146 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000147
148 /* Import _importlib through its frozen version, _frozen_importlib. */
149 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200150 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000151 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200152 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000153 PySys_FormatStderr("import _frozen_importlib # frozen\n");
154 }
155 importlib = PyImport_AddModule("_frozen_importlib");
156 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200157 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000158 }
159 interp->importlib = importlib;
160 Py_INCREF(interp->importlib);
161
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200162 interp->import_func = _PyDict_GetItemStringWithError(interp->builtins, "__import__");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300163 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200164 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300165 Py_INCREF(interp->import_func);
166
Victor Stinnercd6e6942015-09-18 09:11:57 +0200167 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800168 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000169 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200170 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000171 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200172 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200173 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000174 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600175 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200176 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000177 }
178
Victor Stinnercd6e6942015-09-18 09:11:57 +0200179 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000180 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
181 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200182 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200183 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000184 }
185 Py_DECREF(value);
186 Py_DECREF(impmod);
187
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000189}
190
Victor Stinner331a6a52019-05-27 16:39:22 +0200191static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200192init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700193{
194 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200195 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700196 "_install_external_importers", "");
197 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200198 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200199 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700200 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200201 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200202 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700203}
Nick Coghland6009512014-11-20 21:39:37 +1000204
Nick Coghlan6ea41862017-06-11 13:16:15 +1000205/* Helper functions to better handle the legacy C locale
206 *
207 * The legacy C locale assumes ASCII as the default text encoding, which
208 * causes problems not only for the CPython runtime, but also other
209 * components like GNU readline.
210 *
211 * Accordingly, when the CLI detects it, it attempts to coerce it to a
212 * more capable UTF-8 based alternative as follows:
213 *
214 * if (_Py_LegacyLocaleDetected()) {
215 * _Py_CoerceLegacyLocale();
216 * }
217 *
218 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
219 *
220 * Locale coercion also impacts the default error handler for the standard
221 * streams: while the usual default is "strict", the default for the legacy
222 * C locale and for any of the coercion target locales is "surrogateescape".
223 */
224
225int
Victor Stinner0f721472019-05-20 17:16:38 +0200226_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000227{
228#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200229 if (!warn) {
230 const char *locale_override = getenv("LC_ALL");
231 if (locale_override != NULL && *locale_override != '\0') {
232 /* Don't coerce C locale if the LC_ALL environment variable
233 is set */
234 return 0;
235 }
236 }
237
Nick Coghlan6ea41862017-06-11 13:16:15 +1000238 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000239 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
240 * the POSIX locale as a simple alias for the C locale, so
241 * we may also want to check for that explicitly.
242 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000243 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
244 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
245#else
246 /* Windows uses code pages instead of locales, so no locale is legacy */
247 return 0;
248#endif
249}
250
Victor Stinnerb0051362019-11-22 17:52:42 +0100251#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000252static const char *_C_LOCALE_WARNING =
253 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
254 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
255 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
256 "locales is recommended.\n";
257
Nick Coghlaneb817952017-06-18 12:29:42 +1000258static void
Victor Stinner43125222019-04-24 18:23:53 +0200259emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000260{
Victor Stinner331a6a52019-05-27 16:39:22 +0200261 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200262 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200263 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000264 }
265}
Victor Stinnerb0051362019-11-22 17:52:42 +0100266#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000267
Nick Coghlan6ea41862017-06-11 13:16:15 +1000268typedef struct _CandidateLocale {
269 const char *locale_name; /* The locale to try as a coercion target */
270} _LocaleCoercionTarget;
271
272static _LocaleCoercionTarget _TARGET_LOCALES[] = {
273 {"C.UTF-8"},
274 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000275 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276 {NULL}
277};
278
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200279
280int
281_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200283 const _LocaleCoercionTarget *target = NULL;
284 for (target = _TARGET_LOCALES; target->locale_name; target++) {
285 if (strcmp(ctype_loc, target->locale_name) == 0) {
286 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000287 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200288 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200289 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000290}
291
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200292
Nick Coghlan6ea41862017-06-11 13:16:15 +1000293#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100294static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
296 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
297
Victor Stinner0f721472019-05-20 17:16:38 +0200298static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200299_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300{
301 const char *newloc = target->locale_name;
302
303 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100304 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305
306 /* Set the relevant locale environment variable */
307 if (setenv("LC_CTYPE", newloc, 1)) {
308 fprintf(stderr,
309 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200310 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200312 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100313 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000314 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315
316 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100317 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200318 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319}
320#endif
321
Victor Stinner0f721472019-05-20 17:16:38 +0200322int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200323_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000324{
Victor Stinner0f721472019-05-20 17:16:38 +0200325 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200327 char *oldloc = NULL;
328
329 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
330 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200331 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200332 }
333
Victor Stinner94540602017-12-16 04:54:22 +0100334 const char *locale_override = getenv("LC_ALL");
335 if (locale_override == NULL || *locale_override == '\0') {
336 /* LC_ALL is also not set (or is set to an empty string) */
337 const _LocaleCoercionTarget *target = NULL;
338 for (target = _TARGET_LOCALES; target->locale_name; target++) {
339 const char *new_locale = setlocale(LC_CTYPE,
340 target->locale_name);
341 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400342#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100343 /* Also ensure that nl_langinfo works in this locale */
344 char *codeset = nl_langinfo(CODESET);
345 if (!codeset || *codeset == '\0') {
346 /* CODESET is not set or empty, so skip coercion */
347 new_locale = NULL;
348 _Py_SetLocaleFromEnv(LC_CTYPE);
349 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350 }
Victor Stinner94540602017-12-16 04:54:22 +0100351#endif
352 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200353 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200354 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000355 }
356 }
357 }
358 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200359
360 setlocale(LC_CTYPE, oldloc);
361
362done:
363 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000364#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200365 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000366}
367
xdegaye1588be62017-11-12 12:45:59 +0100368/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
369 * isolate the idiosyncrasies of different libc implementations. It reads the
370 * appropriate environment variable and uses its value to select the locale for
371 * 'category'. */
372char *
373_Py_SetLocaleFromEnv(int category)
374{
Victor Stinner353933e2018-11-23 13:08:26 +0100375 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100376#ifdef __ANDROID__
377 const char *locale;
378 const char **pvar;
379#ifdef PY_COERCE_C_LOCALE
380 const char *coerce_c_locale;
381#endif
382 const char *utf8_locale = "C.UTF-8";
383 const char *env_var_set[] = {
384 "LC_ALL",
385 "LC_CTYPE",
386 "LANG",
387 NULL,
388 };
389
390 /* Android setlocale(category, "") doesn't check the environment variables
391 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
392 * check the environment variables listed in env_var_set. */
393 for (pvar=env_var_set; *pvar; pvar++) {
394 locale = getenv(*pvar);
395 if (locale != NULL && *locale != '\0') {
396 if (strcmp(locale, utf8_locale) == 0 ||
397 strcmp(locale, "en_US.UTF-8") == 0) {
398 return setlocale(category, utf8_locale);
399 }
400 return setlocale(category, "C");
401 }
402 }
403
404 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
405 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
406 * Quote from POSIX section "8.2 Internationalization Variables":
407 * "4. If the LANG environment variable is not set or is set to the empty
408 * string, the implementation-defined default locale shall be used." */
409
410#ifdef PY_COERCE_C_LOCALE
411 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
412 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
413 /* Some other ported code may check the environment variables (e.g. in
414 * extension modules), so we make sure that they match the locale
415 * configuration */
416 if (setenv("LC_CTYPE", utf8_locale, 1)) {
417 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
418 "environment variable to %s\n", utf8_locale);
419 }
420 }
421#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100422 res = setlocale(category, utf8_locale);
423#else /* !defined(__ANDROID__) */
424 res = setlocale(category, "");
425#endif
426 _Py_ResetForceASCII();
427 return res;
xdegaye1588be62017-11-12 12:45:59 +0100428}
429
Nick Coghlan6ea41862017-06-11 13:16:15 +1000430
Eric Snow1abcf672017-05-23 21:46:51 -0700431/* Global initializations. Can be undone by Py_Finalize(). Don't
432 call this twice without an intervening Py_Finalize() call.
433
Victor Stinner331a6a52019-05-27 16:39:22 +0200434 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700435 must have a corresponding call to Py_Finalize.
436
437 Locking: you must hold the interpreter lock while calling these APIs.
438 (If the lock has not yet been initialized, that's equivalent to
439 having the lock, but you cannot use multiple threads.)
440
441*/
442
Victor Stinner331a6a52019-05-27 16:39:22 +0200443static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200444pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200445 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200446 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200447{
Victor Stinner331a6a52019-05-27 16:39:22 +0200448 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100449 PyThreadState *tstate = _PyThreadState_GET();
450 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200451 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100452 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200453 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100454
455 PyInterpreterState *interp = tstate->interp;
456 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200457 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100458 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100459
Victor Stinnere81f6e62020-06-08 18:12:59 +0200460 status = _PyConfig_Write(config, runtime);
461 if (_PyStatus_EXCEPTION(status)) {
462 return status;
463 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200464
Victor Stinnerda7933e2020-04-13 03:04:28 +0200465 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200466 if (_PyStatus_EXCEPTION(status)) {
467 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200468 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200469 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470
Victor Stinner331a6a52019-05-27 16:39:22 +0200471 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200472 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200473 if (_PyStatus_EXCEPTION(status)) {
474 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200475 }
476 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200477 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200478}
479
480
Victor Stinner331a6a52019-05-27 16:39:22 +0200481static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200482pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200483 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000484{
Victor Stinner43125222019-04-24 18:23:53 +0200485 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200486 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200487 }
Victor Stinnerda273412017-12-15 01:46:02 +0100488
Victor Stinnere81f6e62020-06-08 18:12:59 +0200489 PyStatus status = _PyConfig_Write(config, runtime);
490 if (_PyStatus_EXCEPTION(status)) {
491 return status;
492 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600493
Eric Snow1abcf672017-05-23 21:46:51 -0700494 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
495 * threads behave a little more gracefully at interpreter shutdown.
496 * We clobber it here so the new interpreter can start with a clean
497 * slate.
498 *
499 * However, this may still lead to misbehaviour if there are daemon
500 * threads still hanging around from a previous Py_Initialize/Finalize
501 * pair :(
502 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100503 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600504
Victor Stinnere81f6e62020-06-08 18:12:59 +0200505 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200506 if (_PyStatus_EXCEPTION(status)) {
507 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800508 }
509
Victor Stinner331a6a52019-05-27 16:39:22 +0200510 status = _PyInterpreterState_Enable(runtime);
511 if (_PyStatus_EXCEPTION(status)) {
512 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800513 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200514 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100515}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800516
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517
Victor Stinner331a6a52019-05-27 16:39:22 +0200518static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200519init_interp_create_gil(PyThreadState *tstate)
520{
521 PyStatus status;
522
523 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
524 only called here. */
525 _PyEval_FiniGIL(tstate);
526
527 /* Auto-thread-state API */
528 status = _PyGILState_Init(tstate);
529 if (_PyStatus_EXCEPTION(status)) {
530 return status;
531 }
532
533 /* Create the GIL and take it */
534 status = _PyEval_InitGIL(tstate);
535 if (_PyStatus_EXCEPTION(status)) {
536 return status;
537 }
538
539 return _PyStatus_OK();
540}
541
542
543static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200544pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200545 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200546 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100547{
548 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100549 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200550 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100551 }
552
Victor Stinnerda7933e2020-04-13 03:04:28 +0200553 PyStatus status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200554 if (_PyStatus_EXCEPTION(status)) {
555 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100556 }
Nick Coghland6009512014-11-20 21:39:37 +1000557
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200558 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200559 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200560 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200561 }
Nick Coghland6009512014-11-20 21:39:37 +1000562 (void) PyThreadState_Swap(tstate);
563
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200564 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100565 if (_PyStatus_EXCEPTION(status)) {
566 return status;
567 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100568
Victor Stinnerb45d2592019-06-20 00:05:23 +0200569 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200570 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100571}
Nick Coghland6009512014-11-20 21:39:37 +1000572
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573
Victor Stinner331a6a52019-05-27 16:39:22 +0200574static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100575pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100576{
Victor Stinner444b39b2019-11-20 01:18:11 +0100577 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100578 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100579
Victor Stinner01b1cc12019-11-20 02:27:56 +0100580 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100581 if (_PyStatus_EXCEPTION(status)) {
582 return status;
583 }
584
Victor Stinner0430dfa2020-06-24 15:21:54 +0200585 // Create the empty tuple singleton. It must be created before the first
586 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
587 // for example.
588 status = _PyTuple_Init(tstate);
589 if (_PyStatus_EXCEPTION(status)) {
590 return status;
591 }
592
Victor Stinnere7e699e2019-11-20 12:08:13 +0100593 if (is_main_interp) {
594 status = _PyTypes_Init();
595 if (_PyStatus_EXCEPTION(status)) {
596 return status;
597 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100598 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100599
Victor Stinner630c8df2019-12-17 13:02:18 +0100600 if (!_PyLong_Init(tstate)) {
601 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100602 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100603
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200604 status = _PyUnicode_Init(tstate);
605 if (_PyStatus_EXCEPTION(status)) {
606 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100607 }
608
Victor Stinner91698d82020-06-25 14:07:40 +0200609 status = _PyBytes_Init(tstate);
610 if (_PyStatus_EXCEPTION(status)) {
611 return status;
612 }
613
Victor Stinner281cce12020-06-23 22:55:46 +0200614 status = _PyExc_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 if (_PyStatus_EXCEPTION(status)) {
616 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100617 }
618
Victor Stinnere7e699e2019-11-20 12:08:13 +0100619 if (is_main_interp) {
620 if (!_PyFloat_Init()) {
621 return _PyStatus_ERR("can't init float");
622 }
Nick Coghland6009512014-11-20 21:39:37 +1000623
Victor Stinnere7e699e2019-11-20 12:08:13 +0100624 if (_PyStructSequence_Init() < 0) {
625 return _PyStatus_ERR("can't initialize structseq");
626 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100627 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200628
Victor Stinner331a6a52019-05-27 16:39:22 +0200629 status = _PyErr_Init();
630 if (_PyStatus_EXCEPTION(status)) {
631 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200632 }
633
Victor Stinnere7e699e2019-11-20 12:08:13 +0100634 if (is_main_interp) {
635 if (!_PyContext_Init()) {
636 return _PyStatus_ERR("can't init context");
637 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100638 }
639
Victor Stinner331a6a52019-05-27 16:39:22 +0200640 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641}
642
643
Victor Stinner331a6a52019-05-27 16:39:22 +0200644static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200645pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100646{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100647 assert(!_PyErr_Occurred(tstate));
648
Victor Stinnerb45d2592019-06-20 00:05:23 +0200649 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100650 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100651 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100652 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100653
Victor Stinner2582d462019-11-22 19:24:49 +0100654 PyInterpreterState *interp = tstate->interp;
655 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
656 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100657 }
Victor Stinner2582d462019-11-22 19:24:49 +0100658
659 PyObject *builtins_dict = PyModule_GetDict(bimod);
660 if (builtins_dict == NULL) {
661 goto error;
662 }
663 Py_INCREF(builtins_dict);
664 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100665
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 PyStatus status = _PyBuiltins_AddExceptions(bimod);
667 if (_PyStatus_EXCEPTION(status)) {
668 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 }
Victor Stinner2582d462019-11-22 19:24:49 +0100670
671 interp->builtins_copy = PyDict_Copy(interp->builtins);
672 if (interp->builtins_copy == NULL) {
673 goto error;
674 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000675 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100676
677 assert(!_PyErr_Occurred(tstate));
678
Victor Stinner331a6a52019-05-27 16:39:22 +0200679 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100680
681error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000682 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100683 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100684}
685
686
Victor Stinner331a6a52019-05-27 16:39:22 +0200687static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200688pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100689{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100690 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200691
Victor Stinner2582d462019-11-22 19:24:49 +0100692 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200693 if (_PyStatus_EXCEPTION(status)) {
694 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800695 }
Nick Coghland6009512014-11-20 21:39:37 +1000696
Victor Stinner30a89332020-06-23 15:55:45 +0200697 /* Initialize _warnings. */
698 status = _PyWarnings_InitState(tstate);
699 if (_PyStatus_EXCEPTION(status)) {
700 return status;
701 }
Nick Coghland6009512014-11-20 21:39:37 +1000702
Victor Stinner30a89332020-06-23 15:55:45 +0200703 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
704 if (config->_install_importlib) {
705 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100706 status = _PyConfig_WritePathConfig(config);
707 if (_PyStatus_EXCEPTION(status)) {
708 return status;
709 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200710 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200711
Victor Stinner30a89332020-06-23 15:55:45 +0200712 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200713 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200714 if (_PyStatus_EXCEPTION(status)) {
715 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 }
Eric Snow1abcf672017-05-23 21:46:51 -0700717 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100718
719 assert(!_PyErr_Occurred(tstate));
720
Victor Stinner331a6a52019-05-27 16:39:22 +0200721 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100722}
723
724
Victor Stinner331a6a52019-05-27 16:39:22 +0200725static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100726pycore_interp_init(PyThreadState *tstate)
727{
728 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100729 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100730
731 status = pycore_init_types(tstate);
732 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100733 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100734 }
735
Victor Stinnerd863ade2019-12-06 03:37:07 +0100736 status = _PySys_Create(tstate, &sysmod);
737 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100738 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100739 }
740
741 status = pycore_init_builtins(tstate);
742 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100743 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100744 }
745
Victor Stinner080ee5a2019-12-08 21:55:58 +0100746 status = pycore_init_import_warnings(tstate, sysmod);
747
748done:
749 /* sys.modules['sys'] contains a strong reference to the module */
750 Py_XDECREF(sysmod);
751 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100752}
753
754
755static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200756pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200757 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200758 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100759{
Victor Stinner331a6a52019-05-27 16:39:22 +0200760 PyStatus status = pycore_init_runtime(runtime, config);
761 if (_PyStatus_EXCEPTION(status)) {
762 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100763 }
764
Victor Stinnerb45d2592019-06-20 00:05:23 +0200765 PyThreadState *tstate;
766 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200767 if (_PyStatus_EXCEPTION(status)) {
768 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100769 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200770 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100771
Victor Stinnerd863ade2019-12-06 03:37:07 +0100772 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200773 if (_PyStatus_EXCEPTION(status)) {
774 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100775 }
Eric Snow1abcf672017-05-23 21:46:51 -0700776
777 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200778 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200779 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700780}
781
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100782
Victor Stinner331a6a52019-05-27 16:39:22 +0200783PyStatus
784_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100785{
Victor Stinner331a6a52019-05-27 16:39:22 +0200786 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100787
Victor Stinner6d1c4672019-05-20 11:02:00 +0200788 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200789 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200790 }
791
Victor Stinner331a6a52019-05-27 16:39:22 +0200792 status = _PyRuntime_Initialize();
793 if (_PyStatus_EXCEPTION(status)) {
794 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100795 }
Victor Stinner43125222019-04-24 18:23:53 +0200796 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100797
Victor Stinnerd3b90412019-09-17 23:59:51 +0200798 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100799 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200800 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100801 }
802
Victor Stinnerd3b90412019-09-17 23:59:51 +0200803 /* Note: preinitialized remains 1 on error, it is only set to 0
804 at exit on success. */
805 runtime->preinitializing = 1;
806
Victor Stinner331a6a52019-05-27 16:39:22 +0200807 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200808
809 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
810 if (_PyStatus_EXCEPTION(status)) {
811 return status;
812 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100813
Victor Stinner331a6a52019-05-27 16:39:22 +0200814 status = _PyPreConfig_Read(&config, args);
815 if (_PyStatus_EXCEPTION(status)) {
816 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100817 }
818
Victor Stinner331a6a52019-05-27 16:39:22 +0200819 status = _PyPreConfig_Write(&config);
820 if (_PyStatus_EXCEPTION(status)) {
821 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100822 }
823
Victor Stinnerd3b90412019-09-17 23:59:51 +0200824 runtime->preinitializing = 0;
825 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100827}
828
Victor Stinner70005ac2019-05-02 15:25:34 -0400829
Victor Stinner331a6a52019-05-27 16:39:22 +0200830PyStatus
831Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100832{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100833 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400834 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100835}
836
837
Victor Stinner331a6a52019-05-27 16:39:22 +0200838PyStatus
839Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100840{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100841 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400842 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100843}
844
845
Victor Stinner331a6a52019-05-27 16:39:22 +0200846PyStatus
847Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100848{
Victor Stinner70005ac2019-05-02 15:25:34 -0400849 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100850}
851
852
Victor Stinner331a6a52019-05-27 16:39:22 +0200853PyStatus
854_Py_PreInitializeFromConfig(const PyConfig *config,
855 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100856{
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200858
Victor Stinner331a6a52019-05-27 16:39:22 +0200859 PyStatus status = _PyRuntime_Initialize();
860 if (_PyStatus_EXCEPTION(status)) {
861 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200862 }
863 _PyRuntimeState *runtime = &_PyRuntime;
864
Victor Stinnerd3b90412019-09-17 23:59:51 +0200865 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200866 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200867 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400868 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200869
Victor Stinner331a6a52019-05-27 16:39:22 +0200870 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200871
Victor Stinner3c30a762019-10-01 10:56:37 +0200872 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200873
Victor Stinner331a6a52019-05-27 16:39:22 +0200874 if (!config->parse_argv) {
875 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200876 }
877 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200878 _PyArgv config_args = {
879 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200880 .argc = config->argv.length,
881 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200882 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200883 }
884 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200885 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200886 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100887}
888
889
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100890/* Begin interpreter initialization
891 *
892 * On return, the first thread and interpreter state have been created,
893 * but the compiler, signal handling, multithreading and
894 * multiple interpreter support, and codec infrastructure are not yet
895 * available.
896 *
897 * The import system will support builtin and frozen modules only.
898 * The only supported io is writing to sys.stderr
899 *
900 * If any operation invoked by this function fails, a fatal error is
901 * issued and the function does not return.
902 *
903 * Any code invoked from this function should *not* assume it has access
904 * to the Python C API (unless the API is explicitly listed as being
905 * safe to call without calling Py_Initialize first)
906 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200907static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200908pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200910 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200911{
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200913
Victor Stinner331a6a52019-05-27 16:39:22 +0200914 status = _Py_PreInitializeFromConfig(src_config, NULL);
915 if (_PyStatus_EXCEPTION(status)) {
916 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200917 }
918
Victor Stinner331a6a52019-05-27 16:39:22 +0200919 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200920 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200921
Victor Stinner331a6a52019-05-27 16:39:22 +0200922 status = _PyConfig_Copy(&config, src_config);
923 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200924 goto done;
925 }
926
Victor Stinner331a6a52019-05-27 16:39:22 +0200927 status = PyConfig_Read(&config);
928 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200929 goto done;
930 }
931
932 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200933 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200934 }
935 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200936 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200937 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200938 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200939 goto done;
940 }
941
942done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200943 PyConfig_Clear(&config);
944 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200945}
946
Victor Stinner5ac27a52019-03-27 13:40:14 +0100947
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200948/* Py_Initialize() has already been called: update the main interpreter
949 configuration. Example of bpo-34008: Py_Main() called after
950 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200951static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100952_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200953{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200954 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100955
Victor Stinner331a6a52019-05-27 16:39:22 +0200956 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100957 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200958 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100959 }
960
Victor Stinnerb0051362019-11-22 17:52:42 +0100961 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100962 Py_DECREF(argv);
963 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200964 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200965 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200967}
968
Victor Stinnerb0051362019-11-22 17:52:42 +0100969
970static PyStatus
971init_interp_main(PyThreadState *tstate)
972{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100973 assert(!_PyErr_Occurred(tstate));
974
Victor Stinnerb0051362019-11-22 17:52:42 +0100975 PyStatus status;
976 int is_main_interp = _Py_IsMainInterpreter(tstate);
977 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200978 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +0100979
980 if (!config->_install_importlib) {
981 /* Special mode for freeze_importlib: run with no import system
982 *
983 * This means anything which needs support from extension modules
984 * or pure Python code in the standard library won't work.
985 */
986 if (is_main_interp) {
987 interp->runtime->initialized = 1;
988 }
989 return _PyStatus_OK();
990 }
991
992 if (is_main_interp) {
993 if (_PyTime_Init() < 0) {
994 return _PyStatus_ERR("can't initialize time");
995 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100996 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100997
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100998 if (_PySys_InitMain(tstate) < 0) {
999 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +01001000 }
1001
1002 status = init_importlib_external(tstate);
1003 if (_PyStatus_EXCEPTION(status)) {
1004 return status;
1005 }
1006
1007 if (is_main_interp) {
1008 /* initialize the faulthandler module */
1009 status = _PyFaulthandler_Init(config->faulthandler);
1010 if (_PyStatus_EXCEPTION(status)) {
1011 return status;
1012 }
1013 }
1014
1015 status = _PyUnicode_InitEncodings(tstate);
1016 if (_PyStatus_EXCEPTION(status)) {
1017 return status;
1018 }
1019
1020 if (is_main_interp) {
1021 if (config->install_signal_handlers) {
1022 status = init_signals(tstate);
1023 if (_PyStatus_EXCEPTION(status)) {
1024 return status;
1025 }
1026 }
1027
1028 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1029 return _PyStatus_ERR("can't initialize tracemalloc");
1030 }
1031 }
1032
1033 status = init_sys_streams(tstate);
1034 if (_PyStatus_EXCEPTION(status)) {
1035 return status;
1036 }
1037
Andy Lester75cd5bf2020-03-12 02:49:05 -05001038 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001039 if (_PyStatus_EXCEPTION(status)) {
1040 return status;
1041 }
1042
1043 status = add_main_module(interp);
1044 if (_PyStatus_EXCEPTION(status)) {
1045 return status;
1046 }
1047
1048 if (is_main_interp) {
1049 /* Initialize warnings. */
1050 PyObject *warnoptions = PySys_GetObject("warnoptions");
1051 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1052 {
1053 PyObject *warnings_module = PyImport_ImportModule("warnings");
1054 if (warnings_module == NULL) {
1055 fprintf(stderr, "'import warnings' failed; traceback:\n");
1056 _PyErr_Print(tstate);
1057 }
1058 Py_XDECREF(warnings_module);
1059 }
1060
1061 interp->runtime->initialized = 1;
1062 }
1063
1064 if (config->site_import) {
1065 status = init_import_site();
1066 if (_PyStatus_EXCEPTION(status)) {
1067 return status;
1068 }
1069 }
1070
1071 if (is_main_interp) {
1072#ifndef MS_WINDOWS
1073 emit_stderr_warning_for_legacy_locale(interp->runtime);
1074#endif
1075 }
1076
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001077 assert(!_PyErr_Occurred(tstate));
1078
Victor Stinnerb0051362019-11-22 17:52:42 +01001079 return _PyStatus_OK();
1080}
1081
1082
Eric Snowc7ec9982017-05-23 23:00:52 -07001083/* Update interpreter state based on supplied configuration settings
1084 *
1085 * After calling this function, most of the restrictions on the interpreter
1086 * are lifted. The only remaining incomplete settings are those related
1087 * to the main module (sys.argv[0], __main__ metadata)
1088 *
1089 * Calling this when the interpreter is not initializing, is already
1090 * initialized or without a valid current thread state is a fatal error.
1091 * Other errors should be reported as normal Python exceptions with a
1092 * non-zero return code.
1093 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001094static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001095pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001096{
Victor Stinnerb0051362019-11-22 17:52:42 +01001097 PyInterpreterState *interp = tstate->interp;
1098 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001099 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001100 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001101
Victor Stinnerb0051362019-11-22 17:52:42 +01001102 if (interp->runtime->initialized) {
1103 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001104 }
1105
Victor Stinnerb0051362019-11-22 17:52:42 +01001106 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001107 if (_PyStatus_EXCEPTION(status)) {
1108 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001109 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001110 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001111}
1112
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001113
Victor Stinner331a6a52019-05-27 16:39:22 +02001114PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001115_Py_InitializeMain(void)
1116{
Victor Stinner331a6a52019-05-27 16:39:22 +02001117 PyStatus status = _PyRuntime_Initialize();
1118 if (_PyStatus_EXCEPTION(status)) {
1119 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001120 }
1121 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001122 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001123 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001124}
1125
1126
Victor Stinner331a6a52019-05-27 16:39:22 +02001127PyStatus
1128Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001129{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001130 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001131 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001132 }
1133
Victor Stinner331a6a52019-05-27 16:39:22 +02001134 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001135
Victor Stinner331a6a52019-05-27 16:39:22 +02001136 status = _PyRuntime_Initialize();
1137 if (_PyStatus_EXCEPTION(status)) {
1138 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001139 }
1140 _PyRuntimeState *runtime = &_PyRuntime;
1141
Victor Stinnerb45d2592019-06-20 00:05:23 +02001142 PyThreadState *tstate = NULL;
1143 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001144 if (_PyStatus_EXCEPTION(status)) {
1145 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001146 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001147 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001148
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001149 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001150 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001151 if (_PyStatus_EXCEPTION(status)) {
1152 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001153 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001154 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001155
Victor Stinner331a6a52019-05-27 16:39:22 +02001156 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001157}
1158
1159
Eric Snow1abcf672017-05-23 21:46:51 -07001160void
Nick Coghland6009512014-11-20 21:39:37 +10001161Py_InitializeEx(int install_sigs)
1162{
Victor Stinner331a6a52019-05-27 16:39:22 +02001163 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001164
Victor Stinner331a6a52019-05-27 16:39:22 +02001165 status = _PyRuntime_Initialize();
1166 if (_PyStatus_EXCEPTION(status)) {
1167 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001168 }
1169 _PyRuntimeState *runtime = &_PyRuntime;
1170
1171 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001172 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1173 return;
1174 }
1175
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001177 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001178
Victor Stinner1dc6e392018-07-25 02:49:17 +02001179 config.install_signal_handlers = install_sigs;
1180
Victor Stinner331a6a52019-05-27 16:39:22 +02001181 status = Py_InitializeFromConfig(&config);
1182 if (_PyStatus_EXCEPTION(status)) {
1183 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001184 }
Nick Coghland6009512014-11-20 21:39:37 +10001185}
1186
1187void
1188Py_Initialize(void)
1189{
1190 Py_InitializeEx(1);
1191}
1192
1193
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001194static void
1195finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1196{
1197 // List of names to clear in sys
1198 static const char * const sys_deletes[] = {
1199 "path", "argv", "ps1", "ps2",
1200 "last_type", "last_value", "last_traceback",
1201 "path_hooks", "path_importer_cache", "meta_path",
1202 "__interactivehook__",
1203 NULL
1204 };
1205
1206 static const char * const sys_files[] = {
1207 "stdin", "__stdin__",
1208 "stdout", "__stdout__",
1209 "stderr", "__stderr__",
1210 NULL
1211 };
1212
1213 PyInterpreterState *interp = tstate->interp;
1214 if (verbose) {
1215 PySys_WriteStderr("# clear builtins._\n");
1216 }
1217 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1218 PyErr_WriteUnraisable(NULL);
1219 }
1220
1221 const char * const *p;
1222 for (p = sys_deletes; *p != NULL; p++) {
1223 if (verbose) {
1224 PySys_WriteStderr("# clear sys.%s\n", *p);
1225 }
1226 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1227 PyErr_WriteUnraisable(NULL);
1228 }
1229 }
1230 for (p = sys_files; *p != NULL; p+=2) {
1231 const char *name = p[0];
1232 const char *orig_name = p[1];
1233 if (verbose) {
1234 PySys_WriteStderr("# restore sys.%s\n", name);
1235 }
1236 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1237 orig_name);
1238 if (value == NULL) {
1239 if (_PyErr_Occurred(tstate)) {
1240 PyErr_WriteUnraisable(NULL);
1241 }
1242 value = Py_None;
1243 }
1244 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1245 PyErr_WriteUnraisable(NULL);
1246 }
1247 }
1248}
1249
1250
1251static PyObject*
1252finalize_remove_modules(PyObject *modules, int verbose)
1253{
1254 PyObject *weaklist = PyList_New(0);
1255 if (weaklist == NULL) {
1256 PyErr_WriteUnraisable(NULL);
1257 }
1258
1259#define STORE_MODULE_WEAKREF(name, mod) \
1260 if (weaklist != NULL) { \
1261 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1262 if (wr) { \
1263 PyObject *tup = PyTuple_Pack(2, name, wr); \
1264 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1265 PyErr_WriteUnraisable(NULL); \
1266 } \
1267 Py_XDECREF(tup); \
1268 Py_DECREF(wr); \
1269 } \
1270 else { \
1271 PyErr_WriteUnraisable(NULL); \
1272 } \
1273 }
1274
1275#define CLEAR_MODULE(name, mod) \
1276 if (PyModule_Check(mod)) { \
1277 if (verbose && PyUnicode_Check(name)) { \
1278 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1279 } \
1280 STORE_MODULE_WEAKREF(name, mod); \
1281 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1282 PyErr_WriteUnraisable(NULL); \
1283 } \
1284 }
1285
1286 if (PyDict_CheckExact(modules)) {
1287 Py_ssize_t pos = 0;
1288 PyObject *key, *value;
1289 while (PyDict_Next(modules, &pos, &key, &value)) {
1290 CLEAR_MODULE(key, value);
1291 }
1292 }
1293 else {
1294 PyObject *iterator = PyObject_GetIter(modules);
1295 if (iterator == NULL) {
1296 PyErr_WriteUnraisable(NULL);
1297 }
1298 else {
1299 PyObject *key;
1300 while ((key = PyIter_Next(iterator))) {
1301 PyObject *value = PyObject_GetItem(modules, key);
1302 if (value == NULL) {
1303 PyErr_WriteUnraisable(NULL);
1304 continue;
1305 }
1306 CLEAR_MODULE(key, value);
1307 Py_DECREF(value);
1308 Py_DECREF(key);
1309 }
1310 if (PyErr_Occurred()) {
1311 PyErr_WriteUnraisable(NULL);
1312 }
1313 Py_DECREF(iterator);
1314 }
1315 }
1316#undef CLEAR_MODULE
1317#undef STORE_MODULE_WEAKREF
1318
1319 return weaklist;
1320}
1321
1322
1323static void
1324finalize_clear_modules_dict(PyObject *modules)
1325{
1326 if (PyDict_CheckExact(modules)) {
1327 PyDict_Clear(modules);
1328 }
1329 else {
1330 _Py_IDENTIFIER(clear);
1331 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1332 PyErr_WriteUnraisable(NULL);
1333 }
1334 }
1335}
1336
1337
1338static void
1339finalize_restore_builtins(PyThreadState *tstate)
1340{
1341 PyInterpreterState *interp = tstate->interp;
1342 PyObject *dict = PyDict_Copy(interp->builtins);
1343 if (dict == NULL) {
1344 PyErr_WriteUnraisable(NULL);
1345 }
1346 PyDict_Clear(interp->builtins);
1347 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1348 _PyErr_Clear(tstate);
1349 }
1350 Py_XDECREF(dict);
1351}
1352
1353
1354static void
1355finalize_modules_clear_weaklist(PyInterpreterState *interp,
1356 PyObject *weaklist, int verbose)
1357{
1358 // First clear modules imported later
1359 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1360 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1361 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1362 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1363 if (mod == Py_None) {
1364 continue;
1365 }
1366 assert(PyModule_Check(mod));
1367 PyObject *dict = PyModule_GetDict(mod);
1368 if (dict == interp->builtins || dict == interp->sysdict) {
1369 continue;
1370 }
1371 Py_INCREF(mod);
1372 if (verbose && PyUnicode_Check(name)) {
1373 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1374 }
1375 _PyModule_Clear(mod);
1376 Py_DECREF(mod);
1377 }
1378}
1379
1380
1381static void
1382finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1383{
1384 // Clear sys dict
1385 if (verbose) {
1386 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1387 }
1388 _PyModule_ClearDict(interp->sysdict);
1389
1390 // Clear builtins dict
1391 if (verbose) {
1392 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1393 }
1394 _PyModule_ClearDict(interp->builtins);
1395}
1396
1397
1398/* Clear modules, as good as we can */
1399static void
1400finalize_modules(PyThreadState *tstate)
1401{
1402 PyInterpreterState *interp = tstate->interp;
1403 PyObject *modules = interp->modules;
1404 if (modules == NULL) {
1405 // Already done
1406 return;
1407 }
1408 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1409
1410 // Delete some special builtins._ and sys attributes first. These are
1411 // common places where user values hide and people complain when their
1412 // destructors fail. Since the modules containing them are
1413 // deleted *last* of all, they would come too late in the normal
1414 // destruction order. Sigh.
1415 //
1416 // XXX Perhaps these precautions are obsolete. Who knows?
1417 finalize_modules_delete_special(tstate, verbose);
1418
1419 // Remove all modules from sys.modules, hoping that garbage collection
1420 // can reclaim most of them: set all sys.modules values to None.
1421 //
1422 // We prepare a list which will receive (name, weakref) tuples of
1423 // modules when they are removed from sys.modules. The name is used
1424 // for diagnosis messages (in verbose mode), while the weakref helps
1425 // detect those modules which have been held alive.
1426 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1427
1428 // Clear the modules dict
1429 finalize_clear_modules_dict(modules);
1430
1431 // Restore the original builtins dict, to ensure that any
1432 // user data gets cleared.
1433 finalize_restore_builtins(tstate);
1434
1435 // Collect garbage
1436 _PyGC_CollectNoFail(tstate);
1437
1438 // Dump GC stats before it's too late, since it uses the warnings
1439 // machinery.
1440 _PyGC_DumpShutdownStats(tstate);
1441
1442 if (weaklist != NULL) {
1443 // Now, if there are any modules left alive, clear their globals to
1444 // minimize potential leaks. All C extension modules actually end
1445 // up here, since they are kept alive in the interpreter state.
1446 //
1447 // The special treatment of "builtins" here is because even
1448 // when it's not referenced as a module, its dictionary is
1449 // referenced by almost every module's __builtins__. Since
1450 // deleting a module clears its dictionary (even if there are
1451 // references left to it), we need to delete the "builtins"
1452 // module last. Likewise, we don't delete sys until the very
1453 // end because it is implicitly referenced (e.g. by print).
1454 //
1455 // Since dict is ordered in CPython 3.6+, modules are saved in
1456 // importing order. First clear modules imported later.
1457 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1458 Py_DECREF(weaklist);
1459 }
1460
1461 // Clear sys and builtins modules dict
1462 finalize_clear_sys_builtins_dict(interp, verbose);
1463
1464 // Clear module dict copies stored in the interpreter state:
1465 // clear PyInterpreterState.modules_by_index and
1466 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1467 // initialization API)
1468 _PyInterpreterState_ClearModules(interp);
1469
1470 // Clear and delete the modules directory. Actual modules will
1471 // still be there only if imported during the execution of some
1472 // destructor.
1473 Py_SETREF(interp->modules, NULL);
1474
1475 // Collect garbage once more
1476 _PyGC_CollectNoFail(tstate);
1477}
1478
1479
Nick Coghland6009512014-11-20 21:39:37 +10001480/* Flush stdout and stderr */
1481
1482static int
1483file_is_closed(PyObject *fobj)
1484{
1485 int r;
1486 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1487 if (tmp == NULL) {
1488 PyErr_Clear();
1489 return 0;
1490 }
1491 r = PyObject_IsTrue(tmp);
1492 Py_DECREF(tmp);
1493 if (r < 0)
1494 PyErr_Clear();
1495 return r > 0;
1496}
1497
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001498
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001499static int
Nick Coghland6009512014-11-20 21:39:37 +10001500flush_std_files(void)
1501{
1502 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1503 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1504 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001505 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001506
1507 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001508 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001509 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001510 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001511 status = -1;
1512 }
Nick Coghland6009512014-11-20 21:39:37 +10001513 else
1514 Py_DECREF(tmp);
1515 }
1516
1517 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001518 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001519 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001520 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001521 status = -1;
1522 }
Nick Coghland6009512014-11-20 21:39:37 +10001523 else
1524 Py_DECREF(tmp);
1525 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001526
1527 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001528}
1529
1530/* Undo the effect of Py_Initialize().
1531
1532 Beware: if multiple interpreter and/or thread states exist, these
1533 are not wiped out; only the current thread and interpreter state
1534 are deleted. But since everything else is deleted, those other
1535 interpreter and thread states should no longer be used.
1536
1537 (XXX We should do better, e.g. wipe out all interpreters and
1538 threads.)
1539
1540 Locking: as above.
1541
1542*/
1543
Victor Stinner7eee5be2019-11-20 10:38:34 +01001544
1545static void
Victor Stinner90db4652020-07-01 23:21:36 +02001546finalize_interp_types(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001547{
Victor Stinner281cce12020-06-23 22:55:46 +02001548 _PyExc_Fini(tstate);
Victor Stinner3744ed22020-06-05 01:39:24 +02001549 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001550 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001551 _PyContext_Fini(tstate);
Victor Stinner666ecfb2020-07-02 01:19:57 +02001552 _PyUnicode_ClearInterned(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001553
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001554 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001555 _PyList_Fini(tstate);
1556 _PyTuple_Fini(tstate);
1557
1558 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001559
Victor Stinnerc41eed12020-06-23 15:54:35 +02001560 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001561 _PyUnicode_Fini(tstate);
1562 _PyFloat_Fini(tstate);
1563 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001564}
1565
1566
1567static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001568finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001569{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001570 int is_main_interp = _Py_IsMainInterpreter(tstate);
1571
Victor Stinner7eee5be2019-11-20 10:38:34 +01001572 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001573 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001574
Kongedaa0fe02020-07-04 05:06:46 +08001575 /* Clear all loghooks */
1576 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1577 Call _PySys_ClearAuditHooks when PyObject available. */
1578 if (is_main_interp) {
1579 _PySys_ClearAuditHooks(tstate);
1580 }
1581
Victor Stinner7907f8c2020-06-08 01:22:36 +02001582 if (is_main_interp) {
1583 _Py_HashRandomization_Fini();
1584 _PyArg_Fini();
1585 _Py_ClearFileSystemEncoding();
1586 }
1587
Victor Stinner90db4652020-07-01 23:21:36 +02001588 finalize_interp_types(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001589}
1590
1591
1592static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001593finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001594{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001595 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001596 /* Cleanup auto-thread-state */
1597 _PyGILState_Fini(tstate);
1598 }
1599
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001600 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1601 fail when it is being awaited by another running daemon thread (see
1602 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1603 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1604 called multiple times. */
1605
Victor Stinner7eee5be2019-11-20 10:38:34 +01001606 PyInterpreterState_Delete(tstate->interp);
1607}
1608
1609
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001610int
1611Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001612{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001613 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001614
Victor Stinner8e91c242019-04-24 17:24:01 +02001615 _PyRuntimeState *runtime = &_PyRuntime;
1616 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001617 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001618 }
Nick Coghland6009512014-11-20 21:39:37 +10001619
Victor Stinnere225beb2019-06-03 18:14:24 +02001620 /* Get current thread state and interpreter pointer */
1621 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1622 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001623
Victor Stinnerb45d2592019-06-20 00:05:23 +02001624 // Wrap up existing "threading"-module-created, non-daemon threads.
1625 wait_for_thread_shutdown(tstate);
1626
1627 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001628 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001629
Nick Coghland6009512014-11-20 21:39:37 +10001630 /* The interpreter is still entirely intact at this point, and the
1631 * exit funcs may be relying on that. In particular, if some thread
1632 * or exit func is still waiting to do an import, the import machinery
1633 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001634 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001635 * Note that Threading.py uses an exit func to do a join on all the
1636 * threads created thru it, so this also protects pending imports in
1637 * the threads created via Threading.
1638 */
Nick Coghland6009512014-11-20 21:39:37 +10001639
Victor Stinnerb45d2592019-06-20 00:05:23 +02001640 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001641
Victor Stinnerda273412017-12-15 01:46:02 +01001642 /* Copy the core config, PyInterpreterState_Delete() free
1643 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001644#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001645 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001646#endif
1647#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001648 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001649#endif
1650#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001651 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001652#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001653
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001654 /* Remaining daemon threads will automatically exit
1655 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001656 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001657 runtime->initialized = 0;
1658 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001659
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001660 /* Destroy the state of all threads of the interpreter, except of the
1661 current thread. In practice, only daemon threads should still be alive,
1662 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1663 Clear frames of other threads to call objects destructors. Destructors
1664 will be called in the current Python thread. Since
1665 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1666 can take the GIL at this point: if they try, they will exit
1667 immediately. */
1668 _PyThreadState_DeleteExcept(runtime, tstate);
1669
Victor Stinnere0deff32015-03-24 13:46:18 +01001670 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001671 if (flush_std_files() < 0) {
1672 status = -1;
1673 }
Nick Coghland6009512014-11-20 21:39:37 +10001674
1675 /* Disable signal handling */
1676 PyOS_FiniInterrupts();
1677
1678 /* Collect garbage. This may call finalizers; it's nice to call these
1679 * before all modules are destroyed.
1680 * XXX If a __del__ or weakref callback is triggered here, and tries to
1681 * XXX import a module, bad things can happen, because Python no
1682 * XXX longer believes it's initialized.
1683 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1684 * XXX is easy to provoke that way. I've also seen, e.g.,
1685 * XXX Exception exceptions.ImportError: 'No module named sha'
1686 * XXX in <function callback at 0x008F5718> ignored
1687 * XXX but I'm unclear on exactly how that one happens. In any case,
1688 * XXX I haven't seen a real-life report of either of these.
1689 */
Victor Stinner8b341482020-10-30 17:00:00 +01001690 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001691
Nick Coghland6009512014-11-20 21:39:37 +10001692 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001693 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001694
Inada Naoki91234a12019-06-03 21:30:58 +09001695 /* Print debug stats if any */
1696 _PyEval_Fini();
1697
Victor Stinnere0deff32015-03-24 13:46:18 +01001698 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001699 if (flush_std_files() < 0) {
1700 status = -1;
1701 }
Nick Coghland6009512014-11-20 21:39:37 +10001702
1703 /* Collect final garbage. This disposes of cycles created by
1704 * class definitions, for example.
1705 * XXX This is disabled because it caused too many problems. If
1706 * XXX a __del__ or weakref callback triggers here, Python code has
1707 * XXX a hard time running, because even the sys module has been
1708 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1709 * XXX One symptom is a sequence of information-free messages
1710 * XXX coming from threads (if a __del__ or callback is invoked,
1711 * XXX other threads can execute too, and any exception they encounter
1712 * XXX triggers a comedy of errors as subsystem after subsystem
1713 * XXX fails to find what it *expects* to find in sys to help report
1714 * XXX the exception and consequent unexpected failures). I've also
1715 * XXX seen segfaults then, after adding print statements to the
1716 * XXX Python code getting called.
1717 */
1718#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001719 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001720#endif
1721
1722 /* Disable tracemalloc after all Python objects have been destroyed,
1723 so it is possible to use tracemalloc in objects destructor. */
1724 _PyTraceMalloc_Fini();
1725
1726 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1727 _PyImport_Fini();
1728
1729 /* Cleanup typeobject.c's internal caches. */
1730 _PyType_Fini();
1731
1732 /* unload faulthandler module */
1733 _PyFaulthandler_Fini();
1734
Nick Coghland6009512014-11-20 21:39:37 +10001735 /* dump hash stats */
1736 _PyHash_Fini();
1737
Eric Snowdae02762017-09-14 00:35:58 -07001738#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001739 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001740 _PyDebug_PrintTotalRefs();
1741 }
Eric Snowdae02762017-09-14 00:35:58 -07001742#endif
Nick Coghland6009512014-11-20 21:39:37 +10001743
1744#ifdef Py_TRACE_REFS
1745 /* Display all objects still alive -- this can invoke arbitrary
1746 * __repr__ overrides, so requires a mostly-intact interpreter.
1747 * Alas, a lot of stuff may still be alive now that will be cleaned
1748 * up later.
1749 */
Victor Stinnerda273412017-12-15 01:46:02 +01001750 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001751 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001752 }
Nick Coghland6009512014-11-20 21:39:37 +10001753#endif /* Py_TRACE_REFS */
1754
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001755 finalize_interp_clear(tstate);
1756 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001757
1758#ifdef Py_TRACE_REFS
1759 /* Display addresses (& refcnts) of all objects still alive.
1760 * An address can be used to find the repr of the object, printed
1761 * above by _Py_PrintReferences.
1762 */
Victor Stinnerda273412017-12-15 01:46:02 +01001763 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001764 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001765 }
Nick Coghland6009512014-11-20 21:39:37 +10001766#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001767#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001768 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001769 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001770 }
Nick Coghland6009512014-11-20 21:39:37 +10001771#endif
1772
Victor Stinner8e91c242019-04-24 17:24:01 +02001773 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001774
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001775 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001776 return status;
1777}
1778
1779void
1780Py_Finalize(void)
1781{
1782 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001783}
1784
Victor Stinnerb0051362019-11-22 17:52:42 +01001785
Nick Coghland6009512014-11-20 21:39:37 +10001786/* Create and initialize a new interpreter and thread, and return the
1787 new thread. This requires that Py_Initialize() has been called
1788 first.
1789
1790 Unsuccessful initialization yields a NULL pointer. Note that *no*
1791 exception information is available even in this case -- the
1792 exception information is held in the thread, and there is no
1793 thread.
1794
1795 Locking: as above.
1796
1797*/
1798
Victor Stinner331a6a52019-05-27 16:39:22 +02001799static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001800new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001801{
Victor Stinner331a6a52019-05-27 16:39:22 +02001802 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001803
Victor Stinner331a6a52019-05-27 16:39:22 +02001804 status = _PyRuntime_Initialize();
1805 if (_PyStatus_EXCEPTION(status)) {
1806 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001807 }
1808 _PyRuntimeState *runtime = &_PyRuntime;
1809
1810 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001811 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001812 }
Nick Coghland6009512014-11-20 21:39:37 +10001813
Victor Stinner8a1be612016-03-14 22:07:55 +01001814 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1815 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001816 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001817
Victor Stinner43125222019-04-24 18:23:53 +02001818 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001819 if (interp == NULL) {
1820 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001821 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001822 }
Nick Coghland6009512014-11-20 21:39:37 +10001823
Victor Stinner43125222019-04-24 18:23:53 +02001824 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001825 if (tstate == NULL) {
1826 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001827 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001828 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001829 }
1830
Victor Stinner43125222019-04-24 18:23:53 +02001831 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001832
Eric Snow1abcf672017-05-23 21:46:51 -07001833 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001834 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001835#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001836 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001837 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001838 }
1839 else
1840#endif
1841 {
Eric Snow1abcf672017-05-23 21:46:51 -07001842 /* No current thread state, copy from the main interpreter */
1843 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001844 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001845 }
1846
Victor Stinnerda7933e2020-04-13 03:04:28 +02001847 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001848 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001849 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001850 }
Victor Stinner252346a2020-05-01 11:33:44 +02001851 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001852
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001853 status = init_interp_create_gil(tstate);
1854 if (_PyStatus_EXCEPTION(status)) {
1855 goto error;
1856 }
1857
Victor Stinnerd863ade2019-12-06 03:37:07 +01001858 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001859 if (_PyStatus_EXCEPTION(status)) {
1860 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001861 }
1862
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001863 status = init_interp_main(tstate);
1864 if (_PyStatus_EXCEPTION(status)) {
1865 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001866 }
Nick Coghland6009512014-11-20 21:39:37 +10001867
Victor Stinnera7368ac2017-11-15 18:11:45 -08001868 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001869 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001870
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001871error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001872 *tstate_p = NULL;
1873
1874 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001875 PyErr_PrintEx(0);
1876 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001877 PyThreadState_Delete(tstate);
1878 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001879 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001880
Victor Stinnerb0051362019-11-22 17:52:42 +01001881 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001882}
1883
1884PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001885_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001886{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001887 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001888 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001889 if (_PyStatus_EXCEPTION(status)) {
1890 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001891 }
1892 return tstate;
1893
Nick Coghland6009512014-11-20 21:39:37 +10001894}
1895
Victor Stinner252346a2020-05-01 11:33:44 +02001896PyThreadState *
1897Py_NewInterpreter(void)
1898{
1899 return _Py_NewInterpreter(0);
1900}
1901
Nick Coghland6009512014-11-20 21:39:37 +10001902/* Delete an interpreter and its last thread. This requires that the
1903 given thread state is current, that the thread has no remaining
1904 frames, and that it is its interpreter's only remaining thread.
1905 It is a fatal error to violate these constraints.
1906
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001907 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001908 everything, regardless.)
1909
1910 Locking: as above.
1911
1912*/
1913
1914void
1915Py_EndInterpreter(PyThreadState *tstate)
1916{
1917 PyInterpreterState *interp = tstate->interp;
1918
Victor Stinnerb45d2592019-06-20 00:05:23 +02001919 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001920 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001921 }
1922 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001923 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001924 }
Eric Snow5be45a62019-03-08 22:47:07 -07001925 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001926
Eric Snow842a2f02019-03-15 15:47:51 -06001927 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001928 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001929
Victor Stinnerb45d2592019-06-20 00:05:23 +02001930 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001931
Victor Stinnerb45d2592019-06-20 00:05:23 +02001932 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001933 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001934 }
Nick Coghland6009512014-11-20 21:39:37 +10001935
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001936 finalize_modules(tstate);
1937
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001938 finalize_interp_clear(tstate);
1939 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001940}
1941
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001942/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001943
Victor Stinner331a6a52019-05-27 16:39:22 +02001944static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001945add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001946{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001947 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001948 m = PyImport_AddModule("__main__");
1949 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001950 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001951
Nick Coghland6009512014-11-20 21:39:37 +10001952 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001953 ann_dict = PyDict_New();
1954 if ((ann_dict == NULL) ||
1955 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001956 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001957 }
1958 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001959
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001960 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1961 if (PyErr_Occurred()) {
1962 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1963 }
Nick Coghland6009512014-11-20 21:39:37 +10001964 PyObject *bimod = PyImport_ImportModule("builtins");
1965 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001966 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001967 }
1968 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001969 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001970 }
1971 Py_DECREF(bimod);
1972 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001973
Nick Coghland6009512014-11-20 21:39:37 +10001974 /* Main is a little special - imp.is_builtin("__main__") will return
1975 * False, but BuiltinImporter is still the most appropriate initial
1976 * setting for its __loader__ attribute. A more suitable value will
1977 * be set if __main__ gets further initialized later in the startup
1978 * process.
1979 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001980 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001981 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001982 if (PyErr_Occurred()) {
1983 return _PyStatus_ERR("Failed to test __main__.__loader__");
1984 }
Nick Coghland6009512014-11-20 21:39:37 +10001985 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1986 "BuiltinImporter");
1987 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001988 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001989 }
1990 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001991 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001992 }
1993 Py_DECREF(loader);
1994 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001995 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001996}
1997
Nick Coghland6009512014-11-20 21:39:37 +10001998/* Import the site module (not into __main__ though) */
1999
Victor Stinner331a6a52019-05-27 16:39:22 +02002000static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002001init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002002{
2003 PyObject *m;
2004 m = PyImport_ImportModule("site");
2005 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002006 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002007 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002008 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002009 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002010}
2011
Victor Stinner874dbe82015-09-04 17:29:57 +02002012/* Check if a file descriptor is valid or not.
2013 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2014static int
2015is_valid_fd(int fd)
2016{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002017/* dup() is faster than fstat(): fstat() can require input/output operations,
2018 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2019 startup. Problem: dup() doesn't check if the file descriptor is valid on
2020 some platforms.
2021
2022 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2023 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2024 EBADF. FreeBSD has similar issue (bpo-32849).
2025
2026 Only use dup() on platforms where dup() is enough to detect invalid FD in
2027 corner cases: on Linux and Windows (bpo-32849). */
2028#if defined(__linux__) || defined(MS_WINDOWS)
2029 if (fd < 0) {
2030 return 0;
2031 }
2032 int fd2;
2033
2034 _Py_BEGIN_SUPPRESS_IPH
2035 fd2 = dup(fd);
2036 if (fd2 >= 0) {
2037 close(fd2);
2038 }
2039 _Py_END_SUPPRESS_IPH
2040
2041 return (fd2 >= 0);
2042#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002043 struct stat st;
2044 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002045#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002046}
2047
2048/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002049static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002050create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002051 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002052 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002053{
2054 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2055 const char* mode;
2056 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002057 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002058 int buffering, isatty;
2059 _Py_IDENTIFIER(open);
2060 _Py_IDENTIFIER(isatty);
2061 _Py_IDENTIFIER(TextIOWrapper);
2062 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002063 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002064
Victor Stinner874dbe82015-09-04 17:29:57 +02002065 if (!is_valid_fd(fd))
2066 Py_RETURN_NONE;
2067
Nick Coghland6009512014-11-20 21:39:37 +10002068 /* stdin is always opened in buffered mode, first because it shouldn't
2069 make a difference in common use cases, second because TextIOWrapper
2070 depends on the presence of a read1() method which only exists on
2071 buffered streams.
2072 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002073 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002074 buffering = 0;
2075 else
2076 buffering = -1;
2077 if (write_mode)
2078 mode = "wb";
2079 else
2080 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002081 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002082 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002083 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002084 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002085 if (buf == NULL)
2086 goto error;
2087
2088 if (buffering) {
2089 _Py_IDENTIFIER(raw);
2090 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2091 if (raw == NULL)
2092 goto error;
2093 }
2094 else {
2095 raw = buf;
2096 Py_INCREF(raw);
2097 }
2098
Steve Dower39294992016-08-30 21:22:36 -07002099#ifdef MS_WINDOWS
2100 /* Windows console IO is always UTF-8 encoded */
2101 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002102 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002103#endif
2104
Nick Coghland6009512014-11-20 21:39:37 +10002105 text = PyUnicode_FromString(name);
2106 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2107 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002108 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002109 if (res == NULL)
2110 goto error;
2111 isatty = PyObject_IsTrue(res);
2112 Py_DECREF(res);
2113 if (isatty == -1)
2114 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002115 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002116 write_through = Py_True;
2117 else
2118 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002119 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002120 line_buffering = Py_True;
2121 else
2122 line_buffering = Py_False;
2123
2124 Py_CLEAR(raw);
2125 Py_CLEAR(text);
2126
2127#ifdef MS_WINDOWS
2128 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2129 newlines to "\n".
2130 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2131 newline = NULL;
2132#else
2133 /* sys.stdin: split lines at "\n".
2134 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2135 newline = "\n";
2136#endif
2137
Victor Stinner709d23d2019-05-02 14:56:30 -04002138 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2139 if (encoding_str == NULL) {
2140 Py_CLEAR(buf);
2141 goto error;
2142 }
2143
2144 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2145 if (errors_str == NULL) {
2146 Py_CLEAR(buf);
2147 Py_CLEAR(encoding_str);
2148 goto error;
2149 }
2150
2151 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2152 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002153 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002154 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002155 Py_CLEAR(encoding_str);
2156 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002157 if (stream == NULL)
2158 goto error;
2159
2160 if (write_mode)
2161 mode = "w";
2162 else
2163 mode = "r";
2164 text = PyUnicode_FromString(mode);
2165 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2166 goto error;
2167 Py_CLEAR(text);
2168 return stream;
2169
2170error:
2171 Py_XDECREF(buf);
2172 Py_XDECREF(stream);
2173 Py_XDECREF(text);
2174 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002175
Victor Stinner874dbe82015-09-04 17:29:57 +02002176 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2177 /* Issue #24891: the file descriptor was closed after the first
2178 is_valid_fd() check was called. Ignore the OSError and set the
2179 stream to None. */
2180 PyErr_Clear();
2181 Py_RETURN_NONE;
2182 }
2183 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002184}
2185
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002186/* Set builtins.open to io.OpenWrapper */
2187static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002188init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002189{
2190 PyObject *iomod = NULL, *wrapper;
2191 PyObject *bimod = NULL;
2192 PyStatus res = _PyStatus_OK();
2193
2194 if (!(iomod = PyImport_ImportModule("io"))) {
2195 goto error;
2196 }
2197
2198 if (!(bimod = PyImport_ImportModule("builtins"))) {
2199 goto error;
2200 }
2201
2202 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2203 goto error;
2204 }
2205
2206 /* Set builtins.open */
2207 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2208 Py_DECREF(wrapper);
2209 goto error;
2210 }
2211 Py_DECREF(wrapper);
2212 goto done;
2213
2214error:
2215 res = _PyStatus_ERR("can't initialize io.open");
2216
2217done:
2218 Py_XDECREF(bimod);
2219 Py_XDECREF(iomod);
2220 return res;
2221}
2222
2223
Nick Coghland6009512014-11-20 21:39:37 +10002224/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002225static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002226init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002227{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002228 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002229 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002230 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002231 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002232 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002233 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002234
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002235 /* Check that stdin is not a directory
2236 Using shell redirection, you can redirect stdin to a directory,
2237 crashing the Python interpreter. Catch this common mistake here
2238 and output a useful error message. Note that under MS Windows,
2239 the shell already prevents that. */
2240#ifndef MS_WINDOWS
2241 struct _Py_stat_struct sb;
2242 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2243 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002244 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002245 }
2246#endif
2247
Nick Coghland6009512014-11-20 21:39:37 +10002248 if (!(iomod = PyImport_ImportModule("io"))) {
2249 goto error;
2250 }
Nick Coghland6009512014-11-20 21:39:37 +10002251
Nick Coghland6009512014-11-20 21:39:37 +10002252 /* Set sys.stdin */
2253 fd = fileno(stdin);
2254 /* Under some conditions stdin, stdout and stderr may not be connected
2255 * and fileno() may point to an invalid file descriptor. For example
2256 * GUI apps don't have valid standard streams by default.
2257 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002258 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002259 config->stdio_encoding,
2260 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002261 if (std == NULL)
2262 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002263 PySys_SetObject("__stdin__", std);
2264 _PySys_SetObjectId(&PyId_stdin, std);
2265 Py_DECREF(std);
2266
2267 /* Set sys.stdout */
2268 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002269 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002270 config->stdio_encoding,
2271 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002272 if (std == NULL)
2273 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002274 PySys_SetObject("__stdout__", std);
2275 _PySys_SetObjectId(&PyId_stdout, std);
2276 Py_DECREF(std);
2277
2278#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2279 /* Set sys.stderr, replaces the preliminary stderr */
2280 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002281 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002282 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002283 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002284 if (std == NULL)
2285 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002286
2287 /* Same as hack above, pre-import stderr's codec to avoid recursion
2288 when import.c tries to write to stderr in verbose mode. */
2289 encoding_attr = PyObject_GetAttrString(std, "encoding");
2290 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002291 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002292 if (std_encoding != NULL) {
2293 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2294 Py_XDECREF(codec_info);
2295 }
2296 Py_DECREF(encoding_attr);
2297 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002298 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002299
2300 if (PySys_SetObject("__stderr__", std) < 0) {
2301 Py_DECREF(std);
2302 goto error;
2303 }
2304 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2305 Py_DECREF(std);
2306 goto error;
2307 }
2308 Py_DECREF(std);
2309#endif
2310
Victor Stinnera7368ac2017-11-15 18:11:45 -08002311 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002312
Victor Stinnera7368ac2017-11-15 18:11:45 -08002313error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002314 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002315
2316done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002317 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002318 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002319 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002320}
2321
2322
Victor Stinner10dc4842015-03-24 12:01:30 +01002323static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002324_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2325 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002326{
Victor Stinner10dc4842015-03-24 12:01:30 +01002327 fputc('\n', stderr);
2328 fflush(stderr);
2329
2330 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002331 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002332}
Victor Stinner791da1c2016-03-14 16:53:12 +01002333
2334/* Print the current exception (if an exception is set) with its traceback,
2335 or display the current Python stack.
2336
2337 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2338 called on catastrophic cases.
2339
2340 Return 1 if the traceback was displayed, 0 otherwise. */
2341
2342static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002343_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002344{
2345 PyObject *ferr, *res;
2346 PyObject *exception, *v, *tb;
2347 int has_tb;
2348
Victor Stinnerb45d2592019-06-20 00:05:23 +02002349 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002350 if (exception == NULL) {
2351 /* No current exception */
2352 return 0;
2353 }
2354
2355 ferr = _PySys_GetObjectId(&PyId_stderr);
2356 if (ferr == NULL || ferr == Py_None) {
2357 /* sys.stderr is not set yet or set to None,
2358 no need to try to display the exception */
2359 return 0;
2360 }
2361
Victor Stinnerb45d2592019-06-20 00:05:23 +02002362 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002363 if (tb == NULL) {
2364 tb = Py_None;
2365 Py_INCREF(tb);
2366 }
2367 PyException_SetTraceback(v, tb);
2368 if (exception == NULL) {
2369 /* PyErr_NormalizeException() failed */
2370 return 0;
2371 }
2372
2373 has_tb = (tb != Py_None);
2374 PyErr_Display(exception, v, tb);
2375 Py_XDECREF(exception);
2376 Py_XDECREF(v);
2377 Py_XDECREF(tb);
2378
2379 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002380 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002381 if (res == NULL) {
2382 _PyErr_Clear(tstate);
2383 }
2384 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002385 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002386 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002387
2388 return has_tb;
2389}
2390
Nick Coghland6009512014-11-20 21:39:37 +10002391/* Print fatal error message and abort */
2392
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002393#ifdef MS_WINDOWS
2394static void
2395fatal_output_debug(const char *msg)
2396{
2397 /* buffer of 256 bytes allocated on the stack */
2398 WCHAR buffer[256 / sizeof(WCHAR)];
2399 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2400 size_t msglen;
2401
2402 OutputDebugStringW(L"Fatal Python error: ");
2403
2404 msglen = strlen(msg);
2405 while (msglen) {
2406 size_t i;
2407
2408 if (buflen > msglen) {
2409 buflen = msglen;
2410 }
2411
2412 /* Convert the message to wchar_t. This uses a simple one-to-one
2413 conversion, assuming that the this error message actually uses
2414 ASCII only. If this ceases to be true, we will have to convert. */
2415 for (i=0; i < buflen; ++i) {
2416 buffer[i] = msg[i];
2417 }
2418 buffer[i] = L'\0';
2419 OutputDebugStringW(buffer);
2420
2421 msg += buflen;
2422 msglen -= buflen;
2423 }
2424 OutputDebugStringW(L"\n");
2425}
2426#endif
2427
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002428
2429static void
2430fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2431{
2432 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002433 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2434 if (finalizing) {
2435 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002436 }
2437 else if (runtime->initialized) {
2438 fprintf(stream, "initialized");
2439 }
2440 else if (runtime->core_initialized) {
2441 fprintf(stream, "core initialized");
2442 }
2443 else if (runtime->preinitialized) {
2444 fprintf(stream, "preinitialized");
2445 }
2446 else if (runtime->preinitializing) {
2447 fprintf(stream, "preinitializing");
2448 }
2449 else {
2450 fprintf(stream, "unknown");
2451 }
2452 fprintf(stream, "\n");
2453 fflush(stream);
2454}
2455
2456
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002457static inline void _Py_NO_RETURN
2458fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002459{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002460 if (status < 0) {
2461#if defined(MS_WINDOWS) && defined(_DEBUG)
2462 DebugBreak();
2463#endif
2464 abort();
2465 }
2466 else {
2467 exit(status);
2468 }
2469}
2470
2471
2472static void _Py_NO_RETURN
2473fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2474 int status)
2475{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002476 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002477 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002478
2479 if (reentrant) {
2480 /* Py_FatalError() caused a second fatal error.
2481 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002482 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002483 }
2484 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002485
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002486 if (header) {
2487 fprintf(stream, "Fatal Python error: ");
2488 if (prefix) {
2489 fputs(prefix, stream);
2490 fputs(": ", stream);
2491 }
2492 if (msg) {
2493 fputs(msg, stream);
2494 }
2495 else {
2496 fprintf(stream, "<message not set>");
2497 }
2498 fputs("\n", stream);
2499 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002500 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002501
2502 _PyRuntimeState *runtime = &_PyRuntime;
2503 fatal_error_dump_runtime(stream, runtime);
2504
2505 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2506 PyInterpreterState *interp = NULL;
2507 if (tstate != NULL) {
2508 interp = tstate->interp;
2509 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002510
Victor Stinner3a228ab2018-11-01 00:26:41 +01002511 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002512 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002513
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002514 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2515 has no Python thread state.
2516
2517 tss_tstate != tstate if the current Python thread does not hold the GIL.
2518 */
2519 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2520 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002521 if (has_tstate_and_gil) {
2522 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002523 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002524 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002525 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002526 }
2527 }
2528 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002529 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002530 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002531
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002532 /* The main purpose of faulthandler is to display the traceback.
2533 This function already did its best to display a traceback.
2534 Disable faulthandler to prevent writing a second traceback
2535 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002536 _PyFaulthandler_Fini();
2537
Victor Stinner791da1c2016-03-14 16:53:12 +01002538 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002539 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002540 /* Flush sys.stdout and sys.stderr */
2541 flush_std_files();
2542 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002543
Nick Coghland6009512014-11-20 21:39:37 +10002544#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002545 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002546#endif /* MS_WINDOWS */
2547
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002548 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002549}
2550
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002551
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002552#undef Py_FatalError
2553
Victor Stinner19760862017-12-20 01:41:59 +01002554void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002555Py_FatalError(const char *msg)
2556{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002557 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002558}
2559
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002560
Victor Stinner19760862017-12-20 01:41:59 +01002561void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002562_Py_FatalErrorFunc(const char *func, const char *msg)
2563{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002564 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002565}
2566
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002567
2568void _Py_NO_RETURN
2569_Py_FatalErrorFormat(const char *func, const char *format, ...)
2570{
2571 static int reentrant = 0;
2572 if (reentrant) {
2573 /* _Py_FatalErrorFormat() caused a second fatal error */
2574 fatal_error_exit(-1);
2575 }
2576 reentrant = 1;
2577
2578 FILE *stream = stderr;
2579 fprintf(stream, "Fatal Python error: ");
2580 if (func) {
2581 fputs(func, stream);
2582 fputs(": ", stream);
2583 }
2584 fflush(stream);
2585
2586 va_list vargs;
2587#ifdef HAVE_STDARG_PROTOTYPES
2588 va_start(vargs, format);
2589#else
2590 va_start(vargs);
2591#endif
2592 vfprintf(stream, format, vargs);
2593 va_end(vargs);
2594
2595 fputs("\n", stream);
2596 fflush(stream);
2597
2598 fatal_error(stream, 0, NULL, NULL, -1);
2599}
2600
2601
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002602void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002603Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002604{
Victor Stinner331a6a52019-05-27 16:39:22 +02002605 if (_PyStatus_IS_EXIT(status)) {
2606 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002607 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002608 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002609 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002610 }
2611 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002612 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002613 }
Nick Coghland6009512014-11-20 21:39:37 +10002614}
2615
2616/* Clean up and exit */
2617
Nick Coghland6009512014-11-20 21:39:37 +10002618/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002619void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002620{
Victor Stinner81a7be32020-04-14 15:14:01 +02002621 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002622
Antoine Pitroufc5db952017-12-13 02:29:07 +01002623 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002624 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2625
2626 is->pyexitfunc = func;
2627 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002628}
2629
2630static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002631call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002632{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002633 PyInterpreterState *interp = tstate->interp;
2634 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002635 return;
2636
Victor Stinnerb45d2592019-06-20 00:05:23 +02002637 (*interp->pyexitfunc)(interp->pyexitmodule);
2638 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002639}
2640
2641/* Wait until threading._shutdown completes, provided
2642 the threading module was imported in the first place.
2643 The shutdown routine will wait until all non-daemon
2644 "threading" threads have completed. */
2645static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002646wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002647{
Nick Coghland6009512014-11-20 21:39:37 +10002648 _Py_IDENTIFIER(_shutdown);
2649 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002650 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002651 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002652 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002653 PyErr_WriteUnraisable(NULL);
2654 }
2655 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002656 return;
2657 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002658 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002659 if (result == NULL) {
2660 PyErr_WriteUnraisable(threading);
2661 }
2662 else {
2663 Py_DECREF(result);
2664 }
2665 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002666}
2667
2668#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002669int Py_AtExit(void (*func)(void))
2670{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002671 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002672 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002673 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002674 return 0;
2675}
2676
2677static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002678call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002679{
Victor Stinner8e91c242019-04-24 17:24:01 +02002680 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002681 /* pop last function from the list */
2682 runtime->nexitfuncs--;
2683 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2684 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2685
2686 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002687 }
Nick Coghland6009512014-11-20 21:39:37 +10002688
2689 fflush(stdout);
2690 fflush(stderr);
2691}
2692
Victor Stinnercfc88312018-08-01 16:41:25 +02002693void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002694Py_Exit(int sts)
2695{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002696 if (Py_FinalizeEx() < 0) {
2697 sts = 120;
2698 }
Nick Coghland6009512014-11-20 21:39:37 +10002699
2700 exit(sts);
2701}
2702
Victor Stinner331a6a52019-05-27 16:39:22 +02002703static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002704init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002705{
2706#ifdef SIGPIPE
2707 PyOS_setsig(SIGPIPE, SIG_IGN);
2708#endif
2709#ifdef SIGXFZ
2710 PyOS_setsig(SIGXFZ, SIG_IGN);
2711#endif
2712#ifdef SIGXFSZ
2713 PyOS_setsig(SIGXFSZ, SIG_IGN);
2714#endif
Victor Stinner400e1db2020-03-31 19:13:10 +02002715 PyOS_InitInterrupts(); /* May imply init_signals() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002716 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002717 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002718 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002719 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002720}
2721
2722
2723/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2724 *
2725 * All of the code in this function must only use async-signal-safe functions,
2726 * listed at `man 7 signal` or
2727 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002728 *
2729 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002730 */
2731void
2732_Py_RestoreSignals(void)
2733{
2734#ifdef SIGPIPE
2735 PyOS_setsig(SIGPIPE, SIG_DFL);
2736#endif
2737#ifdef SIGXFZ
2738 PyOS_setsig(SIGXFZ, SIG_DFL);
2739#endif
2740#ifdef SIGXFSZ
2741 PyOS_setsig(SIGXFSZ, SIG_DFL);
2742#endif
2743}
2744
2745
2746/*
2747 * The file descriptor fd is considered ``interactive'' if either
2748 * a) isatty(fd) is TRUE, or
2749 * b) the -i flag was given, and the filename associated with
2750 * the descriptor is NULL or "<stdin>" or "???".
2751 */
2752int
2753Py_FdIsInteractive(FILE *fp, const char *filename)
2754{
2755 if (isatty((int)fileno(fp)))
2756 return 1;
2757 if (!Py_InteractiveFlag)
2758 return 0;
2759 return (filename == NULL) ||
2760 (strcmp(filename, "<stdin>") == 0) ||
2761 (strcmp(filename, "???") == 0);
2762}
2763
2764
Nick Coghland6009512014-11-20 21:39:37 +10002765/* Wrappers around sigaction() or signal(). */
2766
2767PyOS_sighandler_t
2768PyOS_getsig(int sig)
2769{
2770#ifdef HAVE_SIGACTION
2771 struct sigaction context;
2772 if (sigaction(sig, NULL, &context) == -1)
2773 return SIG_ERR;
2774 return context.sa_handler;
2775#else
2776 PyOS_sighandler_t handler;
2777/* Special signal handling for the secure CRT in Visual Studio 2005 */
2778#if defined(_MSC_VER) && _MSC_VER >= 1400
2779 switch (sig) {
2780 /* Only these signals are valid */
2781 case SIGINT:
2782 case SIGILL:
2783 case SIGFPE:
2784 case SIGSEGV:
2785 case SIGTERM:
2786 case SIGBREAK:
2787 case SIGABRT:
2788 break;
2789 /* Don't call signal() with other values or it will assert */
2790 default:
2791 return SIG_ERR;
2792 }
2793#endif /* _MSC_VER && _MSC_VER >= 1400 */
2794 handler = signal(sig, SIG_IGN);
2795 if (handler != SIG_ERR)
2796 signal(sig, handler);
2797 return handler;
2798#endif
2799}
2800
2801/*
2802 * All of the code in this function must only use async-signal-safe functions,
2803 * listed at `man 7 signal` or
2804 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2805 */
2806PyOS_sighandler_t
2807PyOS_setsig(int sig, PyOS_sighandler_t handler)
2808{
2809#ifdef HAVE_SIGACTION
2810 /* Some code in Modules/signalmodule.c depends on sigaction() being
2811 * used here if HAVE_SIGACTION is defined. Fix that if this code
2812 * changes to invalidate that assumption.
2813 */
2814 struct sigaction context, ocontext;
2815 context.sa_handler = handler;
2816 sigemptyset(&context.sa_mask);
2817 context.sa_flags = 0;
2818 if (sigaction(sig, &context, &ocontext) == -1)
2819 return SIG_ERR;
2820 return ocontext.sa_handler;
2821#else
2822 PyOS_sighandler_t oldhandler;
2823 oldhandler = signal(sig, handler);
2824#ifdef HAVE_SIGINTERRUPT
2825 siginterrupt(sig, 1);
2826#endif
2827 return oldhandler;
2828#endif
2829}
2830
2831#ifdef __cplusplus
2832}
2833#endif