blob: e692d75999d6b7c625ddd174761f94f24ce9d0de [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 Stinner6d43f6f2019-01-22 21:18:05 +0100579
Victor Stinnere7e699e2019-11-20 12:08:13 +0100580 if (!_PyLong_Init()) {
581 return _PyStatus_ERR("can't init longs");
582 }
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100583 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100584
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100585 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100586 status = _PyUnicode_Init();
587 if (_PyStatus_EXCEPTION(status)) {
588 return status;
589 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100590 }
591
Victor Stinner331a6a52019-05-27 16:39:22 +0200592 status = _PyExc_Init();
593 if (_PyStatus_EXCEPTION(status)) {
594 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100595 }
596
Victor Stinnere7e699e2019-11-20 12:08:13 +0100597 if (is_main_interp) {
598 if (!_PyFloat_Init()) {
599 return _PyStatus_ERR("can't init float");
600 }
Nick Coghland6009512014-11-20 21:39:37 +1000601
Victor Stinnere7e699e2019-11-20 12:08:13 +0100602 if (_PyStructSequence_Init() < 0) {
603 return _PyStatus_ERR("can't initialize structseq");
604 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100605 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200606
Victor Stinner331a6a52019-05-27 16:39:22 +0200607 status = _PyErr_Init();
608 if (_PyStatus_EXCEPTION(status)) {
609 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200610 }
611
Victor Stinnere7e699e2019-11-20 12:08:13 +0100612 if (is_main_interp) {
613 if (!_PyContext_Init()) {
614 return _PyStatus_ERR("can't init context");
615 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100616 }
617
Victor Stinner331a6a52019-05-27 16:39:22 +0200618 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100619}
620
621
Victor Stinner331a6a52019-05-27 16:39:22 +0200622static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200623pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100624{
Victor Stinnerb45d2592019-06-20 00:05:23 +0200625 PyInterpreterState *interp = tstate->interp;
626
627 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100628 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200629 return _PyStatus_ERR("can't initialize builtins modules");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100630 }
631 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
632
633 interp->builtins = PyModule_GetDict(bimod);
634 if (interp->builtins == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200635 return _PyStatus_ERR("can't initialize builtins dict");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100636 }
637 Py_INCREF(interp->builtins);
638
Victor Stinner331a6a52019-05-27 16:39:22 +0200639 PyStatus status = _PyBuiltins_AddExceptions(bimod);
640 if (_PyStatus_EXCEPTION(status)) {
641 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100642 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200643 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100644}
645
646
Victor Stinner331a6a52019-05-27 16:39:22 +0200647static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200648pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100649{
Victor Stinnerb45d2592019-06-20 00:05:23 +0200650 const PyConfig *config = &tstate->interp->config;
651
652 PyStatus status = _PyImport_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200653 if (_PyStatus_EXCEPTION(status)) {
654 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800655 }
Nick Coghland6009512014-11-20 21:39:37 +1000656
Victor Stinnerb45d2592019-06-20 00:05:23 +0200657 status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200658 if (_PyStatus_EXCEPTION(status)) {
659 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800660 }
Nick Coghland6009512014-11-20 21:39:37 +1000661
662 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100663 if (_PyWarnings_Init() == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200664 return _PyStatus_ERR("can't initialize warnings");
Victor Stinner1f151112017-11-23 10:43:14 +0100665 }
Nick Coghland6009512014-11-20 21:39:37 +1000666
Victor Stinnerb45d2592019-06-20 00:05:23 +0200667 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200668 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200669 if (_PyStatus_EXCEPTION(status)) {
670 return status;
Victor Stinnerb1147e42018-07-21 02:06:16 +0200671 }
672 }
673
Eric Snow1abcf672017-05-23 21:46:51 -0700674 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200675 if (config->_install_importlib) {
676 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200677 if (_PyStatus_EXCEPTION(status)) {
678 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800679 }
Eric Snow1abcf672017-05-23 21:46:51 -0700680 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200681 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100682}
683
684
Victor Stinner331a6a52019-05-27 16:39:22 +0200685static PyStatus
686pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200687 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200688 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100689{
Victor Stinner331a6a52019-05-27 16:39:22 +0200690 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100691
Victor Stinner331a6a52019-05-27 16:39:22 +0200692 PyStatus status = pycore_init_runtime(runtime, config);
693 if (_PyStatus_EXCEPTION(status)) {
694 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100695 }
696
Victor Stinnerb45d2592019-06-20 00:05:23 +0200697 PyThreadState *tstate;
698 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200699 if (_PyStatus_EXCEPTION(status)) {
700 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100701 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200702 config = &tstate->interp->config;
703 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100704
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100705 status = pycore_init_types(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200706 if (_PyStatus_EXCEPTION(status)) {
707 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100708 }
709
710 PyObject *sysmod;
Victor Stinner01b1cc12019-11-20 02:27:56 +0100711 status = _PySys_Create(tstate, &sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200712 if (_PyStatus_EXCEPTION(status)) {
713 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100714 }
715
Victor Stinnerb45d2592019-06-20 00:05:23 +0200716 status = pycore_init_builtins(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200717 if (_PyStatus_EXCEPTION(status)) {
718 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100719 }
720
Victor Stinnerb45d2592019-06-20 00:05:23 +0200721 status = pycore_init_import_warnings(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200722 if (_PyStatus_EXCEPTION(status)) {
723 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100724 }
Eric Snow1abcf672017-05-23 21:46:51 -0700725
726 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200727 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200728 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700729}
730
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100731
Victor Stinner331a6a52019-05-27 16:39:22 +0200732PyStatus
733_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100734{
Victor Stinner331a6a52019-05-27 16:39:22 +0200735 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100736
Victor Stinner6d1c4672019-05-20 11:02:00 +0200737 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200738 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200739 }
740
Victor Stinner331a6a52019-05-27 16:39:22 +0200741 status = _PyRuntime_Initialize();
742 if (_PyStatus_EXCEPTION(status)) {
743 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100744 }
Victor Stinner43125222019-04-24 18:23:53 +0200745 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100746
Victor Stinnerd3b90412019-09-17 23:59:51 +0200747 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100748 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200749 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100750 }
751
Victor Stinnerd3b90412019-09-17 23:59:51 +0200752 /* Note: preinitialized remains 1 on error, it is only set to 0
753 at exit on success. */
754 runtime->preinitializing = 1;
755
Victor Stinner331a6a52019-05-27 16:39:22 +0200756 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200757
758 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
759 if (_PyStatus_EXCEPTION(status)) {
760 return status;
761 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100762
Victor Stinner331a6a52019-05-27 16:39:22 +0200763 status = _PyPreConfig_Read(&config, args);
764 if (_PyStatus_EXCEPTION(status)) {
765 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100766 }
767
Victor Stinner331a6a52019-05-27 16:39:22 +0200768 status = _PyPreConfig_Write(&config);
769 if (_PyStatus_EXCEPTION(status)) {
770 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100771 }
772
Victor Stinnerd3b90412019-09-17 23:59:51 +0200773 runtime->preinitializing = 0;
774 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200775 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100776}
777
Victor Stinner70005ac2019-05-02 15:25:34 -0400778
Victor Stinner331a6a52019-05-27 16:39:22 +0200779PyStatus
780Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100781{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100782 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400783 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100784}
785
786
Victor Stinner331a6a52019-05-27 16:39:22 +0200787PyStatus
788Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100789{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100790 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400791 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100792}
793
794
Victor Stinner331a6a52019-05-27 16:39:22 +0200795PyStatus
796Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100797{
Victor Stinner70005ac2019-05-02 15:25:34 -0400798 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100799}
800
801
Victor Stinner331a6a52019-05-27 16:39:22 +0200802PyStatus
803_Py_PreInitializeFromConfig(const PyConfig *config,
804 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100805{
Victor Stinner331a6a52019-05-27 16:39:22 +0200806 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200807
Victor Stinner331a6a52019-05-27 16:39:22 +0200808 PyStatus status = _PyRuntime_Initialize();
809 if (_PyStatus_EXCEPTION(status)) {
810 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200811 }
812 _PyRuntimeState *runtime = &_PyRuntime;
813
Victor Stinnerd3b90412019-09-17 23:59:51 +0200814 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200815 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200816 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400817 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200818
Victor Stinner331a6a52019-05-27 16:39:22 +0200819 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200820
Victor Stinner3c30a762019-10-01 10:56:37 +0200821 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200822
Victor Stinner331a6a52019-05-27 16:39:22 +0200823 if (!config->parse_argv) {
824 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200825 }
826 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200827 _PyArgv config_args = {
828 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200829 .argc = config->argv.length,
830 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200831 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200832 }
833 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200834 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200835 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100836}
837
838
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100839/* Begin interpreter initialization
840 *
841 * On return, the first thread and interpreter state have been created,
842 * but the compiler, signal handling, multithreading and
843 * multiple interpreter support, and codec infrastructure are not yet
844 * available.
845 *
846 * The import system will support builtin and frozen modules only.
847 * The only supported io is writing to sys.stderr
848 *
849 * If any operation invoked by this function fails, a fatal error is
850 * issued and the function does not return.
851 *
852 * Any code invoked from this function should *not* assume it has access
853 * to the Python C API (unless the API is explicitly listed as being
854 * safe to call without calling Py_Initialize first)
855 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200856static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200857pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200858 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200859 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200860{
Victor Stinner331a6a52019-05-27 16:39:22 +0200861 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200862
Victor Stinner331a6a52019-05-27 16:39:22 +0200863 status = _Py_PreInitializeFromConfig(src_config, NULL);
864 if (_PyStatus_EXCEPTION(status)) {
865 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200866 }
867
Victor Stinner331a6a52019-05-27 16:39:22 +0200868 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200869 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200870
Victor Stinner331a6a52019-05-27 16:39:22 +0200871 status = _PyConfig_Copy(&config, src_config);
872 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200873 goto done;
874 }
875
Victor Stinner331a6a52019-05-27 16:39:22 +0200876 status = PyConfig_Read(&config);
877 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200878 goto done;
879 }
880
881 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200882 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200883 }
884 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200885 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200886 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200887 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200888 goto done;
889 }
890
891done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200892 PyConfig_Clear(&config);
893 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200894}
895
Victor Stinner5ac27a52019-03-27 13:40:14 +0100896
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200897/* Py_Initialize() has already been called: update the main interpreter
898 configuration. Example of bpo-34008: Py_Main() called after
899 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200900static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100901_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200902{
Victor Stinnerb0051362019-11-22 17:52:42 +0100903 PyConfig *config = &tstate->interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100904
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100906 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200907 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100908 }
909
Victor Stinnerb0051362019-11-22 17:52:42 +0100910 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100911 Py_DECREF(argv);
912 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200913 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200914 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200915 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200916}
917
Victor Stinnerb0051362019-11-22 17:52:42 +0100918
919static PyStatus
920init_interp_main(PyThreadState *tstate)
921{
922 PyStatus status;
923 int is_main_interp = _Py_IsMainInterpreter(tstate);
924 PyInterpreterState *interp = tstate->interp;
925 PyConfig *config = &interp->config;
926
927 if (!config->_install_importlib) {
928 /* Special mode for freeze_importlib: run with no import system
929 *
930 * This means anything which needs support from extension modules
931 * or pure Python code in the standard library won't work.
932 */
933 if (is_main_interp) {
934 interp->runtime->initialized = 1;
935 }
936 return _PyStatus_OK();
937 }
938
939 if (is_main_interp) {
940 if (_PyTime_Init() < 0) {
941 return _PyStatus_ERR("can't initialize time");
942 }
943
944 if (_PySys_InitMain(tstate) < 0) {
945 return _PyStatus_ERR("can't finish initializing sys");
946 }
947 }
948
949 status = init_importlib_external(tstate);
950 if (_PyStatus_EXCEPTION(status)) {
951 return status;
952 }
953
954 if (is_main_interp) {
955 /* initialize the faulthandler module */
956 status = _PyFaulthandler_Init(config->faulthandler);
957 if (_PyStatus_EXCEPTION(status)) {
958 return status;
959 }
960 }
961
962 status = _PyUnicode_InitEncodings(tstate);
963 if (_PyStatus_EXCEPTION(status)) {
964 return status;
965 }
966
967 if (is_main_interp) {
968 if (config->install_signal_handlers) {
969 status = init_signals(tstate);
970 if (_PyStatus_EXCEPTION(status)) {
971 return status;
972 }
973 }
974
975 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
976 return _PyStatus_ERR("can't initialize tracemalloc");
977 }
978 }
979
980 status = init_sys_streams(tstate);
981 if (_PyStatus_EXCEPTION(status)) {
982 return status;
983 }
984
985 status = init_set_builtins_open(tstate);
986 if (_PyStatus_EXCEPTION(status)) {
987 return status;
988 }
989
990 status = add_main_module(interp);
991 if (_PyStatus_EXCEPTION(status)) {
992 return status;
993 }
994
995 if (is_main_interp) {
996 /* Initialize warnings. */
997 PyObject *warnoptions = PySys_GetObject("warnoptions");
998 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
999 {
1000 PyObject *warnings_module = PyImport_ImportModule("warnings");
1001 if (warnings_module == NULL) {
1002 fprintf(stderr, "'import warnings' failed; traceback:\n");
1003 _PyErr_Print(tstate);
1004 }
1005 Py_XDECREF(warnings_module);
1006 }
1007
1008 interp->runtime->initialized = 1;
1009 }
1010
1011 if (config->site_import) {
1012 status = init_import_site();
1013 if (_PyStatus_EXCEPTION(status)) {
1014 return status;
1015 }
1016 }
1017
1018 if (is_main_interp) {
1019#ifndef MS_WINDOWS
1020 emit_stderr_warning_for_legacy_locale(interp->runtime);
1021#endif
1022 }
1023
1024 return _PyStatus_OK();
1025}
1026
1027
Eric Snowc7ec9982017-05-23 23:00:52 -07001028/* Update interpreter state based on supplied configuration settings
1029 *
1030 * After calling this function, most of the restrictions on the interpreter
1031 * are lifted. The only remaining incomplete settings are those related
1032 * to the main module (sys.argv[0], __main__ metadata)
1033 *
1034 * Calling this when the interpreter is not initializing, is already
1035 * initialized or without a valid current thread state is a fatal error.
1036 * Other errors should be reported as normal Python exceptions with a
1037 * non-zero return code.
1038 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001039static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001040pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001041{
Victor Stinnerb0051362019-11-22 17:52:42 +01001042 PyInterpreterState *interp = tstate->interp;
1043 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001044 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001045 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001046
Victor Stinnerb0051362019-11-22 17:52:42 +01001047 if (interp->runtime->initialized) {
1048 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001049 }
1050
Victor Stinnerb0051362019-11-22 17:52:42 +01001051 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001052 if (_PyStatus_EXCEPTION(status)) {
1053 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001054 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001055 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001056}
1057
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001058
Victor Stinner331a6a52019-05-27 16:39:22 +02001059PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001060_Py_InitializeMain(void)
1061{
Victor Stinner331a6a52019-05-27 16:39:22 +02001062 PyStatus status = _PyRuntime_Initialize();
1063 if (_PyStatus_EXCEPTION(status)) {
1064 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001065 }
1066 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001067 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001068 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001069}
1070
1071
Victor Stinner331a6a52019-05-27 16:39:22 +02001072PyStatus
1073Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001074{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001075 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001076 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001077 }
1078
Victor Stinner331a6a52019-05-27 16:39:22 +02001079 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001080
Victor Stinner331a6a52019-05-27 16:39:22 +02001081 status = _PyRuntime_Initialize();
1082 if (_PyStatus_EXCEPTION(status)) {
1083 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001084 }
1085 _PyRuntimeState *runtime = &_PyRuntime;
1086
Victor Stinnerb45d2592019-06-20 00:05:23 +02001087 PyThreadState *tstate = NULL;
1088 status = pyinit_core(runtime, config, &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 Stinnerb45d2592019-06-20 00:05:23 +02001092 config = &tstate->interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001093
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001094 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001095 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001096 if (_PyStatus_EXCEPTION(status)) {
1097 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001098 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001099 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001100
Victor Stinner331a6a52019-05-27 16:39:22 +02001101 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001102}
1103
1104
Eric Snow1abcf672017-05-23 21:46:51 -07001105void
Nick Coghland6009512014-11-20 21:39:37 +10001106Py_InitializeEx(int install_sigs)
1107{
Victor Stinner331a6a52019-05-27 16:39:22 +02001108 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001109
Victor Stinner331a6a52019-05-27 16:39:22 +02001110 status = _PyRuntime_Initialize();
1111 if (_PyStatus_EXCEPTION(status)) {
1112 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001113 }
1114 _PyRuntimeState *runtime = &_PyRuntime;
1115
1116 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001117 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1118 return;
1119 }
1120
Victor Stinner331a6a52019-05-27 16:39:22 +02001121 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001122 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001123
Victor Stinner1dc6e392018-07-25 02:49:17 +02001124 config.install_signal_handlers = install_sigs;
1125
Victor Stinner331a6a52019-05-27 16:39:22 +02001126 status = Py_InitializeFromConfig(&config);
1127 if (_PyStatus_EXCEPTION(status)) {
1128 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001129 }
Nick Coghland6009512014-11-20 21:39:37 +10001130}
1131
1132void
1133Py_Initialize(void)
1134{
1135 Py_InitializeEx(1);
1136}
1137
1138
1139#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001140extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001141#endif
1142
1143/* Flush stdout and stderr */
1144
1145static int
1146file_is_closed(PyObject *fobj)
1147{
1148 int r;
1149 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1150 if (tmp == NULL) {
1151 PyErr_Clear();
1152 return 0;
1153 }
1154 r = PyObject_IsTrue(tmp);
1155 Py_DECREF(tmp);
1156 if (r < 0)
1157 PyErr_Clear();
1158 return r > 0;
1159}
1160
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001161static int
Nick Coghland6009512014-11-20 21:39:37 +10001162flush_std_files(void)
1163{
1164 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1165 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1166 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001167 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001168
1169 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001170 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001171 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001172 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001173 status = -1;
1174 }
Nick Coghland6009512014-11-20 21:39:37 +10001175 else
1176 Py_DECREF(tmp);
1177 }
1178
1179 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001180 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001181 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001182 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001183 status = -1;
1184 }
Nick Coghland6009512014-11-20 21:39:37 +10001185 else
1186 Py_DECREF(tmp);
1187 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001188
1189 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001190}
1191
1192/* Undo the effect of Py_Initialize().
1193
1194 Beware: if multiple interpreter and/or thread states exist, these
1195 are not wiped out; only the current thread and interpreter state
1196 are deleted. But since everything else is deleted, those other
1197 interpreter and thread states should no longer be used.
1198
1199 (XXX We should do better, e.g. wipe out all interpreters and
1200 threads.)
1201
1202 Locking: as above.
1203
1204*/
1205
Victor Stinner7eee5be2019-11-20 10:38:34 +01001206
1207static void
1208finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1209{
1210 if (is_main_interp) {
1211 /* Sundry finalizers */
Victor Stinner7eee5be2019-11-20 10:38:34 +01001212 _PyFrame_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001213 _PyTuple_Fini();
1214 _PyList_Fini();
1215 _PySet_Fini();
1216 _PyBytes_Fini();
1217 _PyLong_Fini();
1218 _PyFloat_Fini();
1219 _PyDict_Fini();
1220 _PySlice_Fini();
1221 }
1222
1223 _PyWarnings_Fini(tstate->interp);
1224
1225 if (is_main_interp) {
1226 _Py_HashRandomization_Fini();
1227 _PyArg_Fini();
1228 _PyAsyncGen_Fini();
1229 _PyContext_Fini();
Victor Stinner3d483342019-11-22 12:27:50 +01001230 }
Victor Stinner7eee5be2019-11-20 10:38:34 +01001231
Victor Stinner3d483342019-11-22 12:27:50 +01001232 /* Cleanup Unicode implementation */
1233 _PyUnicode_Fini(tstate);
1234
1235 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001236 _Py_ClearFileSystemEncoding();
1237 }
1238}
1239
1240
1241static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001242finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001243{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001244 int is_main_interp = _Py_IsMainInterpreter(tstate);
1245
Victor Stinner310e2d22019-11-22 10:58:00 +01001246 /* bpo-36854: Explicitly clear the codec registry
1247 and trigger a GC collection */
1248 PyInterpreterState *interp = tstate->interp;
1249 Py_CLEAR(interp->codec_search_path);
1250 Py_CLEAR(interp->codec_search_cache);
1251 Py_CLEAR(interp->codec_error_registry);
1252 _PyGC_CollectNoFail();
1253
Victor Stinner7eee5be2019-11-20 10:38:34 +01001254 /* Clear interpreter state and all thread states */
1255 PyInterpreterState_Clear(tstate->interp);
1256
1257 finalize_interp_types(tstate, is_main_interp);
1258
1259 if (is_main_interp) {
1260 /* XXX Still allocated:
1261 - various static ad-hoc pointers to interned strings
1262 - int and float free list blocks
1263 - whatever various modules and libraries allocate
1264 */
1265
1266 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1267
1268 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001269 }
Victor Stinner72474072019-11-20 12:25:50 +01001270
1271 _PyGC_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001272}
1273
1274
1275static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001276finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001277{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001278 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001279 /* Cleanup auto-thread-state */
1280 _PyGILState_Fini(tstate);
1281 }
1282
Victor Stinner7eee5be2019-11-20 10:38:34 +01001283 PyInterpreterState_Delete(tstate->interp);
1284}
1285
1286
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001287int
1288Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001289{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001290 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001291
Victor Stinner8e91c242019-04-24 17:24:01 +02001292 _PyRuntimeState *runtime = &_PyRuntime;
1293 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001294 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001295 }
Nick Coghland6009512014-11-20 21:39:37 +10001296
Victor Stinnere225beb2019-06-03 18:14:24 +02001297 /* Get current thread state and interpreter pointer */
1298 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1299 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001300
Victor Stinnerb45d2592019-06-20 00:05:23 +02001301 // Wrap up existing "threading"-module-created, non-daemon threads.
1302 wait_for_thread_shutdown(tstate);
1303
1304 // Make any remaining pending calls.
1305 _Py_FinishPendingCalls(runtime);
1306
Nick Coghland6009512014-11-20 21:39:37 +10001307 /* The interpreter is still entirely intact at this point, and the
1308 * exit funcs may be relying on that. In particular, if some thread
1309 * or exit func is still waiting to do an import, the import machinery
1310 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001311 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001312 * Note that Threading.py uses an exit func to do a join on all the
1313 * threads created thru it, so this also protects pending imports in
1314 * the threads created via Threading.
1315 */
Nick Coghland6009512014-11-20 21:39:37 +10001316
Victor Stinnerb45d2592019-06-20 00:05:23 +02001317 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001318
Victor Stinnerda273412017-12-15 01:46:02 +01001319 /* Copy the core config, PyInterpreterState_Delete() free
1320 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001321#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001322 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001323#endif
1324#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001325 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001326#endif
1327#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001328 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001329#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001330
Nick Coghland6009512014-11-20 21:39:37 +10001331 /* Remaining threads (e.g. daemon threads) will automatically exit
1332 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001333 runtime->finalizing = tstate;
1334 runtime->initialized = 0;
1335 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001336
Victor Stinnere0deff32015-03-24 13:46:18 +01001337 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001338 if (flush_std_files() < 0) {
1339 status = -1;
1340 }
Nick Coghland6009512014-11-20 21:39:37 +10001341
1342 /* Disable signal handling */
1343 PyOS_FiniInterrupts();
1344
1345 /* Collect garbage. This may call finalizers; it's nice to call these
1346 * before all modules are destroyed.
1347 * XXX If a __del__ or weakref callback is triggered here, and tries to
1348 * XXX import a module, bad things can happen, because Python no
1349 * XXX longer believes it's initialized.
1350 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1351 * XXX is easy to provoke that way. I've also seen, e.g.,
1352 * XXX Exception exceptions.ImportError: 'No module named sha'
1353 * XXX in <function callback at 0x008F5718> ignored
1354 * XXX but I'm unclear on exactly how that one happens. In any case,
1355 * XXX I haven't seen a real-life report of either of these.
1356 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001357 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001358#ifdef COUNT_ALLOCS
1359 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1360 each collection might release some types from the type
1361 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001362 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001363 /* nothing */;
1364#endif
Eric Snowdae02762017-09-14 00:35:58 -07001365
Steve Dowerb82e17e2019-05-23 08:45:22 -07001366 /* Clear all loghooks */
1367 /* We want minimal exposure of this function, so define the extern
1368 * here. The linker should discover the correct function without
1369 * exporting a symbol. */
1370 extern void _PySys_ClearAuditHooks(void);
1371 _PySys_ClearAuditHooks();
1372
Nick Coghland6009512014-11-20 21:39:37 +10001373 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001374 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001375
Inada Naoki91234a12019-06-03 21:30:58 +09001376 /* Print debug stats if any */
1377 _PyEval_Fini();
1378
Victor Stinnere0deff32015-03-24 13:46:18 +01001379 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001380 if (flush_std_files() < 0) {
1381 status = -1;
1382 }
Nick Coghland6009512014-11-20 21:39:37 +10001383
1384 /* Collect final garbage. This disposes of cycles created by
1385 * class definitions, for example.
1386 * XXX This is disabled because it caused too many problems. If
1387 * XXX a __del__ or weakref callback triggers here, Python code has
1388 * XXX a hard time running, because even the sys module has been
1389 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1390 * XXX One symptom is a sequence of information-free messages
1391 * XXX coming from threads (if a __del__ or callback is invoked,
1392 * XXX other threads can execute too, and any exception they encounter
1393 * XXX triggers a comedy of errors as subsystem after subsystem
1394 * XXX fails to find what it *expects* to find in sys to help report
1395 * XXX the exception and consequent unexpected failures). I've also
1396 * XXX seen segfaults then, after adding print statements to the
1397 * XXX Python code getting called.
1398 */
1399#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001400 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001401#endif
1402
1403 /* Disable tracemalloc after all Python objects have been destroyed,
1404 so it is possible to use tracemalloc in objects destructor. */
1405 _PyTraceMalloc_Fini();
1406
1407 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1408 _PyImport_Fini();
1409
1410 /* Cleanup typeobject.c's internal caches. */
1411 _PyType_Fini();
1412
1413 /* unload faulthandler module */
1414 _PyFaulthandler_Fini();
1415
1416 /* Debugging stuff */
1417#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001418 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001419#endif
1420 /* dump hash stats */
1421 _PyHash_Fini();
1422
Eric Snowdae02762017-09-14 00:35:58 -07001423#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001424 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001425 _PyDebug_PrintTotalRefs();
1426 }
Eric Snowdae02762017-09-14 00:35:58 -07001427#endif
Nick Coghland6009512014-11-20 21:39:37 +10001428
1429#ifdef Py_TRACE_REFS
1430 /* Display all objects still alive -- this can invoke arbitrary
1431 * __repr__ overrides, so requires a mostly-intact interpreter.
1432 * Alas, a lot of stuff may still be alive now that will be cleaned
1433 * up later.
1434 */
Victor Stinnerda273412017-12-15 01:46:02 +01001435 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001436 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001437 }
Nick Coghland6009512014-11-20 21:39:37 +10001438#endif /* Py_TRACE_REFS */
1439
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001440 finalize_interp_clear(tstate);
1441 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001442
1443#ifdef Py_TRACE_REFS
1444 /* Display addresses (& refcnts) of all objects still alive.
1445 * An address can be used to find the repr of the object, printed
1446 * above by _Py_PrintReferences.
1447 */
Victor Stinnerda273412017-12-15 01:46:02 +01001448 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001449 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001450 }
Nick Coghland6009512014-11-20 21:39:37 +10001451#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001452#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001453 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001454 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001455 }
Nick Coghland6009512014-11-20 21:39:37 +10001456#endif
1457
Victor Stinner8e91c242019-04-24 17:24:01 +02001458 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001459
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001460 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001461 return status;
1462}
1463
1464void
1465Py_Finalize(void)
1466{
1467 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001468}
1469
Victor Stinnerb0051362019-11-22 17:52:42 +01001470
Nick Coghland6009512014-11-20 21:39:37 +10001471/* Create and initialize a new interpreter and thread, and return the
1472 new thread. This requires that Py_Initialize() has been called
1473 first.
1474
1475 Unsuccessful initialization yields a NULL pointer. Note that *no*
1476 exception information is available even in this case -- the
1477 exception information is held in the thread, and there is no
1478 thread.
1479
1480 Locking: as above.
1481
1482*/
1483
Victor Stinner331a6a52019-05-27 16:39:22 +02001484static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001485new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001486{
Victor Stinner331a6a52019-05-27 16:39:22 +02001487 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001488
Victor Stinner331a6a52019-05-27 16:39:22 +02001489 status = _PyRuntime_Initialize();
1490 if (_PyStatus_EXCEPTION(status)) {
1491 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001492 }
1493 _PyRuntimeState *runtime = &_PyRuntime;
1494
1495 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001496 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001497 }
Nick Coghland6009512014-11-20 21:39:37 +10001498
Victor Stinner8a1be612016-03-14 22:07:55 +01001499 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1500 interpreters: disable PyGILState_Check(). */
1501 _PyGILState_check_enabled = 0;
1502
Victor Stinner43125222019-04-24 18:23:53 +02001503 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001504 if (interp == NULL) {
1505 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001506 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001507 }
Nick Coghland6009512014-11-20 21:39:37 +10001508
Victor Stinner43125222019-04-24 18:23:53 +02001509 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001510 if (tstate == NULL) {
1511 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001512 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001513 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001514 }
1515
Victor Stinner43125222019-04-24 18:23:53 +02001516 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001517
Eric Snow1abcf672017-05-23 21:46:51 -07001518 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001519 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001520 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001521 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001522 } else {
1523 /* No current thread state, copy from the main interpreter */
1524 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001525 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001526 }
1527
Victor Stinner331a6a52019-05-27 16:39:22 +02001528 status = _PyConfig_Copy(&interp->config, config);
1529 if (_PyStatus_EXCEPTION(status)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001530 goto done;
Victor Stinnerda273412017-12-15 01:46:02 +01001531 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001532 config = &interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001533
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001534 status = pycore_init_types(tstate);
Victor Stinneref9d9b62019-05-22 11:28:22 +02001535
Nick Coghland6009512014-11-20 21:39:37 +10001536 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001537 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001538 if (modules == NULL) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001539 status = _PyStatus_ERR("can't make modules dictionary");
1540 goto done;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001541 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001542 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001543
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001544 PyObject *sysmod = _PyImport_FindBuiltin(tstate, "sys");
Eric Snowd393c1b2017-09-14 12:18:12 -06001545 if (sysmod != NULL) {
1546 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001547 if (interp->sysdict == NULL) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001548 goto handle_exc;
Victor Stinner43125222019-04-24 18:23:53 +02001549 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001550 Py_INCREF(interp->sysdict);
1551 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001552 if (_PySys_InitMain(tstate) < 0) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001553 status = _PyStatus_ERR("can't finish initializing sys");
1554 goto done;
Victor Stinnerab672812019-01-23 15:04:40 +01001555 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001556 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001557 else if (_PyErr_Occurred(tstate)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001558 goto handle_exc;
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001559 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001560
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001561 PyObject *bimod = _PyImport_FindBuiltin(tstate, "builtins");
Nick Coghland6009512014-11-20 21:39:37 +10001562 if (bimod != NULL) {
1563 interp->builtins = PyModule_GetDict(bimod);
1564 if (interp->builtins == NULL)
Victor Stinnerb0051362019-11-22 17:52:42 +01001565 goto handle_exc;
Nick Coghland6009512014-11-20 21:39:37 +10001566 Py_INCREF(interp->builtins);
1567 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001568 else if (_PyErr_Occurred(tstate)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001569 goto handle_exc;
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001570 }
Nick Coghland6009512014-11-20 21:39:37 +10001571
Nick Coghland6009512014-11-20 21:39:37 +10001572 if (bimod != NULL && sysmod != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001573 status = _PyBuiltins_AddExceptions(bimod);
1574 if (_PyStatus_EXCEPTION(status)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001575 goto done;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001576 }
Nick Coghland6009512014-11-20 21:39:37 +10001577
Victor Stinner331a6a52019-05-27 16:39:22 +02001578 status = _PySys_SetPreliminaryStderr(interp->sysdict);
1579 if (_PyStatus_EXCEPTION(status)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001580 goto done;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001581 }
Nick Coghland6009512014-11-20 21:39:37 +10001582
Victor Stinnerb45d2592019-06-20 00:05:23 +02001583 status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001584 if (_PyStatus_EXCEPTION(status)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001585 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001586 }
Nick Coghland6009512014-11-20 21:39:37 +10001587
Victor Stinnerb45d2592019-06-20 00:05:23 +02001588 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +02001589 if (_PyStatus_EXCEPTION(status)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001590 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001591 }
Nick Coghland6009512014-11-20 21:39:37 +10001592
Victor Stinnerb0051362019-11-22 17:52:42 +01001593 status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001594 if (_PyStatus_EXCEPTION(status)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001595 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001596 }
Nick Coghland6009512014-11-20 21:39:37 +10001597 }
1598
Victor Stinnerb45d2592019-06-20 00:05:23 +02001599 if (_PyErr_Occurred(tstate)) {
Victor Stinnerb0051362019-11-22 17:52:42 +01001600 goto handle_exc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001601 }
Nick Coghland6009512014-11-20 21:39:37 +10001602
Victor Stinnera7368ac2017-11-15 18:11:45 -08001603 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001604 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001605
Victor Stinnerb0051362019-11-22 17:52:42 +01001606handle_exc:
1607 status = _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001608
Victor Stinnerb0051362019-11-22 17:52:42 +01001609done:
1610 *tstate_p = NULL;
1611
1612 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001613 PyErr_PrintEx(0);
1614 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001615 PyThreadState_Delete(tstate);
1616 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001617 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001618
Victor Stinnerb0051362019-11-22 17:52:42 +01001619 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001620}
1621
1622PyThreadState *
1623Py_NewInterpreter(void)
1624{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001625 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001626 PyStatus status = new_interpreter(&tstate);
1627 if (_PyStatus_EXCEPTION(status)) {
1628 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001629 }
1630 return tstate;
1631
Nick Coghland6009512014-11-20 21:39:37 +10001632}
1633
1634/* Delete an interpreter and its last thread. This requires that the
1635 given thread state is current, that the thread has no remaining
1636 frames, and that it is its interpreter's only remaining thread.
1637 It is a fatal error to violate these constraints.
1638
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001639 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001640 everything, regardless.)
1641
1642 Locking: as above.
1643
1644*/
1645
1646void
1647Py_EndInterpreter(PyThreadState *tstate)
1648{
1649 PyInterpreterState *interp = tstate->interp;
1650
Victor Stinnerb45d2592019-06-20 00:05:23 +02001651 if (tstate != _PyThreadState_GET()) {
Nick Coghland6009512014-11-20 21:39:37 +10001652 Py_FatalError("Py_EndInterpreter: thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001653 }
1654 if (tstate->frame != NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001655 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001656 }
Eric Snow5be45a62019-03-08 22:47:07 -07001657 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001658
Eric Snow842a2f02019-03-15 15:47:51 -06001659 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001660 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001661
Victor Stinnerb45d2592019-06-20 00:05:23 +02001662 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001663
Victor Stinnerb45d2592019-06-20 00:05:23 +02001664 if (tstate != interp->tstate_head || tstate->next != NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001665 Py_FatalError("Py_EndInterpreter: not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001666 }
Nick Coghland6009512014-11-20 21:39:37 +10001667
Victor Stinner987a0dc2019-06-19 10:36:10 +02001668 _PyImport_Cleanup(tstate);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001669 finalize_interp_clear(tstate);
1670 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001671}
1672
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001673/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001674
Victor Stinner331a6a52019-05-27 16:39:22 +02001675static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001676add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001677{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001678 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001679 m = PyImport_AddModule("__main__");
1680 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001681 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001682
Nick Coghland6009512014-11-20 21:39:37 +10001683 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001684 ann_dict = PyDict_New();
1685 if ((ann_dict == NULL) ||
1686 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001687 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001688 }
1689 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001690
Nick Coghland6009512014-11-20 21:39:37 +10001691 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1692 PyObject *bimod = PyImport_ImportModule("builtins");
1693 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001694 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001695 }
1696 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001697 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001698 }
1699 Py_DECREF(bimod);
1700 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001701
Nick Coghland6009512014-11-20 21:39:37 +10001702 /* Main is a little special - imp.is_builtin("__main__") will return
1703 * False, but BuiltinImporter is still the most appropriate initial
1704 * setting for its __loader__ attribute. A more suitable value will
1705 * be set if __main__ gets further initialized later in the startup
1706 * process.
1707 */
1708 loader = PyDict_GetItemString(d, "__loader__");
1709 if (loader == NULL || loader == Py_None) {
1710 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1711 "BuiltinImporter");
1712 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001713 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001714 }
1715 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001716 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001717 }
1718 Py_DECREF(loader);
1719 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001720 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001721}
1722
Nick Coghland6009512014-11-20 21:39:37 +10001723/* Import the site module (not into __main__ though) */
1724
Victor Stinner331a6a52019-05-27 16:39:22 +02001725static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001726init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10001727{
1728 PyObject *m;
1729 m = PyImport_ImportModule("site");
1730 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001731 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001732 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001733 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001734 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001735}
1736
Victor Stinner874dbe82015-09-04 17:29:57 +02001737/* Check if a file descriptor is valid or not.
1738 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1739static int
1740is_valid_fd(int fd)
1741{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001742/* dup() is faster than fstat(): fstat() can require input/output operations,
1743 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1744 startup. Problem: dup() doesn't check if the file descriptor is valid on
1745 some platforms.
1746
1747 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1748 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1749 EBADF. FreeBSD has similar issue (bpo-32849).
1750
1751 Only use dup() on platforms where dup() is enough to detect invalid FD in
1752 corner cases: on Linux and Windows (bpo-32849). */
1753#if defined(__linux__) || defined(MS_WINDOWS)
1754 if (fd < 0) {
1755 return 0;
1756 }
1757 int fd2;
1758
1759 _Py_BEGIN_SUPPRESS_IPH
1760 fd2 = dup(fd);
1761 if (fd2 >= 0) {
1762 close(fd2);
1763 }
1764 _Py_END_SUPPRESS_IPH
1765
1766 return (fd2 >= 0);
1767#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001768 struct stat st;
1769 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001770#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001771}
1772
1773/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001774static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001775create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001776 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001777 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001778{
1779 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1780 const char* mode;
1781 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001782 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001783 int buffering, isatty;
1784 _Py_IDENTIFIER(open);
1785 _Py_IDENTIFIER(isatty);
1786 _Py_IDENTIFIER(TextIOWrapper);
1787 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001788 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001789
Victor Stinner874dbe82015-09-04 17:29:57 +02001790 if (!is_valid_fd(fd))
1791 Py_RETURN_NONE;
1792
Nick Coghland6009512014-11-20 21:39:37 +10001793 /* stdin is always opened in buffered mode, first because it shouldn't
1794 make a difference in common use cases, second because TextIOWrapper
1795 depends on the presence of a read1() method which only exists on
1796 buffered streams.
1797 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001798 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001799 buffering = 0;
1800 else
1801 buffering = -1;
1802 if (write_mode)
1803 mode = "wb";
1804 else
1805 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001806 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10001807 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001808 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001809 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001810 if (buf == NULL)
1811 goto error;
1812
1813 if (buffering) {
1814 _Py_IDENTIFIER(raw);
1815 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1816 if (raw == NULL)
1817 goto error;
1818 }
1819 else {
1820 raw = buf;
1821 Py_INCREF(raw);
1822 }
1823
Steve Dower39294992016-08-30 21:22:36 -07001824#ifdef MS_WINDOWS
1825 /* Windows console IO is always UTF-8 encoded */
1826 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001827 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001828#endif
1829
Nick Coghland6009512014-11-20 21:39:37 +10001830 text = PyUnicode_FromString(name);
1831 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1832 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001833 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10001834 if (res == NULL)
1835 goto error;
1836 isatty = PyObject_IsTrue(res);
1837 Py_DECREF(res);
1838 if (isatty == -1)
1839 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001840 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001841 write_through = Py_True;
1842 else
1843 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001844 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001845 line_buffering = Py_True;
1846 else
1847 line_buffering = Py_False;
1848
1849 Py_CLEAR(raw);
1850 Py_CLEAR(text);
1851
1852#ifdef MS_WINDOWS
1853 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1854 newlines to "\n".
1855 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1856 newline = NULL;
1857#else
1858 /* sys.stdin: split lines at "\n".
1859 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1860 newline = "\n";
1861#endif
1862
Victor Stinner709d23d2019-05-02 14:56:30 -04001863 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1864 if (encoding_str == NULL) {
1865 Py_CLEAR(buf);
1866 goto error;
1867 }
1868
1869 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1870 if (errors_str == NULL) {
1871 Py_CLEAR(buf);
1872 Py_CLEAR(encoding_str);
1873 goto error;
1874 }
1875
1876 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1877 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001878 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001879 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001880 Py_CLEAR(encoding_str);
1881 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001882 if (stream == NULL)
1883 goto error;
1884
1885 if (write_mode)
1886 mode = "w";
1887 else
1888 mode = "r";
1889 text = PyUnicode_FromString(mode);
1890 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1891 goto error;
1892 Py_CLEAR(text);
1893 return stream;
1894
1895error:
1896 Py_XDECREF(buf);
1897 Py_XDECREF(stream);
1898 Py_XDECREF(text);
1899 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001900
Victor Stinner874dbe82015-09-04 17:29:57 +02001901 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1902 /* Issue #24891: the file descriptor was closed after the first
1903 is_valid_fd() check was called. Ignore the OSError and set the
1904 stream to None. */
1905 PyErr_Clear();
1906 Py_RETURN_NONE;
1907 }
1908 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001909}
1910
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001911/* Set builtins.open to io.OpenWrapper */
1912static PyStatus
1913init_set_builtins_open(PyThreadState *tstate)
1914{
1915 PyObject *iomod = NULL, *wrapper;
1916 PyObject *bimod = NULL;
1917 PyStatus res = _PyStatus_OK();
1918
1919 if (!(iomod = PyImport_ImportModule("io"))) {
1920 goto error;
1921 }
1922
1923 if (!(bimod = PyImport_ImportModule("builtins"))) {
1924 goto error;
1925 }
1926
1927 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1928 goto error;
1929 }
1930
1931 /* Set builtins.open */
1932 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1933 Py_DECREF(wrapper);
1934 goto error;
1935 }
1936 Py_DECREF(wrapper);
1937 goto done;
1938
1939error:
1940 res = _PyStatus_ERR("can't initialize io.open");
1941
1942done:
1943 Py_XDECREF(bimod);
1944 Py_XDECREF(iomod);
1945 return res;
1946}
1947
1948
Nick Coghland6009512014-11-20 21:39:37 +10001949/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001950static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001951init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10001952{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001953 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001954 PyObject *m;
1955 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001956 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001957 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001958 PyStatus res = _PyStatus_OK();
Victor Stinnerb45d2592019-06-20 00:05:23 +02001959 const PyConfig *config = &tstate->interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001960
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001961 /* Check that stdin is not a directory
1962 Using shell redirection, you can redirect stdin to a directory,
1963 crashing the Python interpreter. Catch this common mistake here
1964 and output a useful error message. Note that under MS Windows,
1965 the shell already prevents that. */
1966#ifndef MS_WINDOWS
1967 struct _Py_stat_struct sb;
1968 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1969 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001970 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001971 }
1972#endif
1973
Nick Coghland6009512014-11-20 21:39:37 +10001974 /* Hack to avoid a nasty recursion issue when Python is invoked
1975 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1976 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1977 goto error;
1978 }
1979 Py_DECREF(m);
1980
1981 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1982 goto error;
1983 }
1984 Py_DECREF(m);
1985
Nick Coghland6009512014-11-20 21:39:37 +10001986 if (!(iomod = PyImport_ImportModule("io"))) {
1987 goto error;
1988 }
Nick Coghland6009512014-11-20 21:39:37 +10001989
Nick Coghland6009512014-11-20 21:39:37 +10001990 /* Set sys.stdin */
1991 fd = fileno(stdin);
1992 /* Under some conditions stdin, stdout and stderr may not be connected
1993 * and fileno() may point to an invalid file descriptor. For example
1994 * GUI apps don't have valid standard streams by default.
1995 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001996 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001997 config->stdio_encoding,
1998 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001999 if (std == NULL)
2000 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002001 PySys_SetObject("__stdin__", std);
2002 _PySys_SetObjectId(&PyId_stdin, std);
2003 Py_DECREF(std);
2004
2005 /* Set sys.stdout */
2006 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002007 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002008 config->stdio_encoding,
2009 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02002010 if (std == NULL)
2011 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002012 PySys_SetObject("__stdout__", std);
2013 _PySys_SetObjectId(&PyId_stdout, std);
2014 Py_DECREF(std);
2015
2016#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
2017 /* Set sys.stderr, replaces the preliminary stderr */
2018 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002019 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02002020 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04002021 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02002022 if (std == NULL)
2023 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10002024
2025 /* Same as hack above, pre-import stderr's codec to avoid recursion
2026 when import.c tries to write to stderr in verbose mode. */
2027 encoding_attr = PyObject_GetAttrString(std, "encoding");
2028 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002029 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10002030 if (std_encoding != NULL) {
2031 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2032 Py_XDECREF(codec_info);
2033 }
2034 Py_DECREF(encoding_attr);
2035 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002036 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002037
2038 if (PySys_SetObject("__stderr__", std) < 0) {
2039 Py_DECREF(std);
2040 goto error;
2041 }
2042 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2043 Py_DECREF(std);
2044 goto error;
2045 }
2046 Py_DECREF(std);
2047#endif
2048
Victor Stinnera7368ac2017-11-15 18:11:45 -08002049 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002050
Victor Stinnera7368ac2017-11-15 18:11:45 -08002051error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002052 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002053
2054done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002055 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002056 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002057 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002058}
2059
2060
Victor Stinner10dc4842015-03-24 12:01:30 +01002061static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002062_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2063 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002064{
Victor Stinner10dc4842015-03-24 12:01:30 +01002065 fputc('\n', stderr);
2066 fflush(stderr);
2067
2068 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002069 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002070}
Victor Stinner791da1c2016-03-14 16:53:12 +01002071
2072/* Print the current exception (if an exception is set) with its traceback,
2073 or display the current Python stack.
2074
2075 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2076 called on catastrophic cases.
2077
2078 Return 1 if the traceback was displayed, 0 otherwise. */
2079
2080static int
2081_Py_FatalError_PrintExc(int fd)
2082{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002083 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner791da1c2016-03-14 16:53:12 +01002084 PyObject *ferr, *res;
2085 PyObject *exception, *v, *tb;
2086 int has_tb;
2087
Victor Stinnerb45d2592019-06-20 00:05:23 +02002088 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002089 if (exception == NULL) {
2090 /* No current exception */
2091 return 0;
2092 }
2093
2094 ferr = _PySys_GetObjectId(&PyId_stderr);
2095 if (ferr == NULL || ferr == Py_None) {
2096 /* sys.stderr is not set yet or set to None,
2097 no need to try to display the exception */
2098 return 0;
2099 }
2100
Victor Stinnerb45d2592019-06-20 00:05:23 +02002101 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002102 if (tb == NULL) {
2103 tb = Py_None;
2104 Py_INCREF(tb);
2105 }
2106 PyException_SetTraceback(v, tb);
2107 if (exception == NULL) {
2108 /* PyErr_NormalizeException() failed */
2109 return 0;
2110 }
2111
2112 has_tb = (tb != Py_None);
2113 PyErr_Display(exception, v, tb);
2114 Py_XDECREF(exception);
2115 Py_XDECREF(v);
2116 Py_XDECREF(tb);
2117
2118 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002119 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002120 if (res == NULL) {
2121 _PyErr_Clear(tstate);
2122 }
2123 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002124 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002125 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002126
2127 return has_tb;
2128}
2129
Nick Coghland6009512014-11-20 21:39:37 +10002130/* Print fatal error message and abort */
2131
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002132#ifdef MS_WINDOWS
2133static void
2134fatal_output_debug(const char *msg)
2135{
2136 /* buffer of 256 bytes allocated on the stack */
2137 WCHAR buffer[256 / sizeof(WCHAR)];
2138 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2139 size_t msglen;
2140
2141 OutputDebugStringW(L"Fatal Python error: ");
2142
2143 msglen = strlen(msg);
2144 while (msglen) {
2145 size_t i;
2146
2147 if (buflen > msglen) {
2148 buflen = msglen;
2149 }
2150
2151 /* Convert the message to wchar_t. This uses a simple one-to-one
2152 conversion, assuming that the this error message actually uses
2153 ASCII only. If this ceases to be true, we will have to convert. */
2154 for (i=0; i < buflen; ++i) {
2155 buffer[i] = msg[i];
2156 }
2157 buffer[i] = L'\0';
2158 OutputDebugStringW(buffer);
2159
2160 msg += buflen;
2161 msglen -= buflen;
2162 }
2163 OutputDebugStringW(L"\n");
2164}
2165#endif
2166
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002167
2168static void
2169fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2170{
2171 fprintf(stream, "Python runtime state: ");
2172 if (runtime->finalizing) {
2173 fprintf(stream, "finalizing (tstate=%p)", runtime->finalizing);
2174 }
2175 else if (runtime->initialized) {
2176 fprintf(stream, "initialized");
2177 }
2178 else if (runtime->core_initialized) {
2179 fprintf(stream, "core initialized");
2180 }
2181 else if (runtime->preinitialized) {
2182 fprintf(stream, "preinitialized");
2183 }
2184 else if (runtime->preinitializing) {
2185 fprintf(stream, "preinitializing");
2186 }
2187 else {
2188 fprintf(stream, "unknown");
2189 }
2190 fprintf(stream, "\n");
2191 fflush(stream);
2192}
2193
2194
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002195static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002196fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002197{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002198 FILE *stream = stderr;
2199 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002200 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002201
2202 if (reentrant) {
2203 /* Py_FatalError() caused a second fatal error.
2204 Example: flush_std_files() raises a recursion error. */
2205 goto exit;
2206 }
2207 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002208
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002209 fprintf(stream, "Fatal Python error: ");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002210 if (prefix) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002211 fputs(prefix, stream);
2212 fputs(": ", stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002213 }
2214 if (msg) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002215 fputs(msg, stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002216 }
2217 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002218 fprintf(stream, "<message not set>");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002219 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002220 fputs("\n", stream);
2221 fflush(stream); /* it helps in Windows debug build */
2222
2223 _PyRuntimeState *runtime = &_PyRuntime;
2224 fatal_error_dump_runtime(stream, runtime);
2225
2226 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2227 PyInterpreterState *interp = NULL;
2228 if (tstate != NULL) {
2229 interp = tstate->interp;
2230 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002231
Victor Stinner3a228ab2018-11-01 00:26:41 +01002232 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002233 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002234
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002235 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2236 has no Python thread state.
2237
2238 tss_tstate != tstate if the current Python thread does not hold the GIL.
2239 */
2240 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2241 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002242 if (has_tstate_and_gil) {
2243 /* If an exception is set, print the exception with its traceback */
2244 if (!_Py_FatalError_PrintExc(fd)) {
2245 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002246 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002247 }
2248 }
2249 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002250 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002251 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002252
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002253 /* The main purpose of faulthandler is to display the traceback.
2254 This function already did its best to display a traceback.
2255 Disable faulthandler to prevent writing a second traceback
2256 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002257 _PyFaulthandler_Fini();
2258
Victor Stinner791da1c2016-03-14 16:53:12 +01002259 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002260 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002261 /* Flush sys.stdout and sys.stderr */
2262 flush_std_files();
2263 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002264
Nick Coghland6009512014-11-20 21:39:37 +10002265#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002266 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002267#endif /* MS_WINDOWS */
2268
2269exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002270 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002271#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002272 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002273#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002274 abort();
2275 }
2276 else {
2277 exit(status);
2278 }
2279}
2280
Victor Stinner19760862017-12-20 01:41:59 +01002281void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002282Py_FatalError(const char *msg)
2283{
2284 fatal_error(NULL, msg, -1);
2285}
2286
Victor Stinner19760862017-12-20 01:41:59 +01002287void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002288Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002289{
Victor Stinner331a6a52019-05-27 16:39:22 +02002290 if (_PyStatus_IS_EXIT(status)) {
2291 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002292 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002293 else if (_PyStatus_IS_ERROR(status)) {
2294 fatal_error(status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002295 }
2296 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002297 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002298 }
Nick Coghland6009512014-11-20 21:39:37 +10002299}
2300
2301/* Clean up and exit */
2302
Victor Stinnerd7292b52016-06-17 12:29:00 +02002303# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002304
Nick Coghland6009512014-11-20 21:39:37 +10002305/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002306void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002307{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002308 PyInterpreterState *is = _PyInterpreterState_GET_UNSAFE();
Marcel Plch776407f2017-12-20 11:17:58 +01002309
Antoine Pitroufc5db952017-12-13 02:29:07 +01002310 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002311 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2312
2313 is->pyexitfunc = func;
2314 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002315}
2316
2317static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002318call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002319{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002320 PyInterpreterState *interp = tstate->interp;
2321 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002322 return;
2323
Victor Stinnerb45d2592019-06-20 00:05:23 +02002324 (*interp->pyexitfunc)(interp->pyexitmodule);
2325 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002326}
2327
2328/* Wait until threading._shutdown completes, provided
2329 the threading module was imported in the first place.
2330 The shutdown routine will wait until all non-daemon
2331 "threading" threads have completed. */
2332static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002333wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002334{
Nick Coghland6009512014-11-20 21:39:37 +10002335 _Py_IDENTIFIER(_shutdown);
2336 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002337 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002338 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002339 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002340 PyErr_WriteUnraisable(NULL);
2341 }
2342 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002343 return;
2344 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002345 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002346 if (result == NULL) {
2347 PyErr_WriteUnraisable(threading);
2348 }
2349 else {
2350 Py_DECREF(result);
2351 }
2352 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002353}
2354
2355#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002356int Py_AtExit(void (*func)(void))
2357{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002358 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002359 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002360 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002361 return 0;
2362}
2363
2364static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002365call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002366{
Victor Stinner8e91c242019-04-24 17:24:01 +02002367 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002368 /* pop last function from the list */
2369 runtime->nexitfuncs--;
2370 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2371 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2372
2373 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002374 }
Nick Coghland6009512014-11-20 21:39:37 +10002375
2376 fflush(stdout);
2377 fflush(stderr);
2378}
2379
Victor Stinnercfc88312018-08-01 16:41:25 +02002380void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002381Py_Exit(int sts)
2382{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002383 if (Py_FinalizeEx() < 0) {
2384 sts = 120;
2385 }
Nick Coghland6009512014-11-20 21:39:37 +10002386
2387 exit(sts);
2388}
2389
Victor Stinner331a6a52019-05-27 16:39:22 +02002390static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002391init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002392{
2393#ifdef SIGPIPE
2394 PyOS_setsig(SIGPIPE, SIG_IGN);
2395#endif
2396#ifdef SIGXFZ
2397 PyOS_setsig(SIGXFZ, SIG_IGN);
2398#endif
2399#ifdef SIGXFSZ
2400 PyOS_setsig(SIGXFSZ, SIG_IGN);
2401#endif
2402 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002403 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002404 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002405 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002406 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002407}
2408
2409
2410/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2411 *
2412 * All of the code in this function must only use async-signal-safe functions,
2413 * listed at `man 7 signal` or
2414 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2415 */
2416void
2417_Py_RestoreSignals(void)
2418{
2419#ifdef SIGPIPE
2420 PyOS_setsig(SIGPIPE, SIG_DFL);
2421#endif
2422#ifdef SIGXFZ
2423 PyOS_setsig(SIGXFZ, SIG_DFL);
2424#endif
2425#ifdef SIGXFSZ
2426 PyOS_setsig(SIGXFSZ, SIG_DFL);
2427#endif
2428}
2429
2430
2431/*
2432 * The file descriptor fd is considered ``interactive'' if either
2433 * a) isatty(fd) is TRUE, or
2434 * b) the -i flag was given, and the filename associated with
2435 * the descriptor is NULL or "<stdin>" or "???".
2436 */
2437int
2438Py_FdIsInteractive(FILE *fp, const char *filename)
2439{
2440 if (isatty((int)fileno(fp)))
2441 return 1;
2442 if (!Py_InteractiveFlag)
2443 return 0;
2444 return (filename == NULL) ||
2445 (strcmp(filename, "<stdin>") == 0) ||
2446 (strcmp(filename, "???") == 0);
2447}
2448
2449
Nick Coghland6009512014-11-20 21:39:37 +10002450/* Wrappers around sigaction() or signal(). */
2451
2452PyOS_sighandler_t
2453PyOS_getsig(int sig)
2454{
2455#ifdef HAVE_SIGACTION
2456 struct sigaction context;
2457 if (sigaction(sig, NULL, &context) == -1)
2458 return SIG_ERR;
2459 return context.sa_handler;
2460#else
2461 PyOS_sighandler_t handler;
2462/* Special signal handling for the secure CRT in Visual Studio 2005 */
2463#if defined(_MSC_VER) && _MSC_VER >= 1400
2464 switch (sig) {
2465 /* Only these signals are valid */
2466 case SIGINT:
2467 case SIGILL:
2468 case SIGFPE:
2469 case SIGSEGV:
2470 case SIGTERM:
2471 case SIGBREAK:
2472 case SIGABRT:
2473 break;
2474 /* Don't call signal() with other values or it will assert */
2475 default:
2476 return SIG_ERR;
2477 }
2478#endif /* _MSC_VER && _MSC_VER >= 1400 */
2479 handler = signal(sig, SIG_IGN);
2480 if (handler != SIG_ERR)
2481 signal(sig, handler);
2482 return handler;
2483#endif
2484}
2485
2486/*
2487 * All of the code in this function must only use async-signal-safe functions,
2488 * listed at `man 7 signal` or
2489 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2490 */
2491PyOS_sighandler_t
2492PyOS_setsig(int sig, PyOS_sighandler_t handler)
2493{
2494#ifdef HAVE_SIGACTION
2495 /* Some code in Modules/signalmodule.c depends on sigaction() being
2496 * used here if HAVE_SIGACTION is defined. Fix that if this code
2497 * changes to invalidate that assumption.
2498 */
2499 struct sigaction context, ocontext;
2500 context.sa_handler = handler;
2501 sigemptyset(&context.sa_mask);
2502 context.sa_flags = 0;
2503 if (sigaction(sig, &context, &ocontext) == -1)
2504 return SIG_ERR;
2505 return ocontext.sa_handler;
2506#else
2507 PyOS_sighandler_t oldhandler;
2508 oldhandler = signal(sig, handler);
2509#ifdef HAVE_SIGINTERRUPT
2510 siginterrupt(sig, 1);
2511#endif
2512 return oldhandler;
2513#endif
2514}
2515
2516#ifdef __cplusplus
2517}
2518#endif