blob: b7019e3bb67abba2cd5b4c9d4e361947360c3b23 [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 Stinner09532fe2019-05-10 23:39:09 +02007#include "pycore_ceval.h"
Victor Stinner99fcc612019-04-29 13:04:07 +02008#include "pycore_context.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02009#include "pycore_import.h" /* _PyImport_FindBuiltin */
Victor Stinner331a6a52019-05-27 16:39:22 +020010#include "pycore_initconfig.h"
Victor Stinner353933e2018-11-23 13:08:26 +010011#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010012#include "pycore_hamt.h"
Victor Stinner4b524162020-02-03 17:28:26 +010013#include "pycore_object.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010014#include "pycore_pathconfig.h"
Victor Stinnerb45d2592019-06-20 00:05:23 +020015#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010016#include "pycore_pylifecycle.h"
17#include "pycore_pymem.h"
18#include "pycore_pystate.h"
Victor Stinnered488662019-05-20 00:14:57 +020019#include "pycore_traceback.h"
Nick Coghland6009512014-11-20 21:39:37 +100020#include "grammar.h"
21#include "node.h"
22#include "token.h"
23#include "parsetok.h"
24#include "errcode.h"
25#include "code.h"
26#include "symtable.h"
27#include "ast.h"
28#include "marshal.h"
29#include "osdefs.h"
30#include <locale.h>
31
32#ifdef HAVE_SIGNAL_H
33#include <signal.h>
34#endif
35
36#ifdef MS_WINDOWS
37#include "malloc.h" /* for alloca */
38#endif
39
40#ifdef HAVE_LANGINFO_H
41#include <langinfo.h>
42#endif
43
44#ifdef MS_WINDOWS
45#undef BYTE
46#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070047
48extern PyTypeObject PyWindowsConsoleIO_Type;
49#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100050#endif
51
52_Py_IDENTIFIER(flush);
53_Py_IDENTIFIER(name);
54_Py_IDENTIFIER(stdin);
55_Py_IDENTIFIER(stdout);
56_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060057_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100058
59#ifdef __cplusplus
60extern "C" {
61#endif
62
Nick Coghland6009512014-11-20 21:39:37 +100063extern grammar _PyParser_Grammar; /* From graminit.c */
64
Victor Stinnerb45d2592019-06-20 00:05:23 +020065/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020066static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020067static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050068static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020069static PyStatus init_sys_streams(PyThreadState *tstate);
70static PyStatus init_signals(PyThreadState *tstate);
71static void call_py_exitfuncs(PyThreadState *tstate);
72static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020073static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100074
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080075int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010077static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078
Victor Stinner331a6a52019-05-27 16:39:22 +020079PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080_PyRuntime_Initialize(void)
81{
82 /* XXX We only initialize once in the process, which aligns with
83 the static initialization of the former globals now found in
84 _PyRuntime. However, _PyRuntime *should* be initialized with
85 every Py_Initialize() call, but doing so breaks the runtime.
86 This is because the runtime state is not properly finalized
87 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010088 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020089 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080090 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010091 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080092
93 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
96void
97_PyRuntime_Finalize(void)
98{
99 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +0100100 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600101}
102
103int
104_Py_IsFinalizing(void)
105{
Victor Stinner7b3c2522020-03-07 00:24:23 +0100106 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Hack to force loading of object files */
110int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
111 PyOS_mystrnicmp; /* Python/pystrcmp.o */
112
113/* PyModule_GetWarningsModule is no longer necessary as of 2.6
114since _warnings is builtin. This API should not be used. */
115PyObject *
116PyModule_GetWarningsModule(void)
117{
118 return PyImport_ImportModule("warnings");
119}
120
Eric Snowc7ec9982017-05-23 23:00:52 -0700121
Eric Snow1abcf672017-05-23 21:46:51 -0700122/* APIs to access the initialization flags
123 *
124 * Can be called prior to Py_Initialize.
125 */
Nick Coghland6009512014-11-20 21:39:37 +1000126
Eric Snow1abcf672017-05-23 21:46:51 -0700127int
128_Py_IsCoreInitialized(void)
129{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600130 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700131}
Nick Coghland6009512014-11-20 21:39:37 +1000132
133int
134Py_IsInitialized(void)
135{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600136 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000137}
138
Nick Coghlan6ea41862017-06-11 13:16:15 +1000139
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000140/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
141 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000142 initializations fail, a fatal error is issued and the function does
143 not return. On return, the first thread and interpreter state have
144 been created.
145
146 Locking: you must hold the interpreter lock while calling this.
147 (If the lock has not yet been initialized, that's equivalent to
148 having the lock, but you cannot use multiple threads.)
149
150*/
151
Victor Stinner331a6a52019-05-27 16:39:22 +0200152static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200153init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000154{
155 PyObject *importlib;
156 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000157 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200158 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +0200159 int verbose = interp->config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000160
161 /* Import _importlib through its frozen version, _frozen_importlib. */
162 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200163 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000164 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200165 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000166 PySys_FormatStderr("import _frozen_importlib # frozen\n");
167 }
168 importlib = PyImport_AddModule("_frozen_importlib");
169 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200170 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000171 }
172 interp->importlib = importlib;
173 Py_INCREF(interp->importlib);
174
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300175 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
176 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200177 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300178 Py_INCREF(interp->import_func);
179
Victor Stinnercd6e6942015-09-18 09:11:57 +0200180 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800181 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000182 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200183 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000184 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200185 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200186 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000187 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600188 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200189 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000190 }
191
Victor Stinnercd6e6942015-09-18 09:11:57 +0200192 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000193 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
194 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200195 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200196 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000197 }
198 Py_DECREF(value);
199 Py_DECREF(impmod);
200
Victor Stinner331a6a52019-05-27 16:39:22 +0200201 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000202}
203
Victor Stinner331a6a52019-05-27 16:39:22 +0200204static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200205init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700206{
207 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200208 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700209 "_install_external_importers", "");
210 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200211 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200212 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700213 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200214 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200215 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700216}
Nick Coghland6009512014-11-20 21:39:37 +1000217
Nick Coghlan6ea41862017-06-11 13:16:15 +1000218/* Helper functions to better handle the legacy C locale
219 *
220 * The legacy C locale assumes ASCII as the default text encoding, which
221 * causes problems not only for the CPython runtime, but also other
222 * components like GNU readline.
223 *
224 * Accordingly, when the CLI detects it, it attempts to coerce it to a
225 * more capable UTF-8 based alternative as follows:
226 *
227 * if (_Py_LegacyLocaleDetected()) {
228 * _Py_CoerceLegacyLocale();
229 * }
230 *
231 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
232 *
233 * Locale coercion also impacts the default error handler for the standard
234 * streams: while the usual default is "strict", the default for the legacy
235 * C locale and for any of the coercion target locales is "surrogateescape".
236 */
237
238int
Victor Stinner0f721472019-05-20 17:16:38 +0200239_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000240{
241#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200242 if (!warn) {
243 const char *locale_override = getenv("LC_ALL");
244 if (locale_override != NULL && *locale_override != '\0') {
245 /* Don't coerce C locale if the LC_ALL environment variable
246 is set */
247 return 0;
248 }
249 }
250
Nick Coghlan6ea41862017-06-11 13:16:15 +1000251 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000252 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
253 * the POSIX locale as a simple alias for the C locale, so
254 * we may also want to check for that explicitly.
255 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000256 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
257 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
258#else
259 /* Windows uses code pages instead of locales, so no locale is legacy */
260 return 0;
261#endif
262}
263
Victor Stinnerb0051362019-11-22 17:52:42 +0100264#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000265static const char *_C_LOCALE_WARNING =
266 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
267 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
268 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
269 "locales is recommended.\n";
270
Nick Coghlaneb817952017-06-18 12:29:42 +1000271static void
Victor Stinner43125222019-04-24 18:23:53 +0200272emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000273{
Victor Stinner331a6a52019-05-27 16:39:22 +0200274 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200275 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200276 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000277 }
278}
Victor Stinnerb0051362019-11-22 17:52:42 +0100279#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000280
Nick Coghlan6ea41862017-06-11 13:16:15 +1000281typedef struct _CandidateLocale {
282 const char *locale_name; /* The locale to try as a coercion target */
283} _LocaleCoercionTarget;
284
285static _LocaleCoercionTarget _TARGET_LOCALES[] = {
286 {"C.UTF-8"},
287 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000288 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289 {NULL}
290};
291
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200292
293int
294_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200296 const _LocaleCoercionTarget *target = NULL;
297 for (target = _TARGET_LOCALES; target->locale_name; target++) {
298 if (strcmp(ctype_loc, target->locale_name) == 0) {
299 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200301 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200302 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000303}
304
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200305
Nick Coghlan6ea41862017-06-11 13:16:15 +1000306#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100307static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000308 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
309 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
310
Victor Stinner0f721472019-05-20 17:16:38 +0200311static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200312_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313{
314 const char *newloc = target->locale_name;
315
316 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100317 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318
319 /* Set the relevant locale environment variable */
320 if (setenv("LC_CTYPE", newloc, 1)) {
321 fprintf(stderr,
322 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200323 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000324 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200325 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100326 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000327 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328
329 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100330 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200331 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000332}
333#endif
334
Victor Stinner0f721472019-05-20 17:16:38 +0200335int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200336_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000337{
Victor Stinner0f721472019-05-20 17:16:38 +0200338 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000339#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200340 char *oldloc = NULL;
341
342 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
343 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200344 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200345 }
346
Victor Stinner94540602017-12-16 04:54:22 +0100347 const char *locale_override = getenv("LC_ALL");
348 if (locale_override == NULL || *locale_override == '\0') {
349 /* LC_ALL is also not set (or is set to an empty string) */
350 const _LocaleCoercionTarget *target = NULL;
351 for (target = _TARGET_LOCALES; target->locale_name; target++) {
352 const char *new_locale = setlocale(LC_CTYPE,
353 target->locale_name);
354 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400355#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100356 /* Also ensure that nl_langinfo works in this locale */
357 char *codeset = nl_langinfo(CODESET);
358 if (!codeset || *codeset == '\0') {
359 /* CODESET is not set or empty, so skip coercion */
360 new_locale = NULL;
361 _Py_SetLocaleFromEnv(LC_CTYPE);
362 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000363 }
Victor Stinner94540602017-12-16 04:54:22 +0100364#endif
365 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200366 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200367 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000368 }
369 }
370 }
371 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200372
373 setlocale(LC_CTYPE, oldloc);
374
375done:
376 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000377#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200378 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000379}
380
xdegaye1588be62017-11-12 12:45:59 +0100381/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
382 * isolate the idiosyncrasies of different libc implementations. It reads the
383 * appropriate environment variable and uses its value to select the locale for
384 * 'category'. */
385char *
386_Py_SetLocaleFromEnv(int category)
387{
Victor Stinner353933e2018-11-23 13:08:26 +0100388 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100389#ifdef __ANDROID__
390 const char *locale;
391 const char **pvar;
392#ifdef PY_COERCE_C_LOCALE
393 const char *coerce_c_locale;
394#endif
395 const char *utf8_locale = "C.UTF-8";
396 const char *env_var_set[] = {
397 "LC_ALL",
398 "LC_CTYPE",
399 "LANG",
400 NULL,
401 };
402
403 /* Android setlocale(category, "") doesn't check the environment variables
404 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
405 * check the environment variables listed in env_var_set. */
406 for (pvar=env_var_set; *pvar; pvar++) {
407 locale = getenv(*pvar);
408 if (locale != NULL && *locale != '\0') {
409 if (strcmp(locale, utf8_locale) == 0 ||
410 strcmp(locale, "en_US.UTF-8") == 0) {
411 return setlocale(category, utf8_locale);
412 }
413 return setlocale(category, "C");
414 }
415 }
416
417 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
418 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
419 * Quote from POSIX section "8.2 Internationalization Variables":
420 * "4. If the LANG environment variable is not set or is set to the empty
421 * string, the implementation-defined default locale shall be used." */
422
423#ifdef PY_COERCE_C_LOCALE
424 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
425 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
426 /* Some other ported code may check the environment variables (e.g. in
427 * extension modules), so we make sure that they match the locale
428 * configuration */
429 if (setenv("LC_CTYPE", utf8_locale, 1)) {
430 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
431 "environment variable to %s\n", utf8_locale);
432 }
433 }
434#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100435 res = setlocale(category, utf8_locale);
436#else /* !defined(__ANDROID__) */
437 res = setlocale(category, "");
438#endif
439 _Py_ResetForceASCII();
440 return res;
xdegaye1588be62017-11-12 12:45:59 +0100441}
442
Nick Coghlan6ea41862017-06-11 13:16:15 +1000443
Eric Snow1abcf672017-05-23 21:46:51 -0700444/* Global initializations. Can be undone by Py_Finalize(). Don't
445 call this twice without an intervening Py_Finalize() call.
446
Victor Stinner331a6a52019-05-27 16:39:22 +0200447 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700448 must have a corresponding call to Py_Finalize.
449
450 Locking: you must hold the interpreter lock while calling these APIs.
451 (If the lock has not yet been initialized, that's equivalent to
452 having the lock, but you cannot use multiple threads.)
453
454*/
455
Victor Stinner331a6a52019-05-27 16:39:22 +0200456static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200457pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200458 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200459 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200460{
Victor Stinner331a6a52019-05-27 16:39:22 +0200461 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100462 PyThreadState *tstate = _PyThreadState_GET();
463 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200464 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100465 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200466 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100467
468 PyInterpreterState *interp = tstate->interp;
469 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200470 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100471 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100472
Victor Stinner331a6a52019-05-27 16:39:22 +0200473 _PyConfig_Write(config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200474
Victor Stinner331a6a52019-05-27 16:39:22 +0200475 status = _PyConfig_Copy(&interp->config, config);
476 if (_PyStatus_EXCEPTION(status)) {
477 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200478 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200479 config = &interp->config;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200480
Victor Stinner331a6a52019-05-27 16:39:22 +0200481 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200482 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200483 if (_PyStatus_EXCEPTION(status)) {
484 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200485 }
486 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200487 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200488}
489
490
Victor Stinner331a6a52019-05-27 16:39:22 +0200491static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200492pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200493 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000494{
Victor Stinner43125222019-04-24 18:23:53 +0200495 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200496 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200497 }
Victor Stinnerda273412017-12-15 01:46:02 +0100498
Victor Stinner331a6a52019-05-27 16:39:22 +0200499 _PyConfig_Write(config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600500
Eric Snow1abcf672017-05-23 21:46:51 -0700501 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
502 * threads behave a little more gracefully at interpreter shutdown.
503 * We clobber it here so the new interpreter can start with a clean
504 * slate.
505 *
506 * However, this may still lead to misbehaviour if there are daemon
507 * threads still hanging around from a previous Py_Initialize/Finalize
508 * pair :(
509 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100510 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600511
Victor Stinner331a6a52019-05-27 16:39:22 +0200512 PyStatus status = _Py_HashRandomization_Init(config);
513 if (_PyStatus_EXCEPTION(status)) {
514 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800515 }
516
Victor Stinner331a6a52019-05-27 16:39:22 +0200517 status = _PyInterpreterState_Enable(runtime);
518 if (_PyStatus_EXCEPTION(status)) {
519 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800520 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200521 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100522}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800523
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100524
Victor Stinner331a6a52019-05-27 16:39:22 +0200525static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200526pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200527 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200528 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100529{
530 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100531 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200532 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100533 }
534
Victor Stinner331a6a52019-05-27 16:39:22 +0200535 PyStatus status = _PyConfig_Copy(&interp->config, config);
536 if (_PyStatus_EXCEPTION(status)) {
537 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100538 }
Nick Coghland6009512014-11-20 21:39:37 +1000539
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200540 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200541 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200542 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200543 }
Nick Coghland6009512014-11-20 21:39:37 +1000544 (void) PyThreadState_Swap(tstate);
545
Victor Stinner99fcc612019-04-29 13:04:07 +0200546 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
547 destroying the GIL might fail when it is being referenced from
548 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000549 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000550 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100551 _PyEval_FiniThreads(tstate);
Victor Stinner2914bb32018-01-29 11:57:45 +0100552
Nick Coghland6009512014-11-20 21:39:37 +1000553 /* Auto-thread-state API */
Victor Stinner4e53abb2020-03-10 23:49:16 +0100554 status = _PyGILState_Init(tstate);
555 if (_PyStatus_EXCEPTION(status)) {
556 return status;
557 }
Nick Coghland6009512014-11-20 21:39:37 +1000558
Victor Stinner50e6e992020-03-19 02:41:21 +0100559 /* Create the GIL and the pending calls lock */
Victor Stinner111e4ee2020-03-09 21:24:14 +0100560 status = _PyEval_InitThreads(tstate);
561 if (_PyStatus_EXCEPTION(status)) {
562 return status;
563 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100564
Victor Stinnerb45d2592019-06-20 00:05:23 +0200565 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200566 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100567}
Nick Coghland6009512014-11-20 21:39:37 +1000568
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100569
Victor Stinner331a6a52019-05-27 16:39:22 +0200570static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100571pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100572{
Victor Stinner444b39b2019-11-20 01:18:11 +0100573 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100574 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100575
Victor Stinner01b1cc12019-11-20 02:27:56 +0100576 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100577 if (_PyStatus_EXCEPTION(status)) {
578 return status;
579 }
580
Victor Stinnere7e699e2019-11-20 12:08:13 +0100581 if (is_main_interp) {
582 status = _PyTypes_Init();
583 if (_PyStatus_EXCEPTION(status)) {
584 return status;
585 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100586 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100587
Victor Stinner630c8df2019-12-17 13:02:18 +0100588
589 if (!_PyLong_Init(tstate)) {
590 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100591 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100592
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100593 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100594 status = _PyUnicode_Init();
595 if (_PyStatus_EXCEPTION(status)) {
596 return status;
597 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100598 }
599
Victor Stinner331a6a52019-05-27 16:39:22 +0200600 status = _PyExc_Init();
601 if (_PyStatus_EXCEPTION(status)) {
602 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100603 }
604
Victor Stinnere7e699e2019-11-20 12:08:13 +0100605 if (is_main_interp) {
606 if (!_PyFloat_Init()) {
607 return _PyStatus_ERR("can't init float");
608 }
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinnere7e699e2019-11-20 12:08:13 +0100610 if (_PyStructSequence_Init() < 0) {
611 return _PyStatus_ERR("can't initialize structseq");
612 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100613 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200614
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 status = _PyErr_Init();
616 if (_PyStatus_EXCEPTION(status)) {
617 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200618 }
619
Victor Stinnere7e699e2019-11-20 12:08:13 +0100620 if (is_main_interp) {
621 if (!_PyContext_Init()) {
622 return _PyStatus_ERR("can't init context");
623 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100624 }
625
Victor Stinner331a6a52019-05-27 16:39:22 +0200626 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100627}
628
629
Victor Stinner331a6a52019-05-27 16:39:22 +0200630static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200631pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100632{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100633 assert(!_PyErr_Occurred(tstate));
634
Victor Stinnerb45d2592019-06-20 00:05:23 +0200635 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100636 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100637 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100638 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100639
Victor Stinner2582d462019-11-22 19:24:49 +0100640 PyInterpreterState *interp = tstate->interp;
641 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
642 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100643 }
Victor Stinner2582d462019-11-22 19:24:49 +0100644
645 PyObject *builtins_dict = PyModule_GetDict(bimod);
646 if (builtins_dict == NULL) {
647 goto error;
648 }
649 Py_INCREF(builtins_dict);
650 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100651
Victor Stinner331a6a52019-05-27 16:39:22 +0200652 PyStatus status = _PyBuiltins_AddExceptions(bimod);
653 if (_PyStatus_EXCEPTION(status)) {
654 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655 }
Victor Stinner2582d462019-11-22 19:24:49 +0100656
657 interp->builtins_copy = PyDict_Copy(interp->builtins);
658 if (interp->builtins_copy == NULL) {
659 goto error;
660 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000661 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100662
663 assert(!_PyErr_Occurred(tstate));
664
Victor Stinner331a6a52019-05-27 16:39:22 +0200665 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100666
667error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000668 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100669 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100670}
671
672
Victor Stinner331a6a52019-05-27 16:39:22 +0200673static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200674pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100675{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100676 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200677
Victor Stinner2582d462019-11-22 19:24:49 +0100678 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200679 if (_PyStatus_EXCEPTION(status)) {
680 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800681 }
Nick Coghland6009512014-11-20 21:39:37 +1000682
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100683 const PyConfig *config = &tstate->interp->config;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100684 if (_Py_IsMainInterpreter(tstate)) {
685 /* Initialize _warnings. */
Victor Stinner66b79732020-03-02 15:02:18 +0100686 status = _PyWarnings_InitState(tstate);
687 if (_PyStatus_EXCEPTION(status)) {
688 return status;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100689 }
Nick Coghland6009512014-11-20 21:39:37 +1000690
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100691 if (config->_install_importlib) {
692 status = _PyConfig_WritePathConfig(config);
693 if (_PyStatus_EXCEPTION(status)) {
694 return status;
695 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200696 }
697 }
698
Eric Snow1abcf672017-05-23 21:46:51 -0700699 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200700 if (config->_install_importlib) {
701 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200702 if (_PyStatus_EXCEPTION(status)) {
703 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800704 }
Eric Snow1abcf672017-05-23 21:46:51 -0700705 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100706
707 assert(!_PyErr_Occurred(tstate));
708
Victor Stinner331a6a52019-05-27 16:39:22 +0200709 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100710}
711
712
Victor Stinner331a6a52019-05-27 16:39:22 +0200713static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100714pycore_interp_init(PyThreadState *tstate)
715{
716 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100717 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100718
719 status = pycore_init_types(tstate);
720 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100721 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100722 }
723
Victor Stinnerd863ade2019-12-06 03:37:07 +0100724 status = _PySys_Create(tstate, &sysmod);
725 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100726 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100727 }
728
729 status = pycore_init_builtins(tstate);
730 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100731 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100732 }
733
Victor Stinner080ee5a2019-12-08 21:55:58 +0100734 status = pycore_init_import_warnings(tstate, sysmod);
735
736done:
737 /* sys.modules['sys'] contains a strong reference to the module */
738 Py_XDECREF(sysmod);
739 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100740}
741
742
743static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200744pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200745 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200746 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100747{
Victor Stinner331a6a52019-05-27 16:39:22 +0200748 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100749
Victor Stinner331a6a52019-05-27 16:39:22 +0200750 PyStatus status = pycore_init_runtime(runtime, config);
751 if (_PyStatus_EXCEPTION(status)) {
752 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100753 }
754
Victor Stinnerb45d2592019-06-20 00:05:23 +0200755 PyThreadState *tstate;
756 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200757 if (_PyStatus_EXCEPTION(status)) {
758 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100759 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200760 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100761
Victor Stinnerd863ade2019-12-06 03:37:07 +0100762 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200763 if (_PyStatus_EXCEPTION(status)) {
764 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100765 }
Eric Snow1abcf672017-05-23 21:46:51 -0700766
767 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200768 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200769 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700770}
771
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100772
Victor Stinner331a6a52019-05-27 16:39:22 +0200773PyStatus
774_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100775{
Victor Stinner331a6a52019-05-27 16:39:22 +0200776 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100777
Victor Stinner6d1c4672019-05-20 11:02:00 +0200778 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200779 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200780 }
781
Victor Stinner331a6a52019-05-27 16:39:22 +0200782 status = _PyRuntime_Initialize();
783 if (_PyStatus_EXCEPTION(status)) {
784 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100785 }
Victor Stinner43125222019-04-24 18:23:53 +0200786 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100787
Victor Stinnerd3b90412019-09-17 23:59:51 +0200788 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100789 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200790 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100791 }
792
Victor Stinnerd3b90412019-09-17 23:59:51 +0200793 /* Note: preinitialized remains 1 on error, it is only set to 0
794 at exit on success. */
795 runtime->preinitializing = 1;
796
Victor Stinner331a6a52019-05-27 16:39:22 +0200797 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200798
799 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
800 if (_PyStatus_EXCEPTION(status)) {
801 return status;
802 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100803
Victor Stinner331a6a52019-05-27 16:39:22 +0200804 status = _PyPreConfig_Read(&config, args);
805 if (_PyStatus_EXCEPTION(status)) {
806 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100807 }
808
Victor Stinner331a6a52019-05-27 16:39:22 +0200809 status = _PyPreConfig_Write(&config);
810 if (_PyStatus_EXCEPTION(status)) {
811 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100812 }
813
Victor Stinnerd3b90412019-09-17 23:59:51 +0200814 runtime->preinitializing = 0;
815 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200816 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100817}
818
Victor Stinner70005ac2019-05-02 15:25:34 -0400819
Victor Stinner331a6a52019-05-27 16:39:22 +0200820PyStatus
821Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100822{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100823 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400824 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100825}
826
827
Victor Stinner331a6a52019-05-27 16:39:22 +0200828PyStatus
829Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100830{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100831 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400832 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100833}
834
835
Victor Stinner331a6a52019-05-27 16:39:22 +0200836PyStatus
837Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100838{
Victor Stinner70005ac2019-05-02 15:25:34 -0400839 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100840}
841
842
Victor Stinner331a6a52019-05-27 16:39:22 +0200843PyStatus
844_Py_PreInitializeFromConfig(const PyConfig *config,
845 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100846{
Victor Stinner331a6a52019-05-27 16:39:22 +0200847 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200848
Victor Stinner331a6a52019-05-27 16:39:22 +0200849 PyStatus status = _PyRuntime_Initialize();
850 if (_PyStatus_EXCEPTION(status)) {
851 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200852 }
853 _PyRuntimeState *runtime = &_PyRuntime;
854
Victor Stinnerd3b90412019-09-17 23:59:51 +0200855 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200856 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400858 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200859
Victor Stinner331a6a52019-05-27 16:39:22 +0200860 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200861
Victor Stinner3c30a762019-10-01 10:56:37 +0200862 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200863
Victor Stinner331a6a52019-05-27 16:39:22 +0200864 if (!config->parse_argv) {
865 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200866 }
867 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200868 _PyArgv config_args = {
869 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200870 .argc = config->argv.length,
871 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200872 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200873 }
874 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200875 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200876 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100877}
878
879
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100880/* Begin interpreter initialization
881 *
882 * On return, the first thread and interpreter state have been created,
883 * but the compiler, signal handling, multithreading and
884 * multiple interpreter support, and codec infrastructure are not yet
885 * available.
886 *
887 * The import system will support builtin and frozen modules only.
888 * The only supported io is writing to sys.stderr
889 *
890 * If any operation invoked by this function fails, a fatal error is
891 * issued and the function does not return.
892 *
893 * Any code invoked from this function should *not* assume it has access
894 * to the Python C API (unless the API is explicitly listed as being
895 * safe to call without calling Py_Initialize first)
896 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200897static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200898pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200899 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200900 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200901{
Victor Stinner331a6a52019-05-27 16:39:22 +0200902 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200903
Victor Stinner331a6a52019-05-27 16:39:22 +0200904 status = _Py_PreInitializeFromConfig(src_config, NULL);
905 if (_PyStatus_EXCEPTION(status)) {
906 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200907 }
908
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200910 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200911
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 status = _PyConfig_Copy(&config, src_config);
913 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200914 goto done;
915 }
916
Victor Stinner331a6a52019-05-27 16:39:22 +0200917 status = PyConfig_Read(&config);
918 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200919 goto done;
920 }
921
922 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200923 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200924 }
925 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200926 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200927 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200928 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200929 goto done;
930 }
931
932done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200933 PyConfig_Clear(&config);
934 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200935}
936
Victor Stinner5ac27a52019-03-27 13:40:14 +0100937
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200938/* Py_Initialize() has already been called: update the main interpreter
939 configuration. Example of bpo-34008: Py_Main() called after
940 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200941static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100942_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200943{
Victor Stinnerb0051362019-11-22 17:52:42 +0100944 PyConfig *config = &tstate->interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100945
Victor Stinner331a6a52019-05-27 16:39:22 +0200946 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100947 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200948 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100949 }
950
Victor Stinnerb0051362019-11-22 17:52:42 +0100951 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100952 Py_DECREF(argv);
953 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200954 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200955 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200956 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200957}
958
Victor Stinnerb0051362019-11-22 17:52:42 +0100959
960static PyStatus
961init_interp_main(PyThreadState *tstate)
962{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100963 assert(!_PyErr_Occurred(tstate));
964
Victor Stinnerb0051362019-11-22 17:52:42 +0100965 PyStatus status;
966 int is_main_interp = _Py_IsMainInterpreter(tstate);
967 PyInterpreterState *interp = tstate->interp;
968 PyConfig *config = &interp->config;
969
970 if (!config->_install_importlib) {
971 /* Special mode for freeze_importlib: run with no import system
972 *
973 * This means anything which needs support from extension modules
974 * or pure Python code in the standard library won't work.
975 */
976 if (is_main_interp) {
977 interp->runtime->initialized = 1;
978 }
979 return _PyStatus_OK();
980 }
981
982 if (is_main_interp) {
983 if (_PyTime_Init() < 0) {
984 return _PyStatus_ERR("can't initialize time");
985 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100986 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100987
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100988 if (_PySys_InitMain(tstate) < 0) {
989 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +0100990 }
991
992 status = init_importlib_external(tstate);
993 if (_PyStatus_EXCEPTION(status)) {
994 return status;
995 }
996
997 if (is_main_interp) {
998 /* initialize the faulthandler module */
999 status = _PyFaulthandler_Init(config->faulthandler);
1000 if (_PyStatus_EXCEPTION(status)) {
1001 return status;
1002 }
1003 }
1004
1005 status = _PyUnicode_InitEncodings(tstate);
1006 if (_PyStatus_EXCEPTION(status)) {
1007 return status;
1008 }
1009
1010 if (is_main_interp) {
1011 if (config->install_signal_handlers) {
1012 status = init_signals(tstate);
1013 if (_PyStatus_EXCEPTION(status)) {
1014 return status;
1015 }
1016 }
1017
1018 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1019 return _PyStatus_ERR("can't initialize tracemalloc");
1020 }
1021 }
1022
1023 status = init_sys_streams(tstate);
1024 if (_PyStatus_EXCEPTION(status)) {
1025 return status;
1026 }
1027
Andy Lester75cd5bf2020-03-12 02:49:05 -05001028 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001029 if (_PyStatus_EXCEPTION(status)) {
1030 return status;
1031 }
1032
1033 status = add_main_module(interp);
1034 if (_PyStatus_EXCEPTION(status)) {
1035 return status;
1036 }
1037
1038 if (is_main_interp) {
1039 /* Initialize warnings. */
1040 PyObject *warnoptions = PySys_GetObject("warnoptions");
1041 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1042 {
1043 PyObject *warnings_module = PyImport_ImportModule("warnings");
1044 if (warnings_module == NULL) {
1045 fprintf(stderr, "'import warnings' failed; traceback:\n");
1046 _PyErr_Print(tstate);
1047 }
1048 Py_XDECREF(warnings_module);
1049 }
1050
1051 interp->runtime->initialized = 1;
1052 }
1053
1054 if (config->site_import) {
1055 status = init_import_site();
1056 if (_PyStatus_EXCEPTION(status)) {
1057 return status;
1058 }
1059 }
1060
1061 if (is_main_interp) {
1062#ifndef MS_WINDOWS
1063 emit_stderr_warning_for_legacy_locale(interp->runtime);
1064#endif
1065 }
1066
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001067 assert(!_PyErr_Occurred(tstate));
1068
Victor Stinnerb0051362019-11-22 17:52:42 +01001069 return _PyStatus_OK();
1070}
1071
1072
Eric Snowc7ec9982017-05-23 23:00:52 -07001073/* Update interpreter state based on supplied configuration settings
1074 *
1075 * After calling this function, most of the restrictions on the interpreter
1076 * are lifted. The only remaining incomplete settings are those related
1077 * to the main module (sys.argv[0], __main__ metadata)
1078 *
1079 * Calling this when the interpreter is not initializing, is already
1080 * initialized or without a valid current thread state is a fatal error.
1081 * Other errors should be reported as normal Python exceptions with a
1082 * non-zero return code.
1083 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001084static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001085pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001086{
Victor Stinnerb0051362019-11-22 17:52:42 +01001087 PyInterpreterState *interp = tstate->interp;
1088 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001089 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001090 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001091
Victor Stinnerb0051362019-11-22 17:52:42 +01001092 if (interp->runtime->initialized) {
1093 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001094 }
1095
Victor Stinnerb0051362019-11-22 17:52:42 +01001096 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001097 if (_PyStatus_EXCEPTION(status)) {
1098 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001099 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001100 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001101}
1102
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001103
Victor Stinner331a6a52019-05-27 16:39:22 +02001104PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001105_Py_InitializeMain(void)
1106{
Victor Stinner331a6a52019-05-27 16:39:22 +02001107 PyStatus status = _PyRuntime_Initialize();
1108 if (_PyStatus_EXCEPTION(status)) {
1109 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001110 }
1111 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001112 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001113 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001114}
1115
1116
Victor Stinner331a6a52019-05-27 16:39:22 +02001117PyStatus
1118Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001119{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001120 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001121 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001122 }
1123
Victor Stinner331a6a52019-05-27 16:39:22 +02001124 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001125
Victor Stinner331a6a52019-05-27 16:39:22 +02001126 status = _PyRuntime_Initialize();
1127 if (_PyStatus_EXCEPTION(status)) {
1128 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001129 }
1130 _PyRuntimeState *runtime = &_PyRuntime;
1131
Victor Stinnerb45d2592019-06-20 00:05:23 +02001132 PyThreadState *tstate = NULL;
1133 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001134 if (_PyStatus_EXCEPTION(status)) {
1135 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001136 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001137 config = &tstate->interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001138
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001139 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001140 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001141 if (_PyStatus_EXCEPTION(status)) {
1142 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001143 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001144 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001145
Victor Stinner331a6a52019-05-27 16:39:22 +02001146 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001147}
1148
1149
Eric Snow1abcf672017-05-23 21:46:51 -07001150void
Nick Coghland6009512014-11-20 21:39:37 +10001151Py_InitializeEx(int install_sigs)
1152{
Victor Stinner331a6a52019-05-27 16:39:22 +02001153 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001154
Victor Stinner331a6a52019-05-27 16:39:22 +02001155 status = _PyRuntime_Initialize();
1156 if (_PyStatus_EXCEPTION(status)) {
1157 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001158 }
1159 _PyRuntimeState *runtime = &_PyRuntime;
1160
1161 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001162 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1163 return;
1164 }
1165
Victor Stinner331a6a52019-05-27 16:39:22 +02001166 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001167 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001168
Victor Stinner1dc6e392018-07-25 02:49:17 +02001169 config.install_signal_handlers = install_sigs;
1170
Victor Stinner331a6a52019-05-27 16:39:22 +02001171 status = Py_InitializeFromConfig(&config);
1172 if (_PyStatus_EXCEPTION(status)) {
1173 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001174 }
Nick Coghland6009512014-11-20 21:39:37 +10001175}
1176
1177void
1178Py_Initialize(void)
1179{
1180 Py_InitializeEx(1);
1181}
1182
1183
Nick Coghland6009512014-11-20 21:39:37 +10001184/* Flush stdout and stderr */
1185
1186static int
1187file_is_closed(PyObject *fobj)
1188{
1189 int r;
1190 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1191 if (tmp == NULL) {
1192 PyErr_Clear();
1193 return 0;
1194 }
1195 r = PyObject_IsTrue(tmp);
1196 Py_DECREF(tmp);
1197 if (r < 0)
1198 PyErr_Clear();
1199 return r > 0;
1200}
1201
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001202static int
Nick Coghland6009512014-11-20 21:39:37 +10001203flush_std_files(void)
1204{
1205 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1206 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1207 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001208 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001209
1210 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001211 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001212 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001213 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001214 status = -1;
1215 }
Nick Coghland6009512014-11-20 21:39:37 +10001216 else
1217 Py_DECREF(tmp);
1218 }
1219
1220 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001221 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001222 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001223 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001224 status = -1;
1225 }
Nick Coghland6009512014-11-20 21:39:37 +10001226 else
1227 Py_DECREF(tmp);
1228 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001229
1230 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001231}
1232
1233/* Undo the effect of Py_Initialize().
1234
1235 Beware: if multiple interpreter and/or thread states exist, these
1236 are not wiped out; only the current thread and interpreter state
1237 are deleted. But since everything else is deleted, those other
1238 interpreter and thread states should no longer be used.
1239
1240 (XXX We should do better, e.g. wipe out all interpreters and
1241 threads.)
1242
1243 Locking: as above.
1244
1245*/
1246
Victor Stinner7eee5be2019-11-20 10:38:34 +01001247
1248static void
1249finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1250{
1251 if (is_main_interp) {
1252 /* Sundry finalizers */
Victor Stinner7eee5be2019-11-20 10:38:34 +01001253 _PyFrame_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001254 _PyTuple_Fini();
1255 _PyList_Fini();
1256 _PySet_Fini();
1257 _PyBytes_Fini();
Victor Stinner630c8df2019-12-17 13:02:18 +01001258 }
1259
1260 _PyLong_Fini(tstate);
1261
1262 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001263 _PyFloat_Fini();
1264 _PyDict_Fini();
1265 _PySlice_Fini();
1266 }
1267
1268 _PyWarnings_Fini(tstate->interp);
1269
1270 if (is_main_interp) {
1271 _Py_HashRandomization_Fini();
1272 _PyArg_Fini();
1273 _PyAsyncGen_Fini();
1274 _PyContext_Fini();
Victor Stinner3d483342019-11-22 12:27:50 +01001275 }
Victor Stinner7eee5be2019-11-20 10:38:34 +01001276
Victor Stinner3d483342019-11-22 12:27:50 +01001277 /* Cleanup Unicode implementation */
1278 _PyUnicode_Fini(tstate);
1279
1280 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001281 _Py_ClearFileSystemEncoding();
1282 }
1283}
1284
1285
1286static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001287finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001288{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001289 int is_main_interp = _Py_IsMainInterpreter(tstate);
1290
Victor Stinner7eee5be2019-11-20 10:38:34 +01001291 /* Clear interpreter state and all thread states */
1292 PyInterpreterState_Clear(tstate->interp);
1293
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001294 /* Trigger a GC collection on subinterpreters*/
1295 if (!is_main_interp) {
1296 _PyGC_CollectNoFail();
1297 }
1298
Victor Stinner7eee5be2019-11-20 10:38:34 +01001299 finalize_interp_types(tstate, is_main_interp);
1300
1301 if (is_main_interp) {
1302 /* XXX Still allocated:
1303 - various static ad-hoc pointers to interned strings
1304 - int and float free list blocks
1305 - whatever various modules and libraries allocate
1306 */
1307
1308 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1309
1310 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001311 }
Victor Stinner72474072019-11-20 12:25:50 +01001312
1313 _PyGC_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001314}
1315
1316
1317static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001318finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001319{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001320 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001321 /* Cleanup auto-thread-state */
1322 _PyGILState_Fini(tstate);
1323 }
1324
Victor Stinner7eee5be2019-11-20 10:38:34 +01001325 PyInterpreterState_Delete(tstate->interp);
1326}
1327
1328
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001329int
1330Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001331{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001332 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001333
Victor Stinner8e91c242019-04-24 17:24:01 +02001334 _PyRuntimeState *runtime = &_PyRuntime;
1335 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001336 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001337 }
Nick Coghland6009512014-11-20 21:39:37 +10001338
Victor Stinnere225beb2019-06-03 18:14:24 +02001339 /* Get current thread state and interpreter pointer */
1340 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1341 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001342
Victor Stinnerb45d2592019-06-20 00:05:23 +02001343 // Wrap up existing "threading"-module-created, non-daemon threads.
1344 wait_for_thread_shutdown(tstate);
1345
1346 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001347 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001348
Nick Coghland6009512014-11-20 21:39:37 +10001349 /* The interpreter is still entirely intact at this point, and the
1350 * exit funcs may be relying on that. In particular, if some thread
1351 * or exit func is still waiting to do an import, the import machinery
1352 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001353 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001354 * Note that Threading.py uses an exit func to do a join on all the
1355 * threads created thru it, so this also protects pending imports in
1356 * the threads created via Threading.
1357 */
Nick Coghland6009512014-11-20 21:39:37 +10001358
Victor Stinnerb45d2592019-06-20 00:05:23 +02001359 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001360
Victor Stinnerda273412017-12-15 01:46:02 +01001361 /* Copy the core config, PyInterpreterState_Delete() free
1362 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001363#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001364 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001365#endif
1366#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001367 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001368#endif
1369#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001370 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001371#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001372
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001373 /* Remaining daemon threads will automatically exit
1374 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001375 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001376 runtime->initialized = 0;
1377 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001378
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001379 /* Destroy the state of all threads of the interpreter, except of the
1380 current thread. In practice, only daemon threads should still be alive,
1381 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1382 Clear frames of other threads to call objects destructors. Destructors
1383 will be called in the current Python thread. Since
1384 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1385 can take the GIL at this point: if they try, they will exit
1386 immediately. */
1387 _PyThreadState_DeleteExcept(runtime, tstate);
1388
Victor Stinnere0deff32015-03-24 13:46:18 +01001389 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001390 if (flush_std_files() < 0) {
1391 status = -1;
1392 }
Nick Coghland6009512014-11-20 21:39:37 +10001393
1394 /* Disable signal handling */
1395 PyOS_FiniInterrupts();
1396
1397 /* Collect garbage. This may call finalizers; it's nice to call these
1398 * before all modules are destroyed.
1399 * XXX If a __del__ or weakref callback is triggered here, and tries to
1400 * XXX import a module, bad things can happen, because Python no
1401 * XXX longer believes it's initialized.
1402 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1403 * XXX is easy to provoke that way. I've also seen, e.g.,
1404 * XXX Exception exceptions.ImportError: 'No module named sha'
1405 * XXX in <function callback at 0x008F5718> ignored
1406 * XXX but I'm unclear on exactly how that one happens. In any case,
1407 * XXX I haven't seen a real-life report of either of these.
1408 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001409 _PyGC_CollectIfEnabled();
Eric Snowdae02762017-09-14 00:35:58 -07001410
Steve Dowerb82e17e2019-05-23 08:45:22 -07001411 /* Clear all loghooks */
1412 /* We want minimal exposure of this function, so define the extern
1413 * here. The linker should discover the correct function without
1414 * exporting a symbol. */
1415 extern void _PySys_ClearAuditHooks(void);
1416 _PySys_ClearAuditHooks();
1417
Nick Coghland6009512014-11-20 21:39:37 +10001418 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001419 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001420
Inada Naoki91234a12019-06-03 21:30:58 +09001421 /* Print debug stats if any */
1422 _PyEval_Fini();
1423
Victor Stinnere0deff32015-03-24 13:46:18 +01001424 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001425 if (flush_std_files() < 0) {
1426 status = -1;
1427 }
Nick Coghland6009512014-11-20 21:39:37 +10001428
1429 /* Collect final garbage. This disposes of cycles created by
1430 * class definitions, for example.
1431 * XXX This is disabled because it caused too many problems. If
1432 * XXX a __del__ or weakref callback triggers here, Python code has
1433 * XXX a hard time running, because even the sys module has been
1434 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1435 * XXX One symptom is a sequence of information-free messages
1436 * XXX coming from threads (if a __del__ or callback is invoked,
1437 * XXX other threads can execute too, and any exception they encounter
1438 * XXX triggers a comedy of errors as subsystem after subsystem
1439 * XXX fails to find what it *expects* to find in sys to help report
1440 * XXX the exception and consequent unexpected failures). I've also
1441 * XXX seen segfaults then, after adding print statements to the
1442 * XXX Python code getting called.
1443 */
1444#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001445 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001446#endif
1447
1448 /* Disable tracemalloc after all Python objects have been destroyed,
1449 so it is possible to use tracemalloc in objects destructor. */
1450 _PyTraceMalloc_Fini();
1451
1452 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1453 _PyImport_Fini();
1454
1455 /* Cleanup typeobject.c's internal caches. */
1456 _PyType_Fini();
1457
1458 /* unload faulthandler module */
1459 _PyFaulthandler_Fini();
1460
Nick Coghland6009512014-11-20 21:39:37 +10001461 /* dump hash stats */
1462 _PyHash_Fini();
1463
Eric Snowdae02762017-09-14 00:35:58 -07001464#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001465 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001466 _PyDebug_PrintTotalRefs();
1467 }
Eric Snowdae02762017-09-14 00:35:58 -07001468#endif
Nick Coghland6009512014-11-20 21:39:37 +10001469
1470#ifdef Py_TRACE_REFS
1471 /* Display all objects still alive -- this can invoke arbitrary
1472 * __repr__ overrides, so requires a mostly-intact interpreter.
1473 * Alas, a lot of stuff may still be alive now that will be cleaned
1474 * up later.
1475 */
Victor Stinnerda273412017-12-15 01:46:02 +01001476 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001477 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001478 }
Nick Coghland6009512014-11-20 21:39:37 +10001479#endif /* Py_TRACE_REFS */
1480
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001481 finalize_interp_clear(tstate);
1482 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001483
1484#ifdef Py_TRACE_REFS
1485 /* Display addresses (& refcnts) of all objects still alive.
1486 * An address can be used to find the repr of the object, printed
1487 * above by _Py_PrintReferences.
1488 */
Victor Stinnerda273412017-12-15 01:46:02 +01001489 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001490 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001491 }
Nick Coghland6009512014-11-20 21:39:37 +10001492#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001493#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001494 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001495 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001496 }
Nick Coghland6009512014-11-20 21:39:37 +10001497#endif
1498
Victor Stinner8e91c242019-04-24 17:24:01 +02001499 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001500
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001501 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001502 return status;
1503}
1504
1505void
1506Py_Finalize(void)
1507{
1508 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001509}
1510
Victor Stinnerb0051362019-11-22 17:52:42 +01001511
Nick Coghland6009512014-11-20 21:39:37 +10001512/* Create and initialize a new interpreter and thread, and return the
1513 new thread. This requires that Py_Initialize() has been called
1514 first.
1515
1516 Unsuccessful initialization yields a NULL pointer. Note that *no*
1517 exception information is available even in this case -- the
1518 exception information is held in the thread, and there is no
1519 thread.
1520
1521 Locking: as above.
1522
1523*/
1524
Victor Stinner331a6a52019-05-27 16:39:22 +02001525static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001526new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001527{
Victor Stinner331a6a52019-05-27 16:39:22 +02001528 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001529
Victor Stinner331a6a52019-05-27 16:39:22 +02001530 status = _PyRuntime_Initialize();
1531 if (_PyStatus_EXCEPTION(status)) {
1532 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001533 }
1534 _PyRuntimeState *runtime = &_PyRuntime;
1535
1536 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001537 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001538 }
Nick Coghland6009512014-11-20 21:39:37 +10001539
Victor Stinner8a1be612016-03-14 22:07:55 +01001540 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1541 interpreters: disable PyGILState_Check(). */
1542 _PyGILState_check_enabled = 0;
1543
Victor Stinner43125222019-04-24 18:23:53 +02001544 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001545 if (interp == NULL) {
1546 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001547 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001548 }
Nick Coghland6009512014-11-20 21:39:37 +10001549
Victor Stinner43125222019-04-24 18:23:53 +02001550 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001551 if (tstate == NULL) {
1552 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001553 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001554 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001555 }
1556
Victor Stinner43125222019-04-24 18:23:53 +02001557 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001558
Eric Snow1abcf672017-05-23 21:46:51 -07001559 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001560 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001561 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001562 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001563 } else {
1564 /* No current thread state, copy from the main interpreter */
1565 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001566 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001567 }
1568
Victor Stinner331a6a52019-05-27 16:39:22 +02001569 status = _PyConfig_Copy(&interp->config, config);
1570 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001571 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001572 }
Eric Snow1abcf672017-05-23 21:46:51 -07001573
Victor Stinnerd863ade2019-12-06 03:37:07 +01001574 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001575 if (_PyStatus_EXCEPTION(status)) {
1576 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001577 }
1578
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001579 status = init_interp_main(tstate);
1580 if (_PyStatus_EXCEPTION(status)) {
1581 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001582 }
Nick Coghland6009512014-11-20 21:39:37 +10001583
Victor Stinner50e6e992020-03-19 02:41:21 +01001584 /* Create the pending calls lock */
1585 status = _PyEval_InitThreads(tstate);
1586 if (_PyStatus_EXCEPTION(status)) {
1587 return status;
1588 }
1589
Victor Stinnera7368ac2017-11-15 18:11:45 -08001590 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001591 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001592
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001593error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001594 *tstate_p = NULL;
1595
1596 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001597 PyErr_PrintEx(0);
1598 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001599 PyThreadState_Delete(tstate);
1600 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001601 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001602
Victor Stinnerb0051362019-11-22 17:52:42 +01001603 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001604}
1605
1606PyThreadState *
1607Py_NewInterpreter(void)
1608{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001609 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001610 PyStatus status = new_interpreter(&tstate);
1611 if (_PyStatus_EXCEPTION(status)) {
1612 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001613 }
1614 return tstate;
1615
Nick Coghland6009512014-11-20 21:39:37 +10001616}
1617
1618/* Delete an interpreter and its last thread. This requires that the
1619 given thread state is current, that the thread has no remaining
1620 frames, and that it is its interpreter's only remaining thread.
1621 It is a fatal error to violate these constraints.
1622
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001623 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001624 everything, regardless.)
1625
1626 Locking: as above.
1627
1628*/
1629
1630void
1631Py_EndInterpreter(PyThreadState *tstate)
1632{
1633 PyInterpreterState *interp = tstate->interp;
1634
Victor Stinnerb45d2592019-06-20 00:05:23 +02001635 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001636 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001637 }
1638 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001639 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001640 }
Eric Snow5be45a62019-03-08 22:47:07 -07001641 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001642
Eric Snow842a2f02019-03-15 15:47:51 -06001643 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001644 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001645
Victor Stinnerb45d2592019-06-20 00:05:23 +02001646 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001647
Victor Stinnerb45d2592019-06-20 00:05:23 +02001648 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001649 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001650 }
Nick Coghland6009512014-11-20 21:39:37 +10001651
Victor Stinner987a0dc2019-06-19 10:36:10 +02001652 _PyImport_Cleanup(tstate);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001653 finalize_interp_clear(tstate);
1654 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001655}
1656
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001657/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001658
Victor Stinner331a6a52019-05-27 16:39:22 +02001659static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001660add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001661{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001662 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001663 m = PyImport_AddModule("__main__");
1664 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001665 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001666
Nick Coghland6009512014-11-20 21:39:37 +10001667 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001668 ann_dict = PyDict_New();
1669 if ((ann_dict == NULL) ||
1670 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001671 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001672 }
1673 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001674
Nick Coghland6009512014-11-20 21:39:37 +10001675 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1676 PyObject *bimod = PyImport_ImportModule("builtins");
1677 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001678 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001679 }
1680 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001681 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001682 }
1683 Py_DECREF(bimod);
1684 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001685
Nick Coghland6009512014-11-20 21:39:37 +10001686 /* Main is a little special - imp.is_builtin("__main__") will return
1687 * False, but BuiltinImporter is still the most appropriate initial
1688 * setting for its __loader__ attribute. A more suitable value will
1689 * be set if __main__ gets further initialized later in the startup
1690 * process.
1691 */
1692 loader = PyDict_GetItemString(d, "__loader__");
1693 if (loader == NULL || loader == Py_None) {
1694 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1695 "BuiltinImporter");
1696 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001697 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001698 }
1699 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001700 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001701 }
1702 Py_DECREF(loader);
1703 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001704 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001705}
1706
Nick Coghland6009512014-11-20 21:39:37 +10001707/* Import the site module (not into __main__ though) */
1708
Victor Stinner331a6a52019-05-27 16:39:22 +02001709static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001710init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10001711{
1712 PyObject *m;
1713 m = PyImport_ImportModule("site");
1714 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001715 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001716 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001717 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001718 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001719}
1720
Victor Stinner874dbe82015-09-04 17:29:57 +02001721/* Check if a file descriptor is valid or not.
1722 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1723static int
1724is_valid_fd(int fd)
1725{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001726/* dup() is faster than fstat(): fstat() can require input/output operations,
1727 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1728 startup. Problem: dup() doesn't check if the file descriptor is valid on
1729 some platforms.
1730
1731 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1732 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1733 EBADF. FreeBSD has similar issue (bpo-32849).
1734
1735 Only use dup() on platforms where dup() is enough to detect invalid FD in
1736 corner cases: on Linux and Windows (bpo-32849). */
1737#if defined(__linux__) || defined(MS_WINDOWS)
1738 if (fd < 0) {
1739 return 0;
1740 }
1741 int fd2;
1742
1743 _Py_BEGIN_SUPPRESS_IPH
1744 fd2 = dup(fd);
1745 if (fd2 >= 0) {
1746 close(fd2);
1747 }
1748 _Py_END_SUPPRESS_IPH
1749
1750 return (fd2 >= 0);
1751#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001752 struct stat st;
1753 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001754#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001755}
1756
1757/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001758static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001759create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001760 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001761 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001762{
1763 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1764 const char* mode;
1765 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001766 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001767 int buffering, isatty;
1768 _Py_IDENTIFIER(open);
1769 _Py_IDENTIFIER(isatty);
1770 _Py_IDENTIFIER(TextIOWrapper);
1771 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001772 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001773
Victor Stinner874dbe82015-09-04 17:29:57 +02001774 if (!is_valid_fd(fd))
1775 Py_RETURN_NONE;
1776
Nick Coghland6009512014-11-20 21:39:37 +10001777 /* stdin is always opened in buffered mode, first because it shouldn't
1778 make a difference in common use cases, second because TextIOWrapper
1779 depends on the presence of a read1() method which only exists on
1780 buffered streams.
1781 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001782 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001783 buffering = 0;
1784 else
1785 buffering = -1;
1786 if (write_mode)
1787 mode = "wb";
1788 else
1789 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001790 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10001791 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001792 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001793 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001794 if (buf == NULL)
1795 goto error;
1796
1797 if (buffering) {
1798 _Py_IDENTIFIER(raw);
1799 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1800 if (raw == NULL)
1801 goto error;
1802 }
1803 else {
1804 raw = buf;
1805 Py_INCREF(raw);
1806 }
1807
Steve Dower39294992016-08-30 21:22:36 -07001808#ifdef MS_WINDOWS
1809 /* Windows console IO is always UTF-8 encoded */
1810 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001811 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001812#endif
1813
Nick Coghland6009512014-11-20 21:39:37 +10001814 text = PyUnicode_FromString(name);
1815 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1816 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001817 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10001818 if (res == NULL)
1819 goto error;
1820 isatty = PyObject_IsTrue(res);
1821 Py_DECREF(res);
1822 if (isatty == -1)
1823 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001824 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001825 write_through = Py_True;
1826 else
1827 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01001828 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10001829 line_buffering = Py_True;
1830 else
1831 line_buffering = Py_False;
1832
1833 Py_CLEAR(raw);
1834 Py_CLEAR(text);
1835
1836#ifdef MS_WINDOWS
1837 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1838 newlines to "\n".
1839 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1840 newline = NULL;
1841#else
1842 /* sys.stdin: split lines at "\n".
1843 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1844 newline = "\n";
1845#endif
1846
Victor Stinner709d23d2019-05-02 14:56:30 -04001847 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1848 if (encoding_str == NULL) {
1849 Py_CLEAR(buf);
1850 goto error;
1851 }
1852
1853 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1854 if (errors_str == NULL) {
1855 Py_CLEAR(buf);
1856 Py_CLEAR(encoding_str);
1857 goto error;
1858 }
1859
1860 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1861 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001862 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001863 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001864 Py_CLEAR(encoding_str);
1865 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001866 if (stream == NULL)
1867 goto error;
1868
1869 if (write_mode)
1870 mode = "w";
1871 else
1872 mode = "r";
1873 text = PyUnicode_FromString(mode);
1874 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1875 goto error;
1876 Py_CLEAR(text);
1877 return stream;
1878
1879error:
1880 Py_XDECREF(buf);
1881 Py_XDECREF(stream);
1882 Py_XDECREF(text);
1883 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001884
Victor Stinner874dbe82015-09-04 17:29:57 +02001885 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1886 /* Issue #24891: the file descriptor was closed after the first
1887 is_valid_fd() check was called. Ignore the OSError and set the
1888 stream to None. */
1889 PyErr_Clear();
1890 Py_RETURN_NONE;
1891 }
1892 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001893}
1894
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001895/* Set builtins.open to io.OpenWrapper */
1896static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05001897init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001898{
1899 PyObject *iomod = NULL, *wrapper;
1900 PyObject *bimod = NULL;
1901 PyStatus res = _PyStatus_OK();
1902
1903 if (!(iomod = PyImport_ImportModule("io"))) {
1904 goto error;
1905 }
1906
1907 if (!(bimod = PyImport_ImportModule("builtins"))) {
1908 goto error;
1909 }
1910
1911 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1912 goto error;
1913 }
1914
1915 /* Set builtins.open */
1916 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1917 Py_DECREF(wrapper);
1918 goto error;
1919 }
1920 Py_DECREF(wrapper);
1921 goto done;
1922
1923error:
1924 res = _PyStatus_ERR("can't initialize io.open");
1925
1926done:
1927 Py_XDECREF(bimod);
1928 Py_XDECREF(iomod);
1929 return res;
1930}
1931
1932
Nick Coghland6009512014-11-20 21:39:37 +10001933/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001934static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001935init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10001936{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001937 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001938 PyObject *m;
1939 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001940 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001941 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001942 PyStatus res = _PyStatus_OK();
Victor Stinnerb45d2592019-06-20 00:05:23 +02001943 const PyConfig *config = &tstate->interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001944
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001945 /* Check that stdin is not a directory
1946 Using shell redirection, you can redirect stdin to a directory,
1947 crashing the Python interpreter. Catch this common mistake here
1948 and output a useful error message. Note that under MS Windows,
1949 the shell already prevents that. */
1950#ifndef MS_WINDOWS
1951 struct _Py_stat_struct sb;
1952 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1953 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001954 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001955 }
1956#endif
1957
Nick Coghland6009512014-11-20 21:39:37 +10001958 /* Hack to avoid a nasty recursion issue when Python is invoked
1959 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1960 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1961 goto error;
1962 }
1963 Py_DECREF(m);
1964
1965 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1966 goto error;
1967 }
1968 Py_DECREF(m);
1969
Nick Coghland6009512014-11-20 21:39:37 +10001970 if (!(iomod = PyImport_ImportModule("io"))) {
1971 goto error;
1972 }
Nick Coghland6009512014-11-20 21:39:37 +10001973
Nick Coghland6009512014-11-20 21:39:37 +10001974 /* Set sys.stdin */
1975 fd = fileno(stdin);
1976 /* Under some conditions stdin, stdout and stderr may not be connected
1977 * and fileno() may point to an invalid file descriptor. For example
1978 * GUI apps don't have valid standard streams by default.
1979 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001980 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001981 config->stdio_encoding,
1982 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001983 if (std == NULL)
1984 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001985 PySys_SetObject("__stdin__", std);
1986 _PySys_SetObjectId(&PyId_stdin, std);
1987 Py_DECREF(std);
1988
1989 /* Set sys.stdout */
1990 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001991 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001992 config->stdio_encoding,
1993 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001994 if (std == NULL)
1995 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001996 PySys_SetObject("__stdout__", std);
1997 _PySys_SetObjectId(&PyId_stdout, std);
1998 Py_DECREF(std);
1999
2000#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2001 /* Set sys.stderr, replaces the preliminary stderr */
2002 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002003 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002004 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002005 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002006 if (std == NULL)
2007 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002008
2009 /* Same as hack above, pre-import stderr's codec to avoid recursion
2010 when import.c tries to write to stderr in verbose mode. */
2011 encoding_attr = PyObject_GetAttrString(std, "encoding");
2012 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002013 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002014 if (std_encoding != NULL) {
2015 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2016 Py_XDECREF(codec_info);
2017 }
2018 Py_DECREF(encoding_attr);
2019 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002020 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002021
2022 if (PySys_SetObject("__stderr__", std) < 0) {
2023 Py_DECREF(std);
2024 goto error;
2025 }
2026 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2027 Py_DECREF(std);
2028 goto error;
2029 }
2030 Py_DECREF(std);
2031#endif
2032
Victor Stinnera7368ac2017-11-15 18:11:45 -08002033 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002034
Victor Stinnera7368ac2017-11-15 18:11:45 -08002035error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002036 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002037
2038done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002039 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002040 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002041 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002042}
2043
2044
Victor Stinner10dc4842015-03-24 12:01:30 +01002045static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002046_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2047 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002048{
Victor Stinner10dc4842015-03-24 12:01:30 +01002049 fputc('\n', stderr);
2050 fflush(stderr);
2051
2052 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002053 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002054}
Victor Stinner791da1c2016-03-14 16:53:12 +01002055
2056/* Print the current exception (if an exception is set) with its traceback,
2057 or display the current Python stack.
2058
2059 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2060 called on catastrophic cases.
2061
2062 Return 1 if the traceback was displayed, 0 otherwise. */
2063
2064static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002065_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002066{
2067 PyObject *ferr, *res;
2068 PyObject *exception, *v, *tb;
2069 int has_tb;
2070
Victor Stinnerb45d2592019-06-20 00:05:23 +02002071 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002072 if (exception == NULL) {
2073 /* No current exception */
2074 return 0;
2075 }
2076
2077 ferr = _PySys_GetObjectId(&PyId_stderr);
2078 if (ferr == NULL || ferr == Py_None) {
2079 /* sys.stderr is not set yet or set to None,
2080 no need to try to display the exception */
2081 return 0;
2082 }
2083
Victor Stinnerb45d2592019-06-20 00:05:23 +02002084 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002085 if (tb == NULL) {
2086 tb = Py_None;
2087 Py_INCREF(tb);
2088 }
2089 PyException_SetTraceback(v, tb);
2090 if (exception == NULL) {
2091 /* PyErr_NormalizeException() failed */
2092 return 0;
2093 }
2094
2095 has_tb = (tb != Py_None);
2096 PyErr_Display(exception, v, tb);
2097 Py_XDECREF(exception);
2098 Py_XDECREF(v);
2099 Py_XDECREF(tb);
2100
2101 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002102 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002103 if (res == NULL) {
2104 _PyErr_Clear(tstate);
2105 }
2106 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002107 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002108 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002109
2110 return has_tb;
2111}
2112
Nick Coghland6009512014-11-20 21:39:37 +10002113/* Print fatal error message and abort */
2114
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002115#ifdef MS_WINDOWS
2116static void
2117fatal_output_debug(const char *msg)
2118{
2119 /* buffer of 256 bytes allocated on the stack */
2120 WCHAR buffer[256 / sizeof(WCHAR)];
2121 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2122 size_t msglen;
2123
2124 OutputDebugStringW(L"Fatal Python error: ");
2125
2126 msglen = strlen(msg);
2127 while (msglen) {
2128 size_t i;
2129
2130 if (buflen > msglen) {
2131 buflen = msglen;
2132 }
2133
2134 /* Convert the message to wchar_t. This uses a simple one-to-one
2135 conversion, assuming that the this error message actually uses
2136 ASCII only. If this ceases to be true, we will have to convert. */
2137 for (i=0; i < buflen; ++i) {
2138 buffer[i] = msg[i];
2139 }
2140 buffer[i] = L'\0';
2141 OutputDebugStringW(buffer);
2142
2143 msg += buflen;
2144 msglen -= buflen;
2145 }
2146 OutputDebugStringW(L"\n");
2147}
2148#endif
2149
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002150
2151static void
2152fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2153{
2154 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002155 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2156 if (finalizing) {
2157 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002158 }
2159 else if (runtime->initialized) {
2160 fprintf(stream, "initialized");
2161 }
2162 else if (runtime->core_initialized) {
2163 fprintf(stream, "core initialized");
2164 }
2165 else if (runtime->preinitialized) {
2166 fprintf(stream, "preinitialized");
2167 }
2168 else if (runtime->preinitializing) {
2169 fprintf(stream, "preinitializing");
2170 }
2171 else {
2172 fprintf(stream, "unknown");
2173 }
2174 fprintf(stream, "\n");
2175 fflush(stream);
2176}
2177
2178
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002179static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002180fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002181{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002182 FILE *stream = stderr;
2183 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002184 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002185
2186 if (reentrant) {
2187 /* Py_FatalError() caused a second fatal error.
2188 Example: flush_std_files() raises a recursion error. */
2189 goto exit;
2190 }
2191 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002192
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002193 fprintf(stream, "Fatal Python error: ");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002194 if (prefix) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002195 fputs(prefix, stream);
2196 fputs(": ", stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002197 }
2198 if (msg) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002199 fputs(msg, stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002200 }
2201 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002202 fprintf(stream, "<message not set>");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002203 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002204 fputs("\n", stream);
2205 fflush(stream); /* it helps in Windows debug build */
2206
2207 _PyRuntimeState *runtime = &_PyRuntime;
2208 fatal_error_dump_runtime(stream, runtime);
2209
2210 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2211 PyInterpreterState *interp = NULL;
2212 if (tstate != NULL) {
2213 interp = tstate->interp;
2214 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002215
Victor Stinner3a228ab2018-11-01 00:26:41 +01002216 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002217 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002218
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002219 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2220 has no Python thread state.
2221
2222 tss_tstate != tstate if the current Python thread does not hold the GIL.
2223 */
2224 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2225 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002226 if (has_tstate_and_gil) {
2227 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002228 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002229 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002230 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002231 }
2232 }
2233 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002234 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002235 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002236
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002237 /* The main purpose of faulthandler is to display the traceback.
2238 This function already did its best to display a traceback.
2239 Disable faulthandler to prevent writing a second traceback
2240 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002241 _PyFaulthandler_Fini();
2242
Victor Stinner791da1c2016-03-14 16:53:12 +01002243 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002244 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002245 /* Flush sys.stdout and sys.stderr */
2246 flush_std_files();
2247 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002248
Nick Coghland6009512014-11-20 21:39:37 +10002249#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002250 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002251#endif /* MS_WINDOWS */
2252
2253exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002254 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002255#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002256 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002257#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002258 abort();
2259 }
2260 else {
2261 exit(status);
2262 }
2263}
2264
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002265#undef Py_FatalError
2266
Victor Stinner19760862017-12-20 01:41:59 +01002267void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002268Py_FatalError(const char *msg)
2269{
2270 fatal_error(NULL, msg, -1);
2271}
2272
Victor Stinner19760862017-12-20 01:41:59 +01002273void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002274_Py_FatalErrorFunc(const char *func, const char *msg)
2275{
2276 fatal_error(func, msg, -1);
2277}
2278
2279void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002280Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002281{
Victor Stinner331a6a52019-05-27 16:39:22 +02002282 if (_PyStatus_IS_EXIT(status)) {
2283 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002284 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002285 else if (_PyStatus_IS_ERROR(status)) {
2286 fatal_error(status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002287 }
2288 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002289 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002290 }
Nick Coghland6009512014-11-20 21:39:37 +10002291}
2292
2293/* Clean up and exit */
2294
Victor Stinnerd7292b52016-06-17 12:29:00 +02002295# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002296
Nick Coghland6009512014-11-20 21:39:37 +10002297/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002298void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002299{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002300 PyInterpreterState *is = _PyInterpreterState_GET_UNSAFE();
Marcel Plch776407f2017-12-20 11:17:58 +01002301
Antoine Pitroufc5db952017-12-13 02:29:07 +01002302 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002303 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2304
2305 is->pyexitfunc = func;
2306 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002307}
2308
2309static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002310call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002311{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002312 PyInterpreterState *interp = tstate->interp;
2313 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002314 return;
2315
Victor Stinnerb45d2592019-06-20 00:05:23 +02002316 (*interp->pyexitfunc)(interp->pyexitmodule);
2317 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002318}
2319
2320/* Wait until threading._shutdown completes, provided
2321 the threading module was imported in the first place.
2322 The shutdown routine will wait until all non-daemon
2323 "threading" threads have completed. */
2324static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002325wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002326{
Nick Coghland6009512014-11-20 21:39:37 +10002327 _Py_IDENTIFIER(_shutdown);
2328 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002329 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002330 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002331 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002332 PyErr_WriteUnraisable(NULL);
2333 }
2334 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002335 return;
2336 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002337 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002338 if (result == NULL) {
2339 PyErr_WriteUnraisable(threading);
2340 }
2341 else {
2342 Py_DECREF(result);
2343 }
2344 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002345}
2346
2347#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002348int Py_AtExit(void (*func)(void))
2349{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002350 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002351 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002352 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002353 return 0;
2354}
2355
2356static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002357call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002358{
Victor Stinner8e91c242019-04-24 17:24:01 +02002359 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002360 /* pop last function from the list */
2361 runtime->nexitfuncs--;
2362 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2363 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2364
2365 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002366 }
Nick Coghland6009512014-11-20 21:39:37 +10002367
2368 fflush(stdout);
2369 fflush(stderr);
2370}
2371
Victor Stinnercfc88312018-08-01 16:41:25 +02002372void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002373Py_Exit(int sts)
2374{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002375 if (Py_FinalizeEx() < 0) {
2376 sts = 120;
2377 }
Nick Coghland6009512014-11-20 21:39:37 +10002378
2379 exit(sts);
2380}
2381
Victor Stinner331a6a52019-05-27 16:39:22 +02002382static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002383init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002384{
2385#ifdef SIGPIPE
2386 PyOS_setsig(SIGPIPE, SIG_IGN);
2387#endif
2388#ifdef SIGXFZ
2389 PyOS_setsig(SIGXFZ, SIG_IGN);
2390#endif
2391#ifdef SIGXFSZ
2392 PyOS_setsig(SIGXFSZ, SIG_IGN);
2393#endif
2394 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002395 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002396 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002397 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002398 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002399}
2400
2401
2402/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2403 *
2404 * All of the code in this function must only use async-signal-safe functions,
2405 * listed at `man 7 signal` or
2406 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002407 *
2408 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002409 */
2410void
2411_Py_RestoreSignals(void)
2412{
2413#ifdef SIGPIPE
2414 PyOS_setsig(SIGPIPE, SIG_DFL);
2415#endif
2416#ifdef SIGXFZ
2417 PyOS_setsig(SIGXFZ, SIG_DFL);
2418#endif
2419#ifdef SIGXFSZ
2420 PyOS_setsig(SIGXFSZ, SIG_DFL);
2421#endif
2422}
2423
2424
2425/*
2426 * The file descriptor fd is considered ``interactive'' if either
2427 * a) isatty(fd) is TRUE, or
2428 * b) the -i flag was given, and the filename associated with
2429 * the descriptor is NULL or "<stdin>" or "???".
2430 */
2431int
2432Py_FdIsInteractive(FILE *fp, const char *filename)
2433{
2434 if (isatty((int)fileno(fp)))
2435 return 1;
2436 if (!Py_InteractiveFlag)
2437 return 0;
2438 return (filename == NULL) ||
2439 (strcmp(filename, "<stdin>") == 0) ||
2440 (strcmp(filename, "???") == 0);
2441}
2442
2443
Nick Coghland6009512014-11-20 21:39:37 +10002444/* Wrappers around sigaction() or signal(). */
2445
2446PyOS_sighandler_t
2447PyOS_getsig(int sig)
2448{
2449#ifdef HAVE_SIGACTION
2450 struct sigaction context;
2451 if (sigaction(sig, NULL, &context) == -1)
2452 return SIG_ERR;
2453 return context.sa_handler;
2454#else
2455 PyOS_sighandler_t handler;
2456/* Special signal handling for the secure CRT in Visual Studio 2005 */
2457#if defined(_MSC_VER) && _MSC_VER >= 1400
2458 switch (sig) {
2459 /* Only these signals are valid */
2460 case SIGINT:
2461 case SIGILL:
2462 case SIGFPE:
2463 case SIGSEGV:
2464 case SIGTERM:
2465 case SIGBREAK:
2466 case SIGABRT:
2467 break;
2468 /* Don't call signal() with other values or it will assert */
2469 default:
2470 return SIG_ERR;
2471 }
2472#endif /* _MSC_VER && _MSC_VER >= 1400 */
2473 handler = signal(sig, SIG_IGN);
2474 if (handler != SIG_ERR)
2475 signal(sig, handler);
2476 return handler;
2477#endif
2478}
2479
2480/*
2481 * All of the code in this function must only use async-signal-safe functions,
2482 * listed at `man 7 signal` or
2483 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2484 */
2485PyOS_sighandler_t
2486PyOS_setsig(int sig, PyOS_sighandler_t handler)
2487{
2488#ifdef HAVE_SIGACTION
2489 /* Some code in Modules/signalmodule.c depends on sigaction() being
2490 * used here if HAVE_SIGACTION is defined. Fix that if this code
2491 * changes to invalidate that assumption.
2492 */
2493 struct sigaction context, ocontext;
2494 context.sa_handler = handler;
2495 sigemptyset(&context.sa_mask);
2496 context.sa_flags = 0;
2497 if (sigaction(sig, &context, &ocontext) == -1)
2498 return SIG_ERR;
2499 return ocontext.sa_handler;
2500#else
2501 PyOS_sighandler_t oldhandler;
2502 oldhandler = signal(sig, handler);
2503#ifdef HAVE_SIGINTERRUPT
2504 siginterrupt(sig, 1);
2505#endif
2506 return oldhandler;
2507#endif
2508}
2509
2510#ifdef __cplusplus
2511}
2512#endif