blob: d03c6c07f710881a9b09fadf2e86e5b86d7f0cab [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +02007
8#include "pycore_ceval.h" // _PyEval_FiniGIL()
9#include "pycore_context.h" // _PyContext_Init()
10#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinner62230712020-11-18 23:18:29 +010011#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner4f98f462020-04-15 04:01:58 +020012#include "pycore_initconfig.h" // _PyStatus_OK()
13#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
14#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
15#include "pycore_pyerrors.h" // _PyErr_Occurred()
16#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020017#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020018#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
19#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
20
Victor Stinner4f98f462020-04-15 04:01:58 +020021#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100022
23#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020024# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100025#endif
26
27#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020028# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100029#endif
30
31#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020032# undef BYTE
33# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070034
Victor Stinner4f98f462020-04-15 04:01:58 +020035 extern PyTypeObject PyWindowsConsoleIO_Type;
36# define PyWindowsConsoleIO_Check(op) \
37 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
Victor Stinner4f98f462020-04-15 04:01:58 +020040
Victor Stinner314b8782021-01-18 18:34:56 +010041#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
42
43
Nick Coghland6009512014-11-20 21:39:37 +100044_Py_IDENTIFIER(flush);
45_Py_IDENTIFIER(name);
46_Py_IDENTIFIER(stdin);
47_Py_IDENTIFIER(stdout);
48_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060049_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100050
51#ifdef __cplusplus
52extern "C" {
53#endif
54
Nick Coghland6009512014-11-20 21:39:37 +100055
Victor Stinnerb45d2592019-06-20 00:05:23 +020056/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020057static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020058static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050059static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020060static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020061static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020062static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100063
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080064int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080065_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010066static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067
Victor Stinner331a6a52019-05-27 16:39:22 +020068PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060069_PyRuntime_Initialize(void)
70{
71 /* XXX We only initialize once in the process, which aligns with
72 the static initialization of the former globals now found in
73 _PyRuntime. However, _PyRuntime *should* be initialized with
74 every Py_Initialize() call, but doing so breaks the runtime.
75 This is because the runtime state is not properly finalized
76 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010077 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020078 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010080 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081
82 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083}
84
85void
86_PyRuntime_Finalize(void)
87{
88 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010089 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090}
91
92int
93_Py_IsFinalizing(void)
94{
Victor Stinner7b3c2522020-03-07 00:24:23 +010095 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
Nick Coghland6009512014-11-20 21:39:37 +100098/* Hack to force loading of object files */
99int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
100 PyOS_mystrnicmp; /* Python/pystrcmp.o */
101
Eric Snowc7ec9982017-05-23 23:00:52 -0700102
Eric Snow1abcf672017-05-23 21:46:51 -0700103/* APIs to access the initialization flags
104 *
105 * Can be called prior to Py_Initialize.
106 */
Nick Coghland6009512014-11-20 21:39:37 +1000107
Eric Snow1abcf672017-05-23 21:46:51 -0700108int
109_Py_IsCoreInitialized(void)
110{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600111 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700112}
Nick Coghland6009512014-11-20 21:39:37 +1000113
114int
115Py_IsInitialized(void)
116{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000118}
119
Nick Coghlan6ea41862017-06-11 13:16:15 +1000120
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000121/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
122 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000123 initializations fail, a fatal error is issued and the function does
124 not return. On return, the first thread and interpreter state have
125 been created.
126
127 Locking: you must hold the interpreter lock while calling this.
128 (If the lock has not yet been initialized, that's equivalent to
129 having the lock, but you cannot use multiple threads.)
130
131*/
Victor Stinneref75a622020-11-12 15:14:13 +0100132static int
Victor Stinnerb45d2592019-06-20 00:05:23 +0200133init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000134{
Victor Stinneref75a622020-11-12 15:14:13 +0100135 assert(!_PyErr_Occurred(tstate));
136
Victor Stinnerb45d2592019-06-20 00:05:23 +0200137 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200138 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000139
Victor Stinneref75a622020-11-12 15:14:13 +0100140 // Import _importlib through its frozen version, _frozen_importlib.
141 if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000142 PySys_FormatStderr("import _frozen_importlib # frozen\n");
143 }
Victor Stinneref75a622020-11-12 15:14:13 +0100144 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
145 return -1;
146 }
147 PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
Nick Coghland6009512014-11-20 21:39:37 +1000148 if (importlib == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100149 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000150 }
Victor Stinneref75a622020-11-12 15:14:13 +0100151 interp->importlib = Py_NewRef(importlib);
Nick Coghland6009512014-11-20 21:39:37 +1000152
Victor Stinneref75a622020-11-12 15:14:13 +0100153 // Import the _imp module
154 if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200155 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000156 }
Victor Stinner62230712020-11-18 23:18:29 +0100157 PyObject *imp_mod = _PyImport_BootstrapImp(tstate);
Victor Stinneref75a622020-11-12 15:14:13 +0100158 if (imp_mod == NULL) {
159 return -1;
160 }
161 if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
162 Py_DECREF(imp_mod);
163 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000164 }
165
Victor Stinneref75a622020-11-12 15:14:13 +0100166 // Install importlib as the implementation of import
167 PyObject *value = PyObject_CallMethod(importlib, "_install",
168 "OO", sysmod, imp_mod);
169 Py_DECREF(imp_mod);
Nick Coghland6009512014-11-20 21:39:37 +1000170 if (value == NULL) {
Victor Stinneref75a622020-11-12 15:14:13 +0100171 return -1;
Nick Coghland6009512014-11-20 21:39:37 +1000172 }
173 Py_DECREF(value);
Nick Coghland6009512014-11-20 21:39:37 +1000174
Victor Stinneref75a622020-11-12 15:14:13 +0100175 assert(!_PyErr_Occurred(tstate));
176 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000177}
178
Victor Stinneref75a622020-11-12 15:14:13 +0100179
Victor Stinner331a6a52019-05-27 16:39:22 +0200180static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200181init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700182{
183 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200184 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700185 "_install_external_importers", "");
186 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200187 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700189 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200190 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200191 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700192}
Nick Coghland6009512014-11-20 21:39:37 +1000193
Nick Coghlan6ea41862017-06-11 13:16:15 +1000194/* Helper functions to better handle the legacy C locale
195 *
196 * The legacy C locale assumes ASCII as the default text encoding, which
197 * causes problems not only for the CPython runtime, but also other
198 * components like GNU readline.
199 *
200 * Accordingly, when the CLI detects it, it attempts to coerce it to a
201 * more capable UTF-8 based alternative as follows:
202 *
203 * if (_Py_LegacyLocaleDetected()) {
204 * _Py_CoerceLegacyLocale();
205 * }
206 *
207 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
208 *
209 * Locale coercion also impacts the default error handler for the standard
210 * streams: while the usual default is "strict", the default for the legacy
211 * C locale and for any of the coercion target locales is "surrogateescape".
212 */
213
214int
Victor Stinner0f721472019-05-20 17:16:38 +0200215_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000216{
217#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200218 if (!warn) {
219 const char *locale_override = getenv("LC_ALL");
220 if (locale_override != NULL && *locale_override != '\0') {
221 /* Don't coerce C locale if the LC_ALL environment variable
222 is set */
223 return 0;
224 }
225 }
226
Nick Coghlan6ea41862017-06-11 13:16:15 +1000227 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000228 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
229 * the POSIX locale as a simple alias for the C locale, so
230 * we may also want to check for that explicitly.
231 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000232 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
233 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
234#else
235 /* Windows uses code pages instead of locales, so no locale is legacy */
236 return 0;
237#endif
238}
239
Victor Stinnerb0051362019-11-22 17:52:42 +0100240#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000241static const char *_C_LOCALE_WARNING =
242 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
243 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
244 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
245 "locales is recommended.\n";
246
Nick Coghlaneb817952017-06-18 12:29:42 +1000247static void
Victor Stinner43125222019-04-24 18:23:53 +0200248emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000249{
Victor Stinner331a6a52019-05-27 16:39:22 +0200250 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200251 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200252 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000253 }
254}
Victor Stinnerb0051362019-11-22 17:52:42 +0100255#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000256
Nick Coghlan6ea41862017-06-11 13:16:15 +1000257typedef struct _CandidateLocale {
258 const char *locale_name; /* The locale to try as a coercion target */
259} _LocaleCoercionTarget;
260
261static _LocaleCoercionTarget _TARGET_LOCALES[] = {
262 {"C.UTF-8"},
263 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000264 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000265 {NULL}
266};
267
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200268
269int
270_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000271{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200272 const _LocaleCoercionTarget *target = NULL;
273 for (target = _TARGET_LOCALES; target->locale_name; target++) {
274 if (strcmp(ctype_loc, target->locale_name) == 0) {
275 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200277 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200278 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000279}
280
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200281
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100283static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000284 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
285 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
286
Victor Stinner0f721472019-05-20 17:16:38 +0200287static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200288_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289{
290 const char *newloc = target->locale_name;
291
292 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100293 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294
295 /* Set the relevant locale environment variable */
296 if (setenv("LC_CTYPE", newloc, 1)) {
297 fprintf(stderr,
298 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200299 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200301 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100302 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000303 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000304
305 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100306 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200307 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000308}
309#endif
310
Victor Stinner0f721472019-05-20 17:16:38 +0200311int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200312_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313{
Victor Stinner0f721472019-05-20 17:16:38 +0200314 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200316 char *oldloc = NULL;
317
318 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
319 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200320 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200321 }
322
Victor Stinner94540602017-12-16 04:54:22 +0100323 const char *locale_override = getenv("LC_ALL");
324 if (locale_override == NULL || *locale_override == '\0') {
325 /* LC_ALL is also not set (or is set to an empty string) */
326 const _LocaleCoercionTarget *target = NULL;
327 for (target = _TARGET_LOCALES; target->locale_name; target++) {
328 const char *new_locale = setlocale(LC_CTYPE,
329 target->locale_name);
330 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400331#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100332 /* Also ensure that nl_langinfo works in this locale */
333 char *codeset = nl_langinfo(CODESET);
334 if (!codeset || *codeset == '\0') {
335 /* CODESET is not set or empty, so skip coercion */
336 new_locale = NULL;
337 _Py_SetLocaleFromEnv(LC_CTYPE);
338 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000339 }
Victor Stinner94540602017-12-16 04:54:22 +0100340#endif
341 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200342 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200343 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000344 }
345 }
346 }
347 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200348
349 setlocale(LC_CTYPE, oldloc);
350
351done:
352 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000353#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200354 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000355}
356
xdegaye1588be62017-11-12 12:45:59 +0100357/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
358 * isolate the idiosyncrasies of different libc implementations. It reads the
359 * appropriate environment variable and uses its value to select the locale for
360 * 'category'. */
361char *
362_Py_SetLocaleFromEnv(int category)
363{
Victor Stinner353933e2018-11-23 13:08:26 +0100364 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100365#ifdef __ANDROID__
366 const char *locale;
367 const char **pvar;
368#ifdef PY_COERCE_C_LOCALE
369 const char *coerce_c_locale;
370#endif
371 const char *utf8_locale = "C.UTF-8";
372 const char *env_var_set[] = {
373 "LC_ALL",
374 "LC_CTYPE",
375 "LANG",
376 NULL,
377 };
378
379 /* Android setlocale(category, "") doesn't check the environment variables
380 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
381 * check the environment variables listed in env_var_set. */
382 for (pvar=env_var_set; *pvar; pvar++) {
383 locale = getenv(*pvar);
384 if (locale != NULL && *locale != '\0') {
385 if (strcmp(locale, utf8_locale) == 0 ||
386 strcmp(locale, "en_US.UTF-8") == 0) {
387 return setlocale(category, utf8_locale);
388 }
389 return setlocale(category, "C");
390 }
391 }
392
393 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
394 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
395 * Quote from POSIX section "8.2 Internationalization Variables":
396 * "4. If the LANG environment variable is not set or is set to the empty
397 * string, the implementation-defined default locale shall be used." */
398
399#ifdef PY_COERCE_C_LOCALE
400 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
401 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
402 /* Some other ported code may check the environment variables (e.g. in
403 * extension modules), so we make sure that they match the locale
404 * configuration */
405 if (setenv("LC_CTYPE", utf8_locale, 1)) {
406 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
407 "environment variable to %s\n", utf8_locale);
408 }
409 }
410#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100411 res = setlocale(category, utf8_locale);
412#else /* !defined(__ANDROID__) */
413 res = setlocale(category, "");
414#endif
415 _Py_ResetForceASCII();
416 return res;
xdegaye1588be62017-11-12 12:45:59 +0100417}
418
Nick Coghlan6ea41862017-06-11 13:16:15 +1000419
Victor Stinner048a3562020-11-05 00:45:56 +0100420static int
Victor Stinner9e1b8282020-11-10 13:21:52 +0100421interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
Victor Stinner048a3562020-11-05 00:45:56 +0100422{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100423 const PyConfig *config = &tstate->interp->config;
Victor Stinner048a3562020-11-05 00:45:56 +0100424
Victor Stinner9e1b8282020-11-10 13:21:52 +0100425 if (!only_update_path_config) {
426 PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
427 if (_PyStatus_EXCEPTION(status)) {
428 _PyErr_SetFromPyStatus(status);
429 return -1;
430 }
Victor Stinner048a3562020-11-05 00:45:56 +0100431 }
432
Victor Stinner101bf692021-02-19 13:33:31 +0100433 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner9e1b8282020-11-10 13:21:52 +0100434 PyStatus status = _PyConfig_WritePathConfig(config);
Victor Stinner048a3562020-11-05 00:45:56 +0100435 if (_PyStatus_EXCEPTION(status)) {
436 _PyErr_SetFromPyStatus(status);
437 return -1;
438 }
439 }
440
441 // Update the sys module for the new configuration
442 if (_PySys_UpdateConfig(tstate) < 0) {
443 return -1;
444 }
445 return 0;
446}
447
448
449int
450_PyInterpreterState_SetConfig(const PyConfig *src_config)
451{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100452 PyThreadState *tstate = PyThreadState_Get();
Victor Stinner048a3562020-11-05 00:45:56 +0100453 int res = -1;
454
455 PyConfig config;
456 PyConfig_InitPythonConfig(&config);
457 PyStatus status = _PyConfig_Copy(&config, src_config);
458 if (_PyStatus_EXCEPTION(status)) {
459 _PyErr_SetFromPyStatus(status);
460 goto done;
461 }
462
463 status = PyConfig_Read(&config);
464 if (_PyStatus_EXCEPTION(status)) {
465 _PyErr_SetFromPyStatus(status);
466 goto done;
467 }
468
Victor Stinner9e1b8282020-11-10 13:21:52 +0100469 status = _PyConfig_Copy(&tstate->interp->config, &config);
470 if (_PyStatus_EXCEPTION(status)) {
471 _PyErr_SetFromPyStatus(status);
472 goto done;
473 }
474
475 res = interpreter_update_config(tstate, 0);
Victor Stinner048a3562020-11-05 00:45:56 +0100476
477done:
478 PyConfig_Clear(&config);
479 return res;
480}
481
482
Eric Snow1abcf672017-05-23 21:46:51 -0700483/* Global initializations. Can be undone by Py_Finalize(). Don't
484 call this twice without an intervening Py_Finalize() call.
485
Victor Stinner331a6a52019-05-27 16:39:22 +0200486 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700487 must have a corresponding call to Py_Finalize.
488
489 Locking: you must hold the interpreter lock while calling these APIs.
490 (If the lock has not yet been initialized, that's equivalent to
491 having the lock, but you cannot use multiple threads.)
492
493*/
494
Victor Stinner331a6a52019-05-27 16:39:22 +0200495static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200496pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200497 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200498 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200499{
Victor Stinner331a6a52019-05-27 16:39:22 +0200500 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100501 PyThreadState *tstate = _PyThreadState_GET();
502 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200503 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100504 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200505 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100506
507 PyInterpreterState *interp = tstate->interp;
508 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200509 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100510 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100511
Victor Stinnere81f6e62020-06-08 18:12:59 +0200512 status = _PyConfig_Write(config, runtime);
513 if (_PyStatus_EXCEPTION(status)) {
514 return status;
515 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200516
Victor Stinner048a3562020-11-05 00:45:56 +0100517 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200518 if (_PyStatus_EXCEPTION(status)) {
519 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200520 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200521 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200522
Victor Stinner331a6a52019-05-27 16:39:22 +0200523 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200524 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200525 if (_PyStatus_EXCEPTION(status)) {
526 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527 }
528 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200529 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200530}
531
532
Victor Stinner331a6a52019-05-27 16:39:22 +0200533static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200534pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000536{
Victor Stinner43125222019-04-24 18:23:53 +0200537 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200538 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200539 }
Victor Stinnerda273412017-12-15 01:46:02 +0100540
Victor Stinnere81f6e62020-06-08 18:12:59 +0200541 PyStatus status = _PyConfig_Write(config, runtime);
542 if (_PyStatus_EXCEPTION(status)) {
543 return status;
544 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600545
Eric Snow1abcf672017-05-23 21:46:51 -0700546 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
547 * threads behave a little more gracefully at interpreter shutdown.
548 * We clobber it here so the new interpreter can start with a clean
549 * slate.
550 *
551 * However, this may still lead to misbehaviour if there are daemon
552 * threads still hanging around from a previous Py_Initialize/Finalize
553 * pair :(
554 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100555 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600556
Victor Stinnere81f6e62020-06-08 18:12:59 +0200557 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200558 if (_PyStatus_EXCEPTION(status)) {
559 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800560 }
561
Victor Stinner331a6a52019-05-27 16:39:22 +0200562 status = _PyInterpreterState_Enable(runtime);
563 if (_PyStatus_EXCEPTION(status)) {
564 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800565 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200566 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100567}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800568
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100569
Victor Stinner331a6a52019-05-27 16:39:22 +0200570static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200571init_interp_create_gil(PyThreadState *tstate)
572{
573 PyStatus status;
574
575 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
576 only called here. */
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100577 _PyEval_FiniGIL(tstate->interp);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200578
579 /* Auto-thread-state API */
580 status = _PyGILState_Init(tstate);
581 if (_PyStatus_EXCEPTION(status)) {
582 return status;
583 }
584
585 /* Create the GIL and take it */
586 status = _PyEval_InitGIL(tstate);
587 if (_PyStatus_EXCEPTION(status)) {
588 return status;
589 }
590
591 return _PyStatus_OK();
592}
593
594
595static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200596pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200597 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200598 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100599{
600 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100601 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200602 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100603 }
604
Victor Stinner048a3562020-11-05 00:45:56 +0100605 PyStatus status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200606 if (_PyStatus_EXCEPTION(status)) {
607 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100608 }
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200610 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200611 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200612 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200613 }
Nick Coghland6009512014-11-20 21:39:37 +1000614 (void) PyThreadState_Swap(tstate);
615
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200616 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100617 if (_PyStatus_EXCEPTION(status)) {
618 return status;
619 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100620
Victor Stinnerb45d2592019-06-20 00:05:23 +0200621 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200622 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100623}
Nick Coghland6009512014-11-20 21:39:37 +1000624
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100625
Victor Stinner331a6a52019-05-27 16:39:22 +0200626static PyStatus
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100627pycore_init_types(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100628{
Victor Stinner444b39b2019-11-20 01:18:11 +0100629 PyStatus status;
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100630 int is_main_interp = _Py_IsMainInterpreter(interp);
Victor Stinner444b39b2019-11-20 01:18:11 +0100631
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100632 status = _PyGC_Init(interp);
Victor Stinner444b39b2019-11-20 01:18:11 +0100633 if (_PyStatus_EXCEPTION(status)) {
634 return status;
635 }
636
Victor Stinner0430dfa2020-06-24 15:21:54 +0200637 // Create the empty tuple singleton. It must be created before the first
638 // PyType_Ready() call since PyType_Ready() creates tuples, for tp_bases
639 // for example.
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100640 status = _PyTuple_Init(interp);
Victor Stinner0430dfa2020-06-24 15:21:54 +0200641 if (_PyStatus_EXCEPTION(status)) {
642 return status;
643 }
644
Victor Stinnere7e699e2019-11-20 12:08:13 +0100645 if (is_main_interp) {
646 status = _PyTypes_Init();
647 if (_PyStatus_EXCEPTION(status)) {
648 return status;
649 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100650 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100651
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100652 if (!_PyLong_Init(interp)) {
Victor Stinner630c8df2019-12-17 13:02:18 +0100653 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100654 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100655
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100656 status = _PyUnicode_Init(interp);
Victor Stinnerf363d0a2020-06-24 00:10:40 +0200657 if (_PyStatus_EXCEPTION(status)) {
658 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100659 }
660
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100661 status = _PyBytes_Init(interp);
Victor Stinner91698d82020-06-25 14:07:40 +0200662 if (_PyStatus_EXCEPTION(status)) {
663 return status;
664 }
665
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100666 status = _PyExc_Init(interp);
Victor Stinner331a6a52019-05-27 16:39:22 +0200667 if (_PyStatus_EXCEPTION(status)) {
668 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 }
670
Victor Stinnere7e699e2019-11-20 12:08:13 +0100671 if (is_main_interp) {
672 if (!_PyFloat_Init()) {
673 return _PyStatus_ERR("can't init float");
674 }
Nick Coghland6009512014-11-20 21:39:37 +1000675
Victor Stinnere7e699e2019-11-20 12:08:13 +0100676 if (_PyStructSequence_Init() < 0) {
677 return _PyStatus_ERR("can't initialize structseq");
678 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100679 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200680
Victor Stinner331a6a52019-05-27 16:39:22 +0200681 status = _PyErr_Init();
682 if (_PyStatus_EXCEPTION(status)) {
683 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200684 }
685
Victor Stinnere7e699e2019-11-20 12:08:13 +0100686 if (is_main_interp) {
687 if (!_PyContext_Init()) {
688 return _PyStatus_ERR("can't init context");
689 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100690 }
691
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100692 if (_PyWarnings_InitState(interp) < 0) {
Victor Stinneref75a622020-11-12 15:14:13 +0100693 return _PyStatus_ERR("can't initialize warnings");
694 }
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100695
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100696 status = _PyAtExit_Init(interp);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100697 if (_PyStatus_EXCEPTION(status)) {
698 return status;
699 }
700
Victor Stinner331a6a52019-05-27 16:39:22 +0200701 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100702}
703
704
Victor Stinner331a6a52019-05-27 16:39:22 +0200705static PyStatus
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100706pycore_init_builtins(PyInterpreterState *interp)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100707{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100708 PyObject *bimod = _PyBuiltin_Init(interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100709 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100710 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100712
Victor Stinner2582d462019-11-22 19:24:49 +0100713 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
714 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100715 }
Victor Stinner2582d462019-11-22 19:24:49 +0100716
717 PyObject *builtins_dict = PyModule_GetDict(bimod);
718 if (builtins_dict == NULL) {
719 goto error;
720 }
721 Py_INCREF(builtins_dict);
722 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100723
Victor Stinner331a6a52019-05-27 16:39:22 +0200724 PyStatus status = _PyBuiltins_AddExceptions(bimod);
725 if (_PyStatus_EXCEPTION(status)) {
726 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100727 }
Victor Stinner2582d462019-11-22 19:24:49 +0100728
729 interp->builtins_copy = PyDict_Copy(interp->builtins);
730 if (interp->builtins_copy == NULL) {
731 goto error;
732 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000733 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100734
Victor Stinner62230712020-11-18 23:18:29 +0100735 // Get the __import__ function
736 PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
737 "__import__");
738 if (import_func == NULL) {
739 goto error;
740 }
741 interp->import_func = Py_NewRef(import_func);
742
Victor Stinner331a6a52019-05-27 16:39:22 +0200743 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100744
745error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000746 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100747 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100748}
749
750
Victor Stinner331a6a52019-05-27 16:39:22 +0200751static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100752pycore_interp_init(PyThreadState *tstate)
753{
754 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100755 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100756
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100757 status = pycore_init_types(tstate->interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100758 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100759 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100760 }
761
Victor Stinnerd863ade2019-12-06 03:37:07 +0100762 status = _PySys_Create(tstate, &sysmod);
763 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100764 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100765 }
766
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100767 assert(!_PyErr_Occurred(tstate));
768
769 status = pycore_init_builtins(tstate->interp);
Victor Stinnerd863ade2019-12-06 03:37:07 +0100770 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100771 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100772 }
773
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100774 assert(!_PyErr_Occurred(tstate));
775
Victor Stinneref75a622020-11-12 15:14:13 +0100776 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
777 if (config->_install_importlib) {
778 /* This call sets up builtin and frozen import support */
779 if (init_importlib(tstate, sysmod) < 0) {
780 return _PyStatus_ERR("failed to initialize importlib");
781 }
782 }
Victor Stinner080ee5a2019-12-08 21:55:58 +0100783
784done:
785 /* sys.modules['sys'] contains a strong reference to the module */
786 Py_XDECREF(sysmod);
787 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100788}
789
790
791static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200792pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200793 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200794 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100795{
Victor Stinner331a6a52019-05-27 16:39:22 +0200796 PyStatus status = pycore_init_runtime(runtime, config);
797 if (_PyStatus_EXCEPTION(status)) {
798 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100799 }
800
Victor Stinnerb45d2592019-06-20 00:05:23 +0200801 PyThreadState *tstate;
802 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200803 if (_PyStatus_EXCEPTION(status)) {
804 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100805 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200806 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100807
Victor Stinnerd863ade2019-12-06 03:37:07 +0100808 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200809 if (_PyStatus_EXCEPTION(status)) {
810 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100811 }
Eric Snow1abcf672017-05-23 21:46:51 -0700812
813 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200814 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200815 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700816}
817
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100818
Victor Stinner331a6a52019-05-27 16:39:22 +0200819PyStatus
820_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100821{
Victor Stinner331a6a52019-05-27 16:39:22 +0200822 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100823
Victor Stinner6d1c4672019-05-20 11:02:00 +0200824 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200825 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200826 }
827
Victor Stinner331a6a52019-05-27 16:39:22 +0200828 status = _PyRuntime_Initialize();
829 if (_PyStatus_EXCEPTION(status)) {
830 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100831 }
Victor Stinner43125222019-04-24 18:23:53 +0200832 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100833
Victor Stinnerd3b90412019-09-17 23:59:51 +0200834 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100835 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200836 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100837 }
838
Victor Stinnerd3b90412019-09-17 23:59:51 +0200839 /* Note: preinitialized remains 1 on error, it is only set to 0
840 at exit on success. */
841 runtime->preinitializing = 1;
842
Victor Stinner331a6a52019-05-27 16:39:22 +0200843 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200844
845 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
846 if (_PyStatus_EXCEPTION(status)) {
847 return status;
848 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100849
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 status = _PyPreConfig_Read(&config, args);
851 if (_PyStatus_EXCEPTION(status)) {
852 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100853 }
854
Victor Stinner331a6a52019-05-27 16:39:22 +0200855 status = _PyPreConfig_Write(&config);
856 if (_PyStatus_EXCEPTION(status)) {
857 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100858 }
859
Victor Stinnerd3b90412019-09-17 23:59:51 +0200860 runtime->preinitializing = 0;
861 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200862 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100863}
864
Victor Stinner70005ac2019-05-02 15:25:34 -0400865
Victor Stinner331a6a52019-05-27 16:39:22 +0200866PyStatus
867Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100868{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100869 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400870 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100871}
872
873
Victor Stinner331a6a52019-05-27 16:39:22 +0200874PyStatus
875Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100876{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100877 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400878 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100879}
880
881
Victor Stinner331a6a52019-05-27 16:39:22 +0200882PyStatus
883Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100884{
Victor Stinner70005ac2019-05-02 15:25:34 -0400885 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100886}
887
888
Victor Stinner331a6a52019-05-27 16:39:22 +0200889PyStatus
890_Py_PreInitializeFromConfig(const PyConfig *config,
891 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100892{
Victor Stinner331a6a52019-05-27 16:39:22 +0200893 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200894
Victor Stinner331a6a52019-05-27 16:39:22 +0200895 PyStatus status = _PyRuntime_Initialize();
896 if (_PyStatus_EXCEPTION(status)) {
897 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200898 }
899 _PyRuntimeState *runtime = &_PyRuntime;
900
Victor Stinnerd3b90412019-09-17 23:59:51 +0200901 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200902 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200903 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400904 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200905
Victor Stinner331a6a52019-05-27 16:39:22 +0200906 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200907
Victor Stinner3c30a762019-10-01 10:56:37 +0200908 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200909
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 if (!config->parse_argv) {
911 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200912 }
913 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200914 _PyArgv config_args = {
915 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200916 .argc = config->argv.length,
917 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200918 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200919 }
920 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200921 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200922 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100923}
924
925
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100926/* Begin interpreter initialization
927 *
928 * On return, the first thread and interpreter state have been created,
929 * but the compiler, signal handling, multithreading and
930 * multiple interpreter support, and codec infrastructure are not yet
931 * available.
932 *
933 * The import system will support builtin and frozen modules only.
934 * The only supported io is writing to sys.stderr
935 *
936 * If any operation invoked by this function fails, a fatal error is
937 * issued and the function does not return.
938 *
939 * Any code invoked from this function should *not* assume it has access
940 * to the Python C API (unless the API is explicitly listed as being
941 * safe to call without calling Py_Initialize first)
942 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200943static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200944pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200945 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200946 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200947{
Victor Stinner331a6a52019-05-27 16:39:22 +0200948 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200949
Victor Stinner331a6a52019-05-27 16:39:22 +0200950 status = _Py_PreInitializeFromConfig(src_config, NULL);
951 if (_PyStatus_EXCEPTION(status)) {
952 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200953 }
954
Victor Stinner331a6a52019-05-27 16:39:22 +0200955 PyConfig config;
Victor Stinner048a3562020-11-05 00:45:56 +0100956 PyConfig_InitPythonConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200957
Victor Stinner331a6a52019-05-27 16:39:22 +0200958 status = _PyConfig_Copy(&config, src_config);
959 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200960 goto done;
961 }
962
Victor Stinner9e1b8282020-11-10 13:21:52 +0100963 // Read the configuration, but don't compute the path configuration
964 // (it is computed in the main init).
965 status = _PyConfig_Read(&config, 0);
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200967 goto done;
968 }
969
970 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200971 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200972 }
973 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200974 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200975 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200976 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200977 goto done;
978 }
979
980done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200981 PyConfig_Clear(&config);
982 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200983}
984
Victor Stinner5ac27a52019-03-27 13:40:14 +0100985
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200986/* Py_Initialize() has already been called: update the main interpreter
987 configuration. Example of bpo-34008: Py_Main() called after
988 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200989static PyStatus
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100990pyinit_main_reconfigure(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200991{
Victor Stinner9e1b8282020-11-10 13:21:52 +0100992 if (interpreter_update_config(tstate, 0) < 0) {
993 return _PyStatus_ERR("fail to reconfigure Python");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200994 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200995 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200996}
997
Victor Stinnerb0051362019-11-22 17:52:42 +0100998
999static PyStatus
1000init_interp_main(PyThreadState *tstate)
1001{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001002 assert(!_PyErr_Occurred(tstate));
1003
Victor Stinnerb0051362019-11-22 17:52:42 +01001004 PyStatus status;
Victor Stinner101bf692021-02-19 13:33:31 +01001005 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001006 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001007 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +01001008
1009 if (!config->_install_importlib) {
1010 /* Special mode for freeze_importlib: run with no import system
1011 *
1012 * This means anything which needs support from extension modules
1013 * or pure Python code in the standard library won't work.
1014 */
1015 if (is_main_interp) {
1016 interp->runtime->initialized = 1;
1017 }
1018 return _PyStatus_OK();
1019 }
1020
Victor Stinner9e1b8282020-11-10 13:21:52 +01001021 // Compute the path configuration
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001022 status = _PyConfig_InitPathConfig(&interp->config, 1);
Victor Stinner9e1b8282020-11-10 13:21:52 +01001023 if (_PyStatus_EXCEPTION(status)) {
1024 return status;
1025 }
1026
Victor Stinner9e1b8282020-11-10 13:21:52 +01001027 if (interpreter_update_config(tstate, 1) < 0) {
1028 return _PyStatus_ERR("failed to update the Python config");
Victor Stinnerb0051362019-11-22 17:52:42 +01001029 }
1030
1031 status = init_importlib_external(tstate);
1032 if (_PyStatus_EXCEPTION(status)) {
1033 return status;
1034 }
1035
1036 if (is_main_interp) {
1037 /* initialize the faulthandler module */
1038 status = _PyFaulthandler_Init(config->faulthandler);
1039 if (_PyStatus_EXCEPTION(status)) {
1040 return status;
1041 }
1042 }
1043
1044 status = _PyUnicode_InitEncodings(tstate);
1045 if (_PyStatus_EXCEPTION(status)) {
1046 return status;
1047 }
1048
1049 if (is_main_interp) {
Victor Stinner296a7962020-11-17 16:22:23 +01001050 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1051 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001052 }
1053
1054 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1055 return _PyStatus_ERR("can't initialize tracemalloc");
1056 }
1057 }
1058
1059 status = init_sys_streams(tstate);
1060 if (_PyStatus_EXCEPTION(status)) {
1061 return status;
1062 }
1063
Andy Lester75cd5bf2020-03-12 02:49:05 -05001064 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001065 if (_PyStatus_EXCEPTION(status)) {
1066 return status;
1067 }
1068
1069 status = add_main_module(interp);
1070 if (_PyStatus_EXCEPTION(status)) {
1071 return status;
1072 }
1073
1074 if (is_main_interp) {
1075 /* Initialize warnings. */
1076 PyObject *warnoptions = PySys_GetObject("warnoptions");
1077 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1078 {
1079 PyObject *warnings_module = PyImport_ImportModule("warnings");
1080 if (warnings_module == NULL) {
1081 fprintf(stderr, "'import warnings' failed; traceback:\n");
1082 _PyErr_Print(tstate);
1083 }
1084 Py_XDECREF(warnings_module);
1085 }
1086
1087 interp->runtime->initialized = 1;
1088 }
1089
1090 if (config->site_import) {
1091 status = init_import_site();
1092 if (_PyStatus_EXCEPTION(status)) {
1093 return status;
1094 }
1095 }
1096
1097 if (is_main_interp) {
1098#ifndef MS_WINDOWS
1099 emit_stderr_warning_for_legacy_locale(interp->runtime);
1100#endif
1101 }
1102
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001103 assert(!_PyErr_Occurred(tstate));
1104
Victor Stinnerb0051362019-11-22 17:52:42 +01001105 return _PyStatus_OK();
1106}
1107
1108
Eric Snowc7ec9982017-05-23 23:00:52 -07001109/* Update interpreter state based on supplied configuration settings
1110 *
1111 * After calling this function, most of the restrictions on the interpreter
1112 * are lifted. The only remaining incomplete settings are those related
1113 * to the main module (sys.argv[0], __main__ metadata)
1114 *
1115 * Calling this when the interpreter is not initializing, is already
1116 * initialized or without a valid current thread state is a fatal error.
1117 * Other errors should be reported as normal Python exceptions with a
1118 * non-zero return code.
1119 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001120static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001121pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001122{
Victor Stinnerb0051362019-11-22 17:52:42 +01001123 PyInterpreterState *interp = tstate->interp;
1124 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001125 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001126 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001127
Victor Stinnerb0051362019-11-22 17:52:42 +01001128 if (interp->runtime->initialized) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001129 return pyinit_main_reconfigure(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001130 }
1131
Victor Stinnerb0051362019-11-22 17:52:42 +01001132 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001133 if (_PyStatus_EXCEPTION(status)) {
1134 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001135 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001136 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001137}
1138
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001139
Victor Stinner331a6a52019-05-27 16:39:22 +02001140PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +02001141Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001142{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001143 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001144 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001145 }
1146
Victor Stinner331a6a52019-05-27 16:39:22 +02001147 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001148
Victor Stinner331a6a52019-05-27 16:39:22 +02001149 status = _PyRuntime_Initialize();
1150 if (_PyStatus_EXCEPTION(status)) {
1151 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001152 }
1153 _PyRuntimeState *runtime = &_PyRuntime;
1154
Victor Stinnerb45d2592019-06-20 00:05:23 +02001155 PyThreadState *tstate = NULL;
1156 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001157 if (_PyStatus_EXCEPTION(status)) {
1158 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001159 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001160 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001161
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001162 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001163 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001164 if (_PyStatus_EXCEPTION(status)) {
1165 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001166 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001167 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001168
Victor Stinner331a6a52019-05-27 16:39:22 +02001169 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001170}
1171
1172
Eric Snow1abcf672017-05-23 21:46:51 -07001173void
Nick Coghland6009512014-11-20 21:39:37 +10001174Py_InitializeEx(int install_sigs)
1175{
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001177
Victor Stinner331a6a52019-05-27 16:39:22 +02001178 status = _PyRuntime_Initialize();
1179 if (_PyStatus_EXCEPTION(status)) {
1180 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001181 }
1182 _PyRuntimeState *runtime = &_PyRuntime;
1183
1184 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001185 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1186 return;
1187 }
1188
Victor Stinner331a6a52019-05-27 16:39:22 +02001189 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001190 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001191
Victor Stinner1dc6e392018-07-25 02:49:17 +02001192 config.install_signal_handlers = install_sigs;
1193
Victor Stinner331a6a52019-05-27 16:39:22 +02001194 status = Py_InitializeFromConfig(&config);
1195 if (_PyStatus_EXCEPTION(status)) {
1196 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001197 }
Nick Coghland6009512014-11-20 21:39:37 +10001198}
1199
1200void
1201Py_Initialize(void)
1202{
1203 Py_InitializeEx(1);
1204}
1205
1206
Victor Stinneraf1d64d2020-11-04 17:34:34 +01001207PyStatus
1208_Py_InitializeMain(void)
1209{
1210 PyStatus status = _PyRuntime_Initialize();
1211 if (_PyStatus_EXCEPTION(status)) {
1212 return status;
1213 }
1214 _PyRuntimeState *runtime = &_PyRuntime;
1215 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1216 return pyinit_main(tstate);
1217}
1218
1219
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001220static void
1221finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1222{
1223 // List of names to clear in sys
1224 static const char * const sys_deletes[] = {
1225 "path", "argv", "ps1", "ps2",
1226 "last_type", "last_value", "last_traceback",
1227 "path_hooks", "path_importer_cache", "meta_path",
1228 "__interactivehook__",
1229 NULL
1230 };
1231
1232 static const char * const sys_files[] = {
1233 "stdin", "__stdin__",
1234 "stdout", "__stdout__",
1235 "stderr", "__stderr__",
1236 NULL
1237 };
1238
1239 PyInterpreterState *interp = tstate->interp;
1240 if (verbose) {
1241 PySys_WriteStderr("# clear builtins._\n");
1242 }
1243 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1244 PyErr_WriteUnraisable(NULL);
1245 }
1246
1247 const char * const *p;
1248 for (p = sys_deletes; *p != NULL; p++) {
1249 if (verbose) {
1250 PySys_WriteStderr("# clear sys.%s\n", *p);
1251 }
1252 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
1253 PyErr_WriteUnraisable(NULL);
1254 }
1255 }
1256 for (p = sys_files; *p != NULL; p+=2) {
1257 const char *name = p[0];
1258 const char *orig_name = p[1];
1259 if (verbose) {
1260 PySys_WriteStderr("# restore sys.%s\n", name);
1261 }
1262 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
1263 orig_name);
1264 if (value == NULL) {
1265 if (_PyErr_Occurred(tstate)) {
1266 PyErr_WriteUnraisable(NULL);
1267 }
1268 value = Py_None;
1269 }
1270 if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1271 PyErr_WriteUnraisable(NULL);
1272 }
1273 }
1274}
1275
1276
1277static PyObject*
1278finalize_remove_modules(PyObject *modules, int verbose)
1279{
1280 PyObject *weaklist = PyList_New(0);
1281 if (weaklist == NULL) {
1282 PyErr_WriteUnraisable(NULL);
1283 }
1284
1285#define STORE_MODULE_WEAKREF(name, mod) \
1286 if (weaklist != NULL) { \
1287 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1288 if (wr) { \
1289 PyObject *tup = PyTuple_Pack(2, name, wr); \
1290 if (!tup || PyList_Append(weaklist, tup) < 0) { \
1291 PyErr_WriteUnraisable(NULL); \
1292 } \
1293 Py_XDECREF(tup); \
1294 Py_DECREF(wr); \
1295 } \
1296 else { \
1297 PyErr_WriteUnraisable(NULL); \
1298 } \
1299 }
1300
1301#define CLEAR_MODULE(name, mod) \
1302 if (PyModule_Check(mod)) { \
1303 if (verbose && PyUnicode_Check(name)) { \
1304 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1305 } \
1306 STORE_MODULE_WEAKREF(name, mod); \
1307 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1308 PyErr_WriteUnraisable(NULL); \
1309 } \
1310 }
1311
1312 if (PyDict_CheckExact(modules)) {
1313 Py_ssize_t pos = 0;
1314 PyObject *key, *value;
1315 while (PyDict_Next(modules, &pos, &key, &value)) {
1316 CLEAR_MODULE(key, value);
1317 }
1318 }
1319 else {
1320 PyObject *iterator = PyObject_GetIter(modules);
1321 if (iterator == NULL) {
1322 PyErr_WriteUnraisable(NULL);
1323 }
1324 else {
1325 PyObject *key;
1326 while ((key = PyIter_Next(iterator))) {
1327 PyObject *value = PyObject_GetItem(modules, key);
1328 if (value == NULL) {
1329 PyErr_WriteUnraisable(NULL);
1330 continue;
1331 }
1332 CLEAR_MODULE(key, value);
1333 Py_DECREF(value);
1334 Py_DECREF(key);
1335 }
1336 if (PyErr_Occurred()) {
1337 PyErr_WriteUnraisable(NULL);
1338 }
1339 Py_DECREF(iterator);
1340 }
1341 }
1342#undef CLEAR_MODULE
1343#undef STORE_MODULE_WEAKREF
1344
1345 return weaklist;
1346}
1347
1348
1349static void
1350finalize_clear_modules_dict(PyObject *modules)
1351{
1352 if (PyDict_CheckExact(modules)) {
1353 PyDict_Clear(modules);
1354 }
1355 else {
1356 _Py_IDENTIFIER(clear);
1357 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
1358 PyErr_WriteUnraisable(NULL);
1359 }
1360 }
1361}
1362
1363
1364static void
1365finalize_restore_builtins(PyThreadState *tstate)
1366{
1367 PyInterpreterState *interp = tstate->interp;
1368 PyObject *dict = PyDict_Copy(interp->builtins);
1369 if (dict == NULL) {
1370 PyErr_WriteUnraisable(NULL);
1371 }
1372 PyDict_Clear(interp->builtins);
1373 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1374 _PyErr_Clear(tstate);
1375 }
1376 Py_XDECREF(dict);
1377}
1378
1379
1380static void
1381finalize_modules_clear_weaklist(PyInterpreterState *interp,
1382 PyObject *weaklist, int verbose)
1383{
1384 // First clear modules imported later
1385 for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1386 PyObject *tup = PyList_GET_ITEM(weaklist, i);
1387 PyObject *name = PyTuple_GET_ITEM(tup, 0);
1388 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
1389 if (mod == Py_None) {
1390 continue;
1391 }
1392 assert(PyModule_Check(mod));
1393 PyObject *dict = PyModule_GetDict(mod);
1394 if (dict == interp->builtins || dict == interp->sysdict) {
1395 continue;
1396 }
1397 Py_INCREF(mod);
1398 if (verbose && PyUnicode_Check(name)) {
1399 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1400 }
1401 _PyModule_Clear(mod);
1402 Py_DECREF(mod);
1403 }
1404}
1405
1406
1407static void
1408finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1409{
1410 // Clear sys dict
1411 if (verbose) {
1412 PySys_FormatStderr("# cleanup[3] wiping sys\n");
1413 }
1414 _PyModule_ClearDict(interp->sysdict);
1415
1416 // Clear builtins dict
1417 if (verbose) {
1418 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1419 }
1420 _PyModule_ClearDict(interp->builtins);
1421}
1422
1423
1424/* Clear modules, as good as we can */
1425static void
1426finalize_modules(PyThreadState *tstate)
1427{
1428 PyInterpreterState *interp = tstate->interp;
1429 PyObject *modules = interp->modules;
1430 if (modules == NULL) {
1431 // Already done
1432 return;
1433 }
1434 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1435
1436 // Delete some special builtins._ and sys attributes first. These are
1437 // common places where user values hide and people complain when their
1438 // destructors fail. Since the modules containing them are
1439 // deleted *last* of all, they would come too late in the normal
1440 // destruction order. Sigh.
1441 //
1442 // XXX Perhaps these precautions are obsolete. Who knows?
1443 finalize_modules_delete_special(tstate, verbose);
1444
1445 // Remove all modules from sys.modules, hoping that garbage collection
1446 // can reclaim most of them: set all sys.modules values to None.
1447 //
1448 // We prepare a list which will receive (name, weakref) tuples of
1449 // modules when they are removed from sys.modules. The name is used
1450 // for diagnosis messages (in verbose mode), while the weakref helps
1451 // detect those modules which have been held alive.
1452 PyObject *weaklist = finalize_remove_modules(modules, verbose);
1453
1454 // Clear the modules dict
1455 finalize_clear_modules_dict(modules);
1456
1457 // Restore the original builtins dict, to ensure that any
1458 // user data gets cleared.
1459 finalize_restore_builtins(tstate);
1460
1461 // Collect garbage
1462 _PyGC_CollectNoFail(tstate);
1463
1464 // Dump GC stats before it's too late, since it uses the warnings
1465 // machinery.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001466 _PyGC_DumpShutdownStats(interp);
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001467
1468 if (weaklist != NULL) {
1469 // Now, if there are any modules left alive, clear their globals to
1470 // minimize potential leaks. All C extension modules actually end
1471 // up here, since they are kept alive in the interpreter state.
1472 //
1473 // The special treatment of "builtins" here is because even
1474 // when it's not referenced as a module, its dictionary is
1475 // referenced by almost every module's __builtins__. Since
1476 // deleting a module clears its dictionary (even if there are
1477 // references left to it), we need to delete the "builtins"
1478 // module last. Likewise, we don't delete sys until the very
1479 // end because it is implicitly referenced (e.g. by print).
1480 //
1481 // Since dict is ordered in CPython 3.6+, modules are saved in
1482 // importing order. First clear modules imported later.
1483 finalize_modules_clear_weaklist(interp, weaklist, verbose);
1484 Py_DECREF(weaklist);
1485 }
1486
1487 // Clear sys and builtins modules dict
1488 finalize_clear_sys_builtins_dict(interp, verbose);
1489
1490 // Clear module dict copies stored in the interpreter state:
1491 // clear PyInterpreterState.modules_by_index and
1492 // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1493 // initialization API)
1494 _PyInterpreterState_ClearModules(interp);
1495
1496 // Clear and delete the modules directory. Actual modules will
1497 // still be there only if imported during the execution of some
1498 // destructor.
1499 Py_SETREF(interp->modules, NULL);
1500
1501 // Collect garbage once more
1502 _PyGC_CollectNoFail(tstate);
1503}
1504
1505
Nick Coghland6009512014-11-20 21:39:37 +10001506/* Flush stdout and stderr */
1507
1508static int
1509file_is_closed(PyObject *fobj)
1510{
1511 int r;
1512 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1513 if (tmp == NULL) {
1514 PyErr_Clear();
1515 return 0;
1516 }
1517 r = PyObject_IsTrue(tmp);
1518 Py_DECREF(tmp);
1519 if (r < 0)
1520 PyErr_Clear();
1521 return r > 0;
1522}
1523
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001524
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001525static int
Nick Coghland6009512014-11-20 21:39:37 +10001526flush_std_files(void)
1527{
1528 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1529 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1530 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001531 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001532
1533 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001534 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001535 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001536 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001537 status = -1;
1538 }
Nick Coghland6009512014-11-20 21:39:37 +10001539 else
1540 Py_DECREF(tmp);
1541 }
1542
1543 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001544 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001545 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001546 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001547 status = -1;
1548 }
Nick Coghland6009512014-11-20 21:39:37 +10001549 else
1550 Py_DECREF(tmp);
1551 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001552
1553 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001554}
1555
1556/* Undo the effect of Py_Initialize().
1557
1558 Beware: if multiple interpreter and/or thread states exist, these
1559 are not wiped out; only the current thread and interpreter state
1560 are deleted. But since everything else is deleted, those other
1561 interpreter and thread states should no longer be used.
1562
1563 (XXX We should do better, e.g. wipe out all interpreters and
1564 threads.)
1565
1566 Locking: as above.
1567
1568*/
1569
Victor Stinner7eee5be2019-11-20 10:38:34 +01001570
1571static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001572finalize_interp_types(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001573{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001574 _PyExc_Fini(interp);
1575 _PyFrame_Fini(interp);
1576 _PyAsyncGen_Fini(interp);
1577 _PyContext_Fini(interp);
1578 _PyType_Fini(interp);
Victor Stinnerea251802020-12-26 02:58:33 +01001579 // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1580 // a dict internally.
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001581 _PyUnicode_ClearInterned(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001582
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001583 _PyDict_Fini(interp);
1584 _PyList_Fini(interp);
1585 _PyTuple_Fini(interp);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001586
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001587 _PySlice_Fini(interp);
Victor Stinner3d483342019-11-22 12:27:50 +01001588
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001589 _PyBytes_Fini(interp);
1590 _PyUnicode_Fini(interp);
1591 _PyFloat_Fini(interp);
1592 _PyLong_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001593}
1594
1595
1596static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001597finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001598{
Victor Stinner101bf692021-02-19 13:33:31 +01001599 int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001600
Victor Stinner7eee5be2019-11-20 10:38:34 +01001601 /* Clear interpreter state and all thread states */
Victor Stinnereba5bf22020-10-30 22:51:02 +01001602 _PyInterpreterState_Clear(tstate);
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001603
Kongedaa0fe02020-07-04 05:06:46 +08001604 /* Clear all loghooks */
1605 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1606 Call _PySys_ClearAuditHooks when PyObject available. */
1607 if (is_main_interp) {
1608 _PySys_ClearAuditHooks(tstate);
1609 }
1610
Victor Stinner7907f8c2020-06-08 01:22:36 +02001611 if (is_main_interp) {
1612 _Py_HashRandomization_Fini();
1613 _PyArg_Fini();
1614 _Py_ClearFileSystemEncoding();
1615 }
1616
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001617 finalize_interp_types(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001618}
1619
1620
1621static void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001622finalize_interp_delete(PyInterpreterState *interp)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001623{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001624 if (_Py_IsMainInterpreter(interp)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001625 /* Cleanup auto-thread-state */
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001626 _PyGILState_Fini(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001627 }
1628
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001629 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1630 fail when it is being awaited by another running daemon thread (see
1631 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1632 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1633 called multiple times. */
1634
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001635 PyInterpreterState_Delete(interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001636}
1637
1638
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001639int
1640Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001641{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001642 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001643
Victor Stinner8e91c242019-04-24 17:24:01 +02001644 _PyRuntimeState *runtime = &_PyRuntime;
1645 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001646 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001647 }
Nick Coghland6009512014-11-20 21:39:37 +10001648
Victor Stinnere225beb2019-06-03 18:14:24 +02001649 /* Get current thread state and interpreter pointer */
1650 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001651
Victor Stinnerb45d2592019-06-20 00:05:23 +02001652 // Wrap up existing "threading"-module-created, non-daemon threads.
1653 wait_for_thread_shutdown(tstate);
1654
1655 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001656 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001657
Nick Coghland6009512014-11-20 21:39:37 +10001658 /* The interpreter is still entirely intact at this point, and the
1659 * exit funcs may be relying on that. In particular, if some thread
1660 * or exit func is still waiting to do an import, the import machinery
1661 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001662 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001663 * Note that Threading.py uses an exit func to do a join on all the
1664 * threads created thru it, so this also protects pending imports in
1665 * the threads created via Threading.
1666 */
Nick Coghland6009512014-11-20 21:39:37 +10001667
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001668 _PyAtExit_Call(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001669
Victor Stinnerda273412017-12-15 01:46:02 +01001670 /* Copy the core config, PyInterpreterState_Delete() free
1671 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001672#ifdef Py_REF_DEBUG
Christian Heimes07f2ade2020-11-18 16:38:53 +01001673 int show_ref_count = tstate->interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001674#endif
1675#ifdef Py_TRACE_REFS
Christian Heimes07f2ade2020-11-18 16:38:53 +01001676 int dump_refs = tstate->interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001677#endif
1678#ifdef WITH_PYMALLOC
Christian Heimes07f2ade2020-11-18 16:38:53 +01001679 int malloc_stats = tstate->interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001680#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001681
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001682 /* Remaining daemon threads will automatically exit
1683 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001684 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001685 runtime->initialized = 0;
1686 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001687
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001688 /* Destroy the state of all threads of the interpreter, except of the
1689 current thread. In practice, only daemon threads should still be alive,
1690 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1691 Clear frames of other threads to call objects destructors. Destructors
1692 will be called in the current Python thread. Since
1693 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1694 can take the GIL at this point: if they try, they will exit
1695 immediately. */
1696 _PyThreadState_DeleteExcept(runtime, tstate);
1697
Victor Stinnere0deff32015-03-24 13:46:18 +01001698 /* Flush sys.stdout and sys.stderr */
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 /* Disable signal handling */
Victor Stinner296a7962020-11-17 16:22:23 +01001704 _PySignal_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001705
1706 /* Collect garbage. This may call finalizers; it's nice to call these
1707 * before all modules are destroyed.
1708 * XXX If a __del__ or weakref callback is triggered here, and tries to
1709 * XXX import a module, bad things can happen, because Python no
1710 * XXX longer believes it's initialized.
1711 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1712 * XXX is easy to provoke that way. I've also seen, e.g.,
1713 * XXX Exception exceptions.ImportError: 'No module named sha'
1714 * XXX in <function callback at 0x008F5718> ignored
1715 * XXX but I'm unclear on exactly how that one happens. In any case,
1716 * XXX I haven't seen a real-life report of either of these.
1717 */
Victor Stinner8b341482020-10-30 17:00:00 +01001718 PyGC_Collect();
Eric Snowdae02762017-09-14 00:35:58 -07001719
Nick Coghland6009512014-11-20 21:39:37 +10001720 /* Destroy all modules */
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001721 finalize_modules(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001722
Inada Naoki91234a12019-06-03 21:30:58 +09001723 /* Print debug stats if any */
1724 _PyEval_Fini();
1725
Victor Stinnere0deff32015-03-24 13:46:18 +01001726 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001727 if (flush_std_files() < 0) {
1728 status = -1;
1729 }
Nick Coghland6009512014-11-20 21:39:37 +10001730
1731 /* Collect final garbage. This disposes of cycles created by
1732 * class definitions, for example.
1733 * XXX This is disabled because it caused too many problems. If
1734 * XXX a __del__ or weakref callback triggers here, Python code has
1735 * XXX a hard time running, because even the sys module has been
1736 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1737 * XXX One symptom is a sequence of information-free messages
1738 * XXX coming from threads (if a __del__ or callback is invoked,
1739 * XXX other threads can execute too, and any exception they encounter
1740 * XXX triggers a comedy of errors as subsystem after subsystem
1741 * XXX fails to find what it *expects* to find in sys to help report
1742 * XXX the exception and consequent unexpected failures). I've also
1743 * XXX seen segfaults then, after adding print statements to the
1744 * XXX Python code getting called.
1745 */
1746#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001747 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001748#endif
1749
1750 /* Disable tracemalloc after all Python objects have been destroyed,
1751 so it is possible to use tracemalloc in objects destructor. */
1752 _PyTraceMalloc_Fini();
1753
1754 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1755 _PyImport_Fini();
1756
Nick Coghland6009512014-11-20 21:39:37 +10001757 /* unload faulthandler module */
1758 _PyFaulthandler_Fini();
1759
Nick Coghland6009512014-11-20 21:39:37 +10001760 /* dump hash stats */
1761 _PyHash_Fini();
1762
Eric Snowdae02762017-09-14 00:35:58 -07001763#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001764 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001765 _PyDebug_PrintTotalRefs();
1766 }
Eric Snowdae02762017-09-14 00:35:58 -07001767#endif
Nick Coghland6009512014-11-20 21:39:37 +10001768
1769#ifdef Py_TRACE_REFS
1770 /* Display all objects still alive -- this can invoke arbitrary
1771 * __repr__ overrides, so requires a mostly-intact interpreter.
1772 * Alas, a lot of stuff may still be alive now that will be cleaned
1773 * up later.
1774 */
Victor Stinnerda273412017-12-15 01:46:02 +01001775 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001776 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001777 }
Nick Coghland6009512014-11-20 21:39:37 +10001778#endif /* Py_TRACE_REFS */
1779
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001780 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001781 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001782
1783#ifdef Py_TRACE_REFS
1784 /* Display addresses (& refcnts) of all objects still alive.
1785 * An address can be used to find the repr of the object, printed
1786 * above by _Py_PrintReferences.
1787 */
Victor Stinnerda273412017-12-15 01:46:02 +01001788 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001789 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001790 }
Nick Coghland6009512014-11-20 21:39:37 +10001791#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001792#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001793 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001794 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001795 }
Nick Coghland6009512014-11-20 21:39:37 +10001796#endif
1797
Victor Stinner8e91c242019-04-24 17:24:01 +02001798 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001799
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001800 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001801 return status;
1802}
1803
1804void
1805Py_Finalize(void)
1806{
1807 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001808}
1809
Victor Stinnerb0051362019-11-22 17:52:42 +01001810
Nick Coghland6009512014-11-20 21:39:37 +10001811/* Create and initialize a new interpreter and thread, and return the
1812 new thread. This requires that Py_Initialize() has been called
1813 first.
1814
1815 Unsuccessful initialization yields a NULL pointer. Note that *no*
1816 exception information is available even in this case -- the
1817 exception information is held in the thread, and there is no
1818 thread.
1819
1820 Locking: as above.
1821
1822*/
1823
Victor Stinner331a6a52019-05-27 16:39:22 +02001824static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001825new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001826{
Victor Stinner331a6a52019-05-27 16:39:22 +02001827 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001828
Victor Stinner331a6a52019-05-27 16:39:22 +02001829 status = _PyRuntime_Initialize();
1830 if (_PyStatus_EXCEPTION(status)) {
1831 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001832 }
1833 _PyRuntimeState *runtime = &_PyRuntime;
1834
1835 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001836 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001837 }
Nick Coghland6009512014-11-20 21:39:37 +10001838
Victor Stinner8a1be612016-03-14 22:07:55 +01001839 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1840 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001841 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001842
Victor Stinner43125222019-04-24 18:23:53 +02001843 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001844 if (interp == NULL) {
1845 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001846 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001847 }
Nick Coghland6009512014-11-20 21:39:37 +10001848
Victor Stinner43125222019-04-24 18:23:53 +02001849 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001850 if (tstate == NULL) {
1851 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001852 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001853 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001854 }
1855
Victor Stinner43125222019-04-24 18:23:53 +02001856 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001857
Eric Snow1abcf672017-05-23 21:46:51 -07001858 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001859 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001860#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001861 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001862 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001863 }
1864 else
1865#endif
1866 {
Eric Snow1abcf672017-05-23 21:46:51 -07001867 /* No current thread state, copy from the main interpreter */
1868 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001869 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001870 }
1871
Victor Stinner048a3562020-11-05 00:45:56 +01001872
1873 status = _PyConfig_Copy(&interp->config, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001874 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001875 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001876 }
Victor Stinner252346a2020-05-01 11:33:44 +02001877 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001878
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001879 status = init_interp_create_gil(tstate);
1880 if (_PyStatus_EXCEPTION(status)) {
1881 goto error;
1882 }
1883
Victor Stinnerd863ade2019-12-06 03:37:07 +01001884 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001885 if (_PyStatus_EXCEPTION(status)) {
1886 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001887 }
1888
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001889 status = init_interp_main(tstate);
1890 if (_PyStatus_EXCEPTION(status)) {
1891 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001892 }
Nick Coghland6009512014-11-20 21:39:37 +10001893
Victor Stinnera7368ac2017-11-15 18:11:45 -08001894 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001895 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001896
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001897error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001898 *tstate_p = NULL;
1899
1900 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001901 PyErr_PrintEx(0);
1902 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001903 PyThreadState_Delete(tstate);
1904 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001905 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001906
Victor Stinnerb0051362019-11-22 17:52:42 +01001907 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001908}
1909
1910PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001911_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001912{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001913 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001914 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001915 if (_PyStatus_EXCEPTION(status)) {
1916 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001917 }
1918 return tstate;
1919
Nick Coghland6009512014-11-20 21:39:37 +10001920}
1921
Victor Stinner252346a2020-05-01 11:33:44 +02001922PyThreadState *
1923Py_NewInterpreter(void)
1924{
1925 return _Py_NewInterpreter(0);
1926}
1927
Nick Coghland6009512014-11-20 21:39:37 +10001928/* Delete an interpreter and its last thread. This requires that the
1929 given thread state is current, that the thread has no remaining
1930 frames, and that it is its interpreter's only remaining thread.
1931 It is a fatal error to violate these constraints.
1932
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001933 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001934 everything, regardless.)
1935
1936 Locking: as above.
1937
1938*/
1939
1940void
1941Py_EndInterpreter(PyThreadState *tstate)
1942{
1943 PyInterpreterState *interp = tstate->interp;
1944
Victor Stinnerb45d2592019-06-20 00:05:23 +02001945 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001946 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001947 }
1948 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001949 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001950 }
Eric Snow5be45a62019-03-08 22:47:07 -07001951 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001952
Eric Snow842a2f02019-03-15 15:47:51 -06001953 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001954 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001955
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001956 _PyAtExit_Call(tstate->interp);
Marcel Plch776407f2017-12-20 11:17:58 +01001957
Victor Stinnerb45d2592019-06-20 00:05:23 +02001958 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001959 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001960 }
Nick Coghland6009512014-11-20 21:39:37 +10001961
Victor Stinnerdff1ad52020-10-30 18:03:28 +01001962 finalize_modules(tstate);
1963
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001964 finalize_interp_clear(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001965 finalize_interp_delete(tstate->interp);
Nick Coghland6009512014-11-20 21:39:37 +10001966}
1967
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001968/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001969
Victor Stinner331a6a52019-05-27 16:39:22 +02001970static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001971add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001972{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001973 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001974 m = PyImport_AddModule("__main__");
1975 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001976 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001977
Nick Coghland6009512014-11-20 21:39:37 +10001978 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001979 ann_dict = PyDict_New();
1980 if ((ann_dict == NULL) ||
1981 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001982 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001983 }
1984 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001985
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001986 if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
1987 if (PyErr_Occurred()) {
1988 return _PyStatus_ERR("Failed to test __main__.__builtins__");
1989 }
Nick Coghland6009512014-11-20 21:39:37 +10001990 PyObject *bimod = PyImport_ImportModule("builtins");
1991 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001992 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001993 }
1994 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001995 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001996 }
1997 Py_DECREF(bimod);
1998 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001999
Nick Coghland6009512014-11-20 21:39:37 +10002000 /* Main is a little special - imp.is_builtin("__main__") will return
2001 * False, but BuiltinImporter is still the most appropriate initial
2002 * setting for its __loader__ attribute. A more suitable value will
2003 * be set if __main__ gets further initialized later in the startup
2004 * process.
2005 */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002006 loader = _PyDict_GetItemStringWithError(d, "__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002007 if (loader == NULL || loader == Py_None) {
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002008 if (PyErr_Occurred()) {
2009 return _PyStatus_ERR("Failed to test __main__.__loader__");
2010 }
Nick Coghland6009512014-11-20 21:39:37 +10002011 PyObject *loader = PyObject_GetAttrString(interp->importlib,
2012 "BuiltinImporter");
2013 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002014 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10002015 }
2016 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002017 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10002018 }
2019 Py_DECREF(loader);
2020 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002021 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002022}
2023
Nick Coghland6009512014-11-20 21:39:37 +10002024/* Import the site module (not into __main__ though) */
2025
Victor Stinner331a6a52019-05-27 16:39:22 +02002026static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002027init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10002028{
2029 PyObject *m;
2030 m = PyImport_ImportModule("site");
2031 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002032 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10002033 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002034 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02002035 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002036}
2037
Victor Stinner874dbe82015-09-04 17:29:57 +02002038/* Check if a file descriptor is valid or not.
2039 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
2040static int
2041is_valid_fd(int fd)
2042{
Victor Stinner3092d6b2019-04-17 18:09:12 +02002043/* dup() is faster than fstat(): fstat() can require input/output operations,
2044 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
2045 startup. Problem: dup() doesn't check if the file descriptor is valid on
2046 some platforms.
2047
2048 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
2049 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
2050 EBADF. FreeBSD has similar issue (bpo-32849).
2051
2052 Only use dup() on platforms where dup() is enough to detect invalid FD in
2053 corner cases: on Linux and Windows (bpo-32849). */
2054#if defined(__linux__) || defined(MS_WINDOWS)
2055 if (fd < 0) {
2056 return 0;
2057 }
2058 int fd2;
2059
2060 _Py_BEGIN_SUPPRESS_IPH
2061 fd2 = dup(fd);
2062 if (fd2 >= 0) {
2063 close(fd2);
2064 }
2065 _Py_END_SUPPRESS_IPH
2066
2067 return (fd2 >= 0);
2068#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02002069 struct stat st;
2070 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02002071#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02002072}
2073
2074/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10002075static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002076create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002077 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04002078 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10002079{
2080 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2081 const char* mode;
2082 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002083 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10002084 int buffering, isatty;
2085 _Py_IDENTIFIER(open);
2086 _Py_IDENTIFIER(isatty);
2087 _Py_IDENTIFIER(TextIOWrapper);
2088 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002089 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10002090
Victor Stinner874dbe82015-09-04 17:29:57 +02002091 if (!is_valid_fd(fd))
2092 Py_RETURN_NONE;
2093
Nick Coghland6009512014-11-20 21:39:37 +10002094 /* stdin is always opened in buffered mode, first because it shouldn't
2095 make a difference in common use cases, second because TextIOWrapper
2096 depends on the presence of a read1() method which only exists on
2097 buffered streams.
2098 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002099 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10002100 buffering = 0;
2101 else
2102 buffering = -1;
2103 if (write_mode)
2104 mode = "wb";
2105 else
2106 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002107 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10002108 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002109 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002110 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10002111 if (buf == NULL)
2112 goto error;
2113
2114 if (buffering) {
2115 _Py_IDENTIFIER(raw);
2116 raw = _PyObject_GetAttrId(buf, &PyId_raw);
2117 if (raw == NULL)
2118 goto error;
2119 }
2120 else {
2121 raw = buf;
2122 Py_INCREF(raw);
2123 }
2124
Steve Dower39294992016-08-30 21:22:36 -07002125#ifdef MS_WINDOWS
2126 /* Windows console IO is always UTF-8 encoded */
2127 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04002128 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07002129#endif
2130
Nick Coghland6009512014-11-20 21:39:37 +10002131 text = PyUnicode_FromString(name);
2132 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
2133 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002134 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10002135 if (res == NULL)
2136 goto error;
2137 isatty = PyObject_IsTrue(res);
2138 Py_DECREF(res);
2139 if (isatty == -1)
2140 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002141 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002142 write_through = Py_True;
2143 else
2144 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01002145 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10002146 line_buffering = Py_True;
2147 else
2148 line_buffering = Py_False;
2149
2150 Py_CLEAR(raw);
2151 Py_CLEAR(text);
2152
2153#ifdef MS_WINDOWS
2154 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2155 newlines to "\n".
2156 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2157 newline = NULL;
2158#else
2159 /* sys.stdin: split lines at "\n".
2160 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2161 newline = "\n";
2162#endif
2163
Victor Stinner709d23d2019-05-02 14:56:30 -04002164 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2165 if (encoding_str == NULL) {
2166 Py_CLEAR(buf);
2167 goto error;
2168 }
2169
2170 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2171 if (errors_str == NULL) {
2172 Py_CLEAR(buf);
2173 Py_CLEAR(encoding_str);
2174 goto error;
2175 }
2176
2177 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
2178 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03002179 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10002180 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04002181 Py_CLEAR(encoding_str);
2182 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10002183 if (stream == NULL)
2184 goto error;
2185
2186 if (write_mode)
2187 mode = "w";
2188 else
2189 mode = "r";
2190 text = PyUnicode_FromString(mode);
2191 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
2192 goto error;
2193 Py_CLEAR(text);
2194 return stream;
2195
2196error:
2197 Py_XDECREF(buf);
2198 Py_XDECREF(stream);
2199 Py_XDECREF(text);
2200 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10002201
Victor Stinner874dbe82015-09-04 17:29:57 +02002202 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
2203 /* Issue #24891: the file descriptor was closed after the first
2204 is_valid_fd() check was called. Ignore the OSError and set the
2205 stream to None. */
2206 PyErr_Clear();
2207 Py_RETURN_NONE;
2208 }
2209 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002210}
2211
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002212/* Set builtins.open to io.OpenWrapper */
2213static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05002214init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002215{
2216 PyObject *iomod = NULL, *wrapper;
2217 PyObject *bimod = NULL;
2218 PyStatus res = _PyStatus_OK();
2219
2220 if (!(iomod = PyImport_ImportModule("io"))) {
2221 goto error;
2222 }
2223
2224 if (!(bimod = PyImport_ImportModule("builtins"))) {
2225 goto error;
2226 }
2227
2228 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
2229 goto error;
2230 }
2231
2232 /* Set builtins.open */
2233 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2234 Py_DECREF(wrapper);
2235 goto error;
2236 }
2237 Py_DECREF(wrapper);
2238 goto done;
2239
2240error:
2241 res = _PyStatus_ERR("can't initialize io.open");
2242
2243done:
2244 Py_XDECREF(bimod);
2245 Py_XDECREF(iomod);
2246 return res;
2247}
2248
2249
Nick Coghland6009512014-11-20 21:39:37 +10002250/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02002251static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002252init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002253{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01002254 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10002255 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08002256 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10002257 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02002258 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02002259 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002260
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002261 /* Check that stdin is not a directory
2262 Using shell redirection, you can redirect stdin to a directory,
2263 crashing the Python interpreter. Catch this common mistake here
2264 and output a useful error message. Note that under MS Windows,
2265 the shell already prevents that. */
2266#ifndef MS_WINDOWS
2267 struct _Py_stat_struct sb;
2268 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2269 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002270 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01002271 }
2272#endif
2273
Nick Coghland6009512014-11-20 21:39:37 +10002274 if (!(iomod = PyImport_ImportModule("io"))) {
2275 goto error;
2276 }
Nick Coghland6009512014-11-20 21:39:37 +10002277
Nick Coghland6009512014-11-20 21:39:37 +10002278 /* Set sys.stdin */
2279 fd = fileno(stdin);
2280 /* Under some conditions stdin, stdout and stderr may not be connected
2281 * and fileno() may point to an invalid file descriptor. For example
2282 * GUI apps don't have valid standard streams by default.
2283 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002284 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002285 config->stdio_encoding,
2286 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002287 if (std == NULL)
2288 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002289 PySys_SetObject("__stdin__", std);
2290 _PySys_SetObjectId(&PyId_stdin, std);
2291 Py_DECREF(std);
2292
2293 /* Set sys.stdout */
2294 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002295 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002296 config->stdio_encoding,
2297 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002298 if (std == NULL)
2299 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002300 PySys_SetObject("__stdout__", std);
2301 _PySys_SetObjectId(&PyId_stdout, std);
2302 Py_DECREF(std);
2303
2304#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2305 /* Set sys.stderr, replaces the preliminary stderr */
2306 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002307 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002308 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002309 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002310 if (std == NULL)
2311 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002312
2313 /* Same as hack above, pre-import stderr's codec to avoid recursion
2314 when import.c tries to write to stderr in verbose mode. */
2315 encoding_attr = PyObject_GetAttrString(std, "encoding");
2316 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002317 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002318 if (std_encoding != NULL) {
2319 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2320 Py_XDECREF(codec_info);
2321 }
2322 Py_DECREF(encoding_attr);
2323 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002324 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002325
2326 if (PySys_SetObject("__stderr__", std) < 0) {
2327 Py_DECREF(std);
2328 goto error;
2329 }
2330 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2331 Py_DECREF(std);
2332 goto error;
2333 }
2334 Py_DECREF(std);
2335#endif
2336
Victor Stinnera7368ac2017-11-15 18:11:45 -08002337 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002338
Victor Stinnera7368ac2017-11-15 18:11:45 -08002339error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002340 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002341
2342done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002343 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002344 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002345 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002346}
2347
2348
Victor Stinner10dc4842015-03-24 12:01:30 +01002349static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002350_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2351 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002352{
Victor Stinner314b8782021-01-18 18:34:56 +01002353 PUTS(fd, "\n");
Victor Stinner10dc4842015-03-24 12:01:30 +01002354
2355 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002356 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002357}
Victor Stinner791da1c2016-03-14 16:53:12 +01002358
2359/* Print the current exception (if an exception is set) with its traceback,
2360 or display the current Python stack.
2361
2362 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2363 called on catastrophic cases.
2364
2365 Return 1 if the traceback was displayed, 0 otherwise. */
2366
2367static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002368_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002369{
2370 PyObject *ferr, *res;
2371 PyObject *exception, *v, *tb;
2372 int has_tb;
2373
Victor Stinnerb45d2592019-06-20 00:05:23 +02002374 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002375 if (exception == NULL) {
2376 /* No current exception */
2377 return 0;
2378 }
2379
2380 ferr = _PySys_GetObjectId(&PyId_stderr);
2381 if (ferr == NULL || ferr == Py_None) {
2382 /* sys.stderr is not set yet or set to None,
2383 no need to try to display the exception */
2384 return 0;
2385 }
2386
Victor Stinnerb45d2592019-06-20 00:05:23 +02002387 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002388 if (tb == NULL) {
2389 tb = Py_None;
2390 Py_INCREF(tb);
2391 }
2392 PyException_SetTraceback(v, tb);
2393 if (exception == NULL) {
2394 /* PyErr_NormalizeException() failed */
2395 return 0;
2396 }
2397
2398 has_tb = (tb != Py_None);
2399 PyErr_Display(exception, v, tb);
2400 Py_XDECREF(exception);
2401 Py_XDECREF(v);
2402 Py_XDECREF(tb);
2403
2404 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002405 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002406 if (res == NULL) {
2407 _PyErr_Clear(tstate);
2408 }
2409 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002410 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002411 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002412
2413 return has_tb;
2414}
2415
Nick Coghland6009512014-11-20 21:39:37 +10002416/* Print fatal error message and abort */
2417
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002418#ifdef MS_WINDOWS
2419static void
2420fatal_output_debug(const char *msg)
2421{
2422 /* buffer of 256 bytes allocated on the stack */
2423 WCHAR buffer[256 / sizeof(WCHAR)];
2424 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2425 size_t msglen;
2426
2427 OutputDebugStringW(L"Fatal Python error: ");
2428
2429 msglen = strlen(msg);
2430 while (msglen) {
2431 size_t i;
2432
2433 if (buflen > msglen) {
2434 buflen = msglen;
2435 }
2436
2437 /* Convert the message to wchar_t. This uses a simple one-to-one
2438 conversion, assuming that the this error message actually uses
2439 ASCII only. If this ceases to be true, we will have to convert. */
2440 for (i=0; i < buflen; ++i) {
2441 buffer[i] = msg[i];
2442 }
2443 buffer[i] = L'\0';
2444 OutputDebugStringW(buffer);
2445
2446 msg += buflen;
2447 msglen -= buflen;
2448 }
2449 OutputDebugStringW(L"\n");
2450}
2451#endif
2452
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002453
2454static void
Victor Stinner314b8782021-01-18 18:34:56 +01002455fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002456{
Victor Stinner314b8782021-01-18 18:34:56 +01002457 PUTS(fd, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002458 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2459 if (finalizing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002460 PUTS(fd, "finalizing (tstate=0x");
2461 _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
2462 PUTS(fd, ")");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002463 }
2464 else if (runtime->initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002465 PUTS(fd, "initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002466 }
2467 else if (runtime->core_initialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002468 PUTS(fd, "core initialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002469 }
2470 else if (runtime->preinitialized) {
Victor Stinner314b8782021-01-18 18:34:56 +01002471 PUTS(fd, "preinitialized");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002472 }
2473 else if (runtime->preinitializing) {
Victor Stinner314b8782021-01-18 18:34:56 +01002474 PUTS(fd, "preinitializing");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002475 }
2476 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002477 PUTS(fd, "unknown");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002478 }
Victor Stinner314b8782021-01-18 18:34:56 +01002479 PUTS(fd, "\n");
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002480}
2481
2482
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002483static inline void _Py_NO_RETURN
2484fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002485{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002486 if (status < 0) {
2487#if defined(MS_WINDOWS) && defined(_DEBUG)
2488 DebugBreak();
2489#endif
2490 abort();
2491 }
2492 else {
2493 exit(status);
2494 }
2495}
2496
2497
Victor Stinner66f77ca2021-01-19 23:35:27 +01002498// Dump the list of extension modules of sys.modules, excluding stdlib modules
Victor Stinner9852cb32021-01-25 23:12:50 +01002499// (sys.stdlib_module_names), into fd file descriptor.
Victor Stinner66f77ca2021-01-19 23:35:27 +01002500//
Victor Stinner250035d2021-01-18 20:47:13 +01002501// This function is called by a signal handler in faulthandler: avoid memory
Victor Stinner66f77ca2021-01-19 23:35:27 +01002502// allocations and keep the implementation simple. For example, the list is not
2503// sorted on purpose.
Victor Stinner250035d2021-01-18 20:47:13 +01002504void
2505_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
2506{
2507 if (interp == NULL) {
2508 return;
2509 }
2510 PyObject *modules = interp->modules;
Victor Stinner66f77ca2021-01-19 23:35:27 +01002511 if (modules == NULL || !PyDict_Check(modules)) {
Victor Stinner250035d2021-01-18 20:47:13 +01002512 return;
2513 }
2514
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002515 Py_ssize_t pos;
2516 PyObject *key, *value;
2517
2518 // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
2519 // memory cannot be allocated on the heap in a signal handler.
2520 // Iterate on the dict instead.
Victor Stinner9852cb32021-01-25 23:12:50 +01002521 PyObject *stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002522 pos = 0;
2523 while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
2524 if (PyUnicode_Check(key)
Victor Stinner9852cb32021-01-25 23:12:50 +01002525 && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
2526 stdlib_module_names = value;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002527 break;
2528 }
2529 }
Victor Stinner9852cb32021-01-25 23:12:50 +01002530 // If we failed to get sys.stdlib_module_names or it's not a frozenset,
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002531 // don't exclude stdlib modules.
Victor Stinner9852cb32021-01-25 23:12:50 +01002532 if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
2533 stdlib_module_names = NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002534 }
2535
2536 // List extensions
Victor Stinner66f77ca2021-01-19 23:35:27 +01002537 int header = 1;
2538 Py_ssize_t count = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002539 pos = 0;
Victor Stinner250035d2021-01-18 20:47:13 +01002540 while (PyDict_Next(modules, &pos, &key, &value)) {
2541 if (!PyUnicode_Check(key)) {
2542 continue;
2543 }
2544 if (!_PyModule_IsExtension(value)) {
2545 continue;
2546 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002547 // Use the module name from the sys.modules key,
2548 // don't attempt to get the module object name.
Victor Stinner9852cb32021-01-25 23:12:50 +01002549 if (stdlib_module_names != NULL) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002550 int is_stdlib_ext = 0;
2551
Victor Stinner9852cb32021-01-25 23:12:50 +01002552 Py_ssize_t i = 0;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002553 PyObject *item;
2554 Py_hash_t hash;
Victor Stinner9852cb32021-01-25 23:12:50 +01002555 while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002556 if (PyUnicode_Check(item)
2557 && PyUnicode_Compare(key, item) == 0)
2558 {
2559 is_stdlib_ext = 1;
2560 break;
2561 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002562 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002563 if (is_stdlib_ext) {
2564 // Ignore stdlib extension
2565 continue;
2566 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002567 }
2568
2569 if (header) {
2570 PUTS(fd, "\nExtension modules: ");
2571 header = 0;
2572 }
2573 else {
Victor Stinner250035d2021-01-18 20:47:13 +01002574 PUTS(fd, ", ");
2575 }
Victor Stinner250035d2021-01-18 20:47:13 +01002576
2577 _Py_DumpASCII(fd, key);
Victor Stinner66f77ca2021-01-19 23:35:27 +01002578 count++;
Victor Stinner250035d2021-01-18 20:47:13 +01002579 }
Victor Stinner66f77ca2021-01-19 23:35:27 +01002580
2581 if (count) {
2582 PUTS(fd, " (total: ");
2583 _Py_DumpDecimal(fd, count);
2584 PUTS(fd, ")");
2585 PUTS(fd, "\n");
2586 }
Victor Stinner250035d2021-01-18 20:47:13 +01002587}
2588
2589
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002590static void _Py_NO_RETURN
Victor Stinner314b8782021-01-18 18:34:56 +01002591fatal_error(int fd, int header, const char *prefix, const char *msg,
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002592 int status)
2593{
Victor Stinner53345a42015-03-25 01:55:14 +01002594 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002595
2596 if (reentrant) {
2597 /* Py_FatalError() caused a second fatal error.
2598 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002599 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002600 }
2601 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002602
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002603 if (header) {
Victor Stinner314b8782021-01-18 18:34:56 +01002604 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002605 if (prefix) {
Victor Stinner314b8782021-01-18 18:34:56 +01002606 PUTS(fd, prefix);
2607 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002608 }
2609 if (msg) {
Victor Stinner314b8782021-01-18 18:34:56 +01002610 PUTS(fd, msg);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002611 }
2612 else {
Victor Stinner314b8782021-01-18 18:34:56 +01002613 PUTS(fd, "<message not set>");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002614 }
Victor Stinner314b8782021-01-18 18:34:56 +01002615 PUTS(fd, "\n");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002616 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002617
2618 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner314b8782021-01-18 18:34:56 +01002619 fatal_error_dump_runtime(fd, runtime);
Victor Stinner10dc4842015-03-24 12:01:30 +01002620
Victor Stinner3a228ab2018-11-01 00:26:41 +01002621 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002622 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002623
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002624 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2625 has no Python thread state.
2626
2627 tss_tstate != tstate if the current Python thread does not hold the GIL.
2628 */
Victor Stinner314b8782021-01-18 18:34:56 +01002629 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2630 PyInterpreterState *interp = NULL;
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002631 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
Victor Stinner314b8782021-01-18 18:34:56 +01002632 if (tstate != NULL) {
2633 interp = tstate->interp;
2634 }
2635 else if (tss_tstate != NULL) {
2636 interp = tss_tstate->interp;
2637 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002638 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner314b8782021-01-18 18:34:56 +01002639
Victor Stinner3a228ab2018-11-01 00:26:41 +01002640 if (has_tstate_and_gil) {
2641 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002642 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002643 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002644 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002645 }
2646 }
2647 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002648 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002649 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002650
Victor Stinner250035d2021-01-18 20:47:13 +01002651 _Py_DumpExtensionModules(fd, interp);
2652
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002653 /* The main purpose of faulthandler is to display the traceback.
2654 This function already did its best to display a traceback.
2655 Disable faulthandler to prevent writing a second traceback
2656 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002657 _PyFaulthandler_Fini();
2658
Victor Stinner791da1c2016-03-14 16:53:12 +01002659 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002660 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002661 /* Flush sys.stdout and sys.stderr */
2662 flush_std_files();
2663 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002664
Nick Coghland6009512014-11-20 21:39:37 +10002665#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002666 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002667#endif /* MS_WINDOWS */
2668
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002669 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002670}
2671
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002672
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002673#undef Py_FatalError
2674
Victor Stinner19760862017-12-20 01:41:59 +01002675void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002676Py_FatalError(const char *msg)
2677{
Victor Stinner314b8782021-01-18 18:34:56 +01002678 fatal_error(fileno(stderr), 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002679}
2680
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002681
Victor Stinner19760862017-12-20 01:41:59 +01002682void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002683_Py_FatalErrorFunc(const char *func, const char *msg)
2684{
Victor Stinner314b8782021-01-18 18:34:56 +01002685 fatal_error(fileno(stderr), 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002686}
2687
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002688
2689void _Py_NO_RETURN
2690_Py_FatalErrorFormat(const char *func, const char *format, ...)
2691{
2692 static int reentrant = 0;
2693 if (reentrant) {
2694 /* _Py_FatalErrorFormat() caused a second fatal error */
2695 fatal_error_exit(-1);
2696 }
2697 reentrant = 1;
2698
2699 FILE *stream = stderr;
Victor Stinner314b8782021-01-18 18:34:56 +01002700 const int fd = fileno(stream);
2701 PUTS(fd, "Fatal Python error: ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002702 if (func) {
Victor Stinner314b8782021-01-18 18:34:56 +01002703 PUTS(fd, func);
2704 PUTS(fd, ": ");
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002705 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002706
2707 va_list vargs;
2708#ifdef HAVE_STDARG_PROTOTYPES
2709 va_start(vargs, format);
2710#else
2711 va_start(vargs);
2712#endif
2713 vfprintf(stream, format, vargs);
2714 va_end(vargs);
2715
2716 fputs("\n", stream);
2717 fflush(stream);
2718
Victor Stinner314b8782021-01-18 18:34:56 +01002719 fatal_error(fd, 0, NULL, NULL, -1);
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002720}
2721
2722
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002723void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002724Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002725{
Victor Stinner331a6a52019-05-27 16:39:22 +02002726 if (_PyStatus_IS_EXIT(status)) {
2727 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002728 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002729 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner314b8782021-01-18 18:34:56 +01002730 fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002731 }
2732 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002733 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002734 }
Nick Coghland6009512014-11-20 21:39:37 +10002735}
2736
Victor Stinner357704c2020-12-14 23:07:54 +01002737
Nick Coghland6009512014-11-20 21:39:37 +10002738/* Wait until threading._shutdown completes, provided
2739 the threading module was imported in the first place.
2740 The shutdown routine will wait until all non-daemon
2741 "threading" threads have completed. */
2742static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002743wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002744{
Nick Coghland6009512014-11-20 21:39:37 +10002745 _Py_IDENTIFIER(_shutdown);
2746 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002747 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002748 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002749 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002750 PyErr_WriteUnraisable(NULL);
2751 }
2752 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002753 return;
2754 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002755 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002756 if (result == NULL) {
2757 PyErr_WriteUnraisable(threading);
2758 }
2759 else {
2760 Py_DECREF(result);
2761 }
2762 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002763}
2764
2765#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002766int Py_AtExit(void (*func)(void))
2767{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002768 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002769 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002770 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002771 return 0;
2772}
2773
2774static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002775call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002776{
Victor Stinner8e91c242019-04-24 17:24:01 +02002777 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002778 /* pop last function from the list */
2779 runtime->nexitfuncs--;
2780 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2781 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2782
2783 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002784 }
Nick Coghland6009512014-11-20 21:39:37 +10002785
2786 fflush(stdout);
2787 fflush(stderr);
2788}
2789
Victor Stinnercfc88312018-08-01 16:41:25 +02002790void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002791Py_Exit(int sts)
2792{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002793 if (Py_FinalizeEx() < 0) {
2794 sts = 120;
2795 }
Nick Coghland6009512014-11-20 21:39:37 +10002796
2797 exit(sts);
2798}
2799
Nick Coghland6009512014-11-20 21:39:37 +10002800
Nick Coghland6009512014-11-20 21:39:37 +10002801/*
2802 * The file descriptor fd is considered ``interactive'' if either
2803 * a) isatty(fd) is TRUE, or
2804 * b) the -i flag was given, and the filename associated with
2805 * the descriptor is NULL or "<stdin>" or "???".
2806 */
2807int
2808Py_FdIsInteractive(FILE *fp, const char *filename)
2809{
2810 if (isatty((int)fileno(fp)))
2811 return 1;
2812 if (!Py_InteractiveFlag)
2813 return 0;
2814 return (filename == NULL) ||
2815 (strcmp(filename, "<stdin>") == 0) ||
2816 (strcmp(filename, "???") == 0);
2817}
2818
2819
Victor Stinnera82f63f2020-12-09 22:37:27 +01002820int
2821_Py_FdIsInteractive(FILE *fp, PyObject *filename)
2822{
2823 if (isatty((int)fileno(fp))) {
2824 return 1;
2825 }
2826 if (!Py_InteractiveFlag) {
2827 return 0;
2828 }
2829 return (filename == NULL) ||
2830 (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0) ||
2831 (PyUnicode_CompareWithASCIIString(filename, "???") == 0);
2832}
2833
2834
Nick Coghland6009512014-11-20 21:39:37 +10002835/* Wrappers around sigaction() or signal(). */
2836
2837PyOS_sighandler_t
2838PyOS_getsig(int sig)
2839{
2840#ifdef HAVE_SIGACTION
2841 struct sigaction context;
2842 if (sigaction(sig, NULL, &context) == -1)
2843 return SIG_ERR;
2844 return context.sa_handler;
2845#else
2846 PyOS_sighandler_t handler;
2847/* Special signal handling for the secure CRT in Visual Studio 2005 */
2848#if defined(_MSC_VER) && _MSC_VER >= 1400
2849 switch (sig) {
2850 /* Only these signals are valid */
2851 case SIGINT:
2852 case SIGILL:
2853 case SIGFPE:
2854 case SIGSEGV:
2855 case SIGTERM:
2856 case SIGBREAK:
2857 case SIGABRT:
2858 break;
2859 /* Don't call signal() with other values or it will assert */
2860 default:
2861 return SIG_ERR;
2862 }
2863#endif /* _MSC_VER && _MSC_VER >= 1400 */
2864 handler = signal(sig, SIG_IGN);
2865 if (handler != SIG_ERR)
2866 signal(sig, handler);
2867 return handler;
2868#endif
2869}
2870
2871/*
2872 * All of the code in this function must only use async-signal-safe functions,
2873 * listed at `man 7 signal` or
2874 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2875 */
2876PyOS_sighandler_t
2877PyOS_setsig(int sig, PyOS_sighandler_t handler)
2878{
2879#ifdef HAVE_SIGACTION
2880 /* Some code in Modules/signalmodule.c depends on sigaction() being
2881 * used here if HAVE_SIGACTION is defined. Fix that if this code
2882 * changes to invalidate that assumption.
2883 */
2884 struct sigaction context, ocontext;
2885 context.sa_handler = handler;
2886 sigemptyset(&context.sa_mask);
Gregory P. Smith02ac6f42021-03-04 21:49:30 -08002887 /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
2888 * extension module or embedding code may use where tiny thread stacks
2889 * are used. https://bugs.python.org/issue43390 */
2890 context.sa_flags = SA_ONSTACK;
Nick Coghland6009512014-11-20 21:39:37 +10002891 if (sigaction(sig, &context, &ocontext) == -1)
2892 return SIG_ERR;
2893 return ocontext.sa_handler;
2894#else
2895 PyOS_sighandler_t oldhandler;
2896 oldhandler = signal(sig, handler);
2897#ifdef HAVE_SIGINTERRUPT
2898 siginterrupt(sig, 1);
2899#endif
2900 return oldhandler;
2901#endif
2902}
2903
2904#ifdef __cplusplus
2905}
2906#endif