blob: 5c50d4d290f4dbf3fb2beaaae73385a3c259d1e2 [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 Stinner4f98f462020-04-15 04:01:58 +02007
8#include "pycore_ceval.h" // _PyEval_FiniGIL()
9#include "pycore_context.h" // _PyContext_Init()
10#include "pycore_fileutils.h" // _Py_ResetForceASCII()
Victor Stinnere5014be2020-04-14 17:52:15 +020011#include "pycore_import.h" // _PyImport_Cleanup()
Victor Stinner4f98f462020-04-15 04:01:58 +020012#include "pycore_initconfig.h" // _PyStatus_OK()
13#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
14#include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
15#include "pycore_pyerrors.h" // _PyErr_Occurred()
16#include "pycore_pylifecycle.h" // _PyErr_Print()
Victor Stinnere5014be2020-04-14 17:52:15 +020017#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020018#include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
19#include "pycore_traceback.h" // _Py_DumpTracebackThreads()
20
21#include "grammar.h" // PyGrammar_RemoveAccelerators()
22#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100023
24#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020025# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100026#endif
27
28#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020029# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100030#endif
31
32#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020033# undef BYTE
34# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
Victor Stinner4f98f462020-04-15 04:01:58 +020036 extern PyTypeObject PyWindowsConsoleIO_Type;
37# define PyWindowsConsoleIO_Check(op) \
38 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100039#endif
40
Victor Stinner4f98f462020-04-15 04:01:58 +020041
Nick Coghland6009512014-11-20 21:39:37 +100042_Py_IDENTIFIER(flush);
43_Py_IDENTIFIER(name);
44_Py_IDENTIFIER(stdin);
45_Py_IDENTIFIER(stdout);
46_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060047_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100048
49#ifdef __cplusplus
50extern "C" {
51#endif
52
Nick Coghland6009512014-11-20 21:39:37 +100053extern grammar _PyParser_Grammar; /* From graminit.c */
54
Victor Stinnerb45d2592019-06-20 00:05:23 +020055/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020056static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020057static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050058static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020059static PyStatus init_sys_streams(PyThreadState *tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +020060static void call_py_exitfuncs(PyThreadState *tstate);
61static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020062static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100063
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080064int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080065_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010066static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067
Victor Stinner331a6a52019-05-27 16:39:22 +020068PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060069_PyRuntime_Initialize(void)
70{
71 /* XXX We only initialize once in the process, which aligns with
72 the static initialization of the former globals now found in
73 _PyRuntime. However, _PyRuntime *should* be initialized with
74 every Py_Initialize() call, but doing so breaks the runtime.
75 This is because the runtime state is not properly finalized
76 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010077 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020078 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010080 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081
82 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083}
84
85void
86_PyRuntime_Finalize(void)
87{
88 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010089 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090}
91
92int
93_Py_IsFinalizing(void)
94{
Victor Stinner7b3c2522020-03-07 00:24:23 +010095 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
Nick Coghland6009512014-11-20 21:39:37 +100098/* Hack to force loading of object files */
99int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
100 PyOS_mystrnicmp; /* Python/pystrcmp.o */
101
102/* PyModule_GetWarningsModule is no longer necessary as of 2.6
103since _warnings is builtin. This API should not be used. */
104PyObject *
105PyModule_GetWarningsModule(void)
106{
107 return PyImport_ImportModule("warnings");
108}
109
Eric Snowc7ec9982017-05-23 23:00:52 -0700110
Eric Snow1abcf672017-05-23 21:46:51 -0700111/* APIs to access the initialization flags
112 *
113 * Can be called prior to Py_Initialize.
114 */
Nick Coghland6009512014-11-20 21:39:37 +1000115
Eric Snow1abcf672017-05-23 21:46:51 -0700116int
117_Py_IsCoreInitialized(void)
118{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600119 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700120}
Nick Coghland6009512014-11-20 21:39:37 +1000121
122int
123Py_IsInitialized(void)
124{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600125 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000126}
127
Nick Coghlan6ea41862017-06-11 13:16:15 +1000128
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000129/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
130 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000131 initializations fail, a fatal error is issued and the function does
132 not return. On return, the first thread and interpreter state have
133 been created.
134
135 Locking: you must hold the interpreter lock while calling this.
136 (If the lock has not yet been initialized, that's equivalent to
137 having the lock, but you cannot use multiple threads.)
138
139*/
140
Victor Stinner331a6a52019-05-27 16:39:22 +0200141static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200142init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000143{
144 PyObject *importlib;
145 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000146 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200147 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200148 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000149
150 /* Import _importlib through its frozen version, _frozen_importlib. */
151 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200152 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000153 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200154 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000155 PySys_FormatStderr("import _frozen_importlib # frozen\n");
156 }
157 importlib = PyImport_AddModule("_frozen_importlib");
158 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200159 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000160 }
161 interp->importlib = importlib;
162 Py_INCREF(interp->importlib);
163
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300164 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
165 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200166 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300167 Py_INCREF(interp->import_func);
168
Victor Stinnercd6e6942015-09-18 09:11:57 +0200169 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800170 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000171 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200172 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000173 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200174 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200175 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000176 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600177 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200178 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000179 }
180
Victor Stinnercd6e6942015-09-18 09:11:57 +0200181 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000182 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
183 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200184 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200185 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000186 }
187 Py_DECREF(value);
188 Py_DECREF(impmod);
189
Victor Stinner331a6a52019-05-27 16:39:22 +0200190 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000191}
192
Victor Stinner331a6a52019-05-27 16:39:22 +0200193static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200194init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700195{
196 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200197 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700198 "_install_external_importers", "");
199 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200200 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200201 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700202 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200203 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200204 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700205}
Nick Coghland6009512014-11-20 21:39:37 +1000206
Nick Coghlan6ea41862017-06-11 13:16:15 +1000207/* Helper functions to better handle the legacy C locale
208 *
209 * The legacy C locale assumes ASCII as the default text encoding, which
210 * causes problems not only for the CPython runtime, but also other
211 * components like GNU readline.
212 *
213 * Accordingly, when the CLI detects it, it attempts to coerce it to a
214 * more capable UTF-8 based alternative as follows:
215 *
216 * if (_Py_LegacyLocaleDetected()) {
217 * _Py_CoerceLegacyLocale();
218 * }
219 *
220 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
221 *
222 * Locale coercion also impacts the default error handler for the standard
223 * streams: while the usual default is "strict", the default for the legacy
224 * C locale and for any of the coercion target locales is "surrogateescape".
225 */
226
227int
Victor Stinner0f721472019-05-20 17:16:38 +0200228_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000229{
230#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200231 if (!warn) {
232 const char *locale_override = getenv("LC_ALL");
233 if (locale_override != NULL && *locale_override != '\0') {
234 /* Don't coerce C locale if the LC_ALL environment variable
235 is set */
236 return 0;
237 }
238 }
239
Nick Coghlan6ea41862017-06-11 13:16:15 +1000240 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000241 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
242 * the POSIX locale as a simple alias for the C locale, so
243 * we may also want to check for that explicitly.
244 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000245 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
246 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
247#else
248 /* Windows uses code pages instead of locales, so no locale is legacy */
249 return 0;
250#endif
251}
252
Victor Stinnerb0051362019-11-22 17:52:42 +0100253#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000254static const char *_C_LOCALE_WARNING =
255 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
256 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
257 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
258 "locales is recommended.\n";
259
Nick Coghlaneb817952017-06-18 12:29:42 +1000260static void
Victor Stinner43125222019-04-24 18:23:53 +0200261emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000262{
Victor Stinner331a6a52019-05-27 16:39:22 +0200263 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200264 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200265 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000266 }
267}
Victor Stinnerb0051362019-11-22 17:52:42 +0100268#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000269
Nick Coghlan6ea41862017-06-11 13:16:15 +1000270typedef struct _CandidateLocale {
271 const char *locale_name; /* The locale to try as a coercion target */
272} _LocaleCoercionTarget;
273
274static _LocaleCoercionTarget _TARGET_LOCALES[] = {
275 {"C.UTF-8"},
276 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000277 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000278 {NULL}
279};
280
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200281
282int
283_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000284{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200285 const _LocaleCoercionTarget *target = NULL;
286 for (target = _TARGET_LOCALES; target->locale_name; target++) {
287 if (strcmp(ctype_loc, target->locale_name) == 0) {
288 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200290 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200291 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000292}
293
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200294
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100296static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
298 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
299
Victor Stinner0f721472019-05-20 17:16:38 +0200300static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200301_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302{
303 const char *newloc = target->locale_name;
304
305 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100306 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307
308 /* Set the relevant locale environment variable */
309 if (setenv("LC_CTYPE", newloc, 1)) {
310 fprintf(stderr,
311 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200312 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200314 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100315 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000316 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317
318 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100319 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200320 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000321}
322#endif
323
Victor Stinner0f721472019-05-20 17:16:38 +0200324int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200325_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326{
Victor Stinner0f721472019-05-20 17:16:38 +0200327 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200329 char *oldloc = NULL;
330
331 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
332 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200333 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200334 }
335
Victor Stinner94540602017-12-16 04:54:22 +0100336 const char *locale_override = getenv("LC_ALL");
337 if (locale_override == NULL || *locale_override == '\0') {
338 /* LC_ALL is also not set (or is set to an empty string) */
339 const _LocaleCoercionTarget *target = NULL;
340 for (target = _TARGET_LOCALES; target->locale_name; target++) {
341 const char *new_locale = setlocale(LC_CTYPE,
342 target->locale_name);
343 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400344#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100345 /* Also ensure that nl_langinfo works in this locale */
346 char *codeset = nl_langinfo(CODESET);
347 if (!codeset || *codeset == '\0') {
348 /* CODESET is not set or empty, so skip coercion */
349 new_locale = NULL;
350 _Py_SetLocaleFromEnv(LC_CTYPE);
351 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000352 }
Victor Stinner94540602017-12-16 04:54:22 +0100353#endif
354 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200355 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200356 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357 }
358 }
359 }
360 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200361
362 setlocale(LC_CTYPE, oldloc);
363
364done:
365 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000366#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200367 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000368}
369
xdegaye1588be62017-11-12 12:45:59 +0100370/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
371 * isolate the idiosyncrasies of different libc implementations. It reads the
372 * appropriate environment variable and uses its value to select the locale for
373 * 'category'. */
374char *
375_Py_SetLocaleFromEnv(int category)
376{
Victor Stinner353933e2018-11-23 13:08:26 +0100377 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100378#ifdef __ANDROID__
379 const char *locale;
380 const char **pvar;
381#ifdef PY_COERCE_C_LOCALE
382 const char *coerce_c_locale;
383#endif
384 const char *utf8_locale = "C.UTF-8";
385 const char *env_var_set[] = {
386 "LC_ALL",
387 "LC_CTYPE",
388 "LANG",
389 NULL,
390 };
391
392 /* Android setlocale(category, "") doesn't check the environment variables
393 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
394 * check the environment variables listed in env_var_set. */
395 for (pvar=env_var_set; *pvar; pvar++) {
396 locale = getenv(*pvar);
397 if (locale != NULL && *locale != '\0') {
398 if (strcmp(locale, utf8_locale) == 0 ||
399 strcmp(locale, "en_US.UTF-8") == 0) {
400 return setlocale(category, utf8_locale);
401 }
402 return setlocale(category, "C");
403 }
404 }
405
406 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
407 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
408 * Quote from POSIX section "8.2 Internationalization Variables":
409 * "4. If the LANG environment variable is not set or is set to the empty
410 * string, the implementation-defined default locale shall be used." */
411
412#ifdef PY_COERCE_C_LOCALE
413 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
414 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
415 /* Some other ported code may check the environment variables (e.g. in
416 * extension modules), so we make sure that they match the locale
417 * configuration */
418 if (setenv("LC_CTYPE", utf8_locale, 1)) {
419 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
420 "environment variable to %s\n", utf8_locale);
421 }
422 }
423#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100424 res = setlocale(category, utf8_locale);
425#else /* !defined(__ANDROID__) */
426 res = setlocale(category, "");
427#endif
428 _Py_ResetForceASCII();
429 return res;
xdegaye1588be62017-11-12 12:45:59 +0100430}
431
Nick Coghlan6ea41862017-06-11 13:16:15 +1000432
Eric Snow1abcf672017-05-23 21:46:51 -0700433/* Global initializations. Can be undone by Py_Finalize(). Don't
434 call this twice without an intervening Py_Finalize() call.
435
Victor Stinner331a6a52019-05-27 16:39:22 +0200436 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700437 must have a corresponding call to Py_Finalize.
438
439 Locking: you must hold the interpreter lock while calling these APIs.
440 (If the lock has not yet been initialized, that's equivalent to
441 having the lock, but you cannot use multiple threads.)
442
443*/
444
Victor Stinner331a6a52019-05-27 16:39:22 +0200445static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200446pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200447 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200448 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200449{
Victor Stinner331a6a52019-05-27 16:39:22 +0200450 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100451 PyThreadState *tstate = _PyThreadState_GET();
452 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200453 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100454 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200455 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100456
457 PyInterpreterState *interp = tstate->interp;
458 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200459 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100460 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100461
Victor Stinnerdedaac02020-06-08 18:44:50 +0200462 status = _PyConfig_Write(config, runtime);
463 if (_PyStatus_EXCEPTION(status)) {
464 return status;
465 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200466
Victor Stinnerda7933e2020-04-13 03:04:28 +0200467 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200468 if (_PyStatus_EXCEPTION(status)) {
469 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200471 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200472
Victor Stinner331a6a52019-05-27 16:39:22 +0200473 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200474 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200475 if (_PyStatus_EXCEPTION(status)) {
476 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200477 }
478 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200479 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200480}
481
482
Victor Stinner331a6a52019-05-27 16:39:22 +0200483static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200484pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200485 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000486{
Victor Stinner43125222019-04-24 18:23:53 +0200487 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200488 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200489 }
Victor Stinnerda273412017-12-15 01:46:02 +0100490
Victor Stinnerdedaac02020-06-08 18:44:50 +0200491 PyStatus status = _PyConfig_Write(config, runtime);
492 if (_PyStatus_EXCEPTION(status)) {
493 return status;
494 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600495
Eric Snow1abcf672017-05-23 21:46:51 -0700496 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
497 * threads behave a little more gracefully at interpreter shutdown.
498 * We clobber it here so the new interpreter can start with a clean
499 * slate.
500 *
501 * However, this may still lead to misbehaviour if there are daemon
502 * threads still hanging around from a previous Py_Initialize/Finalize
503 * pair :(
504 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100505 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600506
Victor Stinnerdedaac02020-06-08 18:44:50 +0200507 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200508 if (_PyStatus_EXCEPTION(status)) {
509 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800510 }
511
Victor Stinner331a6a52019-05-27 16:39:22 +0200512 status = _PyInterpreterState_Enable(runtime);
513 if (_PyStatus_EXCEPTION(status)) {
514 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800515 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200516 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800518
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100519
Victor Stinner331a6a52019-05-27 16:39:22 +0200520static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200521init_interp_create_gil(PyThreadState *tstate)
522{
523 PyStatus status;
524
525 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
526 only called here. */
527 _PyEval_FiniGIL(tstate);
528
529 /* Auto-thread-state API */
530 status = _PyGILState_Init(tstate);
531 if (_PyStatus_EXCEPTION(status)) {
532 return status;
533 }
534
535 /* Create the GIL and take it */
536 status = _PyEval_InitGIL(tstate);
537 if (_PyStatus_EXCEPTION(status)) {
538 return status;
539 }
540
541 return _PyStatus_OK();
542}
543
544
545static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200546pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200547 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200548 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100549{
550 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100551 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200552 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100553 }
554
Victor Stinnerda7933e2020-04-13 03:04:28 +0200555 PyStatus status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200556 if (_PyStatus_EXCEPTION(status)) {
557 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100558 }
Nick Coghland6009512014-11-20 21:39:37 +1000559
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200560 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200561 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200562 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200563 }
Nick Coghland6009512014-11-20 21:39:37 +1000564 (void) PyThreadState_Swap(tstate);
565
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200566 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100567 if (_PyStatus_EXCEPTION(status)) {
568 return status;
569 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100570
Victor Stinnerb45d2592019-06-20 00:05:23 +0200571 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200572 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573}
Nick Coghland6009512014-11-20 21:39:37 +1000574
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100575
Victor Stinner331a6a52019-05-27 16:39:22 +0200576static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100577pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100578{
Victor Stinner444b39b2019-11-20 01:18:11 +0100579 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100580 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100581
Victor Stinner01b1cc12019-11-20 02:27:56 +0100582 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100583 if (_PyStatus_EXCEPTION(status)) {
584 return status;
585 }
586
Victor Stinnere7e699e2019-11-20 12:08:13 +0100587 if (is_main_interp) {
588 status = _PyTypes_Init();
589 if (_PyStatus_EXCEPTION(status)) {
590 return status;
591 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100592 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100593
Victor Stinner630c8df2019-12-17 13:02:18 +0100594
595 if (!_PyLong_Init(tstate)) {
596 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100597 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100598
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100599 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100600 status = _PyUnicode_Init();
601 if (_PyStatus_EXCEPTION(status)) {
602 return status;
603 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100604 }
605
Victor Stinner331a6a52019-05-27 16:39:22 +0200606 status = _PyExc_Init();
607 if (_PyStatus_EXCEPTION(status)) {
608 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100609 }
610
Victor Stinnere7e699e2019-11-20 12:08:13 +0100611 if (is_main_interp) {
612 if (!_PyFloat_Init()) {
613 return _PyStatus_ERR("can't init float");
614 }
Nick Coghland6009512014-11-20 21:39:37 +1000615
Victor Stinnere7e699e2019-11-20 12:08:13 +0100616 if (_PyStructSequence_Init() < 0) {
617 return _PyStatus_ERR("can't initialize structseq");
618 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100619 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200620
Victor Stinner331a6a52019-05-27 16:39:22 +0200621 status = _PyErr_Init();
622 if (_PyStatus_EXCEPTION(status)) {
623 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200624 }
625
Victor Stinnere7e699e2019-11-20 12:08:13 +0100626 if (is_main_interp) {
627 if (!_PyContext_Init()) {
628 return _PyStatus_ERR("can't init context");
629 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100630 }
631
Victor Stinner331a6a52019-05-27 16:39:22 +0200632 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100633}
634
635
Victor Stinner331a6a52019-05-27 16:39:22 +0200636static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200637pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100638{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100639 assert(!_PyErr_Occurred(tstate));
640
Victor Stinnerb45d2592019-06-20 00:05:23 +0200641 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100642 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100643 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100644 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100645
Victor Stinner2582d462019-11-22 19:24:49 +0100646 PyInterpreterState *interp = tstate->interp;
647 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
648 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100649 }
Victor Stinner2582d462019-11-22 19:24:49 +0100650
651 PyObject *builtins_dict = PyModule_GetDict(bimod);
652 if (builtins_dict == NULL) {
653 goto error;
654 }
655 Py_INCREF(builtins_dict);
656 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100657
Victor Stinner331a6a52019-05-27 16:39:22 +0200658 PyStatus status = _PyBuiltins_AddExceptions(bimod);
659 if (_PyStatus_EXCEPTION(status)) {
660 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100661 }
Victor Stinner2582d462019-11-22 19:24:49 +0100662
663 interp->builtins_copy = PyDict_Copy(interp->builtins);
664 if (interp->builtins_copy == NULL) {
665 goto error;
666 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000667 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100668
669 assert(!_PyErr_Occurred(tstate));
670
Victor Stinner331a6a52019-05-27 16:39:22 +0200671 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100672
673error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000674 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100675 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100676}
677
678
Victor Stinner331a6a52019-05-27 16:39:22 +0200679static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200680pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100681{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100682 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200683
Victor Stinner2582d462019-11-22 19:24:49 +0100684 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200685 if (_PyStatus_EXCEPTION(status)) {
686 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800687 }
Nick Coghland6009512014-11-20 21:39:37 +1000688
Victor Stinnerda7933e2020-04-13 03:04:28 +0200689 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100690 if (_Py_IsMainInterpreter(tstate)) {
691 /* Initialize _warnings. */
Victor Stinner66b79732020-03-02 15:02:18 +0100692 status = _PyWarnings_InitState(tstate);
693 if (_PyStatus_EXCEPTION(status)) {
694 return status;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100695 }
Nick Coghland6009512014-11-20 21:39:37 +1000696
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100697 if (config->_install_importlib) {
698 status = _PyConfig_WritePathConfig(config);
699 if (_PyStatus_EXCEPTION(status)) {
700 return status;
701 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200702 }
703 }
704
Eric Snow1abcf672017-05-23 21:46:51 -0700705 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200706 if (config->_install_importlib) {
707 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200708 if (_PyStatus_EXCEPTION(status)) {
709 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800710 }
Eric Snow1abcf672017-05-23 21:46:51 -0700711 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100712
713 assert(!_PyErr_Occurred(tstate));
714
Victor Stinner331a6a52019-05-27 16:39:22 +0200715 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100716}
717
718
Victor Stinner331a6a52019-05-27 16:39:22 +0200719static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100720pycore_interp_init(PyThreadState *tstate)
721{
722 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100723 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100724
725 status = pycore_init_types(tstate);
726 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100727 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100728 }
729
Victor Stinnerd863ade2019-12-06 03:37:07 +0100730 status = _PySys_Create(tstate, &sysmod);
731 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100732 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100733 }
734
735 status = pycore_init_builtins(tstate);
736 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100737 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100738 }
739
Victor Stinner080ee5a2019-12-08 21:55:58 +0100740 status = pycore_init_import_warnings(tstate, sysmod);
741
742done:
743 /* sys.modules['sys'] contains a strong reference to the module */
744 Py_XDECREF(sysmod);
745 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100746}
747
748
749static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200750pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200751 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200752 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100753{
Victor Stinner331a6a52019-05-27 16:39:22 +0200754 PyStatus status = pycore_init_runtime(runtime, config);
755 if (_PyStatus_EXCEPTION(status)) {
756 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100757 }
758
Victor Stinnerb45d2592019-06-20 00:05:23 +0200759 PyThreadState *tstate;
760 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200761 if (_PyStatus_EXCEPTION(status)) {
762 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100763 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200764 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100765
Victor Stinnerd863ade2019-12-06 03:37:07 +0100766 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200767 if (_PyStatus_EXCEPTION(status)) {
768 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100769 }
Eric Snow1abcf672017-05-23 21:46:51 -0700770
771 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200772 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200773 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700774}
775
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100776
Victor Stinner331a6a52019-05-27 16:39:22 +0200777PyStatus
778_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100779{
Victor Stinner331a6a52019-05-27 16:39:22 +0200780 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100781
Victor Stinner6d1c4672019-05-20 11:02:00 +0200782 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200783 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200784 }
785
Victor Stinner331a6a52019-05-27 16:39:22 +0200786 status = _PyRuntime_Initialize();
787 if (_PyStatus_EXCEPTION(status)) {
788 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100789 }
Victor Stinner43125222019-04-24 18:23:53 +0200790 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100791
Victor Stinnerd3b90412019-09-17 23:59:51 +0200792 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100793 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200794 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100795 }
796
Victor Stinnerd3b90412019-09-17 23:59:51 +0200797 /* Note: preinitialized remains 1 on error, it is only set to 0
798 at exit on success. */
799 runtime->preinitializing = 1;
800
Victor Stinner331a6a52019-05-27 16:39:22 +0200801 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200802
803 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
804 if (_PyStatus_EXCEPTION(status)) {
805 return status;
806 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100807
Victor Stinner331a6a52019-05-27 16:39:22 +0200808 status = _PyPreConfig_Read(&config, args);
809 if (_PyStatus_EXCEPTION(status)) {
810 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100811 }
812
Victor Stinner331a6a52019-05-27 16:39:22 +0200813 status = _PyPreConfig_Write(&config);
814 if (_PyStatus_EXCEPTION(status)) {
815 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100816 }
817
Victor Stinnerd3b90412019-09-17 23:59:51 +0200818 runtime->preinitializing = 0;
819 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200820 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100821}
822
Victor Stinner70005ac2019-05-02 15:25:34 -0400823
Victor Stinner331a6a52019-05-27 16:39:22 +0200824PyStatus
825Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100826{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100827 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400828 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100829}
830
831
Victor Stinner331a6a52019-05-27 16:39:22 +0200832PyStatus
833Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100834{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100835 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400836 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100837}
838
839
Victor Stinner331a6a52019-05-27 16:39:22 +0200840PyStatus
841Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100842{
Victor Stinner70005ac2019-05-02 15:25:34 -0400843 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100844}
845
846
Victor Stinner331a6a52019-05-27 16:39:22 +0200847PyStatus
848_Py_PreInitializeFromConfig(const PyConfig *config,
849 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100850{
Victor Stinner331a6a52019-05-27 16:39:22 +0200851 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200852
Victor Stinner331a6a52019-05-27 16:39:22 +0200853 PyStatus status = _PyRuntime_Initialize();
854 if (_PyStatus_EXCEPTION(status)) {
855 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200856 }
857 _PyRuntimeState *runtime = &_PyRuntime;
858
Victor Stinnerd3b90412019-09-17 23:59:51 +0200859 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200860 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200861 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400862 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200863
Victor Stinner331a6a52019-05-27 16:39:22 +0200864 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200865
Victor Stinner3c30a762019-10-01 10:56:37 +0200866 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200867
Victor Stinner331a6a52019-05-27 16:39:22 +0200868 if (!config->parse_argv) {
869 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200870 }
871 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200872 _PyArgv config_args = {
873 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200874 .argc = config->argv.length,
875 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200876 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200877 }
878 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200879 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200880 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100881}
882
883
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100884/* Begin interpreter initialization
885 *
886 * On return, the first thread and interpreter state have been created,
887 * but the compiler, signal handling, multithreading and
888 * multiple interpreter support, and codec infrastructure are not yet
889 * available.
890 *
891 * The import system will support builtin and frozen modules only.
892 * The only supported io is writing to sys.stderr
893 *
894 * If any operation invoked by this function fails, a fatal error is
895 * issued and the function does not return.
896 *
897 * Any code invoked from this function should *not* assume it has access
898 * to the Python C API (unless the API is explicitly listed as being
899 * safe to call without calling Py_Initialize first)
900 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200901static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200902pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200903 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200904 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200905{
Victor Stinner331a6a52019-05-27 16:39:22 +0200906 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200907
Victor Stinner331a6a52019-05-27 16:39:22 +0200908 status = _Py_PreInitializeFromConfig(src_config, NULL);
909 if (_PyStatus_EXCEPTION(status)) {
910 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200911 }
912
Victor Stinner331a6a52019-05-27 16:39:22 +0200913 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200914 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200915
Victor Stinner331a6a52019-05-27 16:39:22 +0200916 status = _PyConfig_Copy(&config, src_config);
917 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200918 goto done;
919 }
920
Victor Stinner331a6a52019-05-27 16:39:22 +0200921 status = PyConfig_Read(&config);
922 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200923 goto done;
924 }
925
926 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200927 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200928 }
929 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200930 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200931 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200932 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200933 goto done;
934 }
935
936done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200937 PyConfig_Clear(&config);
938 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200939}
940
Victor Stinner5ac27a52019-03-27 13:40:14 +0100941
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200942/* Py_Initialize() has already been called: update the main interpreter
943 configuration. Example of bpo-34008: Py_Main() called after
944 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200945static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100946_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200947{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200948 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100949
Victor Stinner331a6a52019-05-27 16:39:22 +0200950 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100951 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200952 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100953 }
954
Victor Stinnerb0051362019-11-22 17:52:42 +0100955 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100956 Py_DECREF(argv);
957 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200958 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200959 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200960 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200961}
962
Victor Stinnerb0051362019-11-22 17:52:42 +0100963
964static PyStatus
965init_interp_main(PyThreadState *tstate)
966{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100967 assert(!_PyErr_Occurred(tstate));
968
Victor Stinnerb0051362019-11-22 17:52:42 +0100969 PyStatus status;
970 int is_main_interp = _Py_IsMainInterpreter(tstate);
971 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200972 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +0100973
974 if (!config->_install_importlib) {
975 /* Special mode for freeze_importlib: run with no import system
976 *
977 * This means anything which needs support from extension modules
978 * or pure Python code in the standard library won't work.
979 */
980 if (is_main_interp) {
981 interp->runtime->initialized = 1;
982 }
983 return _PyStatus_OK();
984 }
985
986 if (is_main_interp) {
987 if (_PyTime_Init() < 0) {
988 return _PyStatus_ERR("can't initialize time");
989 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100990 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100991
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100992 if (_PySys_InitMain(tstate) < 0) {
993 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +0100994 }
995
996 status = init_importlib_external(tstate);
997 if (_PyStatus_EXCEPTION(status)) {
998 return status;
999 }
1000
1001 if (is_main_interp) {
1002 /* initialize the faulthandler module */
1003 status = _PyFaulthandler_Init(config->faulthandler);
1004 if (_PyStatus_EXCEPTION(status)) {
1005 return status;
1006 }
1007 }
1008
1009 status = _PyUnicode_InitEncodings(tstate);
1010 if (_PyStatus_EXCEPTION(status)) {
1011 return status;
1012 }
1013
1014 if (is_main_interp) {
Victor Stinner05a5d692020-11-17 18:58:12 +01001015 if (_PySignal_Init(config->install_signal_handlers) < 0) {
1016 return _PyStatus_ERR("can't initialize signals");
Victor Stinnerb0051362019-11-22 17:52:42 +01001017 }
1018
1019 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1020 return _PyStatus_ERR("can't initialize tracemalloc");
1021 }
1022 }
1023
1024 status = init_sys_streams(tstate);
1025 if (_PyStatus_EXCEPTION(status)) {
1026 return status;
1027 }
1028
Andy Lester75cd5bf2020-03-12 02:49:05 -05001029 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001030 if (_PyStatus_EXCEPTION(status)) {
1031 return status;
1032 }
1033
1034 status = add_main_module(interp);
1035 if (_PyStatus_EXCEPTION(status)) {
1036 return status;
1037 }
1038
1039 if (is_main_interp) {
1040 /* Initialize warnings. */
1041 PyObject *warnoptions = PySys_GetObject("warnoptions");
1042 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1043 {
1044 PyObject *warnings_module = PyImport_ImportModule("warnings");
1045 if (warnings_module == NULL) {
1046 fprintf(stderr, "'import warnings' failed; traceback:\n");
1047 _PyErr_Print(tstate);
1048 }
1049 Py_XDECREF(warnings_module);
1050 }
1051
1052 interp->runtime->initialized = 1;
1053 }
1054
1055 if (config->site_import) {
1056 status = init_import_site();
1057 if (_PyStatus_EXCEPTION(status)) {
1058 return status;
1059 }
1060 }
1061
1062 if (is_main_interp) {
1063#ifndef MS_WINDOWS
1064 emit_stderr_warning_for_legacy_locale(interp->runtime);
1065#endif
1066 }
1067
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001068 assert(!_PyErr_Occurred(tstate));
1069
Victor Stinnerb0051362019-11-22 17:52:42 +01001070 return _PyStatus_OK();
1071}
1072
1073
Eric Snowc7ec9982017-05-23 23:00:52 -07001074/* Update interpreter state based on supplied configuration settings
1075 *
1076 * After calling this function, most of the restrictions on the interpreter
1077 * are lifted. The only remaining incomplete settings are those related
1078 * to the main module (sys.argv[0], __main__ metadata)
1079 *
1080 * Calling this when the interpreter is not initializing, is already
1081 * initialized or without a valid current thread state is a fatal error.
1082 * Other errors should be reported as normal Python exceptions with a
1083 * non-zero return code.
1084 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001085static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001086pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001087{
Victor Stinnerb0051362019-11-22 17:52:42 +01001088 PyInterpreterState *interp = tstate->interp;
1089 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001090 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001091 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001092
Victor Stinnerb0051362019-11-22 17:52:42 +01001093 if (interp->runtime->initialized) {
1094 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001095 }
1096
Victor Stinnerb0051362019-11-22 17:52:42 +01001097 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001098 if (_PyStatus_EXCEPTION(status)) {
1099 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001100 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001101 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001102}
1103
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001104
Victor Stinner331a6a52019-05-27 16:39:22 +02001105PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001106_Py_InitializeMain(void)
1107{
Victor Stinner331a6a52019-05-27 16:39:22 +02001108 PyStatus status = _PyRuntime_Initialize();
1109 if (_PyStatus_EXCEPTION(status)) {
1110 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001111 }
1112 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001113 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001114 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001115}
1116
1117
Victor Stinner331a6a52019-05-27 16:39:22 +02001118PyStatus
1119Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001120{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001121 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001122 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001123 }
1124
Victor Stinner331a6a52019-05-27 16:39:22 +02001125 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001126
Victor Stinner331a6a52019-05-27 16:39:22 +02001127 status = _PyRuntime_Initialize();
1128 if (_PyStatus_EXCEPTION(status)) {
1129 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001130 }
1131 _PyRuntimeState *runtime = &_PyRuntime;
1132
Victor Stinnerb45d2592019-06-20 00:05:23 +02001133 PyThreadState *tstate = NULL;
1134 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001135 if (_PyStatus_EXCEPTION(status)) {
1136 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001137 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001138 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001139
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001140 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001141 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001142 if (_PyStatus_EXCEPTION(status)) {
1143 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001144 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001145 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001146
Victor Stinner331a6a52019-05-27 16:39:22 +02001147 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001148}
1149
1150
Eric Snow1abcf672017-05-23 21:46:51 -07001151void
Nick Coghland6009512014-11-20 21:39:37 +10001152Py_InitializeEx(int install_sigs)
1153{
Victor Stinner331a6a52019-05-27 16:39:22 +02001154 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001155
Victor Stinner331a6a52019-05-27 16:39:22 +02001156 status = _PyRuntime_Initialize();
1157 if (_PyStatus_EXCEPTION(status)) {
1158 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001159 }
1160 _PyRuntimeState *runtime = &_PyRuntime;
1161
1162 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001163 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1164 return;
1165 }
1166
Victor Stinner331a6a52019-05-27 16:39:22 +02001167 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001168 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001169
Victor Stinner1dc6e392018-07-25 02:49:17 +02001170 config.install_signal_handlers = install_sigs;
1171
Victor Stinner331a6a52019-05-27 16:39:22 +02001172 status = Py_InitializeFromConfig(&config);
1173 if (_PyStatus_EXCEPTION(status)) {
1174 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001175 }
Nick Coghland6009512014-11-20 21:39:37 +10001176}
1177
1178void
1179Py_Initialize(void)
1180{
1181 Py_InitializeEx(1);
1182}
1183
1184
Nick Coghland6009512014-11-20 21:39:37 +10001185/* Flush stdout and stderr */
1186
1187static int
1188file_is_closed(PyObject *fobj)
1189{
1190 int r;
1191 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1192 if (tmp == NULL) {
1193 PyErr_Clear();
1194 return 0;
1195 }
1196 r = PyObject_IsTrue(tmp);
1197 Py_DECREF(tmp);
1198 if (r < 0)
1199 PyErr_Clear();
1200 return r > 0;
1201}
1202
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001203static int
Nick Coghland6009512014-11-20 21:39:37 +10001204flush_std_files(void)
1205{
1206 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1207 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1208 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001209 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001210
1211 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001212 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001213 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001214 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001215 status = -1;
1216 }
Nick Coghland6009512014-11-20 21:39:37 +10001217 else
1218 Py_DECREF(tmp);
1219 }
1220
1221 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001222 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001223 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001224 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001225 status = -1;
1226 }
Nick Coghland6009512014-11-20 21:39:37 +10001227 else
1228 Py_DECREF(tmp);
1229 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001230
1231 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001232}
1233
1234/* Undo the effect of Py_Initialize().
1235
1236 Beware: if multiple interpreter and/or thread states exist, these
1237 are not wiped out; only the current thread and interpreter state
1238 are deleted. But since everything else is deleted, those other
1239 interpreter and thread states should no longer be used.
1240
1241 (XXX We should do better, e.g. wipe out all interpreters and
1242 threads.)
1243
1244 Locking: as above.
1245
1246*/
1247
Victor Stinner7eee5be2019-11-20 10:38:34 +01001248
1249static void
1250finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1251{
1252 if (is_main_interp) {
1253 /* Sundry finalizers */
Pablo Galindo55e08362020-09-15 19:32:56 +01001254 _PyAST_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001255 _PyFrame_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001256 _PyTuple_Fini();
1257 _PyList_Fini();
1258 _PySet_Fini();
1259 _PyBytes_Fini();
Victor Stinner630c8df2019-12-17 13:02:18 +01001260 }
1261
1262 _PyLong_Fini(tstate);
1263
1264 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001265 _PyFloat_Fini();
1266 _PyDict_Fini();
1267 _PySlice_Fini();
1268 }
1269
1270 _PyWarnings_Fini(tstate->interp);
1271
1272 if (is_main_interp) {
1273 _Py_HashRandomization_Fini();
1274 _PyArg_Fini();
1275 _PyAsyncGen_Fini();
1276 _PyContext_Fini();
Victor Stinner3d483342019-11-22 12:27:50 +01001277 }
Victor Stinner7eee5be2019-11-20 10:38:34 +01001278
Victor Stinner3d483342019-11-22 12:27:50 +01001279 /* Cleanup Unicode implementation */
1280 _PyUnicode_Fini(tstate);
1281
1282 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001283 _Py_ClearFileSystemEncoding();
1284 }
1285}
1286
1287
1288static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001289finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001290{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001291 int is_main_interp = _Py_IsMainInterpreter(tstate);
1292
Victor Stinner7eee5be2019-11-20 10:38:34 +01001293 /* Clear interpreter state and all thread states */
1294 PyInterpreterState_Clear(tstate->interp);
1295
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001296 /* Trigger a GC collection on subinterpreters*/
1297 if (!is_main_interp) {
1298 _PyGC_CollectNoFail();
1299 }
1300
Steve Dowere1d4fdc2020-07-03 22:58:29 +01001301 /* Clear all loghooks */
1302 /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1303 Call _PySys_ClearAuditHooks when PyObject available. */
1304 if (is_main_interp) {
1305 _PySys_ClearAuditHooks(tstate);
1306 }
1307
Steve Dower941117a2020-07-03 23:34:46 +01001308 finalize_interp_types(tstate, is_main_interp);
1309
Victor Stinner7eee5be2019-11-20 10:38:34 +01001310 if (is_main_interp) {
1311 /* XXX Still allocated:
1312 - various static ad-hoc pointers to interned strings
1313 - int and float free list blocks
1314 - whatever various modules and libraries allocate
1315 */
1316
1317 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1318
1319 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001320 }
Victor Stinner72474072019-11-20 12:25:50 +01001321
1322 _PyGC_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001323}
1324
1325
1326static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001327finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001328{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001329 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001330 /* Cleanup auto-thread-state */
1331 _PyGILState_Fini(tstate);
1332 }
1333
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001334 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1335 fail when it is being awaited by another running daemon thread (see
1336 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1337 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1338 called multiple times. */
1339
Victor Stinner7eee5be2019-11-20 10:38:34 +01001340 PyInterpreterState_Delete(tstate->interp);
1341}
1342
1343
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001344int
1345Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001346{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001347 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001348
Victor Stinner8e91c242019-04-24 17:24:01 +02001349 _PyRuntimeState *runtime = &_PyRuntime;
1350 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001351 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001352 }
Nick Coghland6009512014-11-20 21:39:37 +10001353
Victor Stinnere225beb2019-06-03 18:14:24 +02001354 /* Get current thread state and interpreter pointer */
1355 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1356 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001357
Victor Stinnerb45d2592019-06-20 00:05:23 +02001358 // Wrap up existing "threading"-module-created, non-daemon threads.
1359 wait_for_thread_shutdown(tstate);
1360
1361 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001362 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001363
Nick Coghland6009512014-11-20 21:39:37 +10001364 /* The interpreter is still entirely intact at this point, and the
1365 * exit funcs may be relying on that. In particular, if some thread
1366 * or exit func is still waiting to do an import, the import machinery
1367 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001368 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001369 * Note that Threading.py uses an exit func to do a join on all the
1370 * threads created thru it, so this also protects pending imports in
1371 * the threads created via Threading.
1372 */
Nick Coghland6009512014-11-20 21:39:37 +10001373
Victor Stinnerb45d2592019-06-20 00:05:23 +02001374 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001375
Victor Stinnerda273412017-12-15 01:46:02 +01001376 /* Copy the core config, PyInterpreterState_Delete() free
1377 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001378#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001379 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001380#endif
1381#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001382 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001383#endif
1384#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001385 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001386#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001387
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001388 /* Remaining daemon threads will automatically exit
1389 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001390 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001391 runtime->initialized = 0;
1392 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001393
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001394 /* Destroy the state of all threads of the interpreter, except of the
1395 current thread. In practice, only daemon threads should still be alive,
1396 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1397 Clear frames of other threads to call objects destructors. Destructors
1398 will be called in the current Python thread. Since
1399 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1400 can take the GIL at this point: if they try, they will exit
1401 immediately. */
1402 _PyThreadState_DeleteExcept(runtime, tstate);
1403
Victor Stinnere0deff32015-03-24 13:46:18 +01001404 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001405 if (flush_std_files() < 0) {
1406 status = -1;
1407 }
Nick Coghland6009512014-11-20 21:39:37 +10001408
1409 /* Disable signal handling */
1410 PyOS_FiniInterrupts();
1411
1412 /* Collect garbage. This may call finalizers; it's nice to call these
1413 * before all modules are destroyed.
1414 * XXX If a __del__ or weakref callback is triggered here, and tries to
1415 * XXX import a module, bad things can happen, because Python no
1416 * XXX longer believes it's initialized.
1417 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1418 * XXX is easy to provoke that way. I've also seen, e.g.,
1419 * XXX Exception exceptions.ImportError: 'No module named sha'
1420 * XXX in <function callback at 0x008F5718> ignored
1421 * XXX but I'm unclear on exactly how that one happens. In any case,
1422 * XXX I haven't seen a real-life report of either of these.
1423 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001424 _PyGC_CollectIfEnabled();
Eric Snowdae02762017-09-14 00:35:58 -07001425
Nick Coghland6009512014-11-20 21:39:37 +10001426 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001427 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001428
Inada Naoki91234a12019-06-03 21:30:58 +09001429 /* Print debug stats if any */
1430 _PyEval_Fini();
1431
Victor Stinnere0deff32015-03-24 13:46:18 +01001432 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001433 if (flush_std_files() < 0) {
1434 status = -1;
1435 }
Nick Coghland6009512014-11-20 21:39:37 +10001436
1437 /* Collect final garbage. This disposes of cycles created by
1438 * class definitions, for example.
1439 * XXX This is disabled because it caused too many problems. If
1440 * XXX a __del__ or weakref callback triggers here, Python code has
1441 * XXX a hard time running, because even the sys module has been
1442 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1443 * XXX One symptom is a sequence of information-free messages
1444 * XXX coming from threads (if a __del__ or callback is invoked,
1445 * XXX other threads can execute too, and any exception they encounter
1446 * XXX triggers a comedy of errors as subsystem after subsystem
1447 * XXX fails to find what it *expects* to find in sys to help report
1448 * XXX the exception and consequent unexpected failures). I've also
1449 * XXX seen segfaults then, after adding print statements to the
1450 * XXX Python code getting called.
1451 */
1452#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001453 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001454#endif
1455
1456 /* Disable tracemalloc after all Python objects have been destroyed,
1457 so it is possible to use tracemalloc in objects destructor. */
1458 _PyTraceMalloc_Fini();
1459
1460 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1461 _PyImport_Fini();
1462
1463 /* Cleanup typeobject.c's internal caches. */
1464 _PyType_Fini();
1465
1466 /* unload faulthandler module */
1467 _PyFaulthandler_Fini();
1468
Nick Coghland6009512014-11-20 21:39:37 +10001469 /* dump hash stats */
1470 _PyHash_Fini();
1471
Eric Snowdae02762017-09-14 00:35:58 -07001472#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001473 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001474 _PyDebug_PrintTotalRefs();
1475 }
Eric Snowdae02762017-09-14 00:35:58 -07001476#endif
Nick Coghland6009512014-11-20 21:39:37 +10001477
1478#ifdef Py_TRACE_REFS
1479 /* Display all objects still alive -- this can invoke arbitrary
1480 * __repr__ overrides, so requires a mostly-intact interpreter.
1481 * Alas, a lot of stuff may still be alive now that will be cleaned
1482 * up later.
1483 */
Victor Stinnerda273412017-12-15 01:46:02 +01001484 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001485 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001486 }
Nick Coghland6009512014-11-20 21:39:37 +10001487#endif /* Py_TRACE_REFS */
1488
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001489 finalize_interp_clear(tstate);
1490 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001491
1492#ifdef Py_TRACE_REFS
1493 /* Display addresses (& refcnts) of all objects still alive.
1494 * An address can be used to find the repr of the object, printed
1495 * above by _Py_PrintReferences.
1496 */
Victor Stinnerda273412017-12-15 01:46:02 +01001497 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001498 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001499 }
Nick Coghland6009512014-11-20 21:39:37 +10001500#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001501#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001502 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001503 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001504 }
Nick Coghland6009512014-11-20 21:39:37 +10001505#endif
1506
Victor Stinner8e91c242019-04-24 17:24:01 +02001507 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001508
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001509 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001510 return status;
1511}
1512
1513void
1514Py_Finalize(void)
1515{
1516 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001517}
1518
Victor Stinnerb0051362019-11-22 17:52:42 +01001519
Nick Coghland6009512014-11-20 21:39:37 +10001520/* Create and initialize a new interpreter and thread, and return the
1521 new thread. This requires that Py_Initialize() has been called
1522 first.
1523
1524 Unsuccessful initialization yields a NULL pointer. Note that *no*
1525 exception information is available even in this case -- the
1526 exception information is held in the thread, and there is no
1527 thread.
1528
1529 Locking: as above.
1530
1531*/
1532
Victor Stinner331a6a52019-05-27 16:39:22 +02001533static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001534new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001535{
Victor Stinner331a6a52019-05-27 16:39:22 +02001536 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001537
Victor Stinner331a6a52019-05-27 16:39:22 +02001538 status = _PyRuntime_Initialize();
1539 if (_PyStatus_EXCEPTION(status)) {
1540 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001541 }
1542 _PyRuntimeState *runtime = &_PyRuntime;
1543
1544 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001545 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001546 }
Nick Coghland6009512014-11-20 21:39:37 +10001547
Victor Stinner8a1be612016-03-14 22:07:55 +01001548 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1549 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001550 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001551
Victor Stinner43125222019-04-24 18:23:53 +02001552 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001553 if (interp == NULL) {
1554 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001555 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001556 }
Nick Coghland6009512014-11-20 21:39:37 +10001557
Victor Stinner43125222019-04-24 18:23:53 +02001558 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001559 if (tstate == NULL) {
1560 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001561 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001562 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001563 }
1564
Victor Stinner43125222019-04-24 18:23:53 +02001565 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001566
Eric Snow1abcf672017-05-23 21:46:51 -07001567 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001568 const PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001569 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001570 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001571 }
1572 else
Victor Stinner7be4e352020-05-05 20:27:47 +02001573 {
Eric Snow1abcf672017-05-23 21:46:51 -07001574 /* No current thread state, copy from the main interpreter */
1575 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001576 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001577 }
1578
Victor Stinnerda7933e2020-04-13 03:04:28 +02001579 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001580 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001581 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001582 }
Victor Stinner252346a2020-05-01 11:33:44 +02001583 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001584
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001585 status = init_interp_create_gil(tstate);
1586 if (_PyStatus_EXCEPTION(status)) {
1587 goto error;
1588 }
1589
Victor Stinnerd863ade2019-12-06 03:37:07 +01001590 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001591 if (_PyStatus_EXCEPTION(status)) {
1592 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001593 }
1594
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001595 status = init_interp_main(tstate);
1596 if (_PyStatus_EXCEPTION(status)) {
1597 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001598 }
Nick Coghland6009512014-11-20 21:39:37 +10001599
Victor Stinnera7368ac2017-11-15 18:11:45 -08001600 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001601 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001602
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001603error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001604 *tstate_p = NULL;
1605
1606 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001607 PyErr_PrintEx(0);
1608 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001609 PyThreadState_Delete(tstate);
1610 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001611 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001612
Victor Stinnerb0051362019-11-22 17:52:42 +01001613 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001614}
1615
1616PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001617_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001618{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001619 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001620 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001621 if (_PyStatus_EXCEPTION(status)) {
1622 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001623 }
1624 return tstate;
1625
Nick Coghland6009512014-11-20 21:39:37 +10001626}
1627
Victor Stinner252346a2020-05-01 11:33:44 +02001628PyThreadState *
1629Py_NewInterpreter(void)
1630{
1631 return _Py_NewInterpreter(0);
1632}
1633
Nick Coghland6009512014-11-20 21:39:37 +10001634/* 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()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001652 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001653 }
1654 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001655 Py_FatalError("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) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001665 Py_FatalError("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;
Jendrik Seipp5b907712020-01-01 23:21:43 +01001844 if (buffered_stdio && (isatty || fd == fileno(stderr)))
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
Andy Lester75cd5bf2020-03-12 02:49:05 -05001913init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001914{
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 Stinnerda7933e2020-04-13 03:04:28 +02001959 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
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
Andy Lester75cd5bf2020-03-12 02:49:05 -05002081_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002082{
2083 PyObject *ferr, *res;
2084 PyObject *exception, *v, *tb;
2085 int has_tb;
2086
Victor Stinnerb45d2592019-06-20 00:05:23 +02002087 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002088 if (exception == NULL) {
2089 /* No current exception */
2090 return 0;
2091 }
2092
2093 ferr = _PySys_GetObjectId(&PyId_stderr);
2094 if (ferr == NULL || ferr == Py_None) {
2095 /* sys.stderr is not set yet or set to None,
2096 no need to try to display the exception */
2097 return 0;
2098 }
2099
Victor Stinnerb45d2592019-06-20 00:05:23 +02002100 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002101 if (tb == NULL) {
2102 tb = Py_None;
2103 Py_INCREF(tb);
2104 }
2105 PyException_SetTraceback(v, tb);
2106 if (exception == NULL) {
2107 /* PyErr_NormalizeException() failed */
2108 return 0;
2109 }
2110
2111 has_tb = (tb != Py_None);
2112 PyErr_Display(exception, v, tb);
2113 Py_XDECREF(exception);
2114 Py_XDECREF(v);
2115 Py_XDECREF(tb);
2116
2117 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002118 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002119 if (res == NULL) {
2120 _PyErr_Clear(tstate);
2121 }
2122 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002123 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002124 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002125
2126 return has_tb;
2127}
2128
Nick Coghland6009512014-11-20 21:39:37 +10002129/* Print fatal error message and abort */
2130
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002131#ifdef MS_WINDOWS
2132static void
2133fatal_output_debug(const char *msg)
2134{
2135 /* buffer of 256 bytes allocated on the stack */
2136 WCHAR buffer[256 / sizeof(WCHAR)];
2137 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2138 size_t msglen;
2139
2140 OutputDebugStringW(L"Fatal Python error: ");
2141
2142 msglen = strlen(msg);
2143 while (msglen) {
2144 size_t i;
2145
2146 if (buflen > msglen) {
2147 buflen = msglen;
2148 }
2149
2150 /* Convert the message to wchar_t. This uses a simple one-to-one
2151 conversion, assuming that the this error message actually uses
2152 ASCII only. If this ceases to be true, we will have to convert. */
2153 for (i=0; i < buflen; ++i) {
2154 buffer[i] = msg[i];
2155 }
2156 buffer[i] = L'\0';
2157 OutputDebugStringW(buffer);
2158
2159 msg += buflen;
2160 msglen -= buflen;
2161 }
2162 OutputDebugStringW(L"\n");
2163}
2164#endif
2165
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002166
2167static void
2168fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2169{
2170 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002171 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2172 if (finalizing) {
2173 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002174 }
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
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002195static inline void _Py_NO_RETURN
2196fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002197{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002198 if (status < 0) {
2199#if defined(MS_WINDOWS) && defined(_DEBUG)
2200 DebugBreak();
2201#endif
2202 abort();
2203 }
2204 else {
2205 exit(status);
2206 }
2207}
2208
2209
2210static void _Py_NO_RETURN
2211fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2212 int status)
2213{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002214 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002215 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002216
2217 if (reentrant) {
2218 /* Py_FatalError() caused a second fatal error.
2219 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002220 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002221 }
2222 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002223
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002224 if (header) {
2225 fprintf(stream, "Fatal Python error: ");
2226 if (prefix) {
2227 fputs(prefix, stream);
2228 fputs(": ", stream);
2229 }
2230 if (msg) {
2231 fputs(msg, stream);
2232 }
2233 else {
2234 fprintf(stream, "<message not set>");
2235 }
2236 fputs("\n", stream);
2237 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002238 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002239
2240 _PyRuntimeState *runtime = &_PyRuntime;
2241 fatal_error_dump_runtime(stream, runtime);
2242
2243 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2244 PyInterpreterState *interp = NULL;
2245 if (tstate != NULL) {
2246 interp = tstate->interp;
2247 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002248
Victor Stinner3a228ab2018-11-01 00:26:41 +01002249 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002250 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002251
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002252 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2253 has no Python thread state.
2254
2255 tss_tstate != tstate if the current Python thread does not hold the GIL.
2256 */
2257 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2258 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002259 if (has_tstate_and_gil) {
2260 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002261 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002262 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002263 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002264 }
2265 }
2266 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002267 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002268 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002269
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002270 /* The main purpose of faulthandler is to display the traceback.
2271 This function already did its best to display a traceback.
2272 Disable faulthandler to prevent writing a second traceback
2273 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002274 _PyFaulthandler_Fini();
2275
Victor Stinner791da1c2016-03-14 16:53:12 +01002276 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002277 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002278 /* Flush sys.stdout and sys.stderr */
2279 flush_std_files();
2280 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002281
Nick Coghland6009512014-11-20 21:39:37 +10002282#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002283 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002284#endif /* MS_WINDOWS */
2285
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002286 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002287}
2288
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002289
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002290#undef Py_FatalError
2291
Victor Stinner19760862017-12-20 01:41:59 +01002292void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002293Py_FatalError(const char *msg)
2294{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002295 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002296}
2297
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002298
Victor Stinner19760862017-12-20 01:41:59 +01002299void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002300_Py_FatalErrorFunc(const char *func, const char *msg)
2301{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002302 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002303}
2304
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002305
2306void _Py_NO_RETURN
2307_Py_FatalErrorFormat(const char *func, const char *format, ...)
2308{
2309 static int reentrant = 0;
2310 if (reentrant) {
2311 /* _Py_FatalErrorFormat() caused a second fatal error */
2312 fatal_error_exit(-1);
2313 }
2314 reentrant = 1;
2315
2316 FILE *stream = stderr;
2317 fprintf(stream, "Fatal Python error: ");
2318 if (func) {
2319 fputs(func, stream);
2320 fputs(": ", stream);
2321 }
2322 fflush(stream);
2323
2324 va_list vargs;
2325#ifdef HAVE_STDARG_PROTOTYPES
2326 va_start(vargs, format);
2327#else
2328 va_start(vargs);
2329#endif
2330 vfprintf(stream, format, vargs);
2331 va_end(vargs);
2332
2333 fputs("\n", stream);
2334 fflush(stream);
2335
2336 fatal_error(stream, 0, NULL, NULL, -1);
2337}
2338
2339
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002340void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002341Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002342{
Victor Stinner331a6a52019-05-27 16:39:22 +02002343 if (_PyStatus_IS_EXIT(status)) {
2344 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002345 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002346 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002347 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002348 }
2349 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002350 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002351 }
Nick Coghland6009512014-11-20 21:39:37 +10002352}
2353
2354/* Clean up and exit */
2355
Nick Coghland6009512014-11-20 21:39:37 +10002356/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002357void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002358{
Victor Stinner81a7be32020-04-14 15:14:01 +02002359 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002360
Antoine Pitroufc5db952017-12-13 02:29:07 +01002361 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002362 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2363
2364 is->pyexitfunc = func;
2365 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002366}
2367
2368static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002369call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002370{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002371 PyInterpreterState *interp = tstate->interp;
2372 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002373 return;
2374
Victor Stinnerb45d2592019-06-20 00:05:23 +02002375 (*interp->pyexitfunc)(interp->pyexitmodule);
2376 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002377}
2378
2379/* Wait until threading._shutdown completes, provided
2380 the threading module was imported in the first place.
2381 The shutdown routine will wait until all non-daemon
2382 "threading" threads have completed. */
2383static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002384wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002385{
Nick Coghland6009512014-11-20 21:39:37 +10002386 _Py_IDENTIFIER(_shutdown);
2387 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002388 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002389 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002390 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002391 PyErr_WriteUnraisable(NULL);
2392 }
2393 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002394 return;
2395 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002396 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002397 if (result == NULL) {
2398 PyErr_WriteUnraisable(threading);
2399 }
2400 else {
2401 Py_DECREF(result);
2402 }
2403 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002404}
2405
2406#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002407int Py_AtExit(void (*func)(void))
2408{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002409 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002410 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002411 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002412 return 0;
2413}
2414
2415static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002416call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002417{
Victor Stinner8e91c242019-04-24 17:24:01 +02002418 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002419 /* pop last function from the list */
2420 runtime->nexitfuncs--;
2421 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2422 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2423
2424 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002425 }
Nick Coghland6009512014-11-20 21:39:37 +10002426
2427 fflush(stdout);
2428 fflush(stderr);
2429}
2430
Victor Stinnercfc88312018-08-01 16:41:25 +02002431void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002432Py_Exit(int sts)
2433{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002434 if (Py_FinalizeEx() < 0) {
2435 sts = 120;
2436 }
Nick Coghland6009512014-11-20 21:39:37 +10002437
2438 exit(sts);
2439}
2440
Nick Coghland6009512014-11-20 21:39:37 +10002441
2442/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2443 *
2444 * All of the code in this function must only use async-signal-safe functions,
2445 * listed at `man 7 signal` or
2446 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002447 *
2448 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002449 */
2450void
2451_Py_RestoreSignals(void)
2452{
2453#ifdef SIGPIPE
2454 PyOS_setsig(SIGPIPE, SIG_DFL);
2455#endif
2456#ifdef SIGXFZ
2457 PyOS_setsig(SIGXFZ, SIG_DFL);
2458#endif
2459#ifdef SIGXFSZ
2460 PyOS_setsig(SIGXFSZ, SIG_DFL);
2461#endif
2462}
2463
2464
2465/*
2466 * The file descriptor fd is considered ``interactive'' if either
2467 * a) isatty(fd) is TRUE, or
2468 * b) the -i flag was given, and the filename associated with
2469 * the descriptor is NULL or "<stdin>" or "???".
2470 */
2471int
2472Py_FdIsInteractive(FILE *fp, const char *filename)
2473{
2474 if (isatty((int)fileno(fp)))
2475 return 1;
2476 if (!Py_InteractiveFlag)
2477 return 0;
2478 return (filename == NULL) ||
2479 (strcmp(filename, "<stdin>") == 0) ||
2480 (strcmp(filename, "???") == 0);
2481}
2482
2483
Nick Coghland6009512014-11-20 21:39:37 +10002484/* Wrappers around sigaction() or signal(). */
2485
2486PyOS_sighandler_t
2487PyOS_getsig(int sig)
2488{
2489#ifdef HAVE_SIGACTION
2490 struct sigaction context;
2491 if (sigaction(sig, NULL, &context) == -1)
2492 return SIG_ERR;
2493 return context.sa_handler;
2494#else
2495 PyOS_sighandler_t handler;
2496/* Special signal handling for the secure CRT in Visual Studio 2005 */
2497#if defined(_MSC_VER) && _MSC_VER >= 1400
2498 switch (sig) {
2499 /* Only these signals are valid */
2500 case SIGINT:
2501 case SIGILL:
2502 case SIGFPE:
2503 case SIGSEGV:
2504 case SIGTERM:
2505 case SIGBREAK:
2506 case SIGABRT:
2507 break;
2508 /* Don't call signal() with other values or it will assert */
2509 default:
2510 return SIG_ERR;
2511 }
2512#endif /* _MSC_VER && _MSC_VER >= 1400 */
2513 handler = signal(sig, SIG_IGN);
2514 if (handler != SIG_ERR)
2515 signal(sig, handler);
2516 return handler;
2517#endif
2518}
2519
2520/*
2521 * All of the code in this function must only use async-signal-safe functions,
2522 * listed at `man 7 signal` or
2523 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2524 */
2525PyOS_sighandler_t
2526PyOS_setsig(int sig, PyOS_sighandler_t handler)
2527{
2528#ifdef HAVE_SIGACTION
2529 /* Some code in Modules/signalmodule.c depends on sigaction() being
2530 * used here if HAVE_SIGACTION is defined. Fix that if this code
2531 * changes to invalidate that assumption.
2532 */
2533 struct sigaction context, ocontext;
2534 context.sa_handler = handler;
2535 sigemptyset(&context.sa_mask);
2536 context.sa_flags = 0;
2537 if (sigaction(sig, &context, &ocontext) == -1)
2538 return SIG_ERR;
2539 return ocontext.sa_handler;
2540#else
2541 PyOS_sighandler_t oldhandler;
2542 oldhandler = signal(sig, handler);
2543#ifdef HAVE_SIGINTERRUPT
2544 siginterrupt(sig, 1);
2545#endif
2546 return oldhandler;
2547#endif
2548}
2549
2550#ifdef __cplusplus
2551}
2552#endif