blob: d5d60d0a6d4d97b179a1308f0c81c8ac7128311b [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 Stinnera1c249c2018-11-01 03:15:58 +010013#include "pycore_pathconfig.h"
Victor Stinnerb45d2592019-06-20 00:05:23 +020014#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010015#include "pycore_pylifecycle.h"
16#include "pycore_pymem.h"
17#include "pycore_pystate.h"
Victor Stinnered488662019-05-20 00:14:57 +020018#include "pycore_traceback.h"
Nick Coghland6009512014-11-20 21:39:37 +100019#include "grammar.h"
20#include "node.h"
21#include "token.h"
22#include "parsetok.h"
23#include "errcode.h"
24#include "code.h"
25#include "symtable.h"
26#include "ast.h"
27#include "marshal.h"
28#include "osdefs.h"
29#include <locale.h>
30
31#ifdef HAVE_SIGNAL_H
32#include <signal.h>
33#endif
34
35#ifdef MS_WINDOWS
36#include "malloc.h" /* for alloca */
37#endif
38
39#ifdef HAVE_LANGINFO_H
40#include <langinfo.h>
41#endif
42
43#ifdef MS_WINDOWS
44#undef BYTE
45#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070046
47extern PyTypeObject PyWindowsConsoleIO_Type;
48#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100049#endif
50
51_Py_IDENTIFIER(flush);
52_Py_IDENTIFIER(name);
53_Py_IDENTIFIER(stdin);
54_Py_IDENTIFIER(stdout);
55_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060056_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100057
58#ifdef __cplusplus
59extern "C" {
60#endif
61
Nick Coghland6009512014-11-20 21:39:37 +100062extern grammar _PyParser_Grammar; /* From graminit.c */
63
Victor Stinnerb45d2592019-06-20 00:05:23 +020064/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020065static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020066static PyStatus init_import_site(void);
Victor Stinnere0c9ab82019-11-22 16:19:14 +010067static PyStatus init_set_builtins_open(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020068static PyStatus init_sys_streams(PyThreadState *tstate);
69static PyStatus init_signals(PyThreadState *tstate);
70static void call_py_exitfuncs(PyThreadState *tstate);
71static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020072static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100073
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080074int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010076static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077
Victor Stinner331a6a52019-05-27 16:39:22 +020078PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079_PyRuntime_Initialize(void)
80{
81 /* XXX We only initialize once in the process, which aligns with
82 the static initialization of the former globals now found in
83 _PyRuntime. However, _PyRuntime *should* be initialized with
84 every Py_Initialize() call, but doing so breaks the runtime.
85 This is because the runtime state is not properly finalized
86 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010087 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020088 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080089 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010090 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091
92 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060093}
94
95void
96_PyRuntime_Finalize(void)
97{
98 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010099 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600100}
101
102int
103_Py_IsFinalizing(void)
104{
105 return _PyRuntime.finalizing != NULL;
106}
107
Nick Coghland6009512014-11-20 21:39:37 +1000108/* Hack to force loading of object files */
109int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
110 PyOS_mystrnicmp; /* Python/pystrcmp.o */
111
112/* PyModule_GetWarningsModule is no longer necessary as of 2.6
113since _warnings is builtin. This API should not be used. */
114PyObject *
115PyModule_GetWarningsModule(void)
116{
117 return PyImport_ImportModule("warnings");
118}
119
Eric Snowc7ec9982017-05-23 23:00:52 -0700120
Eric Snow1abcf672017-05-23 21:46:51 -0700121/* APIs to access the initialization flags
122 *
123 * Can be called prior to Py_Initialize.
124 */
Nick Coghland6009512014-11-20 21:39:37 +1000125
Eric Snow1abcf672017-05-23 21:46:51 -0700126int
127_Py_IsCoreInitialized(void)
128{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600129 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700130}
Nick Coghland6009512014-11-20 21:39:37 +1000131
132int
133Py_IsInitialized(void)
134{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600135 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000136}
137
Nick Coghlan6ea41862017-06-11 13:16:15 +1000138
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000139/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
140 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000141 initializations fail, a fatal error is issued and the function does
142 not return. On return, the first thread and interpreter state have
143 been created.
144
145 Locking: you must hold the interpreter lock while calling this.
146 (If the lock has not yet been initialized, that's equivalent to
147 having the lock, but you cannot use multiple threads.)
148
149*/
150
Victor Stinner331a6a52019-05-27 16:39:22 +0200151static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200152init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000153{
154 PyObject *importlib;
155 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000156 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200157 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +0200158 int verbose = interp->config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000159
160 /* Import _importlib through its frozen version, _frozen_importlib. */
161 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200162 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000163 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200164 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000165 PySys_FormatStderr("import _frozen_importlib # frozen\n");
166 }
167 importlib = PyImport_AddModule("_frozen_importlib");
168 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200169 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000170 }
171 interp->importlib = importlib;
172 Py_INCREF(interp->importlib);
173
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300174 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
175 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200176 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300177 Py_INCREF(interp->import_func);
178
Victor Stinnercd6e6942015-09-18 09:11:57 +0200179 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800180 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000181 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200182 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000183 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200184 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200185 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000186 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600187 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000189 }
190
Victor Stinnercd6e6942015-09-18 09:11:57 +0200191 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000192 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
193 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200194 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200195 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000196 }
197 Py_DECREF(value);
198 Py_DECREF(impmod);
199
Victor Stinner331a6a52019-05-27 16:39:22 +0200200 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000201}
202
Victor Stinner331a6a52019-05-27 16:39:22 +0200203static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200204init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700205{
206 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200207 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700208 "_install_external_importers", "");
209 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200210 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200211 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700212 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200213 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200214 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700215}
Nick Coghland6009512014-11-20 21:39:37 +1000216
Nick Coghlan6ea41862017-06-11 13:16:15 +1000217/* Helper functions to better handle the legacy C locale
218 *
219 * The legacy C locale assumes ASCII as the default text encoding, which
220 * causes problems not only for the CPython runtime, but also other
221 * components like GNU readline.
222 *
223 * Accordingly, when the CLI detects it, it attempts to coerce it to a
224 * more capable UTF-8 based alternative as follows:
225 *
226 * if (_Py_LegacyLocaleDetected()) {
227 * _Py_CoerceLegacyLocale();
228 * }
229 *
230 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
231 *
232 * Locale coercion also impacts the default error handler for the standard
233 * streams: while the usual default is "strict", the default for the legacy
234 * C locale and for any of the coercion target locales is "surrogateescape".
235 */
236
237int
Victor Stinner0f721472019-05-20 17:16:38 +0200238_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000239{
240#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200241 if (!warn) {
242 const char *locale_override = getenv("LC_ALL");
243 if (locale_override != NULL && *locale_override != '\0') {
244 /* Don't coerce C locale if the LC_ALL environment variable
245 is set */
246 return 0;
247 }
248 }
249
Nick Coghlan6ea41862017-06-11 13:16:15 +1000250 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000251 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
252 * the POSIX locale as a simple alias for the C locale, so
253 * we may also want to check for that explicitly.
254 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000255 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
256 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
257#else
258 /* Windows uses code pages instead of locales, so no locale is legacy */
259 return 0;
260#endif
261}
262
Victor Stinnerb0051362019-11-22 17:52:42 +0100263#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000264static const char *_C_LOCALE_WARNING =
265 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
266 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
267 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
268 "locales is recommended.\n";
269
Nick Coghlaneb817952017-06-18 12:29:42 +1000270static void
Victor Stinner43125222019-04-24 18:23:53 +0200271emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000272{
Victor Stinner331a6a52019-05-27 16:39:22 +0200273 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200274 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200275 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000276 }
277}
Victor Stinnerb0051362019-11-22 17:52:42 +0100278#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000279
Nick Coghlan6ea41862017-06-11 13:16:15 +1000280typedef struct _CandidateLocale {
281 const char *locale_name; /* The locale to try as a coercion target */
282} _LocaleCoercionTarget;
283
284static _LocaleCoercionTarget _TARGET_LOCALES[] = {
285 {"C.UTF-8"},
286 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000287 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000288 {NULL}
289};
290
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200291
292int
293_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200295 const _LocaleCoercionTarget *target = NULL;
296 for (target = _TARGET_LOCALES; target->locale_name; target++) {
297 if (strcmp(ctype_loc, target->locale_name) == 0) {
298 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000299 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200300 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200301 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302}
303
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200304
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100306static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
308 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
309
Victor Stinner0f721472019-05-20 17:16:38 +0200310static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200311_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312{
313 const char *newloc = target->locale_name;
314
315 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100316 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317
318 /* Set the relevant locale environment variable */
319 if (setenv("LC_CTYPE", newloc, 1)) {
320 fprintf(stderr,
321 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200322 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000323 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200324 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100325 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000326 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000327
328 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100329 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200330 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000331}
332#endif
333
Victor Stinner0f721472019-05-20 17:16:38 +0200334int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200335_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000336{
Victor Stinner0f721472019-05-20 17:16:38 +0200337 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000338#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200339 char *oldloc = NULL;
340
341 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
342 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200343 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200344 }
345
Victor Stinner94540602017-12-16 04:54:22 +0100346 const char *locale_override = getenv("LC_ALL");
347 if (locale_override == NULL || *locale_override == '\0') {
348 /* LC_ALL is also not set (or is set to an empty string) */
349 const _LocaleCoercionTarget *target = NULL;
350 for (target = _TARGET_LOCALES; target->locale_name; target++) {
351 const char *new_locale = setlocale(LC_CTYPE,
352 target->locale_name);
353 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400354#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100355 /* Also ensure that nl_langinfo works in this locale */
356 char *codeset = nl_langinfo(CODESET);
357 if (!codeset || *codeset == '\0') {
358 /* CODESET is not set or empty, so skip coercion */
359 new_locale = NULL;
360 _Py_SetLocaleFromEnv(LC_CTYPE);
361 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000362 }
Victor Stinner94540602017-12-16 04:54:22 +0100363#endif
364 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200365 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200366 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000367 }
368 }
369 }
370 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200371
372 setlocale(LC_CTYPE, oldloc);
373
374done:
375 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000376#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200377 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000378}
379
xdegaye1588be62017-11-12 12:45:59 +0100380/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
381 * isolate the idiosyncrasies of different libc implementations. It reads the
382 * appropriate environment variable and uses its value to select the locale for
383 * 'category'. */
384char *
385_Py_SetLocaleFromEnv(int category)
386{
Victor Stinner353933e2018-11-23 13:08:26 +0100387 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100388#ifdef __ANDROID__
389 const char *locale;
390 const char **pvar;
391#ifdef PY_COERCE_C_LOCALE
392 const char *coerce_c_locale;
393#endif
394 const char *utf8_locale = "C.UTF-8";
395 const char *env_var_set[] = {
396 "LC_ALL",
397 "LC_CTYPE",
398 "LANG",
399 NULL,
400 };
401
402 /* Android setlocale(category, "") doesn't check the environment variables
403 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
404 * check the environment variables listed in env_var_set. */
405 for (pvar=env_var_set; *pvar; pvar++) {
406 locale = getenv(*pvar);
407 if (locale != NULL && *locale != '\0') {
408 if (strcmp(locale, utf8_locale) == 0 ||
409 strcmp(locale, "en_US.UTF-8") == 0) {
410 return setlocale(category, utf8_locale);
411 }
412 return setlocale(category, "C");
413 }
414 }
415
416 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
417 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
418 * Quote from POSIX section "8.2 Internationalization Variables":
419 * "4. If the LANG environment variable is not set or is set to the empty
420 * string, the implementation-defined default locale shall be used." */
421
422#ifdef PY_COERCE_C_LOCALE
423 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
424 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
425 /* Some other ported code may check the environment variables (e.g. in
426 * extension modules), so we make sure that they match the locale
427 * configuration */
428 if (setenv("LC_CTYPE", utf8_locale, 1)) {
429 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
430 "environment variable to %s\n", utf8_locale);
431 }
432 }
433#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100434 res = setlocale(category, utf8_locale);
435#else /* !defined(__ANDROID__) */
436 res = setlocale(category, "");
437#endif
438 _Py_ResetForceASCII();
439 return res;
xdegaye1588be62017-11-12 12:45:59 +0100440}
441
Nick Coghlan6ea41862017-06-11 13:16:15 +1000442
Eric Snow1abcf672017-05-23 21:46:51 -0700443/* Global initializations. Can be undone by Py_Finalize(). Don't
444 call this twice without an intervening Py_Finalize() call.
445
Victor Stinner331a6a52019-05-27 16:39:22 +0200446 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700447 must have a corresponding call to Py_Finalize.
448
449 Locking: you must hold the interpreter lock while calling these APIs.
450 (If the lock has not yet been initialized, that's equivalent to
451 having the lock, but you cannot use multiple threads.)
452
453*/
454
Victor Stinner331a6a52019-05-27 16:39:22 +0200455static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200456pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200457 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200458 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200459{
Victor Stinner331a6a52019-05-27 16:39:22 +0200460 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100461 PyThreadState *tstate = _PyThreadState_GET();
462 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200463 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100464 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200465 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100466
467 PyInterpreterState *interp = tstate->interp;
468 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200469 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100470 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100471
Victor Stinner331a6a52019-05-27 16:39:22 +0200472 _PyConfig_Write(config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200473
Victor Stinner331a6a52019-05-27 16:39:22 +0200474 status = _PyConfig_Copy(&interp->config, config);
475 if (_PyStatus_EXCEPTION(status)) {
476 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200477 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200478 config = &interp->config;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200479
Victor Stinner331a6a52019-05-27 16:39:22 +0200480 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200481 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200482 if (_PyStatus_EXCEPTION(status)) {
483 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200484 }
485 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200486 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200487}
488
489
Victor Stinner331a6a52019-05-27 16:39:22 +0200490static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200491pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200492 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000493{
Victor Stinner43125222019-04-24 18:23:53 +0200494 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200495 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200496 }
Victor Stinnerda273412017-12-15 01:46:02 +0100497
Victor Stinner331a6a52019-05-27 16:39:22 +0200498 _PyConfig_Write(config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600499
Eric Snow1abcf672017-05-23 21:46:51 -0700500 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
501 * threads behave a little more gracefully at interpreter shutdown.
502 * We clobber it here so the new interpreter can start with a clean
503 * slate.
504 *
505 * However, this may still lead to misbehaviour if there are daemon
506 * threads still hanging around from a previous Py_Initialize/Finalize
507 * pair :(
508 */
Victor Stinner43125222019-04-24 18:23:53 +0200509 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600510
Victor Stinner331a6a52019-05-27 16:39:22 +0200511 PyStatus status = _Py_HashRandomization_Init(config);
512 if (_PyStatus_EXCEPTION(status)) {
513 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800514 }
515
Victor Stinner331a6a52019-05-27 16:39:22 +0200516 status = _PyInterpreterState_Enable(runtime);
517 if (_PyStatus_EXCEPTION(status)) {
518 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800519 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200520 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100521}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800522
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100523
Victor Stinner331a6a52019-05-27 16:39:22 +0200524static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200525pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200526 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200527 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100528{
529 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100530 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200531 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100532 }
533
Victor Stinner331a6a52019-05-27 16:39:22 +0200534 PyStatus status = _PyConfig_Copy(&interp->config, config);
535 if (_PyStatus_EXCEPTION(status)) {
536 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100537 }
Nick Coghland6009512014-11-20 21:39:37 +1000538
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200539 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200540 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200541 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200542 }
Nick Coghland6009512014-11-20 21:39:37 +1000543 (void) PyThreadState_Swap(tstate);
544
Victor Stinner99fcc612019-04-29 13:04:07 +0200545 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
546 destroying the GIL might fail when it is being referenced from
547 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000548 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000549 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner09532fe2019-05-10 23:39:09 +0200550 _PyEval_FiniThreads(&runtime->ceval);
Victor Stinner2914bb32018-01-29 11:57:45 +0100551
Nick Coghland6009512014-11-20 21:39:37 +1000552 /* Auto-thread-state API */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100553 _PyGILState_Init(tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000554
Victor Stinner2914bb32018-01-29 11:57:45 +0100555 /* Create the GIL */
556 PyEval_InitThreads();
557
Victor Stinnerb45d2592019-06-20 00:05:23 +0200558 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200559 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100560}
Nick Coghland6009512014-11-20 21:39:37 +1000561
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100562
Victor Stinner331a6a52019-05-27 16:39:22 +0200563static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100564pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100565{
Victor Stinner444b39b2019-11-20 01:18:11 +0100566 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100567 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100568
Victor Stinner01b1cc12019-11-20 02:27:56 +0100569 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100570 if (_PyStatus_EXCEPTION(status)) {
571 return status;
572 }
573
Victor Stinnere7e699e2019-11-20 12:08:13 +0100574 if (is_main_interp) {
575 status = _PyTypes_Init();
576 if (_PyStatus_EXCEPTION(status)) {
577 return status;
578 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100579 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100580
Victor Stinner630c8df2019-12-17 13:02:18 +0100581
582 if (!_PyLong_Init(tstate)) {
583 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100584 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100585
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100586 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100587 status = _PyUnicode_Init();
588 if (_PyStatus_EXCEPTION(status)) {
589 return status;
590 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100591 }
592
Victor Stinner331a6a52019-05-27 16:39:22 +0200593 status = _PyExc_Init();
594 if (_PyStatus_EXCEPTION(status)) {
595 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596 }
597
Victor Stinnere7e699e2019-11-20 12:08:13 +0100598 if (is_main_interp) {
599 if (!_PyFloat_Init()) {
600 return _PyStatus_ERR("can't init float");
601 }
Nick Coghland6009512014-11-20 21:39:37 +1000602
Victor Stinnere7e699e2019-11-20 12:08:13 +0100603 if (_PyStructSequence_Init() < 0) {
604 return _PyStatus_ERR("can't initialize structseq");
605 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100606 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200607
Victor Stinner331a6a52019-05-27 16:39:22 +0200608 status = _PyErr_Init();
609 if (_PyStatus_EXCEPTION(status)) {
610 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200611 }
612
Victor Stinnere7e699e2019-11-20 12:08:13 +0100613 if (is_main_interp) {
614 if (!_PyContext_Init()) {
615 return _PyStatus_ERR("can't init context");
616 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100617 }
618
Victor Stinner331a6a52019-05-27 16:39:22 +0200619 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100620}
621
622
Victor Stinner331a6a52019-05-27 16:39:22 +0200623static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200624pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100625{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100626 assert(!_PyErr_Occurred(tstate));
627
Victor Stinnerb45d2592019-06-20 00:05:23 +0200628 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100629 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100630 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100631 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100632
Victor Stinner2582d462019-11-22 19:24:49 +0100633 PyInterpreterState *interp = tstate->interp;
634 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
635 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100636 }
Victor Stinner2582d462019-11-22 19:24:49 +0100637
638 PyObject *builtins_dict = PyModule_GetDict(bimod);
639 if (builtins_dict == NULL) {
640 goto error;
641 }
642 Py_INCREF(builtins_dict);
643 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100644
Victor Stinner331a6a52019-05-27 16:39:22 +0200645 PyStatus status = _PyBuiltins_AddExceptions(bimod);
646 if (_PyStatus_EXCEPTION(status)) {
647 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100648 }
Victor Stinner2582d462019-11-22 19:24:49 +0100649
650 interp->builtins_copy = PyDict_Copy(interp->builtins);
651 if (interp->builtins_copy == NULL) {
652 goto error;
653 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000654 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100655
656 assert(!_PyErr_Occurred(tstate));
657
Victor Stinner331a6a52019-05-27 16:39:22 +0200658 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100659
660error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000661 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100662 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100663}
664
665
Victor Stinner331a6a52019-05-27 16:39:22 +0200666static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200667pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100668{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100669 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200670
Victor Stinner2582d462019-11-22 19:24:49 +0100671 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200672 if (_PyStatus_EXCEPTION(status)) {
673 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800674 }
Nick Coghland6009512014-11-20 21:39:37 +1000675
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100676 const PyConfig *config = &tstate->interp->config;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100677 if (_Py_IsMainInterpreter(tstate)) {
678 /* Initialize _warnings. */
679 if (_PyWarnings_Init() == NULL) {
680 return _PyStatus_ERR("can't initialize warnings");
681 }
Nick Coghland6009512014-11-20 21:39:37 +1000682
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100683 if (config->_install_importlib) {
684 status = _PyConfig_WritePathConfig(config);
685 if (_PyStatus_EXCEPTION(status)) {
686 return status;
687 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200688 }
689 }
690
Eric Snow1abcf672017-05-23 21:46:51 -0700691 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200692 if (config->_install_importlib) {
693 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200694 if (_PyStatus_EXCEPTION(status)) {
695 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800696 }
Eric Snow1abcf672017-05-23 21:46:51 -0700697 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100698
699 assert(!_PyErr_Occurred(tstate));
700
Victor Stinner331a6a52019-05-27 16:39:22 +0200701 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100702}
703
704
Victor Stinner331a6a52019-05-27 16:39:22 +0200705static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100706pycore_interp_init(PyThreadState *tstate)
707{
708 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100709 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100710
711 status = pycore_init_types(tstate);
712 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100713 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100714 }
715
Victor Stinnerd863ade2019-12-06 03:37:07 +0100716 status = _PySys_Create(tstate, &sysmod);
717 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100718 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100719 }
720
721 status = pycore_init_builtins(tstate);
722 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100723 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100724 }
725
Victor Stinner080ee5a2019-12-08 21:55:58 +0100726 status = pycore_init_import_warnings(tstate, sysmod);
727
728done:
729 /* sys.modules['sys'] contains a strong reference to the module */
730 Py_XDECREF(sysmod);
731 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100732}
733
734
735static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200736pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200737 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200738 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100739{
Victor Stinner331a6a52019-05-27 16:39:22 +0200740 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100741
Victor Stinner331a6a52019-05-27 16:39:22 +0200742 PyStatus status = pycore_init_runtime(runtime, config);
743 if (_PyStatus_EXCEPTION(status)) {
744 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100745 }
746
Victor Stinnerb45d2592019-06-20 00:05:23 +0200747 PyThreadState *tstate;
748 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200749 if (_PyStatus_EXCEPTION(status)) {
750 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100751 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200752 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100753
Victor Stinnerd863ade2019-12-06 03:37:07 +0100754 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200755 if (_PyStatus_EXCEPTION(status)) {
756 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100757 }
Eric Snow1abcf672017-05-23 21:46:51 -0700758
759 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200760 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200761 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700762}
763
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100764
Victor Stinner331a6a52019-05-27 16:39:22 +0200765PyStatus
766_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100767{
Victor Stinner331a6a52019-05-27 16:39:22 +0200768 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100769
Victor Stinner6d1c4672019-05-20 11:02:00 +0200770 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200771 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200772 }
773
Victor Stinner331a6a52019-05-27 16:39:22 +0200774 status = _PyRuntime_Initialize();
775 if (_PyStatus_EXCEPTION(status)) {
776 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100777 }
Victor Stinner43125222019-04-24 18:23:53 +0200778 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100779
Victor Stinnerd3b90412019-09-17 23:59:51 +0200780 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100781 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200782 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100783 }
784
Victor Stinnerd3b90412019-09-17 23:59:51 +0200785 /* Note: preinitialized remains 1 on error, it is only set to 0
786 at exit on success. */
787 runtime->preinitializing = 1;
788
Victor Stinner331a6a52019-05-27 16:39:22 +0200789 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200790
791 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
792 if (_PyStatus_EXCEPTION(status)) {
793 return status;
794 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100795
Victor Stinner331a6a52019-05-27 16:39:22 +0200796 status = _PyPreConfig_Read(&config, args);
797 if (_PyStatus_EXCEPTION(status)) {
798 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100799 }
800
Victor Stinner331a6a52019-05-27 16:39:22 +0200801 status = _PyPreConfig_Write(&config);
802 if (_PyStatus_EXCEPTION(status)) {
803 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100804 }
805
Victor Stinnerd3b90412019-09-17 23:59:51 +0200806 runtime->preinitializing = 0;
807 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200808 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100809}
810
Victor Stinner70005ac2019-05-02 15:25:34 -0400811
Victor Stinner331a6a52019-05-27 16:39:22 +0200812PyStatus
813Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100814{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100815 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400816 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100817}
818
819
Victor Stinner331a6a52019-05-27 16:39:22 +0200820PyStatus
821Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100822{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100823 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400824 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100825}
826
827
Victor Stinner331a6a52019-05-27 16:39:22 +0200828PyStatus
829Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100830{
Victor Stinner70005ac2019-05-02 15:25:34 -0400831 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100832}
833
834
Victor Stinner331a6a52019-05-27 16:39:22 +0200835PyStatus
836_Py_PreInitializeFromConfig(const PyConfig *config,
837 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100838{
Victor Stinner331a6a52019-05-27 16:39:22 +0200839 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200840
Victor Stinner331a6a52019-05-27 16:39:22 +0200841 PyStatus status = _PyRuntime_Initialize();
842 if (_PyStatus_EXCEPTION(status)) {
843 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200844 }
845 _PyRuntimeState *runtime = &_PyRuntime;
846
Victor Stinnerd3b90412019-09-17 23:59:51 +0200847 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200848 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200849 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400850 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200851
Victor Stinner331a6a52019-05-27 16:39:22 +0200852 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200853
Victor Stinner3c30a762019-10-01 10:56:37 +0200854 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200855
Victor Stinner331a6a52019-05-27 16:39:22 +0200856 if (!config->parse_argv) {
857 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200858 }
859 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200860 _PyArgv config_args = {
861 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200862 .argc = config->argv.length,
863 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200864 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200865 }
866 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200867 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200868 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100869}
870
871
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100872/* Begin interpreter initialization
873 *
874 * On return, the first thread and interpreter state have been created,
875 * but the compiler, signal handling, multithreading and
876 * multiple interpreter support, and codec infrastructure are not yet
877 * available.
878 *
879 * The import system will support builtin and frozen modules only.
880 * The only supported io is writing to sys.stderr
881 *
882 * If any operation invoked by this function fails, a fatal error is
883 * issued and the function does not return.
884 *
885 * Any code invoked from this function should *not* assume it has access
886 * to the Python C API (unless the API is explicitly listed as being
887 * safe to call without calling Py_Initialize first)
888 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200889static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200890pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200891 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200892 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200893{
Victor Stinner331a6a52019-05-27 16:39:22 +0200894 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200895
Victor Stinner331a6a52019-05-27 16:39:22 +0200896 status = _Py_PreInitializeFromConfig(src_config, NULL);
897 if (_PyStatus_EXCEPTION(status)) {
898 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200899 }
900
Victor Stinner331a6a52019-05-27 16:39:22 +0200901 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200902 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200903
Victor Stinner331a6a52019-05-27 16:39:22 +0200904 status = _PyConfig_Copy(&config, src_config);
905 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200906 goto done;
907 }
908
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 status = PyConfig_Read(&config);
910 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200911 goto done;
912 }
913
914 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200915 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200916 }
917 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200918 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200919 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200920 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200921 goto done;
922 }
923
924done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200925 PyConfig_Clear(&config);
926 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200927}
928
Victor Stinner5ac27a52019-03-27 13:40:14 +0100929
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200930/* Py_Initialize() has already been called: update the main interpreter
931 configuration. Example of bpo-34008: Py_Main() called after
932 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200933static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100934_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200935{
Victor Stinnerb0051362019-11-22 17:52:42 +0100936 PyConfig *config = &tstate->interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100937
Victor Stinner331a6a52019-05-27 16:39:22 +0200938 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100939 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200940 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100941 }
942
Victor Stinnerb0051362019-11-22 17:52:42 +0100943 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100944 Py_DECREF(argv);
945 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200946 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200947 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200948 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200949}
950
Victor Stinnerb0051362019-11-22 17:52:42 +0100951
952static PyStatus
953init_interp_main(PyThreadState *tstate)
954{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100955 assert(!_PyErr_Occurred(tstate));
956
Victor Stinnerb0051362019-11-22 17:52:42 +0100957 PyStatus status;
958 int is_main_interp = _Py_IsMainInterpreter(tstate);
959 PyInterpreterState *interp = tstate->interp;
960 PyConfig *config = &interp->config;
961
962 if (!config->_install_importlib) {
963 /* Special mode for freeze_importlib: run with no import system
964 *
965 * This means anything which needs support from extension modules
966 * or pure Python code in the standard library won't work.
967 */
968 if (is_main_interp) {
969 interp->runtime->initialized = 1;
970 }
971 return _PyStatus_OK();
972 }
973
974 if (is_main_interp) {
975 if (_PyTime_Init() < 0) {
976 return _PyStatus_ERR("can't initialize time");
977 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100978 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100979
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100980 if (_PySys_InitMain(tstate) < 0) {
981 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +0100982 }
983
984 status = init_importlib_external(tstate);
985 if (_PyStatus_EXCEPTION(status)) {
986 return status;
987 }
988
989 if (is_main_interp) {
990 /* initialize the faulthandler module */
991 status = _PyFaulthandler_Init(config->faulthandler);
992 if (_PyStatus_EXCEPTION(status)) {
993 return status;
994 }
995 }
996
997 status = _PyUnicode_InitEncodings(tstate);
998 if (_PyStatus_EXCEPTION(status)) {
999 return status;
1000 }
1001
1002 if (is_main_interp) {
1003 if (config->install_signal_handlers) {
1004 status = init_signals(tstate);
1005 if (_PyStatus_EXCEPTION(status)) {
1006 return status;
1007 }
1008 }
1009
1010 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1011 return _PyStatus_ERR("can't initialize tracemalloc");
1012 }
1013 }
1014
1015 status = init_sys_streams(tstate);
1016 if (_PyStatus_EXCEPTION(status)) {
1017 return status;
1018 }
1019
1020 status = init_set_builtins_open(tstate);
1021 if (_PyStatus_EXCEPTION(status)) {
1022 return status;
1023 }
1024
1025 status = add_main_module(interp);
1026 if (_PyStatus_EXCEPTION(status)) {
1027 return status;
1028 }
1029
1030 if (is_main_interp) {
1031 /* Initialize warnings. */
1032 PyObject *warnoptions = PySys_GetObject("warnoptions");
1033 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1034 {
1035 PyObject *warnings_module = PyImport_ImportModule("warnings");
1036 if (warnings_module == NULL) {
1037 fprintf(stderr, "'import warnings' failed; traceback:\n");
1038 _PyErr_Print(tstate);
1039 }
1040 Py_XDECREF(warnings_module);
1041 }
1042
1043 interp->runtime->initialized = 1;
1044 }
1045
1046 if (config->site_import) {
1047 status = init_import_site();
1048 if (_PyStatus_EXCEPTION(status)) {
1049 return status;
1050 }
1051 }
1052
1053 if (is_main_interp) {
1054#ifndef MS_WINDOWS
1055 emit_stderr_warning_for_legacy_locale(interp->runtime);
1056#endif
1057 }
1058
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001059 assert(!_PyErr_Occurred(tstate));
1060
Victor Stinnerb0051362019-11-22 17:52:42 +01001061 return _PyStatus_OK();
1062}
1063
1064
Eric Snowc7ec9982017-05-23 23:00:52 -07001065/* Update interpreter state based on supplied configuration settings
1066 *
1067 * After calling this function, most of the restrictions on the interpreter
1068 * are lifted. The only remaining incomplete settings are those related
1069 * to the main module (sys.argv[0], __main__ metadata)
1070 *
1071 * Calling this when the interpreter is not initializing, is already
1072 * initialized or without a valid current thread state is a fatal error.
1073 * Other errors should be reported as normal Python exceptions with a
1074 * non-zero return code.
1075 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001076static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001077pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001078{
Victor Stinnerb0051362019-11-22 17:52:42 +01001079 PyInterpreterState *interp = tstate->interp;
1080 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001081 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001082 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001083
Victor Stinnerb0051362019-11-22 17:52:42 +01001084 if (interp->runtime->initialized) {
1085 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001086 }
1087
Victor Stinnerb0051362019-11-22 17:52:42 +01001088 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001089 if (_PyStatus_EXCEPTION(status)) {
1090 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001091 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001092 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001093}
1094
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001095
Victor Stinner331a6a52019-05-27 16:39:22 +02001096PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001097_Py_InitializeMain(void)
1098{
Victor Stinner331a6a52019-05-27 16:39:22 +02001099 PyStatus status = _PyRuntime_Initialize();
1100 if (_PyStatus_EXCEPTION(status)) {
1101 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001102 }
1103 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001104 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001105 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001106}
1107
1108
Victor Stinner331a6a52019-05-27 16:39:22 +02001109PyStatus
1110Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001111{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001112 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001113 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001114 }
1115
Victor Stinner331a6a52019-05-27 16:39:22 +02001116 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001117
Victor Stinner331a6a52019-05-27 16:39:22 +02001118 status = _PyRuntime_Initialize();
1119 if (_PyStatus_EXCEPTION(status)) {
1120 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001121 }
1122 _PyRuntimeState *runtime = &_PyRuntime;
1123
Victor Stinnerb45d2592019-06-20 00:05:23 +02001124 PyThreadState *tstate = NULL;
1125 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001126 if (_PyStatus_EXCEPTION(status)) {
1127 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001128 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001129 config = &tstate->interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001130
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001131 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001132 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001133 if (_PyStatus_EXCEPTION(status)) {
1134 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001135 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001136 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001137
Victor Stinner331a6a52019-05-27 16:39:22 +02001138 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001139}
1140
1141
Eric Snow1abcf672017-05-23 21:46:51 -07001142void
Nick Coghland6009512014-11-20 21:39:37 +10001143Py_InitializeEx(int install_sigs)
1144{
Victor Stinner331a6a52019-05-27 16:39:22 +02001145 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001146
Victor Stinner331a6a52019-05-27 16:39:22 +02001147 status = _PyRuntime_Initialize();
1148 if (_PyStatus_EXCEPTION(status)) {
1149 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001150 }
1151 _PyRuntimeState *runtime = &_PyRuntime;
1152
1153 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001154 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1155 return;
1156 }
1157
Victor Stinner331a6a52019-05-27 16:39:22 +02001158 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001159 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001160
Victor Stinner1dc6e392018-07-25 02:49:17 +02001161 config.install_signal_handlers = install_sigs;
1162
Victor Stinner331a6a52019-05-27 16:39:22 +02001163 status = Py_InitializeFromConfig(&config);
1164 if (_PyStatus_EXCEPTION(status)) {
1165 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001166 }
Nick Coghland6009512014-11-20 21:39:37 +10001167}
1168
1169void
1170Py_Initialize(void)
1171{
1172 Py_InitializeEx(1);
1173}
1174
1175
1176#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001177extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001178#endif
1179
1180/* Flush stdout and stderr */
1181
1182static int
1183file_is_closed(PyObject *fobj)
1184{
1185 int r;
1186 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1187 if (tmp == NULL) {
1188 PyErr_Clear();
1189 return 0;
1190 }
1191 r = PyObject_IsTrue(tmp);
1192 Py_DECREF(tmp);
1193 if (r < 0)
1194 PyErr_Clear();
1195 return r > 0;
1196}
1197
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001198static int
Nick Coghland6009512014-11-20 21:39:37 +10001199flush_std_files(void)
1200{
1201 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1202 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1203 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001204 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001205
1206 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001207 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001208 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001209 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001210 status = -1;
1211 }
Nick Coghland6009512014-11-20 21:39:37 +10001212 else
1213 Py_DECREF(tmp);
1214 }
1215
1216 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001217 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001218 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001219 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001220 status = -1;
1221 }
Nick Coghland6009512014-11-20 21:39:37 +10001222 else
1223 Py_DECREF(tmp);
1224 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001225
1226 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001227}
1228
1229/* Undo the effect of Py_Initialize().
1230
1231 Beware: if multiple interpreter and/or thread states exist, these
1232 are not wiped out; only the current thread and interpreter state
1233 are deleted. But since everything else is deleted, those other
1234 interpreter and thread states should no longer be used.
1235
1236 (XXX We should do better, e.g. wipe out all interpreters and
1237 threads.)
1238
1239 Locking: as above.
1240
1241*/
1242
Victor Stinner7eee5be2019-11-20 10:38:34 +01001243
1244static void
1245finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1246{
1247 if (is_main_interp) {
1248 /* Sundry finalizers */
Victor Stinner7eee5be2019-11-20 10:38:34 +01001249 _PyFrame_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001250 _PyTuple_Fini();
1251 _PyList_Fini();
1252 _PySet_Fini();
1253 _PyBytes_Fini();
Victor Stinner630c8df2019-12-17 13:02:18 +01001254 }
1255
1256 _PyLong_Fini(tstate);
1257
1258 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001259 _PyFloat_Fini();
1260 _PyDict_Fini();
1261 _PySlice_Fini();
1262 }
1263
1264 _PyWarnings_Fini(tstate->interp);
1265
1266 if (is_main_interp) {
1267 _Py_HashRandomization_Fini();
1268 _PyArg_Fini();
1269 _PyAsyncGen_Fini();
1270 _PyContext_Fini();
Victor Stinner3d483342019-11-22 12:27:50 +01001271 }
Victor Stinner7eee5be2019-11-20 10:38:34 +01001272
Victor Stinner3d483342019-11-22 12:27:50 +01001273 /* Cleanup Unicode implementation */
1274 _PyUnicode_Fini(tstate);
1275
1276 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001277 _Py_ClearFileSystemEncoding();
1278 }
1279}
1280
1281
1282static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001283finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001284{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001285 int is_main_interp = _Py_IsMainInterpreter(tstate);
1286
Victor Stinner7eee5be2019-11-20 10:38:34 +01001287 /* Clear interpreter state and all thread states */
1288 PyInterpreterState_Clear(tstate->interp);
1289
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001290 /* Trigger a GC collection on subinterpreters*/
1291 if (!is_main_interp) {
1292 _PyGC_CollectNoFail();
1293 }
1294
Victor Stinner7eee5be2019-11-20 10:38:34 +01001295 finalize_interp_types(tstate, is_main_interp);
1296
1297 if (is_main_interp) {
1298 /* XXX Still allocated:
1299 - various static ad-hoc pointers to interned strings
1300 - int and float free list blocks
1301 - whatever various modules and libraries allocate
1302 */
1303
1304 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1305
1306 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001307 }
Victor Stinner72474072019-11-20 12:25:50 +01001308
1309 _PyGC_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001310}
1311
1312
1313static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001314finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001315{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001316 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001317 /* Cleanup auto-thread-state */
1318 _PyGILState_Fini(tstate);
1319 }
1320
Victor Stinner7eee5be2019-11-20 10:38:34 +01001321 PyInterpreterState_Delete(tstate->interp);
1322}
1323
1324
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001325int
1326Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001327{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001328 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001329
Victor Stinner8e91c242019-04-24 17:24:01 +02001330 _PyRuntimeState *runtime = &_PyRuntime;
1331 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001332 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001333 }
Nick Coghland6009512014-11-20 21:39:37 +10001334
Victor Stinnere225beb2019-06-03 18:14:24 +02001335 /* Get current thread state and interpreter pointer */
1336 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1337 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001338
Victor Stinnerb45d2592019-06-20 00:05:23 +02001339 // Wrap up existing "threading"-module-created, non-daemon threads.
1340 wait_for_thread_shutdown(tstate);
1341
1342 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001343 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001344
Nick Coghland6009512014-11-20 21:39:37 +10001345 /* The interpreter is still entirely intact at this point, and the
1346 * exit funcs may be relying on that. In particular, if some thread
1347 * or exit func is still waiting to do an import, the import machinery
1348 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001349 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001350 * Note that Threading.py uses an exit func to do a join on all the
1351 * threads created thru it, so this also protects pending imports in
1352 * the threads created via Threading.
1353 */
Nick Coghland6009512014-11-20 21:39:37 +10001354
Victor Stinnerb45d2592019-06-20 00:05:23 +02001355 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001356
Victor Stinnerda273412017-12-15 01:46:02 +01001357 /* Copy the core config, PyInterpreterState_Delete() free
1358 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001359#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001360 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001361#endif
1362#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001363 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001364#endif
1365#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001366 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001367#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001368
Nick Coghland6009512014-11-20 21:39:37 +10001369 /* Remaining threads (e.g. daemon threads) will automatically exit
1370 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001371 runtime->finalizing = tstate;
1372 runtime->initialized = 0;
1373 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001374
Victor Stinnere0deff32015-03-24 13:46:18 +01001375 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001376 if (flush_std_files() < 0) {
1377 status = -1;
1378 }
Nick Coghland6009512014-11-20 21:39:37 +10001379
1380 /* Disable signal handling */
1381 PyOS_FiniInterrupts();
1382
1383 /* Collect garbage. This may call finalizers; it's nice to call these
1384 * before all modules are destroyed.
1385 * XXX If a __del__ or weakref callback is triggered here, and tries to
1386 * XXX import a module, bad things can happen, because Python no
1387 * XXX longer believes it's initialized.
1388 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1389 * XXX is easy to provoke that way. I've also seen, e.g.,
1390 * XXX Exception exceptions.ImportError: 'No module named sha'
1391 * XXX in <function callback at 0x008F5718> ignored
1392 * XXX but I'm unclear on exactly how that one happens. In any case,
1393 * XXX I haven't seen a real-life report of either of these.
1394 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001395 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001396#ifdef COUNT_ALLOCS
1397 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1398 each collection might release some types from the type
1399 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001400 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001401 /* nothing */;
1402#endif
Eric Snowdae02762017-09-14 00:35:58 -07001403
Steve Dowerb82e17e2019-05-23 08:45:22 -07001404 /* Clear all loghooks */
1405 /* We want minimal exposure of this function, so define the extern
1406 * here. The linker should discover the correct function without
1407 * exporting a symbol. */
1408 extern void _PySys_ClearAuditHooks(void);
1409 _PySys_ClearAuditHooks();
1410
Nick Coghland6009512014-11-20 21:39:37 +10001411 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001412 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001413
Inada Naoki91234a12019-06-03 21:30:58 +09001414 /* Print debug stats if any */
1415 _PyEval_Fini();
1416
Victor Stinnere0deff32015-03-24 13:46:18 +01001417 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001418 if (flush_std_files() < 0) {
1419 status = -1;
1420 }
Nick Coghland6009512014-11-20 21:39:37 +10001421
1422 /* Collect final garbage. This disposes of cycles created by
1423 * class definitions, for example.
1424 * XXX This is disabled because it caused too many problems. If
1425 * XXX a __del__ or weakref callback triggers here, Python code has
1426 * XXX a hard time running, because even the sys module has been
1427 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1428 * XXX One symptom is a sequence of information-free messages
1429 * XXX coming from threads (if a __del__ or callback is invoked,
1430 * XXX other threads can execute too, and any exception they encounter
1431 * XXX triggers a comedy of errors as subsystem after subsystem
1432 * XXX fails to find what it *expects* to find in sys to help report
1433 * XXX the exception and consequent unexpected failures). I've also
1434 * XXX seen segfaults then, after adding print statements to the
1435 * XXX Python code getting called.
1436 */
1437#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001438 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001439#endif
1440
1441 /* Disable tracemalloc after all Python objects have been destroyed,
1442 so it is possible to use tracemalloc in objects destructor. */
1443 _PyTraceMalloc_Fini();
1444
1445 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1446 _PyImport_Fini();
1447
1448 /* Cleanup typeobject.c's internal caches. */
1449 _PyType_Fini();
1450
1451 /* unload faulthandler module */
1452 _PyFaulthandler_Fini();
1453
1454 /* Debugging stuff */
1455#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001456 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001457#endif
1458 /* dump hash stats */
1459 _PyHash_Fini();
1460
Eric Snowdae02762017-09-14 00:35:58 -07001461#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001462 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001463 _PyDebug_PrintTotalRefs();
1464 }
Eric Snowdae02762017-09-14 00:35:58 -07001465#endif
Nick Coghland6009512014-11-20 21:39:37 +10001466
1467#ifdef Py_TRACE_REFS
1468 /* Display all objects still alive -- this can invoke arbitrary
1469 * __repr__ overrides, so requires a mostly-intact interpreter.
1470 * Alas, a lot of stuff may still be alive now that will be cleaned
1471 * up later.
1472 */
Victor Stinnerda273412017-12-15 01:46:02 +01001473 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001474 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001475 }
Nick Coghland6009512014-11-20 21:39:37 +10001476#endif /* Py_TRACE_REFS */
1477
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001478 finalize_interp_clear(tstate);
1479 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001480
1481#ifdef Py_TRACE_REFS
1482 /* Display addresses (& refcnts) of all objects still alive.
1483 * An address can be used to find the repr of the object, printed
1484 * above by _Py_PrintReferences.
1485 */
Victor Stinnerda273412017-12-15 01:46:02 +01001486 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001487 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001488 }
Nick Coghland6009512014-11-20 21:39:37 +10001489#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001490#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001491 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001492 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001493 }
Nick Coghland6009512014-11-20 21:39:37 +10001494#endif
1495
Victor Stinner8e91c242019-04-24 17:24:01 +02001496 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001497
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001498 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001499 return status;
1500}
1501
1502void
1503Py_Finalize(void)
1504{
1505 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001506}
1507
Victor Stinnerb0051362019-11-22 17:52:42 +01001508
Nick Coghland6009512014-11-20 21:39:37 +10001509/* Create and initialize a new interpreter and thread, and return the
1510 new thread. This requires that Py_Initialize() has been called
1511 first.
1512
1513 Unsuccessful initialization yields a NULL pointer. Note that *no*
1514 exception information is available even in this case -- the
1515 exception information is held in the thread, and there is no
1516 thread.
1517
1518 Locking: as above.
1519
1520*/
1521
Victor Stinner331a6a52019-05-27 16:39:22 +02001522static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001523new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001524{
Victor Stinner331a6a52019-05-27 16:39:22 +02001525 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001526
Victor Stinner331a6a52019-05-27 16:39:22 +02001527 status = _PyRuntime_Initialize();
1528 if (_PyStatus_EXCEPTION(status)) {
1529 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001530 }
1531 _PyRuntimeState *runtime = &_PyRuntime;
1532
1533 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001534 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001535 }
Nick Coghland6009512014-11-20 21:39:37 +10001536
Victor Stinner8a1be612016-03-14 22:07:55 +01001537 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1538 interpreters: disable PyGILState_Check(). */
1539 _PyGILState_check_enabled = 0;
1540
Victor Stinner43125222019-04-24 18:23:53 +02001541 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001542 if (interp == NULL) {
1543 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001544 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001545 }
Nick Coghland6009512014-11-20 21:39:37 +10001546
Victor Stinner43125222019-04-24 18:23:53 +02001547 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001548 if (tstate == NULL) {
1549 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001550 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001551 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001552 }
1553
Victor Stinner43125222019-04-24 18:23:53 +02001554 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001555
Eric Snow1abcf672017-05-23 21:46:51 -07001556 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001557 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001558 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001559 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001560 } else {
1561 /* No current thread state, copy from the main interpreter */
1562 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001563 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001564 }
1565
Victor Stinner331a6a52019-05-27 16:39:22 +02001566 status = _PyConfig_Copy(&interp->config, config);
1567 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001568 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001569 }
Eric Snow1abcf672017-05-23 21:46:51 -07001570
Victor Stinnerd863ade2019-12-06 03:37:07 +01001571 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001572 if (_PyStatus_EXCEPTION(status)) {
1573 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001574 }
1575
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001576 status = init_interp_main(tstate);
1577 if (_PyStatus_EXCEPTION(status)) {
1578 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001579 }
Nick Coghland6009512014-11-20 21:39:37 +10001580
Victor Stinnera7368ac2017-11-15 18:11:45 -08001581 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001582 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001583
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001584error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001585 *tstate_p = NULL;
1586
1587 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001588 PyErr_PrintEx(0);
1589 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001590 PyThreadState_Delete(tstate);
1591 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001592 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001593
Victor Stinnerb0051362019-11-22 17:52:42 +01001594 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001595}
1596
1597PyThreadState *
1598Py_NewInterpreter(void)
1599{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001600 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001601 PyStatus status = new_interpreter(&tstate);
1602 if (_PyStatus_EXCEPTION(status)) {
1603 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001604 }
1605 return tstate;
1606
Nick Coghland6009512014-11-20 21:39:37 +10001607}
1608
1609/* Delete an interpreter and its last thread. This requires that the
1610 given thread state is current, that the thread has no remaining
1611 frames, and that it is its interpreter's only remaining thread.
1612 It is a fatal error to violate these constraints.
1613
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001614 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001615 everything, regardless.)
1616
1617 Locking: as above.
1618
1619*/
1620
1621void
1622Py_EndInterpreter(PyThreadState *tstate)
1623{
1624 PyInterpreterState *interp = tstate->interp;
1625
Victor Stinnerb45d2592019-06-20 00:05:23 +02001626 if (tstate != _PyThreadState_GET()) {
Nick Coghland6009512014-11-20 21:39:37 +10001627 Py_FatalError("Py_EndInterpreter: thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001628 }
1629 if (tstate->frame != NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001630 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001631 }
Eric Snow5be45a62019-03-08 22:47:07 -07001632 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001633
Eric Snow842a2f02019-03-15 15:47:51 -06001634 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001635 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001636
Victor Stinnerb45d2592019-06-20 00:05:23 +02001637 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001638
Victor Stinnerb45d2592019-06-20 00:05:23 +02001639 if (tstate != interp->tstate_head || tstate->next != NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001640 Py_FatalError("Py_EndInterpreter: not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001641 }
Nick Coghland6009512014-11-20 21:39:37 +10001642
Victor Stinner987a0dc2019-06-19 10:36:10 +02001643 _PyImport_Cleanup(tstate);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001644 finalize_interp_clear(tstate);
1645 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001646}
1647
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001648/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001649
Victor Stinner331a6a52019-05-27 16:39:22 +02001650static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001651add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001652{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001653 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001654 m = PyImport_AddModule("__main__");
1655 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001656 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001657
Nick Coghland6009512014-11-20 21:39:37 +10001658 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001659 ann_dict = PyDict_New();
1660 if ((ann_dict == NULL) ||
1661 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001662 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001663 }
1664 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001665
Nick Coghland6009512014-11-20 21:39:37 +10001666 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1667 PyObject *bimod = PyImport_ImportModule("builtins");
1668 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001669 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001670 }
1671 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001672 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001673 }
1674 Py_DECREF(bimod);
1675 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001676
Nick Coghland6009512014-11-20 21:39:37 +10001677 /* Main is a little special - imp.is_builtin("__main__") will return
1678 * False, but BuiltinImporter is still the most appropriate initial
1679 * setting for its __loader__ attribute. A more suitable value will
1680 * be set if __main__ gets further initialized later in the startup
1681 * process.
1682 */
1683 loader = PyDict_GetItemString(d, "__loader__");
1684 if (loader == NULL || loader == Py_None) {
1685 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1686 "BuiltinImporter");
1687 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001688 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001689 }
1690 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001691 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001692 }
1693 Py_DECREF(loader);
1694 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001695 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001696}
1697
Nick Coghland6009512014-11-20 21:39:37 +10001698/* Import the site module (not into __main__ though) */
1699
Victor Stinner331a6a52019-05-27 16:39:22 +02001700static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001701init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10001702{
1703 PyObject *m;
1704 m = PyImport_ImportModule("site");
1705 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001706 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001707 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001708 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001709 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001710}
1711
Victor Stinner874dbe82015-09-04 17:29:57 +02001712/* Check if a file descriptor is valid or not.
1713 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1714static int
1715is_valid_fd(int fd)
1716{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001717/* dup() is faster than fstat(): fstat() can require input/output operations,
1718 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1719 startup. Problem: dup() doesn't check if the file descriptor is valid on
1720 some platforms.
1721
1722 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1723 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1724 EBADF. FreeBSD has similar issue (bpo-32849).
1725
1726 Only use dup() on platforms where dup() is enough to detect invalid FD in
1727 corner cases: on Linux and Windows (bpo-32849). */
1728#if defined(__linux__) || defined(MS_WINDOWS)
1729 if (fd < 0) {
1730 return 0;
1731 }
1732 int fd2;
1733
1734 _Py_BEGIN_SUPPRESS_IPH
1735 fd2 = dup(fd);
1736 if (fd2 >= 0) {
1737 close(fd2);
1738 }
1739 _Py_END_SUPPRESS_IPH
1740
1741 return (fd2 >= 0);
1742#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001743 struct stat st;
1744 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001745#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001746}
1747
1748/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001749static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001750create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001751 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001752 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001753{
1754 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1755 const char* mode;
1756 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001757 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001758 int buffering, isatty;
1759 _Py_IDENTIFIER(open);
1760 _Py_IDENTIFIER(isatty);
1761 _Py_IDENTIFIER(TextIOWrapper);
1762 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001763 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001764
Victor Stinner874dbe82015-09-04 17:29:57 +02001765 if (!is_valid_fd(fd))
1766 Py_RETURN_NONE;
1767
Nick Coghland6009512014-11-20 21:39:37 +10001768 /* stdin is always opened in buffered mode, first because it shouldn't
1769 make a difference in common use cases, second because TextIOWrapper
1770 depends on the presence of a read1() method which only exists on
1771 buffered streams.
1772 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001773 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001774 buffering = 0;
1775 else
1776 buffering = -1;
1777 if (write_mode)
1778 mode = "wb";
1779 else
1780 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001781 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10001782 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001783 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001784 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001785 if (buf == NULL)
1786 goto error;
1787
1788 if (buffering) {
1789 _Py_IDENTIFIER(raw);
1790 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1791 if (raw == NULL)
1792 goto error;
1793 }
1794 else {
1795 raw = buf;
1796 Py_INCREF(raw);
1797 }
1798
Steve Dower39294992016-08-30 21:22:36 -07001799#ifdef MS_WINDOWS
1800 /* Windows console IO is always UTF-8 encoded */
1801 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001802 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001803#endif
1804
Nick Coghland6009512014-11-20 21:39:37 +10001805 text = PyUnicode_FromString(name);
1806 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1807 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001808 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10001809 if (res == NULL)
1810 goto error;
1811 isatty = PyObject_IsTrue(res);
1812 Py_DECREF(res);
1813 if (isatty == -1)
1814 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001815 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001816 write_through = Py_True;
1817 else
1818 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01001819 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10001820 line_buffering = Py_True;
1821 else
1822 line_buffering = Py_False;
1823
1824 Py_CLEAR(raw);
1825 Py_CLEAR(text);
1826
1827#ifdef MS_WINDOWS
1828 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1829 newlines to "\n".
1830 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1831 newline = NULL;
1832#else
1833 /* sys.stdin: split lines at "\n".
1834 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1835 newline = "\n";
1836#endif
1837
Victor Stinner709d23d2019-05-02 14:56:30 -04001838 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1839 if (encoding_str == NULL) {
1840 Py_CLEAR(buf);
1841 goto error;
1842 }
1843
1844 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1845 if (errors_str == NULL) {
1846 Py_CLEAR(buf);
1847 Py_CLEAR(encoding_str);
1848 goto error;
1849 }
1850
1851 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1852 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001853 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001854 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001855 Py_CLEAR(encoding_str);
1856 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001857 if (stream == NULL)
1858 goto error;
1859
1860 if (write_mode)
1861 mode = "w";
1862 else
1863 mode = "r";
1864 text = PyUnicode_FromString(mode);
1865 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1866 goto error;
1867 Py_CLEAR(text);
1868 return stream;
1869
1870error:
1871 Py_XDECREF(buf);
1872 Py_XDECREF(stream);
1873 Py_XDECREF(text);
1874 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001875
Victor Stinner874dbe82015-09-04 17:29:57 +02001876 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1877 /* Issue #24891: the file descriptor was closed after the first
1878 is_valid_fd() check was called. Ignore the OSError and set the
1879 stream to None. */
1880 PyErr_Clear();
1881 Py_RETURN_NONE;
1882 }
1883 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001884}
1885
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001886/* Set builtins.open to io.OpenWrapper */
1887static PyStatus
1888init_set_builtins_open(PyThreadState *tstate)
1889{
1890 PyObject *iomod = NULL, *wrapper;
1891 PyObject *bimod = NULL;
1892 PyStatus res = _PyStatus_OK();
1893
1894 if (!(iomod = PyImport_ImportModule("io"))) {
1895 goto error;
1896 }
1897
1898 if (!(bimod = PyImport_ImportModule("builtins"))) {
1899 goto error;
1900 }
1901
1902 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1903 goto error;
1904 }
1905
1906 /* Set builtins.open */
1907 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1908 Py_DECREF(wrapper);
1909 goto error;
1910 }
1911 Py_DECREF(wrapper);
1912 goto done;
1913
1914error:
1915 res = _PyStatus_ERR("can't initialize io.open");
1916
1917done:
1918 Py_XDECREF(bimod);
1919 Py_XDECREF(iomod);
1920 return res;
1921}
1922
1923
Nick Coghland6009512014-11-20 21:39:37 +10001924/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001925static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001926init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10001927{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001928 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001929 PyObject *m;
1930 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001931 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001932 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001933 PyStatus res = _PyStatus_OK();
Victor Stinnerb45d2592019-06-20 00:05:23 +02001934 const PyConfig *config = &tstate->interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001935
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001936 /* Check that stdin is not a directory
1937 Using shell redirection, you can redirect stdin to a directory,
1938 crashing the Python interpreter. Catch this common mistake here
1939 and output a useful error message. Note that under MS Windows,
1940 the shell already prevents that. */
1941#ifndef MS_WINDOWS
1942 struct _Py_stat_struct sb;
1943 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1944 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001945 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001946 }
1947#endif
1948
Nick Coghland6009512014-11-20 21:39:37 +10001949 /* Hack to avoid a nasty recursion issue when Python is invoked
1950 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1951 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1952 goto error;
1953 }
1954 Py_DECREF(m);
1955
1956 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1957 goto error;
1958 }
1959 Py_DECREF(m);
1960
Nick Coghland6009512014-11-20 21:39:37 +10001961 if (!(iomod = PyImport_ImportModule("io"))) {
1962 goto error;
1963 }
Nick Coghland6009512014-11-20 21:39:37 +10001964
Nick Coghland6009512014-11-20 21:39:37 +10001965 /* Set sys.stdin */
1966 fd = fileno(stdin);
1967 /* Under some conditions stdin, stdout and stderr may not be connected
1968 * and fileno() may point to an invalid file descriptor. For example
1969 * GUI apps don't have valid standard streams by default.
1970 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001971 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001972 config->stdio_encoding,
1973 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001974 if (std == NULL)
1975 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001976 PySys_SetObject("__stdin__", std);
1977 _PySys_SetObjectId(&PyId_stdin, std);
1978 Py_DECREF(std);
1979
1980 /* Set sys.stdout */
1981 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001982 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001983 config->stdio_encoding,
1984 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001985 if (std == NULL)
1986 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001987 PySys_SetObject("__stdout__", std);
1988 _PySys_SetObjectId(&PyId_stdout, std);
1989 Py_DECREF(std);
1990
1991#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1992 /* Set sys.stderr, replaces the preliminary stderr */
1993 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001994 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001995 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001996 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001997 if (std == NULL)
1998 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001999
2000 /* Same as hack above, pre-import stderr's codec to avoid recursion
2001 when import.c tries to write to stderr in verbose mode. */
2002 encoding_attr = PyObject_GetAttrString(std, "encoding");
2003 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002004 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002005 if (std_encoding != NULL) {
2006 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2007 Py_XDECREF(codec_info);
2008 }
2009 Py_DECREF(encoding_attr);
2010 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002011 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002012
2013 if (PySys_SetObject("__stderr__", std) < 0) {
2014 Py_DECREF(std);
2015 goto error;
2016 }
2017 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2018 Py_DECREF(std);
2019 goto error;
2020 }
2021 Py_DECREF(std);
2022#endif
2023
Victor Stinnera7368ac2017-11-15 18:11:45 -08002024 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002025
Victor Stinnera7368ac2017-11-15 18:11:45 -08002026error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002027 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002028
2029done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002030 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002031 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002032 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002033}
2034
2035
Victor Stinner10dc4842015-03-24 12:01:30 +01002036static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002037_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2038 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002039{
Victor Stinner10dc4842015-03-24 12:01:30 +01002040 fputc('\n', stderr);
2041 fflush(stderr);
2042
2043 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002044 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002045}
Victor Stinner791da1c2016-03-14 16:53:12 +01002046
2047/* Print the current exception (if an exception is set) with its traceback,
2048 or display the current Python stack.
2049
2050 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2051 called on catastrophic cases.
2052
2053 Return 1 if the traceback was displayed, 0 otherwise. */
2054
2055static int
2056_Py_FatalError_PrintExc(int fd)
2057{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002058 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner791da1c2016-03-14 16:53:12 +01002059 PyObject *ferr, *res;
2060 PyObject *exception, *v, *tb;
2061 int has_tb;
2062
Victor Stinnerb45d2592019-06-20 00:05:23 +02002063 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002064 if (exception == NULL) {
2065 /* No current exception */
2066 return 0;
2067 }
2068
2069 ferr = _PySys_GetObjectId(&PyId_stderr);
2070 if (ferr == NULL || ferr == Py_None) {
2071 /* sys.stderr is not set yet or set to None,
2072 no need to try to display the exception */
2073 return 0;
2074 }
2075
Victor Stinnerb45d2592019-06-20 00:05:23 +02002076 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002077 if (tb == NULL) {
2078 tb = Py_None;
2079 Py_INCREF(tb);
2080 }
2081 PyException_SetTraceback(v, tb);
2082 if (exception == NULL) {
2083 /* PyErr_NormalizeException() failed */
2084 return 0;
2085 }
2086
2087 has_tb = (tb != Py_None);
2088 PyErr_Display(exception, v, tb);
2089 Py_XDECREF(exception);
2090 Py_XDECREF(v);
2091 Py_XDECREF(tb);
2092
2093 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002094 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002095 if (res == NULL) {
2096 _PyErr_Clear(tstate);
2097 }
2098 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002099 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002100 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002101
2102 return has_tb;
2103}
2104
Nick Coghland6009512014-11-20 21:39:37 +10002105/* Print fatal error message and abort */
2106
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002107#ifdef MS_WINDOWS
2108static void
2109fatal_output_debug(const char *msg)
2110{
2111 /* buffer of 256 bytes allocated on the stack */
2112 WCHAR buffer[256 / sizeof(WCHAR)];
2113 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2114 size_t msglen;
2115
2116 OutputDebugStringW(L"Fatal Python error: ");
2117
2118 msglen = strlen(msg);
2119 while (msglen) {
2120 size_t i;
2121
2122 if (buflen > msglen) {
2123 buflen = msglen;
2124 }
2125
2126 /* Convert the message to wchar_t. This uses a simple one-to-one
2127 conversion, assuming that the this error message actually uses
2128 ASCII only. If this ceases to be true, we will have to convert. */
2129 for (i=0; i < buflen; ++i) {
2130 buffer[i] = msg[i];
2131 }
2132 buffer[i] = L'\0';
2133 OutputDebugStringW(buffer);
2134
2135 msg += buflen;
2136 msglen -= buflen;
2137 }
2138 OutputDebugStringW(L"\n");
2139}
2140#endif
2141
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002142
2143static void
2144fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2145{
2146 fprintf(stream, "Python runtime state: ");
2147 if (runtime->finalizing) {
2148 fprintf(stream, "finalizing (tstate=%p)", runtime->finalizing);
2149 }
2150 else if (runtime->initialized) {
2151 fprintf(stream, "initialized");
2152 }
2153 else if (runtime->core_initialized) {
2154 fprintf(stream, "core initialized");
2155 }
2156 else if (runtime->preinitialized) {
2157 fprintf(stream, "preinitialized");
2158 }
2159 else if (runtime->preinitializing) {
2160 fprintf(stream, "preinitializing");
2161 }
2162 else {
2163 fprintf(stream, "unknown");
2164 }
2165 fprintf(stream, "\n");
2166 fflush(stream);
2167}
2168
2169
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002170static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002171fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002172{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002173 FILE *stream = stderr;
2174 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002175 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002176
2177 if (reentrant) {
2178 /* Py_FatalError() caused a second fatal error.
2179 Example: flush_std_files() raises a recursion error. */
2180 goto exit;
2181 }
2182 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002183
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002184 fprintf(stream, "Fatal Python error: ");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002185 if (prefix) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002186 fputs(prefix, stream);
2187 fputs(": ", stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002188 }
2189 if (msg) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002190 fputs(msg, stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002191 }
2192 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002193 fprintf(stream, "<message not set>");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002194 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002195 fputs("\n", stream);
2196 fflush(stream); /* it helps in Windows debug build */
2197
2198 _PyRuntimeState *runtime = &_PyRuntime;
2199 fatal_error_dump_runtime(stream, runtime);
2200
2201 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2202 PyInterpreterState *interp = NULL;
2203 if (tstate != NULL) {
2204 interp = tstate->interp;
2205 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002206
Victor Stinner3a228ab2018-11-01 00:26:41 +01002207 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002208 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002209
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002210 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2211 has no Python thread state.
2212
2213 tss_tstate != tstate if the current Python thread does not hold the GIL.
2214 */
2215 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2216 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002217 if (has_tstate_and_gil) {
2218 /* If an exception is set, print the exception with its traceback */
2219 if (!_Py_FatalError_PrintExc(fd)) {
2220 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002221 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002222 }
2223 }
2224 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002225 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002226 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002227
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002228 /* The main purpose of faulthandler is to display the traceback.
2229 This function already did its best to display a traceback.
2230 Disable faulthandler to prevent writing a second traceback
2231 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002232 _PyFaulthandler_Fini();
2233
Victor Stinner791da1c2016-03-14 16:53:12 +01002234 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002235 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002236 /* Flush sys.stdout and sys.stderr */
2237 flush_std_files();
2238 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002239
Nick Coghland6009512014-11-20 21:39:37 +10002240#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002241 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002242#endif /* MS_WINDOWS */
2243
2244exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002245 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002246#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002247 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002248#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002249 abort();
2250 }
2251 else {
2252 exit(status);
2253 }
2254}
2255
Victor Stinner19760862017-12-20 01:41:59 +01002256void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002257Py_FatalError(const char *msg)
2258{
2259 fatal_error(NULL, msg, -1);
2260}
2261
Victor Stinner19760862017-12-20 01:41:59 +01002262void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002263Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002264{
Victor Stinner331a6a52019-05-27 16:39:22 +02002265 if (_PyStatus_IS_EXIT(status)) {
2266 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002267 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002268 else if (_PyStatus_IS_ERROR(status)) {
2269 fatal_error(status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002270 }
2271 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002272 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002273 }
Nick Coghland6009512014-11-20 21:39:37 +10002274}
2275
2276/* Clean up and exit */
2277
Victor Stinnerd7292b52016-06-17 12:29:00 +02002278# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002279
Nick Coghland6009512014-11-20 21:39:37 +10002280/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002281void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002282{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002283 PyInterpreterState *is = _PyInterpreterState_GET_UNSAFE();
Marcel Plch776407f2017-12-20 11:17:58 +01002284
Antoine Pitroufc5db952017-12-13 02:29:07 +01002285 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002286 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2287
2288 is->pyexitfunc = func;
2289 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002290}
2291
2292static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002293call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002294{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002295 PyInterpreterState *interp = tstate->interp;
2296 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002297 return;
2298
Victor Stinnerb45d2592019-06-20 00:05:23 +02002299 (*interp->pyexitfunc)(interp->pyexitmodule);
2300 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002301}
2302
2303/* Wait until threading._shutdown completes, provided
2304 the threading module was imported in the first place.
2305 The shutdown routine will wait until all non-daemon
2306 "threading" threads have completed. */
2307static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002308wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002309{
Nick Coghland6009512014-11-20 21:39:37 +10002310 _Py_IDENTIFIER(_shutdown);
2311 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002312 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002313 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002314 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002315 PyErr_WriteUnraisable(NULL);
2316 }
2317 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002318 return;
2319 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002320 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002321 if (result == NULL) {
2322 PyErr_WriteUnraisable(threading);
2323 }
2324 else {
2325 Py_DECREF(result);
2326 }
2327 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002328}
2329
2330#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002331int Py_AtExit(void (*func)(void))
2332{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002333 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002334 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002335 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002336 return 0;
2337}
2338
2339static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002340call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002341{
Victor Stinner8e91c242019-04-24 17:24:01 +02002342 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002343 /* pop last function from the list */
2344 runtime->nexitfuncs--;
2345 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2346 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2347
2348 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002349 }
Nick Coghland6009512014-11-20 21:39:37 +10002350
2351 fflush(stdout);
2352 fflush(stderr);
2353}
2354
Victor Stinnercfc88312018-08-01 16:41:25 +02002355void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002356Py_Exit(int sts)
2357{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002358 if (Py_FinalizeEx() < 0) {
2359 sts = 120;
2360 }
Nick Coghland6009512014-11-20 21:39:37 +10002361
2362 exit(sts);
2363}
2364
Victor Stinner331a6a52019-05-27 16:39:22 +02002365static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002366init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002367{
2368#ifdef SIGPIPE
2369 PyOS_setsig(SIGPIPE, SIG_IGN);
2370#endif
2371#ifdef SIGXFZ
2372 PyOS_setsig(SIGXFZ, SIG_IGN);
2373#endif
2374#ifdef SIGXFSZ
2375 PyOS_setsig(SIGXFSZ, SIG_IGN);
2376#endif
2377 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002378 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002379 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002380 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002381 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002382}
2383
2384
2385/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2386 *
2387 * All of the code in this function must only use async-signal-safe functions,
2388 * listed at `man 7 signal` or
2389 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2390 */
2391void
2392_Py_RestoreSignals(void)
2393{
2394#ifdef SIGPIPE
2395 PyOS_setsig(SIGPIPE, SIG_DFL);
2396#endif
2397#ifdef SIGXFZ
2398 PyOS_setsig(SIGXFZ, SIG_DFL);
2399#endif
2400#ifdef SIGXFSZ
2401 PyOS_setsig(SIGXFSZ, SIG_DFL);
2402#endif
2403}
2404
2405
2406/*
2407 * The file descriptor fd is considered ``interactive'' if either
2408 * a) isatty(fd) is TRUE, or
2409 * b) the -i flag was given, and the filename associated with
2410 * the descriptor is NULL or "<stdin>" or "???".
2411 */
2412int
2413Py_FdIsInteractive(FILE *fp, const char *filename)
2414{
2415 if (isatty((int)fileno(fp)))
2416 return 1;
2417 if (!Py_InteractiveFlag)
2418 return 0;
2419 return (filename == NULL) ||
2420 (strcmp(filename, "<stdin>") == 0) ||
2421 (strcmp(filename, "???") == 0);
2422}
2423
2424
Nick Coghland6009512014-11-20 21:39:37 +10002425/* Wrappers around sigaction() or signal(). */
2426
2427PyOS_sighandler_t
2428PyOS_getsig(int sig)
2429{
2430#ifdef HAVE_SIGACTION
2431 struct sigaction context;
2432 if (sigaction(sig, NULL, &context) == -1)
2433 return SIG_ERR;
2434 return context.sa_handler;
2435#else
2436 PyOS_sighandler_t handler;
2437/* Special signal handling for the secure CRT in Visual Studio 2005 */
2438#if defined(_MSC_VER) && _MSC_VER >= 1400
2439 switch (sig) {
2440 /* Only these signals are valid */
2441 case SIGINT:
2442 case SIGILL:
2443 case SIGFPE:
2444 case SIGSEGV:
2445 case SIGTERM:
2446 case SIGBREAK:
2447 case SIGABRT:
2448 break;
2449 /* Don't call signal() with other values or it will assert */
2450 default:
2451 return SIG_ERR;
2452 }
2453#endif /* _MSC_VER && _MSC_VER >= 1400 */
2454 handler = signal(sig, SIG_IGN);
2455 if (handler != SIG_ERR)
2456 signal(sig, handler);
2457 return handler;
2458#endif
2459}
2460
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.
2465 */
2466PyOS_sighandler_t
2467PyOS_setsig(int sig, PyOS_sighandler_t handler)
2468{
2469#ifdef HAVE_SIGACTION
2470 /* Some code in Modules/signalmodule.c depends on sigaction() being
2471 * used here if HAVE_SIGACTION is defined. Fix that if this code
2472 * changes to invalidate that assumption.
2473 */
2474 struct sigaction context, ocontext;
2475 context.sa_handler = handler;
2476 sigemptyset(&context.sa_mask);
2477 context.sa_flags = 0;
2478 if (sigaction(sig, &context, &ocontext) == -1)
2479 return SIG_ERR;
2480 return ocontext.sa_handler;
2481#else
2482 PyOS_sighandler_t oldhandler;
2483 oldhandler = signal(sig, handler);
2484#ifdef HAVE_SIGINTERRUPT
2485 siginterrupt(sig, 1);
2486#endif
2487 return oldhandler;
2488#endif
2489}
2490
2491#ifdef __cplusplus
2492}
2493#endif