blob: 4c27738693a6f60cecdd78f7a3bc5316481e5321 [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 Stinner08faf002020-03-26 18:57:32 +010019#include "pycore_sysmodule.h"
Victor Stinnered488662019-05-20 00:14:57 +020020#include "pycore_traceback.h"
Nick Coghland6009512014-11-20 21:39:37 +100021#include "grammar.h"
22#include "node.h"
23#include "token.h"
24#include "parsetok.h"
25#include "errcode.h"
26#include "code.h"
27#include "symtable.h"
28#include "ast.h"
29#include "marshal.h"
30#include "osdefs.h"
31#include <locale.h>
32
33#ifdef HAVE_SIGNAL_H
34#include <signal.h>
35#endif
36
37#ifdef MS_WINDOWS
38#include "malloc.h" /* for alloca */
39#endif
40
41#ifdef HAVE_LANGINFO_H
42#include <langinfo.h>
43#endif
44
45#ifdef MS_WINDOWS
46#undef BYTE
47#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070048
49extern PyTypeObject PyWindowsConsoleIO_Type;
50#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100051#endif
52
53_Py_IDENTIFIER(flush);
54_Py_IDENTIFIER(name);
55_Py_IDENTIFIER(stdin);
56_Py_IDENTIFIER(stdout);
57_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060058_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100059
60#ifdef __cplusplus
61extern "C" {
62#endif
63
Nick Coghland6009512014-11-20 21:39:37 +100064extern grammar _PyParser_Grammar; /* From graminit.c */
65
Victor Stinnerb45d2592019-06-20 00:05:23 +020066/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020067static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020068static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050069static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020070static PyStatus init_sys_streams(PyThreadState *tstate);
71static PyStatus init_signals(PyThreadState *tstate);
72static void call_py_exitfuncs(PyThreadState *tstate);
73static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020074static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100075
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080076int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010078static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079
Victor Stinner331a6a52019-05-27 16:39:22 +020080PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081_PyRuntime_Initialize(void)
82{
83 /* XXX We only initialize once in the process, which aligns with
84 the static initialization of the former globals now found in
85 _PyRuntime. However, _PyRuntime *should* be initialized with
86 every Py_Initialize() call, but doing so breaks the runtime.
87 This is because the runtime state is not properly finalized
88 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010089 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020090 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010092 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080093
94 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +0100101 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600102}
103
104int
105_Py_IsFinalizing(void)
106{
Victor Stinner7b3c2522020-03-07 00:24:23 +0100107 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600108}
109
Nick Coghland6009512014-11-20 21:39:37 +1000110/* Hack to force loading of object files */
111int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
112 PyOS_mystrnicmp; /* Python/pystrcmp.o */
113
114/* PyModule_GetWarningsModule is no longer necessary as of 2.6
115since _warnings is builtin. This API should not be used. */
116PyObject *
117PyModule_GetWarningsModule(void)
118{
119 return PyImport_ImportModule("warnings");
120}
121
Eric Snowc7ec9982017-05-23 23:00:52 -0700122
Eric Snow1abcf672017-05-23 21:46:51 -0700123/* APIs to access the initialization flags
124 *
125 * Can be called prior to Py_Initialize.
126 */
Nick Coghland6009512014-11-20 21:39:37 +1000127
Eric Snow1abcf672017-05-23 21:46:51 -0700128int
129_Py_IsCoreInitialized(void)
130{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600131 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700132}
Nick Coghland6009512014-11-20 21:39:37 +1000133
134int
135Py_IsInitialized(void)
136{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600137 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000138}
139
Nick Coghlan6ea41862017-06-11 13:16:15 +1000140
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000141/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
142 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000143 initializations fail, a fatal error is issued and the function does
144 not return. On return, the first thread and interpreter state have
145 been created.
146
147 Locking: you must hold the interpreter lock while calling this.
148 (If the lock has not yet been initialized, that's equivalent to
149 having the lock, but you cannot use multiple threads.)
150
151*/
152
Victor Stinner331a6a52019-05-27 16:39:22 +0200153static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200154init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000155{
156 PyObject *importlib;
157 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000158 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200159 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +0200160 int verbose = interp->config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000161
162 /* Import _importlib through its frozen version, _frozen_importlib. */
163 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200164 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000165 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200166 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000167 PySys_FormatStderr("import _frozen_importlib # frozen\n");
168 }
169 importlib = PyImport_AddModule("_frozen_importlib");
170 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200171 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000172 }
173 interp->importlib = importlib;
174 Py_INCREF(interp->importlib);
175
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300176 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
177 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200178 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300179 Py_INCREF(interp->import_func);
180
Victor Stinnercd6e6942015-09-18 09:11:57 +0200181 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800182 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000183 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200184 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000185 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200186 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200187 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000188 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600189 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200190 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000191 }
192
Victor Stinnercd6e6942015-09-18 09:11:57 +0200193 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000194 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
195 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200196 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200197 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 Py_DECREF(value);
200 Py_DECREF(impmod);
201
Victor Stinner331a6a52019-05-27 16:39:22 +0200202 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000203}
204
Victor Stinner331a6a52019-05-27 16:39:22 +0200205static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200206init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700207{
208 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200209 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700210 "_install_external_importers", "");
211 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200212 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200213 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700214 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200215 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200216 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700217}
Nick Coghland6009512014-11-20 21:39:37 +1000218
Nick Coghlan6ea41862017-06-11 13:16:15 +1000219/* Helper functions to better handle the legacy C locale
220 *
221 * The legacy C locale assumes ASCII as the default text encoding, which
222 * causes problems not only for the CPython runtime, but also other
223 * components like GNU readline.
224 *
225 * Accordingly, when the CLI detects it, it attempts to coerce it to a
226 * more capable UTF-8 based alternative as follows:
227 *
228 * if (_Py_LegacyLocaleDetected()) {
229 * _Py_CoerceLegacyLocale();
230 * }
231 *
232 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
233 *
234 * Locale coercion also impacts the default error handler for the standard
235 * streams: while the usual default is "strict", the default for the legacy
236 * C locale and for any of the coercion target locales is "surrogateescape".
237 */
238
239int
Victor Stinner0f721472019-05-20 17:16:38 +0200240_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000241{
242#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200243 if (!warn) {
244 const char *locale_override = getenv("LC_ALL");
245 if (locale_override != NULL && *locale_override != '\0') {
246 /* Don't coerce C locale if the LC_ALL environment variable
247 is set */
248 return 0;
249 }
250 }
251
Nick Coghlan6ea41862017-06-11 13:16:15 +1000252 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000253 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
254 * the POSIX locale as a simple alias for the C locale, so
255 * we may also want to check for that explicitly.
256 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000257 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
258 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
259#else
260 /* Windows uses code pages instead of locales, so no locale is legacy */
261 return 0;
262#endif
263}
264
Victor Stinnerb0051362019-11-22 17:52:42 +0100265#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000266static const char *_C_LOCALE_WARNING =
267 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
268 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
269 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
270 "locales is recommended.\n";
271
Nick Coghlaneb817952017-06-18 12:29:42 +1000272static void
Victor Stinner43125222019-04-24 18:23:53 +0200273emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000274{
Victor Stinner331a6a52019-05-27 16:39:22 +0200275 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200276 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200277 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000278 }
279}
Victor Stinnerb0051362019-11-22 17:52:42 +0100280#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000281
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282typedef struct _CandidateLocale {
283 const char *locale_name; /* The locale to try as a coercion target */
284} _LocaleCoercionTarget;
285
286static _LocaleCoercionTarget _TARGET_LOCALES[] = {
287 {"C.UTF-8"},
288 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000289 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000290 {NULL}
291};
292
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200293
294int
295_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200297 const _LocaleCoercionTarget *target = NULL;
298 for (target = _TARGET_LOCALES; target->locale_name; target++) {
299 if (strcmp(ctype_loc, target->locale_name) == 0) {
300 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200302 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200303 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000304}
305
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200306
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100308static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000309 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
310 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
311
Victor Stinner0f721472019-05-20 17:16:38 +0200312static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200313_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000314{
315 const char *newloc = target->locale_name;
316
317 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100318 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319
320 /* Set the relevant locale environment variable */
321 if (setenv("LC_CTYPE", newloc, 1)) {
322 fprintf(stderr,
323 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200324 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000325 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200326 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100327 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000328 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000329
330 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100331 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200332 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000333}
334#endif
335
Victor Stinner0f721472019-05-20 17:16:38 +0200336int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200337_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000338{
Victor Stinner0f721472019-05-20 17:16:38 +0200339 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000340#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200341 char *oldloc = NULL;
342
343 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
344 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200345 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200346 }
347
Victor Stinner94540602017-12-16 04:54:22 +0100348 const char *locale_override = getenv("LC_ALL");
349 if (locale_override == NULL || *locale_override == '\0') {
350 /* LC_ALL is also not set (or is set to an empty string) */
351 const _LocaleCoercionTarget *target = NULL;
352 for (target = _TARGET_LOCALES; target->locale_name; target++) {
353 const char *new_locale = setlocale(LC_CTYPE,
354 target->locale_name);
355 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400356#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100357 /* Also ensure that nl_langinfo works in this locale */
358 char *codeset = nl_langinfo(CODESET);
359 if (!codeset || *codeset == '\0') {
360 /* CODESET is not set or empty, so skip coercion */
361 new_locale = NULL;
362 _Py_SetLocaleFromEnv(LC_CTYPE);
363 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000364 }
Victor Stinner94540602017-12-16 04:54:22 +0100365#endif
366 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200367 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200368 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000369 }
370 }
371 }
372 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200373
374 setlocale(LC_CTYPE, oldloc);
375
376done:
377 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000378#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200379 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000380}
381
xdegaye1588be62017-11-12 12:45:59 +0100382/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
383 * isolate the idiosyncrasies of different libc implementations. It reads the
384 * appropriate environment variable and uses its value to select the locale for
385 * 'category'. */
386char *
387_Py_SetLocaleFromEnv(int category)
388{
Victor Stinner353933e2018-11-23 13:08:26 +0100389 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100390#ifdef __ANDROID__
391 const char *locale;
392 const char **pvar;
393#ifdef PY_COERCE_C_LOCALE
394 const char *coerce_c_locale;
395#endif
396 const char *utf8_locale = "C.UTF-8";
397 const char *env_var_set[] = {
398 "LC_ALL",
399 "LC_CTYPE",
400 "LANG",
401 NULL,
402 };
403
404 /* Android setlocale(category, "") doesn't check the environment variables
405 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
406 * check the environment variables listed in env_var_set. */
407 for (pvar=env_var_set; *pvar; pvar++) {
408 locale = getenv(*pvar);
409 if (locale != NULL && *locale != '\0') {
410 if (strcmp(locale, utf8_locale) == 0 ||
411 strcmp(locale, "en_US.UTF-8") == 0) {
412 return setlocale(category, utf8_locale);
413 }
414 return setlocale(category, "C");
415 }
416 }
417
418 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
419 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
420 * Quote from POSIX section "8.2 Internationalization Variables":
421 * "4. If the LANG environment variable is not set or is set to the empty
422 * string, the implementation-defined default locale shall be used." */
423
424#ifdef PY_COERCE_C_LOCALE
425 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
426 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
427 /* Some other ported code may check the environment variables (e.g. in
428 * extension modules), so we make sure that they match the locale
429 * configuration */
430 if (setenv("LC_CTYPE", utf8_locale, 1)) {
431 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
432 "environment variable to %s\n", utf8_locale);
433 }
434 }
435#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100436 res = setlocale(category, utf8_locale);
437#else /* !defined(__ANDROID__) */
438 res = setlocale(category, "");
439#endif
440 _Py_ResetForceASCII();
441 return res;
xdegaye1588be62017-11-12 12:45:59 +0100442}
443
Nick Coghlan6ea41862017-06-11 13:16:15 +1000444
Eric Snow1abcf672017-05-23 21:46:51 -0700445/* Global initializations. Can be undone by Py_Finalize(). Don't
446 call this twice without an intervening Py_Finalize() call.
447
Victor Stinner331a6a52019-05-27 16:39:22 +0200448 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700449 must have a corresponding call to Py_Finalize.
450
451 Locking: you must hold the interpreter lock while calling these APIs.
452 (If the lock has not yet been initialized, that's equivalent to
453 having the lock, but you cannot use multiple threads.)
454
455*/
456
Victor Stinner331a6a52019-05-27 16:39:22 +0200457static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200458pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200459 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200460 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200461{
Victor Stinner331a6a52019-05-27 16:39:22 +0200462 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100463 PyThreadState *tstate = _PyThreadState_GET();
464 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200465 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100466 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200467 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100468
469 PyInterpreterState *interp = tstate->interp;
470 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200471 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100472 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100473
Victor Stinner331a6a52019-05-27 16:39:22 +0200474 _PyConfig_Write(config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200475
Victor Stinner331a6a52019-05-27 16:39:22 +0200476 status = _PyConfig_Copy(&interp->config, config);
477 if (_PyStatus_EXCEPTION(status)) {
478 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200479 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200480 config = &interp->config;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200481
Victor Stinner331a6a52019-05-27 16:39:22 +0200482 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200483 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200484 if (_PyStatus_EXCEPTION(status)) {
485 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200486 }
487 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200488 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200489}
490
491
Victor Stinner331a6a52019-05-27 16:39:22 +0200492static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200493pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200494 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000495{
Victor Stinner43125222019-04-24 18:23:53 +0200496 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200497 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200498 }
Victor Stinnerda273412017-12-15 01:46:02 +0100499
Victor Stinner331a6a52019-05-27 16:39:22 +0200500 _PyConfig_Write(config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600501
Eric Snow1abcf672017-05-23 21:46:51 -0700502 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
503 * threads behave a little more gracefully at interpreter shutdown.
504 * We clobber it here so the new interpreter can start with a clean
505 * slate.
506 *
507 * However, this may still lead to misbehaviour if there are daemon
508 * threads still hanging around from a previous Py_Initialize/Finalize
509 * pair :(
510 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100511 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600512
Victor Stinner331a6a52019-05-27 16:39:22 +0200513 PyStatus status = _Py_HashRandomization_Init(config);
514 if (_PyStatus_EXCEPTION(status)) {
515 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800516 }
517
Victor Stinner331a6a52019-05-27 16:39:22 +0200518 status = _PyInterpreterState_Enable(runtime);
519 if (_PyStatus_EXCEPTION(status)) {
520 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800521 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200522 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100523}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800524
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100525
Victor Stinner331a6a52019-05-27 16:39:22 +0200526static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200527pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200528 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200529 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100530{
531 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100532 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200533 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100534 }
535
Victor Stinner331a6a52019-05-27 16:39:22 +0200536 PyStatus status = _PyConfig_Copy(&interp->config, config);
537 if (_PyStatus_EXCEPTION(status)) {
538 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100539 }
Nick Coghland6009512014-11-20 21:39:37 +1000540
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200541 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200542 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200543 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200544 }
Nick Coghland6009512014-11-20 21:39:37 +1000545 (void) PyThreadState_Swap(tstate);
546
Victor Stinner99fcc612019-04-29 13:04:07 +0200547 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
548 destroying the GIL might fail when it is being referenced from
549 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000550 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000551 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner56bfdeb2020-03-18 09:26:25 +0100552 _PyEval_FiniThreads(tstate);
Victor Stinner2914bb32018-01-29 11:57:45 +0100553
Nick Coghland6009512014-11-20 21:39:37 +1000554 /* Auto-thread-state API */
Victor Stinner4e53abb2020-03-10 23:49:16 +0100555 status = _PyGILState_Init(tstate);
556 if (_PyStatus_EXCEPTION(status)) {
557 return status;
558 }
Nick Coghland6009512014-11-20 21:39:37 +1000559
Victor Stinner50e6e992020-03-19 02:41:21 +0100560 /* Create the GIL and the pending calls lock */
Victor Stinner111e4ee2020-03-09 21:24:14 +0100561 status = _PyEval_InitThreads(tstate);
562 if (_PyStatus_EXCEPTION(status)) {
563 return status;
564 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100565
Victor Stinnerb45d2592019-06-20 00:05:23 +0200566 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200567 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100568}
Nick Coghland6009512014-11-20 21:39:37 +1000569
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100570
Victor Stinner331a6a52019-05-27 16:39:22 +0200571static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100572pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573{
Victor Stinner444b39b2019-11-20 01:18:11 +0100574 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100575 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100576
Victor Stinner01b1cc12019-11-20 02:27:56 +0100577 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100578 if (_PyStatus_EXCEPTION(status)) {
579 return status;
580 }
581
Victor Stinnere7e699e2019-11-20 12:08:13 +0100582 if (is_main_interp) {
583 status = _PyTypes_Init();
584 if (_PyStatus_EXCEPTION(status)) {
585 return status;
586 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100587 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100588
Victor Stinner630c8df2019-12-17 13:02:18 +0100589
590 if (!_PyLong_Init(tstate)) {
591 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100592 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100593
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100594 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100595 status = _PyUnicode_Init();
596 if (_PyStatus_EXCEPTION(status)) {
597 return status;
598 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100599 }
600
Victor Stinner331a6a52019-05-27 16:39:22 +0200601 status = _PyExc_Init();
602 if (_PyStatus_EXCEPTION(status)) {
603 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100604 }
605
Victor Stinnere7e699e2019-11-20 12:08:13 +0100606 if (is_main_interp) {
607 if (!_PyFloat_Init()) {
608 return _PyStatus_ERR("can't init float");
609 }
Nick Coghland6009512014-11-20 21:39:37 +1000610
Victor Stinnere7e699e2019-11-20 12:08:13 +0100611 if (_PyStructSequence_Init() < 0) {
612 return _PyStatus_ERR("can't initialize structseq");
613 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100614 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200615
Victor Stinner331a6a52019-05-27 16:39:22 +0200616 status = _PyErr_Init();
617 if (_PyStatus_EXCEPTION(status)) {
618 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200619 }
620
Victor Stinnere7e699e2019-11-20 12:08:13 +0100621 if (is_main_interp) {
622 if (!_PyContext_Init()) {
623 return _PyStatus_ERR("can't init context");
624 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100625 }
626
Victor Stinner331a6a52019-05-27 16:39:22 +0200627 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100628}
629
630
Victor Stinner331a6a52019-05-27 16:39:22 +0200631static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200632pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100633{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100634 assert(!_PyErr_Occurred(tstate));
635
Victor Stinnerb45d2592019-06-20 00:05:23 +0200636 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100637 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100638 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100639 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100640
Victor Stinner2582d462019-11-22 19:24:49 +0100641 PyInterpreterState *interp = tstate->interp;
642 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
643 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100644 }
Victor Stinner2582d462019-11-22 19:24:49 +0100645
646 PyObject *builtins_dict = PyModule_GetDict(bimod);
647 if (builtins_dict == NULL) {
648 goto error;
649 }
650 Py_INCREF(builtins_dict);
651 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100652
Victor Stinner331a6a52019-05-27 16:39:22 +0200653 PyStatus status = _PyBuiltins_AddExceptions(bimod);
654 if (_PyStatus_EXCEPTION(status)) {
655 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100656 }
Victor Stinner2582d462019-11-22 19:24:49 +0100657
658 interp->builtins_copy = PyDict_Copy(interp->builtins);
659 if (interp->builtins_copy == NULL) {
660 goto error;
661 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000662 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100663
664 assert(!_PyErr_Occurred(tstate));
665
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100667
668error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000669 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100670 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100671}
672
673
Victor Stinner331a6a52019-05-27 16:39:22 +0200674static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200675pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100676{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100677 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200678
Victor Stinner2582d462019-11-22 19:24:49 +0100679 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200680 if (_PyStatus_EXCEPTION(status)) {
681 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800682 }
Nick Coghland6009512014-11-20 21:39:37 +1000683
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100684 const PyConfig *config = &tstate->interp->config;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100685 if (_Py_IsMainInterpreter(tstate)) {
686 /* Initialize _warnings. */
Victor Stinner66b79732020-03-02 15:02:18 +0100687 status = _PyWarnings_InitState(tstate);
688 if (_PyStatus_EXCEPTION(status)) {
689 return status;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100690 }
Nick Coghland6009512014-11-20 21:39:37 +1000691
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100692 if (config->_install_importlib) {
693 status = _PyConfig_WritePathConfig(config);
694 if (_PyStatus_EXCEPTION(status)) {
695 return status;
696 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200697 }
698 }
699
Eric Snow1abcf672017-05-23 21:46:51 -0700700 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200701 if (config->_install_importlib) {
702 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200703 if (_PyStatus_EXCEPTION(status)) {
704 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800705 }
Eric Snow1abcf672017-05-23 21:46:51 -0700706 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100707
708 assert(!_PyErr_Occurred(tstate));
709
Victor Stinner331a6a52019-05-27 16:39:22 +0200710 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711}
712
713
Victor Stinner331a6a52019-05-27 16:39:22 +0200714static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100715pycore_interp_init(PyThreadState *tstate)
716{
717 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100718 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100719
720 status = pycore_init_types(tstate);
721 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100722 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100723 }
724
Victor Stinnerd863ade2019-12-06 03:37:07 +0100725 status = _PySys_Create(tstate, &sysmod);
726 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100727 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100728 }
729
730 status = pycore_init_builtins(tstate);
731 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100732 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100733 }
734
Victor Stinner080ee5a2019-12-08 21:55:58 +0100735 status = pycore_init_import_warnings(tstate, sysmod);
736
737done:
738 /* sys.modules['sys'] contains a strong reference to the module */
739 Py_XDECREF(sysmod);
740 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100741}
742
743
744static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200745pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200746 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200747 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100748{
Victor Stinner331a6a52019-05-27 16:39:22 +0200749 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100750
Victor Stinner331a6a52019-05-27 16:39:22 +0200751 PyStatus status = pycore_init_runtime(runtime, config);
752 if (_PyStatus_EXCEPTION(status)) {
753 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100754 }
755
Victor Stinnerb45d2592019-06-20 00:05:23 +0200756 PyThreadState *tstate;
757 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200758 if (_PyStatus_EXCEPTION(status)) {
759 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100760 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200761 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100762
Victor Stinnerd863ade2019-12-06 03:37:07 +0100763 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200764 if (_PyStatus_EXCEPTION(status)) {
765 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100766 }
Eric Snow1abcf672017-05-23 21:46:51 -0700767
768 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200769 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200770 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700771}
772
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100773
Victor Stinner331a6a52019-05-27 16:39:22 +0200774PyStatus
775_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100776{
Victor Stinner331a6a52019-05-27 16:39:22 +0200777 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100778
Victor Stinner6d1c4672019-05-20 11:02:00 +0200779 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200780 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200781 }
782
Victor Stinner331a6a52019-05-27 16:39:22 +0200783 status = _PyRuntime_Initialize();
784 if (_PyStatus_EXCEPTION(status)) {
785 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100786 }
Victor Stinner43125222019-04-24 18:23:53 +0200787 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100788
Victor Stinnerd3b90412019-09-17 23:59:51 +0200789 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100790 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200791 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100792 }
793
Victor Stinnerd3b90412019-09-17 23:59:51 +0200794 /* Note: preinitialized remains 1 on error, it is only set to 0
795 at exit on success. */
796 runtime->preinitializing = 1;
797
Victor Stinner331a6a52019-05-27 16:39:22 +0200798 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200799
800 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
801 if (_PyStatus_EXCEPTION(status)) {
802 return status;
803 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100804
Victor Stinner331a6a52019-05-27 16:39:22 +0200805 status = _PyPreConfig_Read(&config, args);
806 if (_PyStatus_EXCEPTION(status)) {
807 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100808 }
809
Victor Stinner331a6a52019-05-27 16:39:22 +0200810 status = _PyPreConfig_Write(&config);
811 if (_PyStatus_EXCEPTION(status)) {
812 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100813 }
814
Victor Stinnerd3b90412019-09-17 23:59:51 +0200815 runtime->preinitializing = 0;
816 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200817 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100818}
819
Victor Stinner70005ac2019-05-02 15:25:34 -0400820
Victor Stinner331a6a52019-05-27 16:39:22 +0200821PyStatus
822Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100823{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100824 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400825 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100826}
827
828
Victor Stinner331a6a52019-05-27 16:39:22 +0200829PyStatus
830Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100831{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100832 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400833 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100834}
835
836
Victor Stinner331a6a52019-05-27 16:39:22 +0200837PyStatus
838Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100839{
Victor Stinner70005ac2019-05-02 15:25:34 -0400840 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100841}
842
843
Victor Stinner331a6a52019-05-27 16:39:22 +0200844PyStatus
845_Py_PreInitializeFromConfig(const PyConfig *config,
846 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100847{
Victor Stinner331a6a52019-05-27 16:39:22 +0200848 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200849
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 PyStatus status = _PyRuntime_Initialize();
851 if (_PyStatus_EXCEPTION(status)) {
852 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200853 }
854 _PyRuntimeState *runtime = &_PyRuntime;
855
Victor Stinnerd3b90412019-09-17 23:59:51 +0200856 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200857 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200858 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400859 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200860
Victor Stinner331a6a52019-05-27 16:39:22 +0200861 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200862
Victor Stinner3c30a762019-10-01 10:56:37 +0200863 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200864
Victor Stinner331a6a52019-05-27 16:39:22 +0200865 if (!config->parse_argv) {
866 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200867 }
868 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200869 _PyArgv config_args = {
870 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200871 .argc = config->argv.length,
872 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200873 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200874 }
875 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200876 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200877 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100878}
879
880
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100881/* Begin interpreter initialization
882 *
883 * On return, the first thread and interpreter state have been created,
884 * but the compiler, signal handling, multithreading and
885 * multiple interpreter support, and codec infrastructure are not yet
886 * available.
887 *
888 * The import system will support builtin and frozen modules only.
889 * The only supported io is writing to sys.stderr
890 *
891 * If any operation invoked by this function fails, a fatal error is
892 * issued and the function does not return.
893 *
894 * Any code invoked from this function should *not* assume it has access
895 * to the Python C API (unless the API is explicitly listed as being
896 * safe to call without calling Py_Initialize first)
897 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200898static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200899pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200900 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200901 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200902{
Victor Stinner331a6a52019-05-27 16:39:22 +0200903 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200904
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 status = _Py_PreInitializeFromConfig(src_config, NULL);
906 if (_PyStatus_EXCEPTION(status)) {
907 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200908 }
909
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200911 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200912
Victor Stinner331a6a52019-05-27 16:39:22 +0200913 status = _PyConfig_Copy(&config, src_config);
914 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200915 goto done;
916 }
917
Victor Stinner331a6a52019-05-27 16:39:22 +0200918 status = PyConfig_Read(&config);
919 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200920 goto done;
921 }
922
923 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200924 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200925 }
926 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200927 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200928 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200929 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200930 goto done;
931 }
932
933done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200934 PyConfig_Clear(&config);
935 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200936}
937
Victor Stinner5ac27a52019-03-27 13:40:14 +0100938
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200939/* Py_Initialize() has already been called: update the main interpreter
940 configuration. Example of bpo-34008: Py_Main() called after
941 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200942static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100943_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200944{
Victor Stinnerb0051362019-11-22 17:52:42 +0100945 PyConfig *config = &tstate->interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100946
Victor Stinner331a6a52019-05-27 16:39:22 +0200947 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100948 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200949 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100950 }
951
Victor Stinnerb0051362019-11-22 17:52:42 +0100952 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100953 Py_DECREF(argv);
954 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200955 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200956 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200957 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200958}
959
Victor Stinnerb0051362019-11-22 17:52:42 +0100960
961static PyStatus
962init_interp_main(PyThreadState *tstate)
963{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100964 assert(!_PyErr_Occurred(tstate));
965
Victor Stinnerb0051362019-11-22 17:52:42 +0100966 PyStatus status;
967 int is_main_interp = _Py_IsMainInterpreter(tstate);
968 PyInterpreterState *interp = tstate->interp;
969 PyConfig *config = &interp->config;
970
971 if (!config->_install_importlib) {
972 /* Special mode for freeze_importlib: run with no import system
973 *
974 * This means anything which needs support from extension modules
975 * or pure Python code in the standard library won't work.
976 */
977 if (is_main_interp) {
978 interp->runtime->initialized = 1;
979 }
980 return _PyStatus_OK();
981 }
982
983 if (is_main_interp) {
984 if (_PyTime_Init() < 0) {
985 return _PyStatus_ERR("can't initialize time");
986 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100987 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100988
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100989 if (_PySys_InitMain(tstate) < 0) {
990 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +0100991 }
992
993 status = init_importlib_external(tstate);
994 if (_PyStatus_EXCEPTION(status)) {
995 return status;
996 }
997
998 if (is_main_interp) {
999 /* initialize the faulthandler module */
1000 status = _PyFaulthandler_Init(config->faulthandler);
1001 if (_PyStatus_EXCEPTION(status)) {
1002 return status;
1003 }
1004 }
1005
1006 status = _PyUnicode_InitEncodings(tstate);
1007 if (_PyStatus_EXCEPTION(status)) {
1008 return status;
1009 }
1010
1011 if (is_main_interp) {
1012 if (config->install_signal_handlers) {
1013 status = init_signals(tstate);
1014 if (_PyStatus_EXCEPTION(status)) {
1015 return status;
1016 }
1017 }
1018
1019 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1020 return _PyStatus_ERR("can't initialize tracemalloc");
1021 }
1022 }
1023
1024 status = init_sys_streams(tstate);
1025 if (_PyStatus_EXCEPTION(status)) {
1026 return status;
1027 }
1028
Andy Lester75cd5bf2020-03-12 02:49:05 -05001029 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001030 if (_PyStatus_EXCEPTION(status)) {
1031 return status;
1032 }
1033
1034 status = add_main_module(interp);
1035 if (_PyStatus_EXCEPTION(status)) {
1036 return status;
1037 }
1038
1039 if (is_main_interp) {
1040 /* Initialize warnings. */
1041 PyObject *warnoptions = PySys_GetObject("warnoptions");
1042 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1043 {
1044 PyObject *warnings_module = PyImport_ImportModule("warnings");
1045 if (warnings_module == NULL) {
1046 fprintf(stderr, "'import warnings' failed; traceback:\n");
1047 _PyErr_Print(tstate);
1048 }
1049 Py_XDECREF(warnings_module);
1050 }
1051
1052 interp->runtime->initialized = 1;
1053 }
1054
1055 if (config->site_import) {
1056 status = init_import_site();
1057 if (_PyStatus_EXCEPTION(status)) {
1058 return status;
1059 }
1060 }
1061
1062 if (is_main_interp) {
1063#ifndef MS_WINDOWS
1064 emit_stderr_warning_for_legacy_locale(interp->runtime);
1065#endif
1066 }
1067
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001068 assert(!_PyErr_Occurred(tstate));
1069
Victor Stinnerb0051362019-11-22 17:52:42 +01001070 return _PyStatus_OK();
1071}
1072
1073
Eric Snowc7ec9982017-05-23 23:00:52 -07001074/* Update interpreter state based on supplied configuration settings
1075 *
1076 * After calling this function, most of the restrictions on the interpreter
1077 * are lifted. The only remaining incomplete settings are those related
1078 * to the main module (sys.argv[0], __main__ metadata)
1079 *
1080 * Calling this when the interpreter is not initializing, is already
1081 * initialized or without a valid current thread state is a fatal error.
1082 * Other errors should be reported as normal Python exceptions with a
1083 * non-zero return code.
1084 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001085static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001086pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001087{
Victor Stinnerb0051362019-11-22 17:52:42 +01001088 PyInterpreterState *interp = tstate->interp;
1089 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001090 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001091 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001092
Victor Stinnerb0051362019-11-22 17:52:42 +01001093 if (interp->runtime->initialized) {
1094 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001095 }
1096
Victor Stinnerb0051362019-11-22 17:52:42 +01001097 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001098 if (_PyStatus_EXCEPTION(status)) {
1099 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001100 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001101 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001102}
1103
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001104
Victor Stinner331a6a52019-05-27 16:39:22 +02001105PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001106_Py_InitializeMain(void)
1107{
Victor Stinner331a6a52019-05-27 16:39:22 +02001108 PyStatus status = _PyRuntime_Initialize();
1109 if (_PyStatus_EXCEPTION(status)) {
1110 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001111 }
1112 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001113 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001114 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001115}
1116
1117
Victor Stinner331a6a52019-05-27 16:39:22 +02001118PyStatus
1119Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001120{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001121 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001122 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001123 }
1124
Victor Stinner331a6a52019-05-27 16:39:22 +02001125 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001126
Victor Stinner331a6a52019-05-27 16:39:22 +02001127 status = _PyRuntime_Initialize();
1128 if (_PyStatus_EXCEPTION(status)) {
1129 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001130 }
1131 _PyRuntimeState *runtime = &_PyRuntime;
1132
Victor Stinnerb45d2592019-06-20 00:05:23 +02001133 PyThreadState *tstate = NULL;
1134 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001135 if (_PyStatus_EXCEPTION(status)) {
1136 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001137 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001138 config = &tstate->interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001139
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001140 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001141 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001142 if (_PyStatus_EXCEPTION(status)) {
1143 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001144 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001145 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001146
Victor Stinner331a6a52019-05-27 16:39:22 +02001147 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001148}
1149
1150
Eric Snow1abcf672017-05-23 21:46:51 -07001151void
Nick Coghland6009512014-11-20 21:39:37 +10001152Py_InitializeEx(int install_sigs)
1153{
Victor Stinner331a6a52019-05-27 16:39:22 +02001154 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001155
Victor Stinner331a6a52019-05-27 16:39:22 +02001156 status = _PyRuntime_Initialize();
1157 if (_PyStatus_EXCEPTION(status)) {
1158 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001159 }
1160 _PyRuntimeState *runtime = &_PyRuntime;
1161
1162 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001163 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1164 return;
1165 }
1166
Victor Stinner331a6a52019-05-27 16:39:22 +02001167 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001168 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001169
Victor Stinner1dc6e392018-07-25 02:49:17 +02001170 config.install_signal_handlers = install_sigs;
1171
Victor Stinner331a6a52019-05-27 16:39:22 +02001172 status = Py_InitializeFromConfig(&config);
1173 if (_PyStatus_EXCEPTION(status)) {
1174 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001175 }
Nick Coghland6009512014-11-20 21:39:37 +10001176}
1177
1178void
1179Py_Initialize(void)
1180{
1181 Py_InitializeEx(1);
1182}
1183
1184
Nick Coghland6009512014-11-20 21:39:37 +10001185/* Flush stdout and stderr */
1186
1187static int
1188file_is_closed(PyObject *fobj)
1189{
1190 int r;
1191 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1192 if (tmp == NULL) {
1193 PyErr_Clear();
1194 return 0;
1195 }
1196 r = PyObject_IsTrue(tmp);
1197 Py_DECREF(tmp);
1198 if (r < 0)
1199 PyErr_Clear();
1200 return r > 0;
1201}
1202
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001203static int
Nick Coghland6009512014-11-20 21:39:37 +10001204flush_std_files(void)
1205{
1206 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1207 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1208 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001209 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001210
1211 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001212 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001213 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001214 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001215 status = -1;
1216 }
Nick Coghland6009512014-11-20 21:39:37 +10001217 else
1218 Py_DECREF(tmp);
1219 }
1220
1221 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001222 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001223 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001224 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001225 status = -1;
1226 }
Nick Coghland6009512014-11-20 21:39:37 +10001227 else
1228 Py_DECREF(tmp);
1229 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001230
1231 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001232}
1233
1234/* Undo the effect of Py_Initialize().
1235
1236 Beware: if multiple interpreter and/or thread states exist, these
1237 are not wiped out; only the current thread and interpreter state
1238 are deleted. But since everything else is deleted, those other
1239 interpreter and thread states should no longer be used.
1240
1241 (XXX We should do better, e.g. wipe out all interpreters and
1242 threads.)
1243
1244 Locking: as above.
1245
1246*/
1247
Victor Stinner7eee5be2019-11-20 10:38:34 +01001248
1249static void
1250finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1251{
1252 if (is_main_interp) {
1253 /* Sundry finalizers */
Victor Stinner7eee5be2019-11-20 10:38:34 +01001254 _PyFrame_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001255 _PyTuple_Fini();
1256 _PyList_Fini();
1257 _PySet_Fini();
1258 _PyBytes_Fini();
Victor Stinner630c8df2019-12-17 13:02:18 +01001259 }
1260
1261 _PyLong_Fini(tstate);
1262
1263 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001264 _PyFloat_Fini();
1265 _PyDict_Fini();
1266 _PySlice_Fini();
1267 }
1268
1269 _PyWarnings_Fini(tstate->interp);
1270
1271 if (is_main_interp) {
1272 _Py_HashRandomization_Fini();
1273 _PyArg_Fini();
1274 _PyAsyncGen_Fini();
1275 _PyContext_Fini();
Victor Stinner3d483342019-11-22 12:27:50 +01001276 }
Victor Stinner7eee5be2019-11-20 10:38:34 +01001277
Victor Stinner3d483342019-11-22 12:27:50 +01001278 /* Cleanup Unicode implementation */
1279 _PyUnicode_Fini(tstate);
1280
1281 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001282 _Py_ClearFileSystemEncoding();
1283 }
1284}
1285
1286
1287static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001288finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001289{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001290 int is_main_interp = _Py_IsMainInterpreter(tstate);
1291
Victor Stinner7eee5be2019-11-20 10:38:34 +01001292 /* Clear interpreter state and all thread states */
1293 PyInterpreterState_Clear(tstate->interp);
1294
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001295 /* Trigger a GC collection on subinterpreters*/
1296 if (!is_main_interp) {
1297 _PyGC_CollectNoFail();
1298 }
1299
Victor Stinner7eee5be2019-11-20 10:38:34 +01001300 finalize_interp_types(tstate, is_main_interp);
1301
1302 if (is_main_interp) {
1303 /* XXX Still allocated:
1304 - various static ad-hoc pointers to interned strings
1305 - int and float free list blocks
1306 - whatever various modules and libraries allocate
1307 */
1308
1309 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1310
1311 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001312 }
Victor Stinner72474072019-11-20 12:25:50 +01001313
1314 _PyGC_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001315}
1316
1317
1318static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001319finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001320{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001321 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001322 /* Cleanup auto-thread-state */
1323 _PyGILState_Fini(tstate);
1324 }
1325
Victor Stinner7eee5be2019-11-20 10:38:34 +01001326 PyInterpreterState_Delete(tstate->interp);
1327}
1328
1329
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001330int
1331Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001332{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001333 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001334
Victor Stinner8e91c242019-04-24 17:24:01 +02001335 _PyRuntimeState *runtime = &_PyRuntime;
1336 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001337 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001338 }
Nick Coghland6009512014-11-20 21:39:37 +10001339
Victor Stinnere225beb2019-06-03 18:14:24 +02001340 /* Get current thread state and interpreter pointer */
1341 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1342 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001343
Victor Stinnerb45d2592019-06-20 00:05:23 +02001344 // Wrap up existing "threading"-module-created, non-daemon threads.
1345 wait_for_thread_shutdown(tstate);
1346
1347 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001348 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001349
Nick Coghland6009512014-11-20 21:39:37 +10001350 /* The interpreter is still entirely intact at this point, and the
1351 * exit funcs may be relying on that. In particular, if some thread
1352 * or exit func is still waiting to do an import, the import machinery
1353 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001354 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001355 * Note that Threading.py uses an exit func to do a join on all the
1356 * threads created thru it, so this also protects pending imports in
1357 * the threads created via Threading.
1358 */
Nick Coghland6009512014-11-20 21:39:37 +10001359
Victor Stinnerb45d2592019-06-20 00:05:23 +02001360 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001361
Victor Stinnerda273412017-12-15 01:46:02 +01001362 /* Copy the core config, PyInterpreterState_Delete() free
1363 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001364#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001365 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001366#endif
1367#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001368 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001369#endif
1370#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001371 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001372#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001373
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001374 /* Remaining daemon threads will automatically exit
1375 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001376 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001377 runtime->initialized = 0;
1378 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001379
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001380 /* Destroy the state of all threads of the interpreter, except of the
1381 current thread. In practice, only daemon threads should still be alive,
1382 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1383 Clear frames of other threads to call objects destructors. Destructors
1384 will be called in the current Python thread. Since
1385 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1386 can take the GIL at this point: if they try, they will exit
1387 immediately. */
1388 _PyThreadState_DeleteExcept(runtime, tstate);
1389
Victor Stinnere0deff32015-03-24 13:46:18 +01001390 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001391 if (flush_std_files() < 0) {
1392 status = -1;
1393 }
Nick Coghland6009512014-11-20 21:39:37 +10001394
1395 /* Disable signal handling */
1396 PyOS_FiniInterrupts();
1397
1398 /* Collect garbage. This may call finalizers; it's nice to call these
1399 * before all modules are destroyed.
1400 * XXX If a __del__ or weakref callback is triggered here, and tries to
1401 * XXX import a module, bad things can happen, because Python no
1402 * XXX longer believes it's initialized.
1403 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1404 * XXX is easy to provoke that way. I've also seen, e.g.,
1405 * XXX Exception exceptions.ImportError: 'No module named sha'
1406 * XXX in <function callback at 0x008F5718> ignored
1407 * XXX but I'm unclear on exactly how that one happens. In any case,
1408 * XXX I haven't seen a real-life report of either of these.
1409 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001410 _PyGC_CollectIfEnabled();
Eric Snowdae02762017-09-14 00:35:58 -07001411
Steve Dowerb82e17e2019-05-23 08:45:22 -07001412 /* Clear all loghooks */
Victor Stinner08faf002020-03-26 18:57:32 +01001413 _PySys_ClearAuditHooks(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001414
Nick Coghland6009512014-11-20 21:39:37 +10001415 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001416 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001417
Inada Naoki91234a12019-06-03 21:30:58 +09001418 /* Print debug stats if any */
1419 _PyEval_Fini();
1420
Victor Stinnere0deff32015-03-24 13:46:18 +01001421 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001422 if (flush_std_files() < 0) {
1423 status = -1;
1424 }
Nick Coghland6009512014-11-20 21:39:37 +10001425
1426 /* Collect final garbage. This disposes of cycles created by
1427 * class definitions, for example.
1428 * XXX This is disabled because it caused too many problems. If
1429 * XXX a __del__ or weakref callback triggers here, Python code has
1430 * XXX a hard time running, because even the sys module has been
1431 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1432 * XXX One symptom is a sequence of information-free messages
1433 * XXX coming from threads (if a __del__ or callback is invoked,
1434 * XXX other threads can execute too, and any exception they encounter
1435 * XXX triggers a comedy of errors as subsystem after subsystem
1436 * XXX fails to find what it *expects* to find in sys to help report
1437 * XXX the exception and consequent unexpected failures). I've also
1438 * XXX seen segfaults then, after adding print statements to the
1439 * XXX Python code getting called.
1440 */
1441#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001442 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001443#endif
1444
1445 /* Disable tracemalloc after all Python objects have been destroyed,
1446 so it is possible to use tracemalloc in objects destructor. */
1447 _PyTraceMalloc_Fini();
1448
1449 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1450 _PyImport_Fini();
1451
1452 /* Cleanup typeobject.c's internal caches. */
1453 _PyType_Fini();
1454
1455 /* unload faulthandler module */
1456 _PyFaulthandler_Fini();
1457
Nick Coghland6009512014-11-20 21:39:37 +10001458 /* dump hash stats */
1459 _PyHash_Fini();
1460
Eric Snowdae02762017-09-14 00:35:58 -07001461#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001462 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001463 _PyDebug_PrintTotalRefs();
1464 }
Eric Snowdae02762017-09-14 00:35:58 -07001465#endif
Nick Coghland6009512014-11-20 21:39:37 +10001466
1467#ifdef Py_TRACE_REFS
1468 /* Display all objects still alive -- this can invoke arbitrary
1469 * __repr__ overrides, so requires a mostly-intact interpreter.
1470 * Alas, a lot of stuff may still be alive now that will be cleaned
1471 * up later.
1472 */
Victor Stinnerda273412017-12-15 01:46:02 +01001473 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001474 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001475 }
Nick Coghland6009512014-11-20 21:39:37 +10001476#endif /* Py_TRACE_REFS */
1477
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001478 finalize_interp_clear(tstate);
1479 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001480
1481#ifdef Py_TRACE_REFS
1482 /* Display addresses (& refcnts) of all objects still alive.
1483 * An address can be used to find the repr of the object, printed
1484 * above by _Py_PrintReferences.
1485 */
Victor Stinnerda273412017-12-15 01:46:02 +01001486 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001487 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001488 }
Nick Coghland6009512014-11-20 21:39:37 +10001489#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001490#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001491 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001492 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001493 }
Nick Coghland6009512014-11-20 21:39:37 +10001494#endif
1495
Victor Stinner8e91c242019-04-24 17:24:01 +02001496 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001497
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001498 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001499 return status;
1500}
1501
1502void
1503Py_Finalize(void)
1504{
1505 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001506}
1507
Victor Stinnerb0051362019-11-22 17:52:42 +01001508
Nick Coghland6009512014-11-20 21:39:37 +10001509/* Create and initialize a new interpreter and thread, and return the
1510 new thread. This requires that Py_Initialize() has been called
1511 first.
1512
1513 Unsuccessful initialization yields a NULL pointer. Note that *no*
1514 exception information is available even in this case -- the
1515 exception information is held in the thread, and there is no
1516 thread.
1517
1518 Locking: as above.
1519
1520*/
1521
Victor Stinner331a6a52019-05-27 16:39:22 +02001522static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001523new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001524{
Victor Stinner331a6a52019-05-27 16:39:22 +02001525 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001526
Victor Stinner331a6a52019-05-27 16:39:22 +02001527 status = _PyRuntime_Initialize();
1528 if (_PyStatus_EXCEPTION(status)) {
1529 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001530 }
1531 _PyRuntimeState *runtime = &_PyRuntime;
1532
1533 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001534 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001535 }
Nick Coghland6009512014-11-20 21:39:37 +10001536
Victor Stinner8a1be612016-03-14 22:07:55 +01001537 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1538 interpreters: disable PyGILState_Check(). */
1539 _PyGILState_check_enabled = 0;
1540
Victor Stinner43125222019-04-24 18:23:53 +02001541 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001542 if (interp == NULL) {
1543 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001544 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001545 }
Nick Coghland6009512014-11-20 21:39:37 +10001546
Victor Stinner43125222019-04-24 18:23:53 +02001547 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001548 if (tstate == NULL) {
1549 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001550 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001551 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001552 }
1553
Victor Stinner43125222019-04-24 18:23:53 +02001554 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001555
Eric Snow1abcf672017-05-23 21:46:51 -07001556 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001557 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001558 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001559 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001560 } else {
1561 /* No current thread state, copy from the main interpreter */
1562 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001563 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001564 }
1565
Victor Stinner331a6a52019-05-27 16:39:22 +02001566 status = _PyConfig_Copy(&interp->config, config);
1567 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001568 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001569 }
Eric Snow1abcf672017-05-23 21:46:51 -07001570
Victor Stinnerd863ade2019-12-06 03:37:07 +01001571 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001572 if (_PyStatus_EXCEPTION(status)) {
1573 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001574 }
1575
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001576 status = init_interp_main(tstate);
1577 if (_PyStatus_EXCEPTION(status)) {
1578 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001579 }
Nick Coghland6009512014-11-20 21:39:37 +10001580
Victor Stinner50e6e992020-03-19 02:41:21 +01001581 /* Create the pending calls lock */
1582 status = _PyEval_InitThreads(tstate);
1583 if (_PyStatus_EXCEPTION(status)) {
1584 return status;
1585 }
1586
Victor Stinnera7368ac2017-11-15 18:11:45 -08001587 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001588 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001589
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001590error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001591 *tstate_p = NULL;
1592
1593 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001594 PyErr_PrintEx(0);
1595 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001596 PyThreadState_Delete(tstate);
1597 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001598 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001599
Victor Stinnerb0051362019-11-22 17:52:42 +01001600 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001601}
1602
1603PyThreadState *
1604Py_NewInterpreter(void)
1605{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001606 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001607 PyStatus status = new_interpreter(&tstate);
1608 if (_PyStatus_EXCEPTION(status)) {
1609 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001610 }
1611 return tstate;
1612
Nick Coghland6009512014-11-20 21:39:37 +10001613}
1614
1615/* Delete an interpreter and its last thread. This requires that the
1616 given thread state is current, that the thread has no remaining
1617 frames, and that it is its interpreter's only remaining thread.
1618 It is a fatal error to violate these constraints.
1619
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001620 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001621 everything, regardless.)
1622
1623 Locking: as above.
1624
1625*/
1626
1627void
1628Py_EndInterpreter(PyThreadState *tstate)
1629{
1630 PyInterpreterState *interp = tstate->interp;
1631
Victor Stinnerb45d2592019-06-20 00:05:23 +02001632 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001633 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001634 }
1635 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001636 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001637 }
Eric Snow5be45a62019-03-08 22:47:07 -07001638 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001639
Eric Snow842a2f02019-03-15 15:47:51 -06001640 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001641 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001642
Victor Stinnerb45d2592019-06-20 00:05:23 +02001643 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001644
Victor Stinnerb45d2592019-06-20 00:05:23 +02001645 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001646 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001647 }
Nick Coghland6009512014-11-20 21:39:37 +10001648
Victor Stinner987a0dc2019-06-19 10:36:10 +02001649 _PyImport_Cleanup(tstate);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001650 finalize_interp_clear(tstate);
1651 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001652}
1653
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001654/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001655
Victor Stinner331a6a52019-05-27 16:39:22 +02001656static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001657add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001658{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001659 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001660 m = PyImport_AddModule("__main__");
1661 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001662 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001663
Nick Coghland6009512014-11-20 21:39:37 +10001664 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001665 ann_dict = PyDict_New();
1666 if ((ann_dict == NULL) ||
1667 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001668 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001669 }
1670 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001671
Nick Coghland6009512014-11-20 21:39:37 +10001672 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1673 PyObject *bimod = PyImport_ImportModule("builtins");
1674 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001675 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001676 }
1677 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001678 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001679 }
1680 Py_DECREF(bimod);
1681 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001682
Nick Coghland6009512014-11-20 21:39:37 +10001683 /* Main is a little special - imp.is_builtin("__main__") will return
1684 * False, but BuiltinImporter is still the most appropriate initial
1685 * setting for its __loader__ attribute. A more suitable value will
1686 * be set if __main__ gets further initialized later in the startup
1687 * process.
1688 */
1689 loader = PyDict_GetItemString(d, "__loader__");
1690 if (loader == NULL || loader == Py_None) {
1691 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1692 "BuiltinImporter");
1693 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001694 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001695 }
1696 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001697 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001698 }
1699 Py_DECREF(loader);
1700 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001701 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001702}
1703
Nick Coghland6009512014-11-20 21:39:37 +10001704/* Import the site module (not into __main__ though) */
1705
Victor Stinner331a6a52019-05-27 16:39:22 +02001706static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001707init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10001708{
1709 PyObject *m;
1710 m = PyImport_ImportModule("site");
1711 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001712 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001713 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001714 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001715 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001716}
1717
Victor Stinner874dbe82015-09-04 17:29:57 +02001718/* Check if a file descriptor is valid or not.
1719 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1720static int
1721is_valid_fd(int fd)
1722{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001723/* dup() is faster than fstat(): fstat() can require input/output operations,
1724 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1725 startup. Problem: dup() doesn't check if the file descriptor is valid on
1726 some platforms.
1727
1728 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1729 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1730 EBADF. FreeBSD has similar issue (bpo-32849).
1731
1732 Only use dup() on platforms where dup() is enough to detect invalid FD in
1733 corner cases: on Linux and Windows (bpo-32849). */
1734#if defined(__linux__) || defined(MS_WINDOWS)
1735 if (fd < 0) {
1736 return 0;
1737 }
1738 int fd2;
1739
1740 _Py_BEGIN_SUPPRESS_IPH
1741 fd2 = dup(fd);
1742 if (fd2 >= 0) {
1743 close(fd2);
1744 }
1745 _Py_END_SUPPRESS_IPH
1746
1747 return (fd2 >= 0);
1748#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001749 struct stat st;
1750 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001751#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001752}
1753
1754/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001755static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001756create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001757 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001758 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001759{
1760 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1761 const char* mode;
1762 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001763 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001764 int buffering, isatty;
1765 _Py_IDENTIFIER(open);
1766 _Py_IDENTIFIER(isatty);
1767 _Py_IDENTIFIER(TextIOWrapper);
1768 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001769 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001770
Victor Stinner874dbe82015-09-04 17:29:57 +02001771 if (!is_valid_fd(fd))
1772 Py_RETURN_NONE;
1773
Nick Coghland6009512014-11-20 21:39:37 +10001774 /* stdin is always opened in buffered mode, first because it shouldn't
1775 make a difference in common use cases, second because TextIOWrapper
1776 depends on the presence of a read1() method which only exists on
1777 buffered streams.
1778 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001779 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001780 buffering = 0;
1781 else
1782 buffering = -1;
1783 if (write_mode)
1784 mode = "wb";
1785 else
1786 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001787 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10001788 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001789 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001790 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001791 if (buf == NULL)
1792 goto error;
1793
1794 if (buffering) {
1795 _Py_IDENTIFIER(raw);
1796 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1797 if (raw == NULL)
1798 goto error;
1799 }
1800 else {
1801 raw = buf;
1802 Py_INCREF(raw);
1803 }
1804
Steve Dower39294992016-08-30 21:22:36 -07001805#ifdef MS_WINDOWS
1806 /* Windows console IO is always UTF-8 encoded */
1807 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001808 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001809#endif
1810
Nick Coghland6009512014-11-20 21:39:37 +10001811 text = PyUnicode_FromString(name);
1812 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1813 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001814 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10001815 if (res == NULL)
1816 goto error;
1817 isatty = PyObject_IsTrue(res);
1818 Py_DECREF(res);
1819 if (isatty == -1)
1820 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001821 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001822 write_through = Py_True;
1823 else
1824 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01001825 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10001826 line_buffering = Py_True;
1827 else
1828 line_buffering = Py_False;
1829
1830 Py_CLEAR(raw);
1831 Py_CLEAR(text);
1832
1833#ifdef MS_WINDOWS
1834 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1835 newlines to "\n".
1836 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1837 newline = NULL;
1838#else
1839 /* sys.stdin: split lines at "\n".
1840 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1841 newline = "\n";
1842#endif
1843
Victor Stinner709d23d2019-05-02 14:56:30 -04001844 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1845 if (encoding_str == NULL) {
1846 Py_CLEAR(buf);
1847 goto error;
1848 }
1849
1850 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1851 if (errors_str == NULL) {
1852 Py_CLEAR(buf);
1853 Py_CLEAR(encoding_str);
1854 goto error;
1855 }
1856
1857 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1858 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001859 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001860 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001861 Py_CLEAR(encoding_str);
1862 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001863 if (stream == NULL)
1864 goto error;
1865
1866 if (write_mode)
1867 mode = "w";
1868 else
1869 mode = "r";
1870 text = PyUnicode_FromString(mode);
1871 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1872 goto error;
1873 Py_CLEAR(text);
1874 return stream;
1875
1876error:
1877 Py_XDECREF(buf);
1878 Py_XDECREF(stream);
1879 Py_XDECREF(text);
1880 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001881
Victor Stinner874dbe82015-09-04 17:29:57 +02001882 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1883 /* Issue #24891: the file descriptor was closed after the first
1884 is_valid_fd() check was called. Ignore the OSError and set the
1885 stream to None. */
1886 PyErr_Clear();
1887 Py_RETURN_NONE;
1888 }
1889 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001890}
1891
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001892/* Set builtins.open to io.OpenWrapper */
1893static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05001894init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001895{
1896 PyObject *iomod = NULL, *wrapper;
1897 PyObject *bimod = NULL;
1898 PyStatus res = _PyStatus_OK();
1899
1900 if (!(iomod = PyImport_ImportModule("io"))) {
1901 goto error;
1902 }
1903
1904 if (!(bimod = PyImport_ImportModule("builtins"))) {
1905 goto error;
1906 }
1907
1908 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1909 goto error;
1910 }
1911
1912 /* Set builtins.open */
1913 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1914 Py_DECREF(wrapper);
1915 goto error;
1916 }
1917 Py_DECREF(wrapper);
1918 goto done;
1919
1920error:
1921 res = _PyStatus_ERR("can't initialize io.open");
1922
1923done:
1924 Py_XDECREF(bimod);
1925 Py_XDECREF(iomod);
1926 return res;
1927}
1928
1929
Nick Coghland6009512014-11-20 21:39:37 +10001930/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001931static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001932init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10001933{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001934 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001935 PyObject *m;
1936 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001937 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001938 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001939 PyStatus res = _PyStatus_OK();
Victor Stinnerb45d2592019-06-20 00:05:23 +02001940 const PyConfig *config = &tstate->interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001941
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001942 /* Check that stdin is not a directory
1943 Using shell redirection, you can redirect stdin to a directory,
1944 crashing the Python interpreter. Catch this common mistake here
1945 and output a useful error message. Note that under MS Windows,
1946 the shell already prevents that. */
1947#ifndef MS_WINDOWS
1948 struct _Py_stat_struct sb;
1949 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1950 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001951 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001952 }
1953#endif
1954
Nick Coghland6009512014-11-20 21:39:37 +10001955 /* Hack to avoid a nasty recursion issue when Python is invoked
1956 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1957 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1958 goto error;
1959 }
1960 Py_DECREF(m);
1961
1962 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1963 goto error;
1964 }
1965 Py_DECREF(m);
1966
Nick Coghland6009512014-11-20 21:39:37 +10001967 if (!(iomod = PyImport_ImportModule("io"))) {
1968 goto error;
1969 }
Nick Coghland6009512014-11-20 21:39:37 +10001970
Nick Coghland6009512014-11-20 21:39:37 +10001971 /* Set sys.stdin */
1972 fd = fileno(stdin);
1973 /* Under some conditions stdin, stdout and stderr may not be connected
1974 * and fileno() may point to an invalid file descriptor. For example
1975 * GUI apps don't have valid standard streams by default.
1976 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001977 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001978 config->stdio_encoding,
1979 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001980 if (std == NULL)
1981 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001982 PySys_SetObject("__stdin__", std);
1983 _PySys_SetObjectId(&PyId_stdin, std);
1984 Py_DECREF(std);
1985
1986 /* Set sys.stdout */
1987 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001988 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001989 config->stdio_encoding,
1990 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001991 if (std == NULL)
1992 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001993 PySys_SetObject("__stdout__", std);
1994 _PySys_SetObjectId(&PyId_stdout, std);
1995 Py_DECREF(std);
1996
1997#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1998 /* Set sys.stderr, replaces the preliminary stderr */
1999 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002000 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002001 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002002 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002003 if (std == NULL)
2004 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002005
2006 /* Same as hack above, pre-import stderr's codec to avoid recursion
2007 when import.c tries to write to stderr in verbose mode. */
2008 encoding_attr = PyObject_GetAttrString(std, "encoding");
2009 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002010 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002011 if (std_encoding != NULL) {
2012 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2013 Py_XDECREF(codec_info);
2014 }
2015 Py_DECREF(encoding_attr);
2016 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002017 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002018
2019 if (PySys_SetObject("__stderr__", std) < 0) {
2020 Py_DECREF(std);
2021 goto error;
2022 }
2023 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2024 Py_DECREF(std);
2025 goto error;
2026 }
2027 Py_DECREF(std);
2028#endif
2029
Victor Stinnera7368ac2017-11-15 18:11:45 -08002030 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002031
Victor Stinnera7368ac2017-11-15 18:11:45 -08002032error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002033 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002034
2035done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002036 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002037 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002038 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002039}
2040
2041
Victor Stinner10dc4842015-03-24 12:01:30 +01002042static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002043_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2044 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002045{
Victor Stinner10dc4842015-03-24 12:01:30 +01002046 fputc('\n', stderr);
2047 fflush(stderr);
2048
2049 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002050 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002051}
Victor Stinner791da1c2016-03-14 16:53:12 +01002052
2053/* Print the current exception (if an exception is set) with its traceback,
2054 or display the current Python stack.
2055
2056 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2057 called on catastrophic cases.
2058
2059 Return 1 if the traceback was displayed, 0 otherwise. */
2060
2061static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002062_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002063{
2064 PyObject *ferr, *res;
2065 PyObject *exception, *v, *tb;
2066 int has_tb;
2067
Victor Stinnerb45d2592019-06-20 00:05:23 +02002068 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002069 if (exception == NULL) {
2070 /* No current exception */
2071 return 0;
2072 }
2073
2074 ferr = _PySys_GetObjectId(&PyId_stderr);
2075 if (ferr == NULL || ferr == Py_None) {
2076 /* sys.stderr is not set yet or set to None,
2077 no need to try to display the exception */
2078 return 0;
2079 }
2080
Victor Stinnerb45d2592019-06-20 00:05:23 +02002081 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002082 if (tb == NULL) {
2083 tb = Py_None;
2084 Py_INCREF(tb);
2085 }
2086 PyException_SetTraceback(v, tb);
2087 if (exception == NULL) {
2088 /* PyErr_NormalizeException() failed */
2089 return 0;
2090 }
2091
2092 has_tb = (tb != Py_None);
2093 PyErr_Display(exception, v, tb);
2094 Py_XDECREF(exception);
2095 Py_XDECREF(v);
2096 Py_XDECREF(tb);
2097
2098 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002099 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002100 if (res == NULL) {
2101 _PyErr_Clear(tstate);
2102 }
2103 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002104 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002105 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002106
2107 return has_tb;
2108}
2109
Nick Coghland6009512014-11-20 21:39:37 +10002110/* Print fatal error message and abort */
2111
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002112#ifdef MS_WINDOWS
2113static void
2114fatal_output_debug(const char *msg)
2115{
2116 /* buffer of 256 bytes allocated on the stack */
2117 WCHAR buffer[256 / sizeof(WCHAR)];
2118 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2119 size_t msglen;
2120
2121 OutputDebugStringW(L"Fatal Python error: ");
2122
2123 msglen = strlen(msg);
2124 while (msglen) {
2125 size_t i;
2126
2127 if (buflen > msglen) {
2128 buflen = msglen;
2129 }
2130
2131 /* Convert the message to wchar_t. This uses a simple one-to-one
2132 conversion, assuming that the this error message actually uses
2133 ASCII only. If this ceases to be true, we will have to convert. */
2134 for (i=0; i < buflen; ++i) {
2135 buffer[i] = msg[i];
2136 }
2137 buffer[i] = L'\0';
2138 OutputDebugStringW(buffer);
2139
2140 msg += buflen;
2141 msglen -= buflen;
2142 }
2143 OutputDebugStringW(L"\n");
2144}
2145#endif
2146
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002147
2148static void
2149fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2150{
2151 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002152 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2153 if (finalizing) {
2154 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002155 }
2156 else if (runtime->initialized) {
2157 fprintf(stream, "initialized");
2158 }
2159 else if (runtime->core_initialized) {
2160 fprintf(stream, "core initialized");
2161 }
2162 else if (runtime->preinitialized) {
2163 fprintf(stream, "preinitialized");
2164 }
2165 else if (runtime->preinitializing) {
2166 fprintf(stream, "preinitializing");
2167 }
2168 else {
2169 fprintf(stream, "unknown");
2170 }
2171 fprintf(stream, "\n");
2172 fflush(stream);
2173}
2174
2175
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002176static inline void _Py_NO_RETURN
2177fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002178{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002179 if (status < 0) {
2180#if defined(MS_WINDOWS) && defined(_DEBUG)
2181 DebugBreak();
2182#endif
2183 abort();
2184 }
2185 else {
2186 exit(status);
2187 }
2188}
2189
2190
2191static void _Py_NO_RETURN
2192fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2193 int status)
2194{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002195 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002196 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002197
2198 if (reentrant) {
2199 /* Py_FatalError() caused a second fatal error.
2200 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002201 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002202 }
2203 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002204
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002205 if (header) {
2206 fprintf(stream, "Fatal Python error: ");
2207 if (prefix) {
2208 fputs(prefix, stream);
2209 fputs(": ", stream);
2210 }
2211 if (msg) {
2212 fputs(msg, stream);
2213 }
2214 else {
2215 fprintf(stream, "<message not set>");
2216 }
2217 fputs("\n", stream);
2218 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002219 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002220
2221 _PyRuntimeState *runtime = &_PyRuntime;
2222 fatal_error_dump_runtime(stream, runtime);
2223
2224 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2225 PyInterpreterState *interp = NULL;
2226 if (tstate != NULL) {
2227 interp = tstate->interp;
2228 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002229
Victor Stinner3a228ab2018-11-01 00:26:41 +01002230 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002231 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002232
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002233 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2234 has no Python thread state.
2235
2236 tss_tstate != tstate if the current Python thread does not hold the GIL.
2237 */
2238 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2239 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002240 if (has_tstate_and_gil) {
2241 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002242 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002243 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002244 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002245 }
2246 }
2247 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002248 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002249 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002250
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002251 /* The main purpose of faulthandler is to display the traceback.
2252 This function already did its best to display a traceback.
2253 Disable faulthandler to prevent writing a second traceback
2254 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002255 _PyFaulthandler_Fini();
2256
Victor Stinner791da1c2016-03-14 16:53:12 +01002257 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002258 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002259 /* Flush sys.stdout and sys.stderr */
2260 flush_std_files();
2261 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002262
Nick Coghland6009512014-11-20 21:39:37 +10002263#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002264 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002265#endif /* MS_WINDOWS */
2266
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002267 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002268}
2269
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002270
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002271#undef Py_FatalError
2272
Victor Stinner19760862017-12-20 01:41:59 +01002273void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002274Py_FatalError(const char *msg)
2275{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002276 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002277}
2278
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002279
Victor Stinner19760862017-12-20 01:41:59 +01002280void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002281_Py_FatalErrorFunc(const char *func, const char *msg)
2282{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002283 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002284}
2285
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002286
2287void _Py_NO_RETURN
2288_Py_FatalErrorFormat(const char *func, const char *format, ...)
2289{
2290 static int reentrant = 0;
2291 if (reentrant) {
2292 /* _Py_FatalErrorFormat() caused a second fatal error */
2293 fatal_error_exit(-1);
2294 }
2295 reentrant = 1;
2296
2297 FILE *stream = stderr;
2298 fprintf(stream, "Fatal Python error: ");
2299 if (func) {
2300 fputs(func, stream);
2301 fputs(": ", stream);
2302 }
2303 fflush(stream);
2304
2305 va_list vargs;
2306#ifdef HAVE_STDARG_PROTOTYPES
2307 va_start(vargs, format);
2308#else
2309 va_start(vargs);
2310#endif
2311 vfprintf(stream, format, vargs);
2312 va_end(vargs);
2313
2314 fputs("\n", stream);
2315 fflush(stream);
2316
2317 fatal_error(stream, 0, NULL, NULL, -1);
2318}
2319
2320
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002321void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002322Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002323{
Victor Stinner331a6a52019-05-27 16:39:22 +02002324 if (_PyStatus_IS_EXIT(status)) {
2325 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002326 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002327 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002328 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002329 }
2330 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002331 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002332 }
Nick Coghland6009512014-11-20 21:39:37 +10002333}
2334
2335/* Clean up and exit */
2336
Victor Stinnerd7292b52016-06-17 12:29:00 +02002337# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002338
Nick Coghland6009512014-11-20 21:39:37 +10002339/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002340void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002341{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002342 PyInterpreterState *is = _PyInterpreterState_GET_UNSAFE();
Marcel Plch776407f2017-12-20 11:17:58 +01002343
Antoine Pitroufc5db952017-12-13 02:29:07 +01002344 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002345 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2346
2347 is->pyexitfunc = func;
2348 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002349}
2350
2351static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002352call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002353{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002354 PyInterpreterState *interp = tstate->interp;
2355 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002356 return;
2357
Victor Stinnerb45d2592019-06-20 00:05:23 +02002358 (*interp->pyexitfunc)(interp->pyexitmodule);
2359 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002360}
2361
2362/* Wait until threading._shutdown completes, provided
2363 the threading module was imported in the first place.
2364 The shutdown routine will wait until all non-daemon
2365 "threading" threads have completed. */
2366static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002367wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002368{
Nick Coghland6009512014-11-20 21:39:37 +10002369 _Py_IDENTIFIER(_shutdown);
2370 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002371 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002372 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002373 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002374 PyErr_WriteUnraisable(NULL);
2375 }
2376 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002377 return;
2378 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002379 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002380 if (result == NULL) {
2381 PyErr_WriteUnraisable(threading);
2382 }
2383 else {
2384 Py_DECREF(result);
2385 }
2386 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002387}
2388
2389#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002390int Py_AtExit(void (*func)(void))
2391{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002392 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002393 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002394 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002395 return 0;
2396}
2397
2398static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002399call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002400{
Victor Stinner8e91c242019-04-24 17:24:01 +02002401 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002402 /* pop last function from the list */
2403 runtime->nexitfuncs--;
2404 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2405 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2406
2407 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002408 }
Nick Coghland6009512014-11-20 21:39:37 +10002409
2410 fflush(stdout);
2411 fflush(stderr);
2412}
2413
Victor Stinnercfc88312018-08-01 16:41:25 +02002414void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002415Py_Exit(int sts)
2416{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002417 if (Py_FinalizeEx() < 0) {
2418 sts = 120;
2419 }
Nick Coghland6009512014-11-20 21:39:37 +10002420
2421 exit(sts);
2422}
2423
Victor Stinner331a6a52019-05-27 16:39:22 +02002424static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002425init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002426{
2427#ifdef SIGPIPE
2428 PyOS_setsig(SIGPIPE, SIG_IGN);
2429#endif
2430#ifdef SIGXFZ
2431 PyOS_setsig(SIGXFZ, SIG_IGN);
2432#endif
2433#ifdef SIGXFSZ
2434 PyOS_setsig(SIGXFSZ, SIG_IGN);
2435#endif
2436 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002437 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002438 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002439 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002440 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002441}
2442
2443
2444/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2445 *
2446 * All of the code in this function must only use async-signal-safe functions,
2447 * listed at `man 7 signal` or
2448 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002449 *
2450 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002451 */
2452void
2453_Py_RestoreSignals(void)
2454{
2455#ifdef SIGPIPE
2456 PyOS_setsig(SIGPIPE, SIG_DFL);
2457#endif
2458#ifdef SIGXFZ
2459 PyOS_setsig(SIGXFZ, SIG_DFL);
2460#endif
2461#ifdef SIGXFSZ
2462 PyOS_setsig(SIGXFSZ, SIG_DFL);
2463#endif
2464}
2465
2466
2467/*
2468 * The file descriptor fd is considered ``interactive'' if either
2469 * a) isatty(fd) is TRUE, or
2470 * b) the -i flag was given, and the filename associated with
2471 * the descriptor is NULL or "<stdin>" or "???".
2472 */
2473int
2474Py_FdIsInteractive(FILE *fp, const char *filename)
2475{
2476 if (isatty((int)fileno(fp)))
2477 return 1;
2478 if (!Py_InteractiveFlag)
2479 return 0;
2480 return (filename == NULL) ||
2481 (strcmp(filename, "<stdin>") == 0) ||
2482 (strcmp(filename, "???") == 0);
2483}
2484
2485
Nick Coghland6009512014-11-20 21:39:37 +10002486/* Wrappers around sigaction() or signal(). */
2487
2488PyOS_sighandler_t
2489PyOS_getsig(int sig)
2490{
2491#ifdef HAVE_SIGACTION
2492 struct sigaction context;
2493 if (sigaction(sig, NULL, &context) == -1)
2494 return SIG_ERR;
2495 return context.sa_handler;
2496#else
2497 PyOS_sighandler_t handler;
2498/* Special signal handling for the secure CRT in Visual Studio 2005 */
2499#if defined(_MSC_VER) && _MSC_VER >= 1400
2500 switch (sig) {
2501 /* Only these signals are valid */
2502 case SIGINT:
2503 case SIGILL:
2504 case SIGFPE:
2505 case SIGSEGV:
2506 case SIGTERM:
2507 case SIGBREAK:
2508 case SIGABRT:
2509 break;
2510 /* Don't call signal() with other values or it will assert */
2511 default:
2512 return SIG_ERR;
2513 }
2514#endif /* _MSC_VER && _MSC_VER >= 1400 */
2515 handler = signal(sig, SIG_IGN);
2516 if (handler != SIG_ERR)
2517 signal(sig, handler);
2518 return handler;
2519#endif
2520}
2521
2522/*
2523 * All of the code in this function must only use async-signal-safe functions,
2524 * listed at `man 7 signal` or
2525 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2526 */
2527PyOS_sighandler_t
2528PyOS_setsig(int sig, PyOS_sighandler_t handler)
2529{
2530#ifdef HAVE_SIGACTION
2531 /* Some code in Modules/signalmodule.c depends on sigaction() being
2532 * used here if HAVE_SIGACTION is defined. Fix that if this code
2533 * changes to invalidate that assumption.
2534 */
2535 struct sigaction context, ocontext;
2536 context.sa_handler = handler;
2537 sigemptyset(&context.sa_mask);
2538 context.sa_flags = 0;
2539 if (sigaction(sig, &context, &ocontext) == -1)
2540 return SIG_ERR;
2541 return ocontext.sa_handler;
2542#else
2543 PyOS_sighandler_t oldhandler;
2544 oldhandler = signal(sig, handler);
2545#ifdef HAVE_SIGINTERRUPT
2546 siginterrupt(sig, 1);
2547#endif
2548 return oldhandler;
2549#endif
2550}
2551
2552#ifdef __cplusplus
2553}
2554#endif