blob: 9b413c631875ae0582ac9d5cd0bea15ee2bc138f [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 Stinnerdda5d6e2020-04-08 17:54:59 +0200527init_interp_create_gil(PyThreadState *tstate)
528{
529 PyStatus status;
530
531 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
532 only called here. */
533 _PyEval_FiniGIL(tstate);
534
535 /* Auto-thread-state API */
536 status = _PyGILState_Init(tstate);
537 if (_PyStatus_EXCEPTION(status)) {
538 return status;
539 }
540
541 /* Create the GIL and take it */
542 status = _PyEval_InitGIL(tstate);
543 if (_PyStatus_EXCEPTION(status)) {
544 return status;
545 }
546
547 return _PyStatus_OK();
548}
549
550
551static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200552pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200553 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200554 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100555{
556 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100557 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200558 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100559 }
560
Victor Stinner331a6a52019-05-27 16:39:22 +0200561 PyStatus status = _PyConfig_Copy(&interp->config, config);
562 if (_PyStatus_EXCEPTION(status)) {
563 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100564 }
Nick Coghland6009512014-11-20 21:39:37 +1000565
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200566 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200567 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200568 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200569 }
Nick Coghland6009512014-11-20 21:39:37 +1000570 (void) PyThreadState_Swap(tstate);
571
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200572 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100573 if (_PyStatus_EXCEPTION(status)) {
574 return status;
575 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100576
Victor Stinnerb45d2592019-06-20 00:05:23 +0200577 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200578 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100579}
Nick Coghland6009512014-11-20 21:39:37 +1000580
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100581
Victor Stinner331a6a52019-05-27 16:39:22 +0200582static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100583pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100584{
Victor Stinner444b39b2019-11-20 01:18:11 +0100585 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100586 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100587
Victor Stinner01b1cc12019-11-20 02:27:56 +0100588 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100589 if (_PyStatus_EXCEPTION(status)) {
590 return status;
591 }
592
Victor Stinnere7e699e2019-11-20 12:08:13 +0100593 if (is_main_interp) {
594 status = _PyTypes_Init();
595 if (_PyStatus_EXCEPTION(status)) {
596 return status;
597 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100598 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100599
Victor Stinner630c8df2019-12-17 13:02:18 +0100600
601 if (!_PyLong_Init(tstate)) {
602 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100603 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100604
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100605 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100606 status = _PyUnicode_Init();
607 if (_PyStatus_EXCEPTION(status)) {
608 return status;
609 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100610 }
611
Victor Stinner331a6a52019-05-27 16:39:22 +0200612 status = _PyExc_Init();
613 if (_PyStatus_EXCEPTION(status)) {
614 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100615 }
616
Victor Stinnere7e699e2019-11-20 12:08:13 +0100617 if (is_main_interp) {
618 if (!_PyFloat_Init()) {
619 return _PyStatus_ERR("can't init float");
620 }
Nick Coghland6009512014-11-20 21:39:37 +1000621
Victor Stinnere7e699e2019-11-20 12:08:13 +0100622 if (_PyStructSequence_Init() < 0) {
623 return _PyStatus_ERR("can't initialize structseq");
624 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100625 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200626
Victor Stinner331a6a52019-05-27 16:39:22 +0200627 status = _PyErr_Init();
628 if (_PyStatus_EXCEPTION(status)) {
629 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200630 }
631
Victor Stinnere7e699e2019-11-20 12:08:13 +0100632 if (is_main_interp) {
633 if (!_PyContext_Init()) {
634 return _PyStatus_ERR("can't init context");
635 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100636 }
637
Victor Stinner331a6a52019-05-27 16:39:22 +0200638 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100639}
640
641
Victor Stinner331a6a52019-05-27 16:39:22 +0200642static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200643pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100644{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100645 assert(!_PyErr_Occurred(tstate));
646
Victor Stinnerb45d2592019-06-20 00:05:23 +0200647 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100648 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100649 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100650 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100651
Victor Stinner2582d462019-11-22 19:24:49 +0100652 PyInterpreterState *interp = tstate->interp;
653 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
654 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655 }
Victor Stinner2582d462019-11-22 19:24:49 +0100656
657 PyObject *builtins_dict = PyModule_GetDict(bimod);
658 if (builtins_dict == NULL) {
659 goto error;
660 }
661 Py_INCREF(builtins_dict);
662 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100663
Victor Stinner331a6a52019-05-27 16:39:22 +0200664 PyStatus status = _PyBuiltins_AddExceptions(bimod);
665 if (_PyStatus_EXCEPTION(status)) {
666 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100667 }
Victor Stinner2582d462019-11-22 19:24:49 +0100668
669 interp->builtins_copy = PyDict_Copy(interp->builtins);
670 if (interp->builtins_copy == NULL) {
671 goto error;
672 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000673 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100674
675 assert(!_PyErr_Occurred(tstate));
676
Victor Stinner331a6a52019-05-27 16:39:22 +0200677 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100678
679error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000680 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100681 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100682}
683
684
Victor Stinner331a6a52019-05-27 16:39:22 +0200685static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200686pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100687{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100688 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200689
Victor Stinner2582d462019-11-22 19:24:49 +0100690 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200691 if (_PyStatus_EXCEPTION(status)) {
692 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800693 }
Nick Coghland6009512014-11-20 21:39:37 +1000694
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100695 const PyConfig *config = &tstate->interp->config;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100696 if (_Py_IsMainInterpreter(tstate)) {
697 /* Initialize _warnings. */
Victor Stinner66b79732020-03-02 15:02:18 +0100698 status = _PyWarnings_InitState(tstate);
699 if (_PyStatus_EXCEPTION(status)) {
700 return status;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100701 }
Nick Coghland6009512014-11-20 21:39:37 +1000702
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100703 if (config->_install_importlib) {
704 status = _PyConfig_WritePathConfig(config);
705 if (_PyStatus_EXCEPTION(status)) {
706 return status;
707 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200708 }
709 }
710
Eric Snow1abcf672017-05-23 21:46:51 -0700711 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200712 if (config->_install_importlib) {
713 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200714 if (_PyStatus_EXCEPTION(status)) {
715 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 }
Eric Snow1abcf672017-05-23 21:46:51 -0700717 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100718
719 assert(!_PyErr_Occurred(tstate));
720
Victor Stinner331a6a52019-05-27 16:39:22 +0200721 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100722}
723
724
Victor Stinner331a6a52019-05-27 16:39:22 +0200725static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100726pycore_interp_init(PyThreadState *tstate)
727{
728 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100729 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100730
731 status = pycore_init_types(tstate);
732 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100733 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100734 }
735
Victor Stinnerd863ade2019-12-06 03:37:07 +0100736 status = _PySys_Create(tstate, &sysmod);
737 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100738 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100739 }
740
741 status = pycore_init_builtins(tstate);
742 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100743 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100744 }
745
Victor Stinner080ee5a2019-12-08 21:55:58 +0100746 status = pycore_init_import_warnings(tstate, sysmod);
747
748done:
749 /* sys.modules['sys'] contains a strong reference to the module */
750 Py_XDECREF(sysmod);
751 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100752}
753
754
755static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200756pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200757 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200758 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100759{
Victor Stinner331a6a52019-05-27 16:39:22 +0200760 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100761
Victor Stinner331a6a52019-05-27 16:39:22 +0200762 PyStatus status = pycore_init_runtime(runtime, config);
763 if (_PyStatus_EXCEPTION(status)) {
764 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100765 }
766
Victor Stinnerb45d2592019-06-20 00:05:23 +0200767 PyThreadState *tstate;
768 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200769 if (_PyStatus_EXCEPTION(status)) {
770 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100771 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200772 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100773
Victor Stinnerd863ade2019-12-06 03:37:07 +0100774 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200775 if (_PyStatus_EXCEPTION(status)) {
776 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100777 }
Eric Snow1abcf672017-05-23 21:46:51 -0700778
779 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200780 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200781 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700782}
783
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100784
Victor Stinner331a6a52019-05-27 16:39:22 +0200785PyStatus
786_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100787{
Victor Stinner331a6a52019-05-27 16:39:22 +0200788 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100789
Victor Stinner6d1c4672019-05-20 11:02:00 +0200790 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200791 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200792 }
793
Victor Stinner331a6a52019-05-27 16:39:22 +0200794 status = _PyRuntime_Initialize();
795 if (_PyStatus_EXCEPTION(status)) {
796 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100797 }
Victor Stinner43125222019-04-24 18:23:53 +0200798 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100799
Victor Stinnerd3b90412019-09-17 23:59:51 +0200800 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100801 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200802 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100803 }
804
Victor Stinnerd3b90412019-09-17 23:59:51 +0200805 /* Note: preinitialized remains 1 on error, it is only set to 0
806 at exit on success. */
807 runtime->preinitializing = 1;
808
Victor Stinner331a6a52019-05-27 16:39:22 +0200809 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200810
811 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
812 if (_PyStatus_EXCEPTION(status)) {
813 return status;
814 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100815
Victor Stinner331a6a52019-05-27 16:39:22 +0200816 status = _PyPreConfig_Read(&config, args);
817 if (_PyStatus_EXCEPTION(status)) {
818 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100819 }
820
Victor Stinner331a6a52019-05-27 16:39:22 +0200821 status = _PyPreConfig_Write(&config);
822 if (_PyStatus_EXCEPTION(status)) {
823 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100824 }
825
Victor Stinnerd3b90412019-09-17 23:59:51 +0200826 runtime->preinitializing = 0;
827 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200828 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100829}
830
Victor Stinner70005ac2019-05-02 15:25:34 -0400831
Victor Stinner331a6a52019-05-27 16:39:22 +0200832PyStatus
833Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100834{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100835 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400836 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100837}
838
839
Victor Stinner331a6a52019-05-27 16:39:22 +0200840PyStatus
841Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100842{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100843 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400844 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100845}
846
847
Victor Stinner331a6a52019-05-27 16:39:22 +0200848PyStatus
849Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100850{
Victor Stinner70005ac2019-05-02 15:25:34 -0400851 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100852}
853
854
Victor Stinner331a6a52019-05-27 16:39:22 +0200855PyStatus
856_Py_PreInitializeFromConfig(const PyConfig *config,
857 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100858{
Victor Stinner331a6a52019-05-27 16:39:22 +0200859 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200860
Victor Stinner331a6a52019-05-27 16:39:22 +0200861 PyStatus status = _PyRuntime_Initialize();
862 if (_PyStatus_EXCEPTION(status)) {
863 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200864 }
865 _PyRuntimeState *runtime = &_PyRuntime;
866
Victor Stinnerd3b90412019-09-17 23:59:51 +0200867 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200868 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200869 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400870 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200871
Victor Stinner331a6a52019-05-27 16:39:22 +0200872 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200873
Victor Stinner3c30a762019-10-01 10:56:37 +0200874 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200875
Victor Stinner331a6a52019-05-27 16:39:22 +0200876 if (!config->parse_argv) {
877 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200878 }
879 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200880 _PyArgv config_args = {
881 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200882 .argc = config->argv.length,
883 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200884 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200885 }
886 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200887 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200888 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100889}
890
891
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100892/* Begin interpreter initialization
893 *
894 * On return, the first thread and interpreter state have been created,
895 * but the compiler, signal handling, multithreading and
896 * multiple interpreter support, and codec infrastructure are not yet
897 * available.
898 *
899 * The import system will support builtin and frozen modules only.
900 * The only supported io is writing to sys.stderr
901 *
902 * If any operation invoked by this function fails, a fatal error is
903 * issued and the function does not return.
904 *
905 * Any code invoked from this function should *not* assume it has access
906 * to the Python C API (unless the API is explicitly listed as being
907 * safe to call without calling Py_Initialize first)
908 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200909static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200910pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200911 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200912 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200913{
Victor Stinner331a6a52019-05-27 16:39:22 +0200914 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200915
Victor Stinner331a6a52019-05-27 16:39:22 +0200916 status = _Py_PreInitializeFromConfig(src_config, NULL);
917 if (_PyStatus_EXCEPTION(status)) {
918 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200919 }
920
Victor Stinner331a6a52019-05-27 16:39:22 +0200921 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200922 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200923
Victor Stinner331a6a52019-05-27 16:39:22 +0200924 status = _PyConfig_Copy(&config, src_config);
925 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200926 goto done;
927 }
928
Victor Stinner331a6a52019-05-27 16:39:22 +0200929 status = PyConfig_Read(&config);
930 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200931 goto done;
932 }
933
934 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200935 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200936 }
937 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200938 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200939 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200940 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200941 goto done;
942 }
943
944done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200945 PyConfig_Clear(&config);
946 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200947}
948
Victor Stinner5ac27a52019-03-27 13:40:14 +0100949
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200950/* Py_Initialize() has already been called: update the main interpreter
951 configuration. Example of bpo-34008: Py_Main() called after
952 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200953static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100954_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200955{
Victor Stinnerb0051362019-11-22 17:52:42 +0100956 PyConfig *config = &tstate->interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100957
Victor Stinner331a6a52019-05-27 16:39:22 +0200958 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100959 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200960 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100961 }
962
Victor Stinnerb0051362019-11-22 17:52:42 +0100963 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100964 Py_DECREF(argv);
965 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200967 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200968 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200969}
970
Victor Stinnerb0051362019-11-22 17:52:42 +0100971
972static PyStatus
973init_interp_main(PyThreadState *tstate)
974{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100975 assert(!_PyErr_Occurred(tstate));
976
Victor Stinnerb0051362019-11-22 17:52:42 +0100977 PyStatus status;
978 int is_main_interp = _Py_IsMainInterpreter(tstate);
979 PyInterpreterState *interp = tstate->interp;
980 PyConfig *config = &interp->config;
981
982 if (!config->_install_importlib) {
983 /* Special mode for freeze_importlib: run with no import system
984 *
985 * This means anything which needs support from extension modules
986 * or pure Python code in the standard library won't work.
987 */
988 if (is_main_interp) {
989 interp->runtime->initialized = 1;
990 }
991 return _PyStatus_OK();
992 }
993
994 if (is_main_interp) {
995 if (_PyTime_Init() < 0) {
996 return _PyStatus_ERR("can't initialize time");
997 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100998 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100999
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001000 if (_PySys_InitMain(tstate) < 0) {
1001 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +01001002 }
1003
1004 status = init_importlib_external(tstate);
1005 if (_PyStatus_EXCEPTION(status)) {
1006 return status;
1007 }
1008
1009 if (is_main_interp) {
1010 /* initialize the faulthandler module */
1011 status = _PyFaulthandler_Init(config->faulthandler);
1012 if (_PyStatus_EXCEPTION(status)) {
1013 return status;
1014 }
1015 }
1016
1017 status = _PyUnicode_InitEncodings(tstate);
1018 if (_PyStatus_EXCEPTION(status)) {
1019 return status;
1020 }
1021
1022 if (is_main_interp) {
1023 if (config->install_signal_handlers) {
1024 status = init_signals(tstate);
1025 if (_PyStatus_EXCEPTION(status)) {
1026 return status;
1027 }
1028 }
1029
1030 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1031 return _PyStatus_ERR("can't initialize tracemalloc");
1032 }
1033 }
1034
1035 status = init_sys_streams(tstate);
1036 if (_PyStatus_EXCEPTION(status)) {
1037 return status;
1038 }
1039
Andy Lester75cd5bf2020-03-12 02:49:05 -05001040 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001041 if (_PyStatus_EXCEPTION(status)) {
1042 return status;
1043 }
1044
1045 status = add_main_module(interp);
1046 if (_PyStatus_EXCEPTION(status)) {
1047 return status;
1048 }
1049
1050 if (is_main_interp) {
1051 /* Initialize warnings. */
1052 PyObject *warnoptions = PySys_GetObject("warnoptions");
1053 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1054 {
1055 PyObject *warnings_module = PyImport_ImportModule("warnings");
1056 if (warnings_module == NULL) {
1057 fprintf(stderr, "'import warnings' failed; traceback:\n");
1058 _PyErr_Print(tstate);
1059 }
1060 Py_XDECREF(warnings_module);
1061 }
1062
1063 interp->runtime->initialized = 1;
1064 }
1065
1066 if (config->site_import) {
1067 status = init_import_site();
1068 if (_PyStatus_EXCEPTION(status)) {
1069 return status;
1070 }
1071 }
1072
1073 if (is_main_interp) {
1074#ifndef MS_WINDOWS
1075 emit_stderr_warning_for_legacy_locale(interp->runtime);
1076#endif
1077 }
1078
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001079 assert(!_PyErr_Occurred(tstate));
1080
Victor Stinnerb0051362019-11-22 17:52:42 +01001081 return _PyStatus_OK();
1082}
1083
1084
Eric Snowc7ec9982017-05-23 23:00:52 -07001085/* Update interpreter state based on supplied configuration settings
1086 *
1087 * After calling this function, most of the restrictions on the interpreter
1088 * are lifted. The only remaining incomplete settings are those related
1089 * to the main module (sys.argv[0], __main__ metadata)
1090 *
1091 * Calling this when the interpreter is not initializing, is already
1092 * initialized or without a valid current thread state is a fatal error.
1093 * Other errors should be reported as normal Python exceptions with a
1094 * non-zero return code.
1095 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001096static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001097pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001098{
Victor Stinnerb0051362019-11-22 17:52:42 +01001099 PyInterpreterState *interp = tstate->interp;
1100 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001101 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001102 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001103
Victor Stinnerb0051362019-11-22 17:52:42 +01001104 if (interp->runtime->initialized) {
1105 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001106 }
1107
Victor Stinnerb0051362019-11-22 17:52:42 +01001108 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001109 if (_PyStatus_EXCEPTION(status)) {
1110 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001111 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001112 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001113}
1114
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001115
Victor Stinner331a6a52019-05-27 16:39:22 +02001116PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001117_Py_InitializeMain(void)
1118{
Victor Stinner331a6a52019-05-27 16:39:22 +02001119 PyStatus status = _PyRuntime_Initialize();
1120 if (_PyStatus_EXCEPTION(status)) {
1121 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001122 }
1123 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001124 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001125 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001126}
1127
1128
Victor Stinner331a6a52019-05-27 16:39:22 +02001129PyStatus
1130Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001131{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001132 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001133 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001134 }
1135
Victor Stinner331a6a52019-05-27 16:39:22 +02001136 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001137
Victor Stinner331a6a52019-05-27 16:39:22 +02001138 status = _PyRuntime_Initialize();
1139 if (_PyStatus_EXCEPTION(status)) {
1140 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001141 }
1142 _PyRuntimeState *runtime = &_PyRuntime;
1143
Victor Stinnerb45d2592019-06-20 00:05:23 +02001144 PyThreadState *tstate = NULL;
1145 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001146 if (_PyStatus_EXCEPTION(status)) {
1147 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001148 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001149 config = &tstate->interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001150
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001151 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001152 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001153 if (_PyStatus_EXCEPTION(status)) {
1154 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001155 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001156 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001157
Victor Stinner331a6a52019-05-27 16:39:22 +02001158 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001159}
1160
1161
Eric Snow1abcf672017-05-23 21:46:51 -07001162void
Nick Coghland6009512014-11-20 21:39:37 +10001163Py_InitializeEx(int install_sigs)
1164{
Victor Stinner331a6a52019-05-27 16:39:22 +02001165 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001166
Victor Stinner331a6a52019-05-27 16:39:22 +02001167 status = _PyRuntime_Initialize();
1168 if (_PyStatus_EXCEPTION(status)) {
1169 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001170 }
1171 _PyRuntimeState *runtime = &_PyRuntime;
1172
1173 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001174 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1175 return;
1176 }
1177
Victor Stinner331a6a52019-05-27 16:39:22 +02001178 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001179 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001180
Victor Stinner1dc6e392018-07-25 02:49:17 +02001181 config.install_signal_handlers = install_sigs;
1182
Victor Stinner331a6a52019-05-27 16:39:22 +02001183 status = Py_InitializeFromConfig(&config);
1184 if (_PyStatus_EXCEPTION(status)) {
1185 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001186 }
Nick Coghland6009512014-11-20 21:39:37 +10001187}
1188
1189void
1190Py_Initialize(void)
1191{
1192 Py_InitializeEx(1);
1193}
1194
1195
Nick Coghland6009512014-11-20 21:39:37 +10001196/* Flush stdout and stderr */
1197
1198static int
1199file_is_closed(PyObject *fobj)
1200{
1201 int r;
1202 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1203 if (tmp == NULL) {
1204 PyErr_Clear();
1205 return 0;
1206 }
1207 r = PyObject_IsTrue(tmp);
1208 Py_DECREF(tmp);
1209 if (r < 0)
1210 PyErr_Clear();
1211 return r > 0;
1212}
1213
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001214static int
Nick Coghland6009512014-11-20 21:39:37 +10001215flush_std_files(void)
1216{
1217 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1218 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1219 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001220 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001221
1222 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001223 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001224 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001225 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001226 status = -1;
1227 }
Nick Coghland6009512014-11-20 21:39:37 +10001228 else
1229 Py_DECREF(tmp);
1230 }
1231
1232 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001233 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001234 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001235 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001236 status = -1;
1237 }
Nick Coghland6009512014-11-20 21:39:37 +10001238 else
1239 Py_DECREF(tmp);
1240 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001241
1242 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001243}
1244
1245/* Undo the effect of Py_Initialize().
1246
1247 Beware: if multiple interpreter and/or thread states exist, these
1248 are not wiped out; only the current thread and interpreter state
1249 are deleted. But since everything else is deleted, those other
1250 interpreter and thread states should no longer be used.
1251
1252 (XXX We should do better, e.g. wipe out all interpreters and
1253 threads.)
1254
1255 Locking: as above.
1256
1257*/
1258
Victor Stinner7eee5be2019-11-20 10:38:34 +01001259
1260static void
1261finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1262{
1263 if (is_main_interp) {
1264 /* Sundry finalizers */
Victor Stinner7eee5be2019-11-20 10:38:34 +01001265 _PyFrame_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001266 _PyTuple_Fini();
1267 _PyList_Fini();
1268 _PySet_Fini();
1269 _PyBytes_Fini();
Victor Stinner630c8df2019-12-17 13:02:18 +01001270 }
1271
1272 _PyLong_Fini(tstate);
1273
1274 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001275 _PyFloat_Fini();
1276 _PyDict_Fini();
1277 _PySlice_Fini();
1278 }
1279
1280 _PyWarnings_Fini(tstate->interp);
1281
1282 if (is_main_interp) {
1283 _Py_HashRandomization_Fini();
1284 _PyArg_Fini();
1285 _PyAsyncGen_Fini();
1286 _PyContext_Fini();
Victor Stinner3d483342019-11-22 12:27:50 +01001287 }
Victor Stinner7eee5be2019-11-20 10:38:34 +01001288
Victor Stinner3d483342019-11-22 12:27:50 +01001289 /* Cleanup Unicode implementation */
1290 _PyUnicode_Fini(tstate);
1291
1292 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001293 _Py_ClearFileSystemEncoding();
1294 }
1295}
1296
1297
1298static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001299finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001300{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001301 int is_main_interp = _Py_IsMainInterpreter(tstate);
1302
Victor Stinner7eee5be2019-11-20 10:38:34 +01001303 /* Clear interpreter state and all thread states */
1304 PyInterpreterState_Clear(tstate->interp);
1305
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001306 /* Trigger a GC collection on subinterpreters*/
1307 if (!is_main_interp) {
1308 _PyGC_CollectNoFail();
1309 }
1310
Victor Stinner7eee5be2019-11-20 10:38:34 +01001311 finalize_interp_types(tstate, is_main_interp);
1312
1313 if (is_main_interp) {
1314 /* XXX Still allocated:
1315 - various static ad-hoc pointers to interned strings
1316 - int and float free list blocks
1317 - whatever various modules and libraries allocate
1318 */
1319
1320 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1321
1322 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001323 }
Victor Stinner72474072019-11-20 12:25:50 +01001324
1325 _PyGC_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001326}
1327
1328
1329static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001330finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001331{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001332 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001333 /* Cleanup auto-thread-state */
1334 _PyGILState_Fini(tstate);
1335 }
1336
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001337 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1338 fail when it is being awaited by another running daemon thread (see
1339 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1340 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1341 called multiple times. */
1342
Victor Stinner7eee5be2019-11-20 10:38:34 +01001343 PyInterpreterState_Delete(tstate->interp);
1344}
1345
1346
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001347int
1348Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001349{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001350 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001351
Victor Stinner8e91c242019-04-24 17:24:01 +02001352 _PyRuntimeState *runtime = &_PyRuntime;
1353 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001354 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001355 }
Nick Coghland6009512014-11-20 21:39:37 +10001356
Victor Stinnere225beb2019-06-03 18:14:24 +02001357 /* Get current thread state and interpreter pointer */
1358 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1359 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001360
Victor Stinnerb45d2592019-06-20 00:05:23 +02001361 // Wrap up existing "threading"-module-created, non-daemon threads.
1362 wait_for_thread_shutdown(tstate);
1363
1364 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001365 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001366
Nick Coghland6009512014-11-20 21:39:37 +10001367 /* The interpreter is still entirely intact at this point, and the
1368 * exit funcs may be relying on that. In particular, if some thread
1369 * or exit func is still waiting to do an import, the import machinery
1370 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001371 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001372 * Note that Threading.py uses an exit func to do a join on all the
1373 * threads created thru it, so this also protects pending imports in
1374 * the threads created via Threading.
1375 */
Nick Coghland6009512014-11-20 21:39:37 +10001376
Victor Stinnerb45d2592019-06-20 00:05:23 +02001377 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001378
Victor Stinnerda273412017-12-15 01:46:02 +01001379 /* Copy the core config, PyInterpreterState_Delete() free
1380 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001381#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001382 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001383#endif
1384#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001385 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001386#endif
1387#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001388 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001389#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001390
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001391 /* Remaining daemon threads will automatically exit
1392 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001393 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001394 runtime->initialized = 0;
1395 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001396
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001397 /* Destroy the state of all threads of the interpreter, except of the
1398 current thread. In practice, only daemon threads should still be alive,
1399 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1400 Clear frames of other threads to call objects destructors. Destructors
1401 will be called in the current Python thread. Since
1402 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1403 can take the GIL at this point: if they try, they will exit
1404 immediately. */
1405 _PyThreadState_DeleteExcept(runtime, tstate);
1406
Victor Stinnere0deff32015-03-24 13:46:18 +01001407 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001408 if (flush_std_files() < 0) {
1409 status = -1;
1410 }
Nick Coghland6009512014-11-20 21:39:37 +10001411
1412 /* Disable signal handling */
1413 PyOS_FiniInterrupts();
1414
1415 /* Collect garbage. This may call finalizers; it's nice to call these
1416 * before all modules are destroyed.
1417 * XXX If a __del__ or weakref callback is triggered here, and tries to
1418 * XXX import a module, bad things can happen, because Python no
1419 * XXX longer believes it's initialized.
1420 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1421 * XXX is easy to provoke that way. I've also seen, e.g.,
1422 * XXX Exception exceptions.ImportError: 'No module named sha'
1423 * XXX in <function callback at 0x008F5718> ignored
1424 * XXX but I'm unclear on exactly how that one happens. In any case,
1425 * XXX I haven't seen a real-life report of either of these.
1426 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001427 _PyGC_CollectIfEnabled();
Eric Snowdae02762017-09-14 00:35:58 -07001428
Steve Dowerb82e17e2019-05-23 08:45:22 -07001429 /* Clear all loghooks */
Victor Stinner08faf002020-03-26 18:57:32 +01001430 _PySys_ClearAuditHooks(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001431
Nick Coghland6009512014-11-20 21:39:37 +10001432 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001433 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001434
Inada Naoki91234a12019-06-03 21:30:58 +09001435 /* Print debug stats if any */
1436 _PyEval_Fini();
1437
Victor Stinnere0deff32015-03-24 13:46:18 +01001438 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001439 if (flush_std_files() < 0) {
1440 status = -1;
1441 }
Nick Coghland6009512014-11-20 21:39:37 +10001442
1443 /* Collect final garbage. This disposes of cycles created by
1444 * class definitions, for example.
1445 * XXX This is disabled because it caused too many problems. If
1446 * XXX a __del__ or weakref callback triggers here, Python code has
1447 * XXX a hard time running, because even the sys module has been
1448 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1449 * XXX One symptom is a sequence of information-free messages
1450 * XXX coming from threads (if a __del__ or callback is invoked,
1451 * XXX other threads can execute too, and any exception they encounter
1452 * XXX triggers a comedy of errors as subsystem after subsystem
1453 * XXX fails to find what it *expects* to find in sys to help report
1454 * XXX the exception and consequent unexpected failures). I've also
1455 * XXX seen segfaults then, after adding print statements to the
1456 * XXX Python code getting called.
1457 */
1458#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001459 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001460#endif
1461
1462 /* Disable tracemalloc after all Python objects have been destroyed,
1463 so it is possible to use tracemalloc in objects destructor. */
1464 _PyTraceMalloc_Fini();
1465
1466 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1467 _PyImport_Fini();
1468
1469 /* Cleanup typeobject.c's internal caches. */
1470 _PyType_Fini();
1471
1472 /* unload faulthandler module */
1473 _PyFaulthandler_Fini();
1474
Nick Coghland6009512014-11-20 21:39:37 +10001475 /* dump hash stats */
1476 _PyHash_Fini();
1477
Eric Snowdae02762017-09-14 00:35:58 -07001478#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001479 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001480 _PyDebug_PrintTotalRefs();
1481 }
Eric Snowdae02762017-09-14 00:35:58 -07001482#endif
Nick Coghland6009512014-11-20 21:39:37 +10001483
1484#ifdef Py_TRACE_REFS
1485 /* Display all objects still alive -- this can invoke arbitrary
1486 * __repr__ overrides, so requires a mostly-intact interpreter.
1487 * Alas, a lot of stuff may still be alive now that will be cleaned
1488 * up later.
1489 */
Victor Stinnerda273412017-12-15 01:46:02 +01001490 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001491 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001492 }
Nick Coghland6009512014-11-20 21:39:37 +10001493#endif /* Py_TRACE_REFS */
1494
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001495 finalize_interp_clear(tstate);
1496 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001497
1498#ifdef Py_TRACE_REFS
1499 /* Display addresses (& refcnts) of all objects still alive.
1500 * An address can be used to find the repr of the object, printed
1501 * above by _Py_PrintReferences.
1502 */
Victor Stinnerda273412017-12-15 01:46:02 +01001503 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001504 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001505 }
Nick Coghland6009512014-11-20 21:39:37 +10001506#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001507#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001508 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001509 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001510 }
Nick Coghland6009512014-11-20 21:39:37 +10001511#endif
1512
Victor Stinner8e91c242019-04-24 17:24:01 +02001513 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001514
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001515 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001516 return status;
1517}
1518
1519void
1520Py_Finalize(void)
1521{
1522 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001523}
1524
Victor Stinnerb0051362019-11-22 17:52:42 +01001525
Nick Coghland6009512014-11-20 21:39:37 +10001526/* Create and initialize a new interpreter and thread, and return the
1527 new thread. This requires that Py_Initialize() has been called
1528 first.
1529
1530 Unsuccessful initialization yields a NULL pointer. Note that *no*
1531 exception information is available even in this case -- the
1532 exception information is held in the thread, and there is no
1533 thread.
1534
1535 Locking: as above.
1536
1537*/
1538
Victor Stinner331a6a52019-05-27 16:39:22 +02001539static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001540new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001541{
Victor Stinner331a6a52019-05-27 16:39:22 +02001542 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001543
Victor Stinner331a6a52019-05-27 16:39:22 +02001544 status = _PyRuntime_Initialize();
1545 if (_PyStatus_EXCEPTION(status)) {
1546 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001547 }
1548 _PyRuntimeState *runtime = &_PyRuntime;
1549
1550 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001551 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001552 }
Nick Coghland6009512014-11-20 21:39:37 +10001553
Victor Stinner8a1be612016-03-14 22:07:55 +01001554 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1555 interpreters: disable PyGILState_Check(). */
1556 _PyGILState_check_enabled = 0;
1557
Victor Stinner43125222019-04-24 18:23:53 +02001558 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001559 if (interp == NULL) {
1560 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001561 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001562 }
Nick Coghland6009512014-11-20 21:39:37 +10001563
Victor Stinner43125222019-04-24 18:23:53 +02001564 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001565 if (tstate == NULL) {
1566 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001567 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001568 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001569 }
1570
Victor Stinner43125222019-04-24 18:23:53 +02001571 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001572
Eric Snow1abcf672017-05-23 21:46:51 -07001573 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001574 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001575 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001576 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001577 } else {
1578 /* No current thread state, copy from the main interpreter */
1579 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001580 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001581 }
1582
Victor Stinner331a6a52019-05-27 16:39:22 +02001583 status = _PyConfig_Copy(&interp->config, config);
1584 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001585 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001586 }
Eric Snow1abcf672017-05-23 21:46:51 -07001587
Victor Stinnerd863ade2019-12-06 03:37:07 +01001588 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001589 if (_PyStatus_EXCEPTION(status)) {
1590 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001591 }
1592
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001593 status = init_interp_main(tstate);
1594 if (_PyStatus_EXCEPTION(status)) {
1595 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001596 }
Nick Coghland6009512014-11-20 21:39:37 +10001597
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001598 status = init_interp_create_gil(tstate);
Victor Stinner50e6e992020-03-19 02:41:21 +01001599 if (_PyStatus_EXCEPTION(status)) {
1600 return status;
1601 }
1602
Victor Stinnera7368ac2017-11-15 18:11:45 -08001603 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001604 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001605
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001606error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001607 *tstate_p = NULL;
1608
1609 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001610 PyErr_PrintEx(0);
1611 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001612 PyThreadState_Delete(tstate);
1613 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001614 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001615
Victor Stinnerb0051362019-11-22 17:52:42 +01001616 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001617}
1618
1619PyThreadState *
1620Py_NewInterpreter(void)
1621{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001622 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001623 PyStatus status = new_interpreter(&tstate);
1624 if (_PyStatus_EXCEPTION(status)) {
1625 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001626 }
1627 return tstate;
1628
Nick Coghland6009512014-11-20 21:39:37 +10001629}
1630
1631/* Delete an interpreter and its last thread. This requires that the
1632 given thread state is current, that the thread has no remaining
1633 frames, and that it is its interpreter's only remaining thread.
1634 It is a fatal error to violate these constraints.
1635
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001636 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001637 everything, regardless.)
1638
1639 Locking: as above.
1640
1641*/
1642
1643void
1644Py_EndInterpreter(PyThreadState *tstate)
1645{
1646 PyInterpreterState *interp = tstate->interp;
1647
Victor Stinnerb45d2592019-06-20 00:05:23 +02001648 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001649 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001650 }
1651 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001652 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001653 }
Eric Snow5be45a62019-03-08 22:47:07 -07001654 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001655
Eric Snow842a2f02019-03-15 15:47:51 -06001656 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001657 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001658
Victor Stinnerb45d2592019-06-20 00:05:23 +02001659 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001660
Victor Stinnerb45d2592019-06-20 00:05:23 +02001661 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001662 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001663 }
Nick Coghland6009512014-11-20 21:39:37 +10001664
Victor Stinner987a0dc2019-06-19 10:36:10 +02001665 _PyImport_Cleanup(tstate);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001666 finalize_interp_clear(tstate);
1667 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001668}
1669
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001670/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001671
Victor Stinner331a6a52019-05-27 16:39:22 +02001672static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001673add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001674{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001675 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001676 m = PyImport_AddModule("__main__");
1677 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001678 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001679
Nick Coghland6009512014-11-20 21:39:37 +10001680 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001681 ann_dict = PyDict_New();
1682 if ((ann_dict == NULL) ||
1683 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001684 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001685 }
1686 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001687
Nick Coghland6009512014-11-20 21:39:37 +10001688 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1689 PyObject *bimod = PyImport_ImportModule("builtins");
1690 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001691 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001692 }
1693 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001694 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001695 }
1696 Py_DECREF(bimod);
1697 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001698
Nick Coghland6009512014-11-20 21:39:37 +10001699 /* Main is a little special - imp.is_builtin("__main__") will return
1700 * False, but BuiltinImporter is still the most appropriate initial
1701 * setting for its __loader__ attribute. A more suitable value will
1702 * be set if __main__ gets further initialized later in the startup
1703 * process.
1704 */
1705 loader = PyDict_GetItemString(d, "__loader__");
1706 if (loader == NULL || loader == Py_None) {
1707 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1708 "BuiltinImporter");
1709 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001710 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001711 }
1712 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001713 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001714 }
1715 Py_DECREF(loader);
1716 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001717 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001718}
1719
Nick Coghland6009512014-11-20 21:39:37 +10001720/* Import the site module (not into __main__ though) */
1721
Victor Stinner331a6a52019-05-27 16:39:22 +02001722static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001723init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10001724{
1725 PyObject *m;
1726 m = PyImport_ImportModule("site");
1727 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001728 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001729 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001730 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001731 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001732}
1733
Victor Stinner874dbe82015-09-04 17:29:57 +02001734/* Check if a file descriptor is valid or not.
1735 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1736static int
1737is_valid_fd(int fd)
1738{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001739/* dup() is faster than fstat(): fstat() can require input/output operations,
1740 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1741 startup. Problem: dup() doesn't check if the file descriptor is valid on
1742 some platforms.
1743
1744 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1745 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1746 EBADF. FreeBSD has similar issue (bpo-32849).
1747
1748 Only use dup() on platforms where dup() is enough to detect invalid FD in
1749 corner cases: on Linux and Windows (bpo-32849). */
1750#if defined(__linux__) || defined(MS_WINDOWS)
1751 if (fd < 0) {
1752 return 0;
1753 }
1754 int fd2;
1755
1756 _Py_BEGIN_SUPPRESS_IPH
1757 fd2 = dup(fd);
1758 if (fd2 >= 0) {
1759 close(fd2);
1760 }
1761 _Py_END_SUPPRESS_IPH
1762
1763 return (fd2 >= 0);
1764#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001765 struct stat st;
1766 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001767#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001768}
1769
1770/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001771static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001772create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001773 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001774 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001775{
1776 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1777 const char* mode;
1778 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001779 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001780 int buffering, isatty;
1781 _Py_IDENTIFIER(open);
1782 _Py_IDENTIFIER(isatty);
1783 _Py_IDENTIFIER(TextIOWrapper);
1784 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001785 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001786
Victor Stinner874dbe82015-09-04 17:29:57 +02001787 if (!is_valid_fd(fd))
1788 Py_RETURN_NONE;
1789
Nick Coghland6009512014-11-20 21:39:37 +10001790 /* stdin is always opened in buffered mode, first because it shouldn't
1791 make a difference in common use cases, second because TextIOWrapper
1792 depends on the presence of a read1() method which only exists on
1793 buffered streams.
1794 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001795 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001796 buffering = 0;
1797 else
1798 buffering = -1;
1799 if (write_mode)
1800 mode = "wb";
1801 else
1802 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001803 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10001804 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001805 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001806 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001807 if (buf == NULL)
1808 goto error;
1809
1810 if (buffering) {
1811 _Py_IDENTIFIER(raw);
1812 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1813 if (raw == NULL)
1814 goto error;
1815 }
1816 else {
1817 raw = buf;
1818 Py_INCREF(raw);
1819 }
1820
Steve Dower39294992016-08-30 21:22:36 -07001821#ifdef MS_WINDOWS
1822 /* Windows console IO is always UTF-8 encoded */
1823 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001824 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001825#endif
1826
Nick Coghland6009512014-11-20 21:39:37 +10001827 text = PyUnicode_FromString(name);
1828 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1829 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001830 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10001831 if (res == NULL)
1832 goto error;
1833 isatty = PyObject_IsTrue(res);
1834 Py_DECREF(res);
1835 if (isatty == -1)
1836 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001837 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001838 write_through = Py_True;
1839 else
1840 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01001841 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10001842 line_buffering = Py_True;
1843 else
1844 line_buffering = Py_False;
1845
1846 Py_CLEAR(raw);
1847 Py_CLEAR(text);
1848
1849#ifdef MS_WINDOWS
1850 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1851 newlines to "\n".
1852 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1853 newline = NULL;
1854#else
1855 /* sys.stdin: split lines at "\n".
1856 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1857 newline = "\n";
1858#endif
1859
Victor Stinner709d23d2019-05-02 14:56:30 -04001860 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1861 if (encoding_str == NULL) {
1862 Py_CLEAR(buf);
1863 goto error;
1864 }
1865
1866 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1867 if (errors_str == NULL) {
1868 Py_CLEAR(buf);
1869 Py_CLEAR(encoding_str);
1870 goto error;
1871 }
1872
1873 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1874 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001875 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001876 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001877 Py_CLEAR(encoding_str);
1878 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001879 if (stream == NULL)
1880 goto error;
1881
1882 if (write_mode)
1883 mode = "w";
1884 else
1885 mode = "r";
1886 text = PyUnicode_FromString(mode);
1887 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1888 goto error;
1889 Py_CLEAR(text);
1890 return stream;
1891
1892error:
1893 Py_XDECREF(buf);
1894 Py_XDECREF(stream);
1895 Py_XDECREF(text);
1896 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001897
Victor Stinner874dbe82015-09-04 17:29:57 +02001898 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1899 /* Issue #24891: the file descriptor was closed after the first
1900 is_valid_fd() check was called. Ignore the OSError and set the
1901 stream to None. */
1902 PyErr_Clear();
1903 Py_RETURN_NONE;
1904 }
1905 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001906}
1907
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001908/* Set builtins.open to io.OpenWrapper */
1909static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05001910init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001911{
1912 PyObject *iomod = NULL, *wrapper;
1913 PyObject *bimod = NULL;
1914 PyStatus res = _PyStatus_OK();
1915
1916 if (!(iomod = PyImport_ImportModule("io"))) {
1917 goto error;
1918 }
1919
1920 if (!(bimod = PyImport_ImportModule("builtins"))) {
1921 goto error;
1922 }
1923
1924 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1925 goto error;
1926 }
1927
1928 /* Set builtins.open */
1929 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1930 Py_DECREF(wrapper);
1931 goto error;
1932 }
1933 Py_DECREF(wrapper);
1934 goto done;
1935
1936error:
1937 res = _PyStatus_ERR("can't initialize io.open");
1938
1939done:
1940 Py_XDECREF(bimod);
1941 Py_XDECREF(iomod);
1942 return res;
1943}
1944
1945
Nick Coghland6009512014-11-20 21:39:37 +10001946/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001947static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001948init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10001949{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001950 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001951 PyObject *m;
1952 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001953 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001954 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001955 PyStatus res = _PyStatus_OK();
Victor Stinnerb45d2592019-06-20 00:05:23 +02001956 const PyConfig *config = &tstate->interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001957
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001958 /* Check that stdin is not a directory
1959 Using shell redirection, you can redirect stdin to a directory,
1960 crashing the Python interpreter. Catch this common mistake here
1961 and output a useful error message. Note that under MS Windows,
1962 the shell already prevents that. */
1963#ifndef MS_WINDOWS
1964 struct _Py_stat_struct sb;
1965 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1966 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001967 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001968 }
1969#endif
1970
Nick Coghland6009512014-11-20 21:39:37 +10001971 /* Hack to avoid a nasty recursion issue when Python is invoked
1972 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1973 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1974 goto error;
1975 }
1976 Py_DECREF(m);
1977
1978 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1979 goto error;
1980 }
1981 Py_DECREF(m);
1982
Nick Coghland6009512014-11-20 21:39:37 +10001983 if (!(iomod = PyImport_ImportModule("io"))) {
1984 goto error;
1985 }
Nick Coghland6009512014-11-20 21:39:37 +10001986
Nick Coghland6009512014-11-20 21:39:37 +10001987 /* Set sys.stdin */
1988 fd = fileno(stdin);
1989 /* Under some conditions stdin, stdout and stderr may not be connected
1990 * and fileno() may point to an invalid file descriptor. For example
1991 * GUI apps don't have valid standard streams by default.
1992 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001993 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001994 config->stdio_encoding,
1995 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001996 if (std == NULL)
1997 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001998 PySys_SetObject("__stdin__", std);
1999 _PySys_SetObjectId(&PyId_stdin, std);
2000 Py_DECREF(std);
2001
2002 /* Set sys.stdout */
2003 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002004 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002005 config->stdio_encoding,
2006 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002007 if (std == NULL)
2008 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002009 PySys_SetObject("__stdout__", std);
2010 _PySys_SetObjectId(&PyId_stdout, std);
2011 Py_DECREF(std);
2012
2013#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2014 /* Set sys.stderr, replaces the preliminary stderr */
2015 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002016 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002017 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002018 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002019 if (std == NULL)
2020 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002021
2022 /* Same as hack above, pre-import stderr's codec to avoid recursion
2023 when import.c tries to write to stderr in verbose mode. */
2024 encoding_attr = PyObject_GetAttrString(std, "encoding");
2025 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002026 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002027 if (std_encoding != NULL) {
2028 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2029 Py_XDECREF(codec_info);
2030 }
2031 Py_DECREF(encoding_attr);
2032 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002033 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002034
2035 if (PySys_SetObject("__stderr__", std) < 0) {
2036 Py_DECREF(std);
2037 goto error;
2038 }
2039 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2040 Py_DECREF(std);
2041 goto error;
2042 }
2043 Py_DECREF(std);
2044#endif
2045
Victor Stinnera7368ac2017-11-15 18:11:45 -08002046 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002047
Victor Stinnera7368ac2017-11-15 18:11:45 -08002048error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002049 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002050
2051done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002052 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002053 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002054 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002055}
2056
2057
Victor Stinner10dc4842015-03-24 12:01:30 +01002058static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002059_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2060 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002061{
Victor Stinner10dc4842015-03-24 12:01:30 +01002062 fputc('\n', stderr);
2063 fflush(stderr);
2064
2065 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002066 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002067}
Victor Stinner791da1c2016-03-14 16:53:12 +01002068
2069/* Print the current exception (if an exception is set) with its traceback,
2070 or display the current Python stack.
2071
2072 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2073 called on catastrophic cases.
2074
2075 Return 1 if the traceback was displayed, 0 otherwise. */
2076
2077static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002078_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002079{
2080 PyObject *ferr, *res;
2081 PyObject *exception, *v, *tb;
2082 int has_tb;
2083
Victor Stinnerb45d2592019-06-20 00:05:23 +02002084 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002085 if (exception == NULL) {
2086 /* No current exception */
2087 return 0;
2088 }
2089
2090 ferr = _PySys_GetObjectId(&PyId_stderr);
2091 if (ferr == NULL || ferr == Py_None) {
2092 /* sys.stderr is not set yet or set to None,
2093 no need to try to display the exception */
2094 return 0;
2095 }
2096
Victor Stinnerb45d2592019-06-20 00:05:23 +02002097 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002098 if (tb == NULL) {
2099 tb = Py_None;
2100 Py_INCREF(tb);
2101 }
2102 PyException_SetTraceback(v, tb);
2103 if (exception == NULL) {
2104 /* PyErr_NormalizeException() failed */
2105 return 0;
2106 }
2107
2108 has_tb = (tb != Py_None);
2109 PyErr_Display(exception, v, tb);
2110 Py_XDECREF(exception);
2111 Py_XDECREF(v);
2112 Py_XDECREF(tb);
2113
2114 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002115 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002116 if (res == NULL) {
2117 _PyErr_Clear(tstate);
2118 }
2119 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002120 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002121 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002122
2123 return has_tb;
2124}
2125
Nick Coghland6009512014-11-20 21:39:37 +10002126/* Print fatal error message and abort */
2127
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002128#ifdef MS_WINDOWS
2129static void
2130fatal_output_debug(const char *msg)
2131{
2132 /* buffer of 256 bytes allocated on the stack */
2133 WCHAR buffer[256 / sizeof(WCHAR)];
2134 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2135 size_t msglen;
2136
2137 OutputDebugStringW(L"Fatal Python error: ");
2138
2139 msglen = strlen(msg);
2140 while (msglen) {
2141 size_t i;
2142
2143 if (buflen > msglen) {
2144 buflen = msglen;
2145 }
2146
2147 /* Convert the message to wchar_t. This uses a simple one-to-one
2148 conversion, assuming that the this error message actually uses
2149 ASCII only. If this ceases to be true, we will have to convert. */
2150 for (i=0; i < buflen; ++i) {
2151 buffer[i] = msg[i];
2152 }
2153 buffer[i] = L'\0';
2154 OutputDebugStringW(buffer);
2155
2156 msg += buflen;
2157 msglen -= buflen;
2158 }
2159 OutputDebugStringW(L"\n");
2160}
2161#endif
2162
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002163
2164static void
2165fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2166{
2167 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002168 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2169 if (finalizing) {
2170 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002171 }
2172 else if (runtime->initialized) {
2173 fprintf(stream, "initialized");
2174 }
2175 else if (runtime->core_initialized) {
2176 fprintf(stream, "core initialized");
2177 }
2178 else if (runtime->preinitialized) {
2179 fprintf(stream, "preinitialized");
2180 }
2181 else if (runtime->preinitializing) {
2182 fprintf(stream, "preinitializing");
2183 }
2184 else {
2185 fprintf(stream, "unknown");
2186 }
2187 fprintf(stream, "\n");
2188 fflush(stream);
2189}
2190
2191
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002192static inline void _Py_NO_RETURN
2193fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002194{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002195 if (status < 0) {
2196#if defined(MS_WINDOWS) && defined(_DEBUG)
2197 DebugBreak();
2198#endif
2199 abort();
2200 }
2201 else {
2202 exit(status);
2203 }
2204}
2205
2206
2207static void _Py_NO_RETURN
2208fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2209 int status)
2210{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002211 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002212 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002213
2214 if (reentrant) {
2215 /* Py_FatalError() caused a second fatal error.
2216 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002217 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002218 }
2219 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002220
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002221 if (header) {
2222 fprintf(stream, "Fatal Python error: ");
2223 if (prefix) {
2224 fputs(prefix, stream);
2225 fputs(": ", stream);
2226 }
2227 if (msg) {
2228 fputs(msg, stream);
2229 }
2230 else {
2231 fprintf(stream, "<message not set>");
2232 }
2233 fputs("\n", stream);
2234 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002235 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002236
2237 _PyRuntimeState *runtime = &_PyRuntime;
2238 fatal_error_dump_runtime(stream, runtime);
2239
2240 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2241 PyInterpreterState *interp = NULL;
2242 if (tstate != NULL) {
2243 interp = tstate->interp;
2244 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002245
Victor Stinner3a228ab2018-11-01 00:26:41 +01002246 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002247 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002248
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002249 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2250 has no Python thread state.
2251
2252 tss_tstate != tstate if the current Python thread does not hold the GIL.
2253 */
2254 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2255 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002256 if (has_tstate_and_gil) {
2257 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002258 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002259 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002260 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002261 }
2262 }
2263 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002264 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002265 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002266
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002267 /* The main purpose of faulthandler is to display the traceback.
2268 This function already did its best to display a traceback.
2269 Disable faulthandler to prevent writing a second traceback
2270 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002271 _PyFaulthandler_Fini();
2272
Victor Stinner791da1c2016-03-14 16:53:12 +01002273 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002274 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002275 /* Flush sys.stdout and sys.stderr */
2276 flush_std_files();
2277 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002278
Nick Coghland6009512014-11-20 21:39:37 +10002279#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002280 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002281#endif /* MS_WINDOWS */
2282
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002283 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002284}
2285
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002286
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002287#undef Py_FatalError
2288
Victor Stinner19760862017-12-20 01:41:59 +01002289void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002290Py_FatalError(const char *msg)
2291{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002292 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002293}
2294
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002295
Victor Stinner19760862017-12-20 01:41:59 +01002296void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002297_Py_FatalErrorFunc(const char *func, const char *msg)
2298{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002299 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002300}
2301
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002302
2303void _Py_NO_RETURN
2304_Py_FatalErrorFormat(const char *func, const char *format, ...)
2305{
2306 static int reentrant = 0;
2307 if (reentrant) {
2308 /* _Py_FatalErrorFormat() caused a second fatal error */
2309 fatal_error_exit(-1);
2310 }
2311 reentrant = 1;
2312
2313 FILE *stream = stderr;
2314 fprintf(stream, "Fatal Python error: ");
2315 if (func) {
2316 fputs(func, stream);
2317 fputs(": ", stream);
2318 }
2319 fflush(stream);
2320
2321 va_list vargs;
2322#ifdef HAVE_STDARG_PROTOTYPES
2323 va_start(vargs, format);
2324#else
2325 va_start(vargs);
2326#endif
2327 vfprintf(stream, format, vargs);
2328 va_end(vargs);
2329
2330 fputs("\n", stream);
2331 fflush(stream);
2332
2333 fatal_error(stream, 0, NULL, NULL, -1);
2334}
2335
2336
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002337void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002338Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002339{
Victor Stinner331a6a52019-05-27 16:39:22 +02002340 if (_PyStatus_IS_EXIT(status)) {
2341 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002342 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002343 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002344 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002345 }
2346 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002347 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002348 }
Nick Coghland6009512014-11-20 21:39:37 +10002349}
2350
2351/* Clean up and exit */
2352
Victor Stinnerd7292b52016-06-17 12:29:00 +02002353# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002354
Nick Coghland6009512014-11-20 21:39:37 +10002355/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002356void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002357{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002358 PyInterpreterState *is = _PyInterpreterState_GET_UNSAFE();
Marcel Plch776407f2017-12-20 11:17:58 +01002359
Antoine Pitroufc5db952017-12-13 02:29:07 +01002360 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002361 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2362
2363 is->pyexitfunc = func;
2364 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002365}
2366
2367static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002368call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002369{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002370 PyInterpreterState *interp = tstate->interp;
2371 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002372 return;
2373
Victor Stinnerb45d2592019-06-20 00:05:23 +02002374 (*interp->pyexitfunc)(interp->pyexitmodule);
2375 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002376}
2377
2378/* Wait until threading._shutdown completes, provided
2379 the threading module was imported in the first place.
2380 The shutdown routine will wait until all non-daemon
2381 "threading" threads have completed. */
2382static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002383wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002384{
Nick Coghland6009512014-11-20 21:39:37 +10002385 _Py_IDENTIFIER(_shutdown);
2386 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002387 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002388 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002389 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002390 PyErr_WriteUnraisable(NULL);
2391 }
2392 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002393 return;
2394 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002395 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002396 if (result == NULL) {
2397 PyErr_WriteUnraisable(threading);
2398 }
2399 else {
2400 Py_DECREF(result);
2401 }
2402 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002403}
2404
2405#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002406int Py_AtExit(void (*func)(void))
2407{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002408 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002409 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002410 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002411 return 0;
2412}
2413
2414static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002415call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002416{
Victor Stinner8e91c242019-04-24 17:24:01 +02002417 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002418 /* pop last function from the list */
2419 runtime->nexitfuncs--;
2420 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2421 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2422
2423 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002424 }
Nick Coghland6009512014-11-20 21:39:37 +10002425
2426 fflush(stdout);
2427 fflush(stderr);
2428}
2429
Victor Stinnercfc88312018-08-01 16:41:25 +02002430void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002431Py_Exit(int sts)
2432{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002433 if (Py_FinalizeEx() < 0) {
2434 sts = 120;
2435 }
Nick Coghland6009512014-11-20 21:39:37 +10002436
2437 exit(sts);
2438}
2439
Victor Stinner331a6a52019-05-27 16:39:22 +02002440static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002441init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002442{
2443#ifdef SIGPIPE
2444 PyOS_setsig(SIGPIPE, SIG_IGN);
2445#endif
2446#ifdef SIGXFZ
2447 PyOS_setsig(SIGXFZ, SIG_IGN);
2448#endif
2449#ifdef SIGXFSZ
2450 PyOS_setsig(SIGXFSZ, SIG_IGN);
2451#endif
Victor Stinner400e1db2020-03-31 19:13:10 +02002452 PyOS_InitInterrupts(); /* May imply init_signals() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002453 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002454 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002455 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002456 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002457}
2458
2459
2460/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2461 *
2462 * All of the code in this function must only use async-signal-safe functions,
2463 * listed at `man 7 signal` or
2464 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002465 *
2466 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002467 */
2468void
2469_Py_RestoreSignals(void)
2470{
2471#ifdef SIGPIPE
2472 PyOS_setsig(SIGPIPE, SIG_DFL);
2473#endif
2474#ifdef SIGXFZ
2475 PyOS_setsig(SIGXFZ, SIG_DFL);
2476#endif
2477#ifdef SIGXFSZ
2478 PyOS_setsig(SIGXFSZ, SIG_DFL);
2479#endif
2480}
2481
2482
2483/*
2484 * The file descriptor fd is considered ``interactive'' if either
2485 * a) isatty(fd) is TRUE, or
2486 * b) the -i flag was given, and the filename associated with
2487 * the descriptor is NULL or "<stdin>" or "???".
2488 */
2489int
2490Py_FdIsInteractive(FILE *fp, const char *filename)
2491{
2492 if (isatty((int)fileno(fp)))
2493 return 1;
2494 if (!Py_InteractiveFlag)
2495 return 0;
2496 return (filename == NULL) ||
2497 (strcmp(filename, "<stdin>") == 0) ||
2498 (strcmp(filename, "???") == 0);
2499}
2500
2501
Nick Coghland6009512014-11-20 21:39:37 +10002502/* Wrappers around sigaction() or signal(). */
2503
2504PyOS_sighandler_t
2505PyOS_getsig(int sig)
2506{
2507#ifdef HAVE_SIGACTION
2508 struct sigaction context;
2509 if (sigaction(sig, NULL, &context) == -1)
2510 return SIG_ERR;
2511 return context.sa_handler;
2512#else
2513 PyOS_sighandler_t handler;
2514/* Special signal handling for the secure CRT in Visual Studio 2005 */
2515#if defined(_MSC_VER) && _MSC_VER >= 1400
2516 switch (sig) {
2517 /* Only these signals are valid */
2518 case SIGINT:
2519 case SIGILL:
2520 case SIGFPE:
2521 case SIGSEGV:
2522 case SIGTERM:
2523 case SIGBREAK:
2524 case SIGABRT:
2525 break;
2526 /* Don't call signal() with other values or it will assert */
2527 default:
2528 return SIG_ERR;
2529 }
2530#endif /* _MSC_VER && _MSC_VER >= 1400 */
2531 handler = signal(sig, SIG_IGN);
2532 if (handler != SIG_ERR)
2533 signal(sig, handler);
2534 return handler;
2535#endif
2536}
2537
2538/*
2539 * All of the code in this function must only use async-signal-safe functions,
2540 * listed at `man 7 signal` or
2541 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2542 */
2543PyOS_sighandler_t
2544PyOS_setsig(int sig, PyOS_sighandler_t handler)
2545{
2546#ifdef HAVE_SIGACTION
2547 /* Some code in Modules/signalmodule.c depends on sigaction() being
2548 * used here if HAVE_SIGACTION is defined. Fix that if this code
2549 * changes to invalidate that assumption.
2550 */
2551 struct sigaction context, ocontext;
2552 context.sa_handler = handler;
2553 sigemptyset(&context.sa_mask);
2554 context.sa_flags = 0;
2555 if (sigaction(sig, &context, &ocontext) == -1)
2556 return SIG_ERR;
2557 return ocontext.sa_handler;
2558#else
2559 PyOS_sighandler_t oldhandler;
2560 oldhandler = signal(sig, handler);
2561#ifdef HAVE_SIGINTERRUPT
2562 siginterrupt(sig, 1);
2563#endif
2564 return oldhandler;
2565#endif
2566}
2567
2568#ifdef __cplusplus
2569}
2570#endif