blob: 4bb32abc4be1f3900de72f4d61e5f1e92667f5d4 [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
Victor Stinner4f98f462020-04-15 04:01:58 +020021#include <locale.h> // setlocale()
Nick Coghland6009512014-11-20 21:39:37 +100022
23#ifdef HAVE_SIGNAL_H
Victor Stinner4f98f462020-04-15 04:01:58 +020024# include <signal.h> // SIG_IGN
Nick Coghland6009512014-11-20 21:39:37 +100025#endif
26
27#ifdef HAVE_LANGINFO_H
Victor Stinner4f98f462020-04-15 04:01:58 +020028# include <langinfo.h> // nl_langinfo(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +100029#endif
30
31#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020032# undef BYTE
33# include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070034
Victor Stinner4f98f462020-04-15 04:01:58 +020035 extern PyTypeObject PyWindowsConsoleIO_Type;
36# define PyWindowsConsoleIO_Check(op) \
37 (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
Victor Stinner4f98f462020-04-15 04:01:58 +020040
Nick Coghland6009512014-11-20 21:39:37 +100041_Py_IDENTIFIER(flush);
42_Py_IDENTIFIER(name);
43_Py_IDENTIFIER(stdin);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060046_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100047
48#ifdef __cplusplus
49extern "C" {
50#endif
51
Nick Coghland6009512014-11-20 21:39:37 +100052
Victor Stinnerb45d2592019-06-20 00:05:23 +020053/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020054static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020055static PyStatus init_import_site(void);
Andy Lester75cd5bf2020-03-12 02:49:05 -050056static PyStatus init_set_builtins_open(void);
Victor Stinnerb45d2592019-06-20 00:05:23 +020057static PyStatus init_sys_streams(PyThreadState *tstate);
58static PyStatus init_signals(PyThreadState *tstate);
59static void call_py_exitfuncs(PyThreadState *tstate);
60static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020061static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100062
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080063int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080064_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010065static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066
Victor Stinner331a6a52019-05-27 16:39:22 +020067PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060068_PyRuntime_Initialize(void)
69{
70 /* XXX We only initialize once in the process, which aligns with
71 the static initialization of the former globals now found in
72 _PyRuntime. However, _PyRuntime *should* be initialized with
73 every Py_Initialize() call, but doing so breaks the runtime.
74 This is because the runtime state is not properly finalized
75 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010076 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020077 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010079 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080
81 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082}
83
84void
85_PyRuntime_Finalize(void)
86{
87 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010088 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
90
91int
92_Py_IsFinalizing(void)
93{
Victor Stinner7b3c2522020-03-07 00:24:23 +010094 return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
96
Nick Coghland6009512014-11-20 21:39:37 +100097/* Hack to force loading of object files */
98int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
99 PyOS_mystrnicmp; /* Python/pystrcmp.o */
100
101/* PyModule_GetWarningsModule is no longer necessary as of 2.6
102since _warnings is builtin. This API should not be used. */
103PyObject *
104PyModule_GetWarningsModule(void)
105{
106 return PyImport_ImportModule("warnings");
107}
108
Eric Snowc7ec9982017-05-23 23:00:52 -0700109
Eric Snow1abcf672017-05-23 21:46:51 -0700110/* APIs to access the initialization flags
111 *
112 * Can be called prior to Py_Initialize.
113 */
Nick Coghland6009512014-11-20 21:39:37 +1000114
Eric Snow1abcf672017-05-23 21:46:51 -0700115int
116_Py_IsCoreInitialized(void)
117{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600118 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700119}
Nick Coghland6009512014-11-20 21:39:37 +1000120
121int
122Py_IsInitialized(void)
123{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600124 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000125}
126
Nick Coghlan6ea41862017-06-11 13:16:15 +1000127
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000128/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
129 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000130 initializations fail, a fatal error is issued and the function does
131 not return. On return, the first thread and interpreter state have
132 been created.
133
134 Locking: you must hold the interpreter lock while calling this.
135 (If the lock has not yet been initialized, that's equivalent to
136 having the lock, but you cannot use multiple threads.)
137
138*/
139
Victor Stinner331a6a52019-05-27 16:39:22 +0200140static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200141init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000142{
143 PyObject *importlib;
144 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000145 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200146 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200147 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000148
149 /* Import _importlib through its frozen version, _frozen_importlib. */
150 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200151 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000152 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200153 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000154 PySys_FormatStderr("import _frozen_importlib # frozen\n");
155 }
156 importlib = PyImport_AddModule("_frozen_importlib");
157 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200158 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000159 }
160 interp->importlib = importlib;
161 Py_INCREF(interp->importlib);
162
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300163 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
164 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200165 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300166 Py_INCREF(interp->import_func);
167
Victor Stinnercd6e6942015-09-18 09:11:57 +0200168 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800169 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000170 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200171 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000172 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200173 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200174 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000175 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600176 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200177 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000178 }
179
Victor Stinnercd6e6942015-09-18 09:11:57 +0200180 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000181 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
182 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200183 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200184 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000185 }
186 Py_DECREF(value);
187 Py_DECREF(impmod);
188
Victor Stinner331a6a52019-05-27 16:39:22 +0200189 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000190}
191
Victor Stinner331a6a52019-05-27 16:39:22 +0200192static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200193init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700194{
195 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200196 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700197 "_install_external_importers", "");
198 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200199 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200200 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700201 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200202 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200203 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700204}
Nick Coghland6009512014-11-20 21:39:37 +1000205
Nick Coghlan6ea41862017-06-11 13:16:15 +1000206/* Helper functions to better handle the legacy C locale
207 *
208 * The legacy C locale assumes ASCII as the default text encoding, which
209 * causes problems not only for the CPython runtime, but also other
210 * components like GNU readline.
211 *
212 * Accordingly, when the CLI detects it, it attempts to coerce it to a
213 * more capable UTF-8 based alternative as follows:
214 *
215 * if (_Py_LegacyLocaleDetected()) {
216 * _Py_CoerceLegacyLocale();
217 * }
218 *
219 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
220 *
221 * Locale coercion also impacts the default error handler for the standard
222 * streams: while the usual default is "strict", the default for the legacy
223 * C locale and for any of the coercion target locales is "surrogateescape".
224 */
225
226int
Victor Stinner0f721472019-05-20 17:16:38 +0200227_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000228{
229#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200230 if (!warn) {
231 const char *locale_override = getenv("LC_ALL");
232 if (locale_override != NULL && *locale_override != '\0') {
233 /* Don't coerce C locale if the LC_ALL environment variable
234 is set */
235 return 0;
236 }
237 }
238
Nick Coghlan6ea41862017-06-11 13:16:15 +1000239 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000240 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
241 * the POSIX locale as a simple alias for the C locale, so
242 * we may also want to check for that explicitly.
243 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000244 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
245 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
246#else
247 /* Windows uses code pages instead of locales, so no locale is legacy */
248 return 0;
249#endif
250}
251
Victor Stinnerb0051362019-11-22 17:52:42 +0100252#ifndef MS_WINDOWS
Nick Coghlaneb817952017-06-18 12:29:42 +1000253static const char *_C_LOCALE_WARNING =
254 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
255 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
256 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
257 "locales is recommended.\n";
258
Nick Coghlaneb817952017-06-18 12:29:42 +1000259static void
Victor Stinner43125222019-04-24 18:23:53 +0200260emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000261{
Victor Stinner331a6a52019-05-27 16:39:22 +0200262 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200263 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200264 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000265 }
266}
Victor Stinnerb0051362019-11-22 17:52:42 +0100267#endif /* !defined(MS_WINDOWS) */
Nick Coghlaneb817952017-06-18 12:29:42 +1000268
Nick Coghlan6ea41862017-06-11 13:16:15 +1000269typedef struct _CandidateLocale {
270 const char *locale_name; /* The locale to try as a coercion target */
271} _LocaleCoercionTarget;
272
273static _LocaleCoercionTarget _TARGET_LOCALES[] = {
274 {"C.UTF-8"},
275 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000276 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000277 {NULL}
278};
279
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200280
281int
282_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000283{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200284 const _LocaleCoercionTarget *target = NULL;
285 for (target = _TARGET_LOCALES; target->locale_name; target++) {
286 if (strcmp(ctype_loc, target->locale_name) == 0) {
287 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000288 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200289 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200290 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291}
292
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200293
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100295static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
297 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
298
Victor Stinner0f721472019-05-20 17:16:38 +0200299static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200300_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301{
302 const char *newloc = target->locale_name;
303
304 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100305 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000306
307 /* Set the relevant locale environment variable */
308 if (setenv("LC_CTYPE", newloc, 1)) {
309 fprintf(stderr,
310 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200311 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200313 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100314 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000315 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000316
317 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100318 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200319 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000320}
321#endif
322
Victor Stinner0f721472019-05-20 17:16:38 +0200323int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200324_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000325{
Victor Stinner0f721472019-05-20 17:16:38 +0200326 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000327#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200328 char *oldloc = NULL;
329
330 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
331 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200332 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200333 }
334
Victor Stinner94540602017-12-16 04:54:22 +0100335 const char *locale_override = getenv("LC_ALL");
336 if (locale_override == NULL || *locale_override == '\0') {
337 /* LC_ALL is also not set (or is set to an empty string) */
338 const _LocaleCoercionTarget *target = NULL;
339 for (target = _TARGET_LOCALES; target->locale_name; target++) {
340 const char *new_locale = setlocale(LC_CTYPE,
341 target->locale_name);
342 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400343#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100344 /* Also ensure that nl_langinfo works in this locale */
345 char *codeset = nl_langinfo(CODESET);
346 if (!codeset || *codeset == '\0') {
347 /* CODESET is not set or empty, so skip coercion */
348 new_locale = NULL;
349 _Py_SetLocaleFromEnv(LC_CTYPE);
350 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000351 }
Victor Stinner94540602017-12-16 04:54:22 +0100352#endif
353 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200354 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200355 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000356 }
357 }
358 }
359 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200360
361 setlocale(LC_CTYPE, oldloc);
362
363done:
364 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000365#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200366 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000367}
368
xdegaye1588be62017-11-12 12:45:59 +0100369/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
370 * isolate the idiosyncrasies of different libc implementations. It reads the
371 * appropriate environment variable and uses its value to select the locale for
372 * 'category'. */
373char *
374_Py_SetLocaleFromEnv(int category)
375{
Victor Stinner353933e2018-11-23 13:08:26 +0100376 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100377#ifdef __ANDROID__
378 const char *locale;
379 const char **pvar;
380#ifdef PY_COERCE_C_LOCALE
381 const char *coerce_c_locale;
382#endif
383 const char *utf8_locale = "C.UTF-8";
384 const char *env_var_set[] = {
385 "LC_ALL",
386 "LC_CTYPE",
387 "LANG",
388 NULL,
389 };
390
391 /* Android setlocale(category, "") doesn't check the environment variables
392 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
393 * check the environment variables listed in env_var_set. */
394 for (pvar=env_var_set; *pvar; pvar++) {
395 locale = getenv(*pvar);
396 if (locale != NULL && *locale != '\0') {
397 if (strcmp(locale, utf8_locale) == 0 ||
398 strcmp(locale, "en_US.UTF-8") == 0) {
399 return setlocale(category, utf8_locale);
400 }
401 return setlocale(category, "C");
402 }
403 }
404
405 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
406 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
407 * Quote from POSIX section "8.2 Internationalization Variables":
408 * "4. If the LANG environment variable is not set or is set to the empty
409 * string, the implementation-defined default locale shall be used." */
410
411#ifdef PY_COERCE_C_LOCALE
412 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
413 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
414 /* Some other ported code may check the environment variables (e.g. in
415 * extension modules), so we make sure that they match the locale
416 * configuration */
417 if (setenv("LC_CTYPE", utf8_locale, 1)) {
418 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
419 "environment variable to %s\n", utf8_locale);
420 }
421 }
422#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100423 res = setlocale(category, utf8_locale);
424#else /* !defined(__ANDROID__) */
425 res = setlocale(category, "");
426#endif
427 _Py_ResetForceASCII();
428 return res;
xdegaye1588be62017-11-12 12:45:59 +0100429}
430
Nick Coghlan6ea41862017-06-11 13:16:15 +1000431
Eric Snow1abcf672017-05-23 21:46:51 -0700432/* Global initializations. Can be undone by Py_Finalize(). Don't
433 call this twice without an intervening Py_Finalize() call.
434
Victor Stinner331a6a52019-05-27 16:39:22 +0200435 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700436 must have a corresponding call to Py_Finalize.
437
438 Locking: you must hold the interpreter lock while calling these APIs.
439 (If the lock has not yet been initialized, that's equivalent to
440 having the lock, but you cannot use multiple threads.)
441
442*/
443
Victor Stinner331a6a52019-05-27 16:39:22 +0200444static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200445pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200446 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200447 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200448{
Victor Stinner331a6a52019-05-27 16:39:22 +0200449 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100450 PyThreadState *tstate = _PyThreadState_GET();
451 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200452 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100453 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200454 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100455
456 PyInterpreterState *interp = tstate->interp;
457 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200458 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100459 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100460
Victor Stinnere81f6e62020-06-08 18:12:59 +0200461 status = _PyConfig_Write(config, runtime);
462 if (_PyStatus_EXCEPTION(status)) {
463 return status;
464 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200465
Victor Stinnerda7933e2020-04-13 03:04:28 +0200466 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200467 if (_PyStatus_EXCEPTION(status)) {
468 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200469 }
Victor Stinnerda7933e2020-04-13 03:04:28 +0200470 config = _PyInterpreterState_GetConfig(interp);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200471
Victor Stinner331a6a52019-05-27 16:39:22 +0200472 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200473 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200474 if (_PyStatus_EXCEPTION(status)) {
475 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200476 }
477 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200478 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200479}
480
481
Victor Stinner331a6a52019-05-27 16:39:22 +0200482static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200483pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200484 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000485{
Victor Stinner43125222019-04-24 18:23:53 +0200486 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200487 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200488 }
Victor Stinnerda273412017-12-15 01:46:02 +0100489
Victor Stinnere81f6e62020-06-08 18:12:59 +0200490 PyStatus status = _PyConfig_Write(config, runtime);
491 if (_PyStatus_EXCEPTION(status)) {
492 return status;
493 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600494
Eric Snow1abcf672017-05-23 21:46:51 -0700495 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
496 * threads behave a little more gracefully at interpreter shutdown.
497 * We clobber it here so the new interpreter can start with a clean
498 * slate.
499 *
500 * However, this may still lead to misbehaviour if there are daemon
501 * threads still hanging around from a previous Py_Initialize/Finalize
502 * pair :(
503 */
Victor Stinner7b3c2522020-03-07 00:24:23 +0100504 _PyRuntimeState_SetFinalizing(runtime, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600505
Victor Stinnere81f6e62020-06-08 18:12:59 +0200506 status = _Py_HashRandomization_Init(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200507 if (_PyStatus_EXCEPTION(status)) {
508 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800509 }
510
Victor Stinner331a6a52019-05-27 16:39:22 +0200511 status = _PyInterpreterState_Enable(runtime);
512 if (_PyStatus_EXCEPTION(status)) {
513 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800514 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200515 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100516}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800517
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100518
Victor Stinner331a6a52019-05-27 16:39:22 +0200519static PyStatus
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200520init_interp_create_gil(PyThreadState *tstate)
521{
522 PyStatus status;
523
524 /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
525 only called here. */
526 _PyEval_FiniGIL(tstate);
527
528 /* Auto-thread-state API */
529 status = _PyGILState_Init(tstate);
530 if (_PyStatus_EXCEPTION(status)) {
531 return status;
532 }
533
534 /* Create the GIL and take it */
535 status = _PyEval_InitGIL(tstate);
536 if (_PyStatus_EXCEPTION(status)) {
537 return status;
538 }
539
540 return _PyStatus_OK();
541}
542
543
544static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200545pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200546 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200547 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100548{
549 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100550 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200551 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100552 }
553
Victor Stinnerda7933e2020-04-13 03:04:28 +0200554 PyStatus status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200555 if (_PyStatus_EXCEPTION(status)) {
556 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100557 }
Nick Coghland6009512014-11-20 21:39:37 +1000558
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200559 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200560 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200561 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200562 }
Nick Coghland6009512014-11-20 21:39:37 +1000563 (void) PyThreadState_Swap(tstate);
564
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200565 status = init_interp_create_gil(tstate);
Victor Stinner111e4ee2020-03-09 21:24:14 +0100566 if (_PyStatus_EXCEPTION(status)) {
567 return status;
568 }
Victor Stinner2914bb32018-01-29 11:57:45 +0100569
Victor Stinnerb45d2592019-06-20 00:05:23 +0200570 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200571 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100572}
Nick Coghland6009512014-11-20 21:39:37 +1000573
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100574
Victor Stinner331a6a52019-05-27 16:39:22 +0200575static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100576pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100577{
Victor Stinner444b39b2019-11-20 01:18:11 +0100578 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100579 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100580
Victor Stinner01b1cc12019-11-20 02:27:56 +0100581 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100582 if (_PyStatus_EXCEPTION(status)) {
583 return status;
584 }
585
Victor Stinnere7e699e2019-11-20 12:08:13 +0100586 if (is_main_interp) {
587 status = _PyTypes_Init();
588 if (_PyStatus_EXCEPTION(status)) {
589 return status;
590 }
Victor Stinner630c8df2019-12-17 13:02:18 +0100591 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100592
Victor Stinner630c8df2019-12-17 13:02:18 +0100593
594 if (!_PyLong_Init(tstate)) {
595 return _PyStatus_ERR("can't init longs");
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100596 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100597
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100598 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100599 status = _PyUnicode_Init();
600 if (_PyStatus_EXCEPTION(status)) {
601 return status;
602 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100603 }
604
Victor Stinner331a6a52019-05-27 16:39:22 +0200605 status = _PyExc_Init();
606 if (_PyStatus_EXCEPTION(status)) {
607 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100608 }
609
Victor Stinnere7e699e2019-11-20 12:08:13 +0100610 if (is_main_interp) {
611 if (!_PyFloat_Init()) {
612 return _PyStatus_ERR("can't init float");
613 }
Nick Coghland6009512014-11-20 21:39:37 +1000614
Victor Stinnere7e699e2019-11-20 12:08:13 +0100615 if (_PyStructSequence_Init() < 0) {
616 return _PyStatus_ERR("can't initialize structseq");
617 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100618 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200619
Victor Stinner331a6a52019-05-27 16:39:22 +0200620 status = _PyErr_Init();
621 if (_PyStatus_EXCEPTION(status)) {
622 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200623 }
624
Victor Stinnere7e699e2019-11-20 12:08:13 +0100625 if (is_main_interp) {
626 if (!_PyContext_Init()) {
627 return _PyStatus_ERR("can't init context");
628 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100629 }
630
Victor Stinner331a6a52019-05-27 16:39:22 +0200631 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100632}
633
634
Victor Stinner331a6a52019-05-27 16:39:22 +0200635static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200636pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100637{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100638 assert(!_PyErr_Occurred(tstate));
639
Victor Stinnerb45d2592019-06-20 00:05:23 +0200640 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641 if (bimod == NULL) {
Victor Stinner2582d462019-11-22 19:24:49 +0100642 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100643 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100644
Victor Stinner2582d462019-11-22 19:24:49 +0100645 PyInterpreterState *interp = tstate->interp;
646 if (_PyImport_FixupBuiltin(bimod, "builtins", interp->modules) < 0) {
647 goto error;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100648 }
Victor Stinner2582d462019-11-22 19:24:49 +0100649
650 PyObject *builtins_dict = PyModule_GetDict(bimod);
651 if (builtins_dict == NULL) {
652 goto error;
653 }
654 Py_INCREF(builtins_dict);
655 interp->builtins = builtins_dict;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100656
Victor Stinner331a6a52019-05-27 16:39:22 +0200657 PyStatus status = _PyBuiltins_AddExceptions(bimod);
658 if (_PyStatus_EXCEPTION(status)) {
659 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100660 }
Victor Stinner2582d462019-11-22 19:24:49 +0100661
662 interp->builtins_copy = PyDict_Copy(interp->builtins);
663 if (interp->builtins_copy == NULL) {
664 goto error;
665 }
Pablo Galindob96c6b02019-12-04 11:19:59 +0000666 Py_DECREF(bimod);
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100667
668 assert(!_PyErr_Occurred(tstate));
669
Victor Stinner331a6a52019-05-27 16:39:22 +0200670 return _PyStatus_OK();
Victor Stinner2582d462019-11-22 19:24:49 +0100671
672error:
Pablo Galindob96c6b02019-12-04 11:19:59 +0000673 Py_XDECREF(bimod);
Victor Stinner2582d462019-11-22 19:24:49 +0100674 return _PyStatus_ERR("can't initialize builtins module");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100675}
676
677
Victor Stinner331a6a52019-05-27 16:39:22 +0200678static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200679pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100680{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100681 assert(!_PyErr_Occurred(tstate));
Victor Stinnerb45d2592019-06-20 00:05:23 +0200682
Victor Stinner2582d462019-11-22 19:24:49 +0100683 PyStatus status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200684 if (_PyStatus_EXCEPTION(status)) {
685 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800686 }
Nick Coghland6009512014-11-20 21:39:37 +1000687
Victor Stinnerda7933e2020-04-13 03:04:28 +0200688 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100689 if (_Py_IsMainInterpreter(tstate)) {
690 /* Initialize _warnings. */
Victor Stinner66b79732020-03-02 15:02:18 +0100691 status = _PyWarnings_InitState(tstate);
692 if (_PyStatus_EXCEPTION(status)) {
693 return status;
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100694 }
Nick Coghland6009512014-11-20 21:39:37 +1000695
Victor Stinner2ec1a1b2019-11-22 21:54:33 +0100696 if (config->_install_importlib) {
697 status = _PyConfig_WritePathConfig(config);
698 if (_PyStatus_EXCEPTION(status)) {
699 return status;
700 }
Victor Stinnerb1147e42018-07-21 02:06:16 +0200701 }
702 }
703
Eric Snow1abcf672017-05-23 21:46:51 -0700704 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200705 if (config->_install_importlib) {
706 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200707 if (_PyStatus_EXCEPTION(status)) {
708 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800709 }
Eric Snow1abcf672017-05-23 21:46:51 -0700710 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100711
712 assert(!_PyErr_Occurred(tstate));
713
Victor Stinner331a6a52019-05-27 16:39:22 +0200714 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100715}
716
717
Victor Stinner331a6a52019-05-27 16:39:22 +0200718static PyStatus
Victor Stinnerd863ade2019-12-06 03:37:07 +0100719pycore_interp_init(PyThreadState *tstate)
720{
721 PyStatus status;
Victor Stinner080ee5a2019-12-08 21:55:58 +0100722 PyObject *sysmod = NULL;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100723
724 status = pycore_init_types(tstate);
725 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100726 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100727 }
728
Victor Stinnerd863ade2019-12-06 03:37:07 +0100729 status = _PySys_Create(tstate, &sysmod);
730 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100731 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100732 }
733
734 status = pycore_init_builtins(tstate);
735 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner080ee5a2019-12-08 21:55:58 +0100736 goto done;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100737 }
738
Victor Stinner080ee5a2019-12-08 21:55:58 +0100739 status = pycore_init_import_warnings(tstate, sysmod);
740
741done:
742 /* sys.modules['sys'] contains a strong reference to the module */
743 Py_XDECREF(sysmod);
744 return status;
Victor Stinnerd863ade2019-12-06 03:37:07 +0100745}
746
747
748static PyStatus
Victor Stinner331a6a52019-05-27 16:39:22 +0200749pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200750 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200751 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100752{
Victor Stinner331a6a52019-05-27 16:39:22 +0200753 PyStatus status = pycore_init_runtime(runtime, config);
754 if (_PyStatus_EXCEPTION(status)) {
755 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100756 }
757
Victor Stinnerb45d2592019-06-20 00:05:23 +0200758 PyThreadState *tstate;
759 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200760 if (_PyStatus_EXCEPTION(status)) {
761 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100762 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200763 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100764
Victor Stinnerd863ade2019-12-06 03:37:07 +0100765 status = pycore_interp_init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200766 if (_PyStatus_EXCEPTION(status)) {
767 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100768 }
Eric Snow1abcf672017-05-23 21:46:51 -0700769
770 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200771 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200772 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700773}
774
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100775
Victor Stinner331a6a52019-05-27 16:39:22 +0200776PyStatus
777_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100778{
Victor Stinner331a6a52019-05-27 16:39:22 +0200779 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100780
Victor Stinner6d1c4672019-05-20 11:02:00 +0200781 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200782 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200783 }
784
Victor Stinner331a6a52019-05-27 16:39:22 +0200785 status = _PyRuntime_Initialize();
786 if (_PyStatus_EXCEPTION(status)) {
787 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100788 }
Victor Stinner43125222019-04-24 18:23:53 +0200789 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100790
Victor Stinnerd3b90412019-09-17 23:59:51 +0200791 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100792 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200793 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100794 }
795
Victor Stinnerd3b90412019-09-17 23:59:51 +0200796 /* Note: preinitialized remains 1 on error, it is only set to 0
797 at exit on success. */
798 runtime->preinitializing = 1;
799
Victor Stinner331a6a52019-05-27 16:39:22 +0200800 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200801
802 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
803 if (_PyStatus_EXCEPTION(status)) {
804 return status;
805 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100806
Victor Stinner331a6a52019-05-27 16:39:22 +0200807 status = _PyPreConfig_Read(&config, args);
808 if (_PyStatus_EXCEPTION(status)) {
809 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100810 }
811
Victor Stinner331a6a52019-05-27 16:39:22 +0200812 status = _PyPreConfig_Write(&config);
813 if (_PyStatus_EXCEPTION(status)) {
814 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100815 }
816
Victor Stinnerd3b90412019-09-17 23:59:51 +0200817 runtime->preinitializing = 0;
818 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200819 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100820}
821
Victor Stinner70005ac2019-05-02 15:25:34 -0400822
Victor Stinner331a6a52019-05-27 16:39:22 +0200823PyStatus
824Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100825{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100826 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400827 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100828}
829
830
Victor Stinner331a6a52019-05-27 16:39:22 +0200831PyStatus
832Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100833{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100834 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400835 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100836}
837
838
Victor Stinner331a6a52019-05-27 16:39:22 +0200839PyStatus
840Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100841{
Victor Stinner70005ac2019-05-02 15:25:34 -0400842 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100843}
844
845
Victor Stinner331a6a52019-05-27 16:39:22 +0200846PyStatus
847_Py_PreInitializeFromConfig(const PyConfig *config,
848 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100849{
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200851
Victor Stinner331a6a52019-05-27 16:39:22 +0200852 PyStatus status = _PyRuntime_Initialize();
853 if (_PyStatus_EXCEPTION(status)) {
854 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200855 }
856 _PyRuntimeState *runtime = &_PyRuntime;
857
Victor Stinnerd3b90412019-09-17 23:59:51 +0200858 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200859 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200860 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400861 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200862
Victor Stinner331a6a52019-05-27 16:39:22 +0200863 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200864
Victor Stinner3c30a762019-10-01 10:56:37 +0200865 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200866
Victor Stinner331a6a52019-05-27 16:39:22 +0200867 if (!config->parse_argv) {
868 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200869 }
870 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200871 _PyArgv config_args = {
872 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200873 .argc = config->argv.length,
874 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200875 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200876 }
877 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200878 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200879 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100880}
881
882
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100883/* Begin interpreter initialization
884 *
885 * On return, the first thread and interpreter state have been created,
886 * but the compiler, signal handling, multithreading and
887 * multiple interpreter support, and codec infrastructure are not yet
888 * available.
889 *
890 * The import system will support builtin and frozen modules only.
891 * The only supported io is writing to sys.stderr
892 *
893 * If any operation invoked by this function fails, a fatal error is
894 * issued and the function does not return.
895 *
896 * Any code invoked from this function should *not* assume it has access
897 * to the Python C API (unless the API is explicitly listed as being
898 * safe to call without calling Py_Initialize first)
899 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200900static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200901pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200902 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200903 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200904{
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200906
Victor Stinner331a6a52019-05-27 16:39:22 +0200907 status = _Py_PreInitializeFromConfig(src_config, NULL);
908 if (_PyStatus_EXCEPTION(status)) {
909 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200910 }
911
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200913 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200914
Victor Stinner331a6a52019-05-27 16:39:22 +0200915 status = _PyConfig_Copy(&config, src_config);
916 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200917 goto done;
918 }
919
Victor Stinner331a6a52019-05-27 16:39:22 +0200920 status = PyConfig_Read(&config);
921 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200922 goto done;
923 }
924
925 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200926 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200927 }
928 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200929 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200930 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200931 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200932 goto done;
933 }
934
935done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200936 PyConfig_Clear(&config);
937 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200938}
939
Victor Stinner5ac27a52019-03-27 13:40:14 +0100940
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200941/* Py_Initialize() has already been called: update the main interpreter
942 configuration. Example of bpo-34008: Py_Main() called after
943 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200944static PyStatus
Victor Stinnerb0051362019-11-22 17:52:42 +0100945_Py_ReconfigureMainInterpreter(PyThreadState *tstate)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200946{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200947 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100948
Victor Stinner331a6a52019-05-27 16:39:22 +0200949 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100950 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200951 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100952 }
953
Victor Stinnerb0051362019-11-22 17:52:42 +0100954 int res = PyDict_SetItemString(tstate->interp->sysdict, "argv", argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100955 Py_DECREF(argv);
956 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200957 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200958 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200959 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200960}
961
Victor Stinnerb0051362019-11-22 17:52:42 +0100962
963static PyStatus
964init_interp_main(PyThreadState *tstate)
965{
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100966 assert(!_PyErr_Occurred(tstate));
967
Victor Stinnerb0051362019-11-22 17:52:42 +0100968 PyStatus status;
969 int is_main_interp = _Py_IsMainInterpreter(tstate);
970 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200971 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerb0051362019-11-22 17:52:42 +0100972
973 if (!config->_install_importlib) {
974 /* Special mode for freeze_importlib: run with no import system
975 *
976 * This means anything which needs support from extension modules
977 * or pure Python code in the standard library won't work.
978 */
979 if (is_main_interp) {
980 interp->runtime->initialized = 1;
981 }
982 return _PyStatus_OK();
983 }
984
985 if (is_main_interp) {
986 if (_PyTime_Init() < 0) {
987 return _PyStatus_ERR("can't initialize time");
988 }
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100989 }
Victor Stinnerb0051362019-11-22 17:52:42 +0100990
Victor Stinner81fe5bd2019-12-06 02:43:30 +0100991 if (_PySys_InitMain(tstate) < 0) {
992 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerb0051362019-11-22 17:52:42 +0100993 }
994
995 status = init_importlib_external(tstate);
996 if (_PyStatus_EXCEPTION(status)) {
997 return status;
998 }
999
1000 if (is_main_interp) {
1001 /* initialize the faulthandler module */
1002 status = _PyFaulthandler_Init(config->faulthandler);
1003 if (_PyStatus_EXCEPTION(status)) {
1004 return status;
1005 }
1006 }
1007
1008 status = _PyUnicode_InitEncodings(tstate);
1009 if (_PyStatus_EXCEPTION(status)) {
1010 return status;
1011 }
1012
1013 if (is_main_interp) {
1014 if (config->install_signal_handlers) {
1015 status = init_signals(tstate);
1016 if (_PyStatus_EXCEPTION(status)) {
1017 return status;
1018 }
1019 }
1020
1021 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
1022 return _PyStatus_ERR("can't initialize tracemalloc");
1023 }
1024 }
1025
1026 status = init_sys_streams(tstate);
1027 if (_PyStatus_EXCEPTION(status)) {
1028 return status;
1029 }
1030
Andy Lester75cd5bf2020-03-12 02:49:05 -05001031 status = init_set_builtins_open();
Victor Stinnerb0051362019-11-22 17:52:42 +01001032 if (_PyStatus_EXCEPTION(status)) {
1033 return status;
1034 }
1035
1036 status = add_main_module(interp);
1037 if (_PyStatus_EXCEPTION(status)) {
1038 return status;
1039 }
1040
1041 if (is_main_interp) {
1042 /* Initialize warnings. */
1043 PyObject *warnoptions = PySys_GetObject("warnoptions");
1044 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
1045 {
1046 PyObject *warnings_module = PyImport_ImportModule("warnings");
1047 if (warnings_module == NULL) {
1048 fprintf(stderr, "'import warnings' failed; traceback:\n");
1049 _PyErr_Print(tstate);
1050 }
1051 Py_XDECREF(warnings_module);
1052 }
1053
1054 interp->runtime->initialized = 1;
1055 }
1056
1057 if (config->site_import) {
1058 status = init_import_site();
1059 if (_PyStatus_EXCEPTION(status)) {
1060 return status;
1061 }
1062 }
1063
1064 if (is_main_interp) {
1065#ifndef MS_WINDOWS
1066 emit_stderr_warning_for_legacy_locale(interp->runtime);
1067#endif
1068 }
1069
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001070 assert(!_PyErr_Occurred(tstate));
1071
Victor Stinnerb0051362019-11-22 17:52:42 +01001072 return _PyStatus_OK();
1073}
1074
1075
Eric Snowc7ec9982017-05-23 23:00:52 -07001076/* Update interpreter state based on supplied configuration settings
1077 *
1078 * After calling this function, most of the restrictions on the interpreter
1079 * are lifted. The only remaining incomplete settings are those related
1080 * to the main module (sys.argv[0], __main__ metadata)
1081 *
1082 * Calling this when the interpreter is not initializing, is already
1083 * initialized or without a valid current thread state is a fatal error.
1084 * Other errors should be reported as normal Python exceptions with a
1085 * non-zero return code.
1086 */
Victor Stinner331a6a52019-05-27 16:39:22 +02001087static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001088pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -07001089{
Victor Stinnerb0051362019-11-22 17:52:42 +01001090 PyInterpreterState *interp = tstate->interp;
1091 if (!interp->runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001092 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -07001093 }
Eric Snowc7ec9982017-05-23 23:00:52 -07001094
Victor Stinnerb0051362019-11-22 17:52:42 +01001095 if (interp->runtime->initialized) {
1096 return _Py_ReconfigureMainInterpreter(tstate);
Victor Stinnerfb47bca2018-07-20 17:34:23 +02001097 }
1098
Victor Stinnerb0051362019-11-22 17:52:42 +01001099 PyStatus status = init_interp_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001100 if (_PyStatus_EXCEPTION(status)) {
1101 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001102 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001103 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001104}
1105
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001106
Victor Stinner331a6a52019-05-27 16:39:22 +02001107PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001108_Py_InitializeMain(void)
1109{
Victor Stinner331a6a52019-05-27 16:39:22 +02001110 PyStatus status = _PyRuntime_Initialize();
1111 if (_PyStatus_EXCEPTION(status)) {
1112 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001113 }
1114 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001115 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001116 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001117}
1118
1119
Victor Stinner331a6a52019-05-27 16:39:22 +02001120PyStatus
1121Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001122{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001123 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001124 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001125 }
1126
Victor Stinner331a6a52019-05-27 16:39:22 +02001127 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001128
Victor Stinner331a6a52019-05-27 16:39:22 +02001129 status = _PyRuntime_Initialize();
1130 if (_PyStatus_EXCEPTION(status)) {
1131 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001132 }
1133 _PyRuntimeState *runtime = &_PyRuntime;
1134
Victor Stinnerb45d2592019-06-20 00:05:23 +02001135 PyThreadState *tstate = NULL;
1136 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001137 if (_PyStatus_EXCEPTION(status)) {
1138 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001139 }
Victor Stinnerda7933e2020-04-13 03:04:28 +02001140 config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001141
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001142 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001143 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001144 if (_PyStatus_EXCEPTION(status)) {
1145 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001146 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001147 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001148
Victor Stinner331a6a52019-05-27 16:39:22 +02001149 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001150}
1151
1152
Eric Snow1abcf672017-05-23 21:46:51 -07001153void
Nick Coghland6009512014-11-20 21:39:37 +10001154Py_InitializeEx(int install_sigs)
1155{
Victor Stinner331a6a52019-05-27 16:39:22 +02001156 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001157
Victor Stinner331a6a52019-05-27 16:39:22 +02001158 status = _PyRuntime_Initialize();
1159 if (_PyStatus_EXCEPTION(status)) {
1160 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001161 }
1162 _PyRuntimeState *runtime = &_PyRuntime;
1163
1164 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001165 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1166 return;
1167 }
1168
Victor Stinner331a6a52019-05-27 16:39:22 +02001169 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001170 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001171
Victor Stinner1dc6e392018-07-25 02:49:17 +02001172 config.install_signal_handlers = install_sigs;
1173
Victor Stinner331a6a52019-05-27 16:39:22 +02001174 status = Py_InitializeFromConfig(&config);
1175 if (_PyStatus_EXCEPTION(status)) {
1176 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001177 }
Nick Coghland6009512014-11-20 21:39:37 +10001178}
1179
1180void
1181Py_Initialize(void)
1182{
1183 Py_InitializeEx(1);
1184}
1185
1186
Nick Coghland6009512014-11-20 21:39:37 +10001187/* Flush stdout and stderr */
1188
1189static int
1190file_is_closed(PyObject *fobj)
1191{
1192 int r;
1193 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1194 if (tmp == NULL) {
1195 PyErr_Clear();
1196 return 0;
1197 }
1198 r = PyObject_IsTrue(tmp);
1199 Py_DECREF(tmp);
1200 if (r < 0)
1201 PyErr_Clear();
1202 return r > 0;
1203}
1204
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001205static int
Nick Coghland6009512014-11-20 21:39:37 +10001206flush_std_files(void)
1207{
1208 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1209 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1210 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001211 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001212
1213 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001214 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001215 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001216 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001217 status = -1;
1218 }
Nick Coghland6009512014-11-20 21:39:37 +10001219 else
1220 Py_DECREF(tmp);
1221 }
1222
1223 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001224 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001225 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001226 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001227 status = -1;
1228 }
Nick Coghland6009512014-11-20 21:39:37 +10001229 else
1230 Py_DECREF(tmp);
1231 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001232
1233 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001234}
1235
1236/* Undo the effect of Py_Initialize().
1237
1238 Beware: if multiple interpreter and/or thread states exist, these
1239 are not wiped out; only the current thread and interpreter state
1240 are deleted. But since everything else is deleted, those other
1241 interpreter and thread states should no longer be used.
1242
1243 (XXX We should do better, e.g. wipe out all interpreters and
1244 threads.)
1245
1246 Locking: as above.
1247
1248*/
1249
Victor Stinner7eee5be2019-11-20 10:38:34 +01001250
1251static void
1252finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1253{
Victor Stinner3744ed22020-06-05 01:39:24 +02001254 _PyFrame_Fini(tstate);
Victor Stinner78a02c22020-06-05 02:34:14 +02001255 _PyAsyncGen_Fini(tstate);
Victor Stinnere005ead2020-06-05 02:56:37 +02001256 _PyContext_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001257
Victor Stinner261cfed2020-06-23 14:07:52 +02001258 _PySet_Fini(tstate);
Victor Stinnerb4e85ca2020-06-23 11:33:18 +02001259 _PyDict_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001260 _PyList_Fini(tstate);
1261 _PyTuple_Fini(tstate);
1262
1263 _PySlice_Fini(tstate);
Victor Stinner3d483342019-11-22 12:27:50 +01001264
Victor Stinnerc41eed12020-06-23 15:54:35 +02001265 _PyBytes_Fini(tstate);
Victor Stinner7907f8c2020-06-08 01:22:36 +02001266 _PyUnicode_Fini(tstate);
1267 _PyFloat_Fini(tstate);
1268 _PyLong_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001269}
1270
1271
1272static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001273finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001274{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001275 int is_main_interp = _Py_IsMainInterpreter(tstate);
1276
Victor Stinner7eee5be2019-11-20 10:38:34 +01001277 /* Clear interpreter state and all thread states */
1278 PyInterpreterState_Clear(tstate->interp);
1279
Pablo Galindoac0e1c22019-12-04 11:51:03 +00001280 /* Trigger a GC collection on subinterpreters*/
1281 if (!is_main_interp) {
1282 _PyGC_CollectNoFail();
1283 }
1284
Victor Stinner88ec9192020-06-05 02:05:41 +02001285 _PyGC_Fini(tstate);
1286
Victor Stinner7907f8c2020-06-08 01:22:36 +02001287 if (is_main_interp) {
1288 _Py_HashRandomization_Fini();
1289 _PyArg_Fini();
1290 _Py_ClearFileSystemEncoding();
1291 }
1292
1293 _PyWarnings_Fini(tstate->interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001294
1295 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001296 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001297 }
Victor Stinner7907f8c2020-06-08 01:22:36 +02001298
1299 finalize_interp_types(tstate, is_main_interp);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001300}
1301
1302
1303static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001304finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001305{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001306 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001307 /* Cleanup auto-thread-state */
1308 _PyGILState_Fini(tstate);
1309 }
1310
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001311 /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
1312 fail when it is being awaited by another running daemon thread (see
1313 bpo-9901). Instead pycore_create_interpreter() destroys the previously
1314 created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
1315 called multiple times. */
1316
Victor Stinner7eee5be2019-11-20 10:38:34 +01001317 PyInterpreterState_Delete(tstate->interp);
1318}
1319
1320
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001321int
1322Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001323{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001324 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001325
Victor Stinner8e91c242019-04-24 17:24:01 +02001326 _PyRuntimeState *runtime = &_PyRuntime;
1327 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001328 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001329 }
Nick Coghland6009512014-11-20 21:39:37 +10001330
Victor Stinnere225beb2019-06-03 18:14:24 +02001331 /* Get current thread state and interpreter pointer */
1332 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1333 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001334
Victor Stinnerb45d2592019-06-20 00:05:23 +02001335 // Wrap up existing "threading"-module-created, non-daemon threads.
1336 wait_for_thread_shutdown(tstate);
1337
1338 // Make any remaining pending calls.
Victor Stinner2b1df452020-01-13 18:46:59 +01001339 _Py_FinishPendingCalls(tstate);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001340
Nick Coghland6009512014-11-20 21:39:37 +10001341 /* The interpreter is still entirely intact at this point, and the
1342 * exit funcs may be relying on that. In particular, if some thread
1343 * or exit func is still waiting to do an import, the import machinery
1344 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001345 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001346 * Note that Threading.py uses an exit func to do a join on all the
1347 * threads created thru it, so this also protects pending imports in
1348 * the threads created via Threading.
1349 */
Nick Coghland6009512014-11-20 21:39:37 +10001350
Victor Stinnerb45d2592019-06-20 00:05:23 +02001351 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001352
Victor Stinnerda273412017-12-15 01:46:02 +01001353 /* Copy the core config, PyInterpreterState_Delete() free
1354 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001355#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001356 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001357#endif
1358#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001359 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001360#endif
1361#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001362 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001363#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001364
Victor Stinnereb4e2ae2020-03-08 11:57:45 +01001365 /* Remaining daemon threads will automatically exit
1366 when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
Victor Stinner7b3c2522020-03-07 00:24:23 +01001367 _PyRuntimeState_SetFinalizing(runtime, tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +02001368 runtime->initialized = 0;
1369 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001370
Victor Stinner9ad58ac2020-03-09 23:37:49 +01001371 /* Destroy the state of all threads of the interpreter, except of the
1372 current thread. In practice, only daemon threads should still be alive,
1373 except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
1374 Clear frames of other threads to call objects destructors. Destructors
1375 will be called in the current Python thread. Since
1376 _PyRuntimeState_SetFinalizing() has been called, no other Python thread
1377 can take the GIL at this point: if they try, they will exit
1378 immediately. */
1379 _PyThreadState_DeleteExcept(runtime, tstate);
1380
Victor Stinnere0deff32015-03-24 13:46:18 +01001381 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001382 if (flush_std_files() < 0) {
1383 status = -1;
1384 }
Nick Coghland6009512014-11-20 21:39:37 +10001385
1386 /* Disable signal handling */
1387 PyOS_FiniInterrupts();
1388
1389 /* Collect garbage. This may call finalizers; it's nice to call these
1390 * before all modules are destroyed.
1391 * XXX If a __del__ or weakref callback is triggered here, and tries to
1392 * XXX import a module, bad things can happen, because Python no
1393 * XXX longer believes it's initialized.
1394 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1395 * XXX is easy to provoke that way. I've also seen, e.g.,
1396 * XXX Exception exceptions.ImportError: 'No module named sha'
1397 * XXX in <function callback at 0x008F5718> ignored
1398 * XXX but I'm unclear on exactly how that one happens. In any case,
1399 * XXX I haven't seen a real-life report of either of these.
1400 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001401 _PyGC_CollectIfEnabled();
Eric Snowdae02762017-09-14 00:35:58 -07001402
Steve Dowerb82e17e2019-05-23 08:45:22 -07001403 /* Clear all loghooks */
Victor Stinner08faf002020-03-26 18:57:32 +01001404 _PySys_ClearAuditHooks(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001405
Nick Coghland6009512014-11-20 21:39:37 +10001406 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001407 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001408
Inada Naoki91234a12019-06-03 21:30:58 +09001409 /* Print debug stats if any */
1410 _PyEval_Fini();
1411
Victor Stinnere0deff32015-03-24 13:46:18 +01001412 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001413 if (flush_std_files() < 0) {
1414 status = -1;
1415 }
Nick Coghland6009512014-11-20 21:39:37 +10001416
1417 /* Collect final garbage. This disposes of cycles created by
1418 * class definitions, for example.
1419 * XXX This is disabled because it caused too many problems. If
1420 * XXX a __del__ or weakref callback triggers here, Python code has
1421 * XXX a hard time running, because even the sys module has been
1422 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1423 * XXX One symptom is a sequence of information-free messages
1424 * XXX coming from threads (if a __del__ or callback is invoked,
1425 * XXX other threads can execute too, and any exception they encounter
1426 * XXX triggers a comedy of errors as subsystem after subsystem
1427 * XXX fails to find what it *expects* to find in sys to help report
1428 * XXX the exception and consequent unexpected failures). I've also
1429 * XXX seen segfaults then, after adding print statements to the
1430 * XXX Python code getting called.
1431 */
1432#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001433 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001434#endif
1435
1436 /* Disable tracemalloc after all Python objects have been destroyed,
1437 so it is possible to use tracemalloc in objects destructor. */
1438 _PyTraceMalloc_Fini();
1439
1440 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1441 _PyImport_Fini();
1442
1443 /* Cleanup typeobject.c's internal caches. */
1444 _PyType_Fini();
1445
1446 /* unload faulthandler module */
1447 _PyFaulthandler_Fini();
1448
Nick Coghland6009512014-11-20 21:39:37 +10001449 /* dump hash stats */
1450 _PyHash_Fini();
1451
Eric Snowdae02762017-09-14 00:35:58 -07001452#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001453 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001454 _PyDebug_PrintTotalRefs();
1455 }
Eric Snowdae02762017-09-14 00:35:58 -07001456#endif
Nick Coghland6009512014-11-20 21:39:37 +10001457
1458#ifdef Py_TRACE_REFS
1459 /* Display all objects still alive -- this can invoke arbitrary
1460 * __repr__ overrides, so requires a mostly-intact interpreter.
1461 * Alas, a lot of stuff may still be alive now that will be cleaned
1462 * up later.
1463 */
Victor Stinnerda273412017-12-15 01:46:02 +01001464 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001465 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001466 }
Nick Coghland6009512014-11-20 21:39:37 +10001467#endif /* Py_TRACE_REFS */
1468
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001469 finalize_interp_clear(tstate);
1470 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001471
1472#ifdef Py_TRACE_REFS
1473 /* Display addresses (& refcnts) of all objects still alive.
1474 * An address can be used to find the repr of the object, printed
1475 * above by _Py_PrintReferences.
1476 */
Victor Stinnerda273412017-12-15 01:46:02 +01001477 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001478 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001479 }
Nick Coghland6009512014-11-20 21:39:37 +10001480#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001481#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001482 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001483 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001484 }
Nick Coghland6009512014-11-20 21:39:37 +10001485#endif
1486
Victor Stinner8e91c242019-04-24 17:24:01 +02001487 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001488
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001489 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001490 return status;
1491}
1492
1493void
1494Py_Finalize(void)
1495{
1496 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001497}
1498
Victor Stinnerb0051362019-11-22 17:52:42 +01001499
Nick Coghland6009512014-11-20 21:39:37 +10001500/* Create and initialize a new interpreter and thread, and return the
1501 new thread. This requires that Py_Initialize() has been called
1502 first.
1503
1504 Unsuccessful initialization yields a NULL pointer. Note that *no*
1505 exception information is available even in this case -- the
1506 exception information is held in the thread, and there is no
1507 thread.
1508
1509 Locking: as above.
1510
1511*/
1512
Victor Stinner331a6a52019-05-27 16:39:22 +02001513static PyStatus
Victor Stinner252346a2020-05-01 11:33:44 +02001514new_interpreter(PyThreadState **tstate_p, int isolated_subinterpreter)
Nick Coghland6009512014-11-20 21:39:37 +10001515{
Victor Stinner331a6a52019-05-27 16:39:22 +02001516 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001517
Victor Stinner331a6a52019-05-27 16:39:22 +02001518 status = _PyRuntime_Initialize();
1519 if (_PyStatus_EXCEPTION(status)) {
1520 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001521 }
1522 _PyRuntimeState *runtime = &_PyRuntime;
1523
1524 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001525 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001526 }
Nick Coghland6009512014-11-20 21:39:37 +10001527
Victor Stinner8a1be612016-03-14 22:07:55 +01001528 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1529 interpreters: disable PyGILState_Check(). */
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001530 runtime->gilstate.check_enabled = 0;
Victor Stinner8a1be612016-03-14 22:07:55 +01001531
Victor Stinner43125222019-04-24 18:23:53 +02001532 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001533 if (interp == NULL) {
1534 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001535 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001536 }
Nick Coghland6009512014-11-20 21:39:37 +10001537
Victor Stinner43125222019-04-24 18:23:53 +02001538 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001539 if (tstate == NULL) {
1540 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001541 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001542 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001543 }
1544
Victor Stinner43125222019-04-24 18:23:53 +02001545 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001546
Eric Snow1abcf672017-05-23 21:46:51 -07001547 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda7933e2020-04-13 03:04:28 +02001548 const PyConfig *config;
Victor Stinner7be4e352020-05-05 20:27:47 +02001549#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Eric Snow1abcf672017-05-23 21:46:51 -07001550 if (save_tstate != NULL) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001551 config = _PyInterpreterState_GetConfig(save_tstate->interp);
Victor Stinner7be4e352020-05-05 20:27:47 +02001552 }
1553 else
1554#endif
1555 {
Eric Snow1abcf672017-05-23 21:46:51 -07001556 /* No current thread state, copy from the main interpreter */
1557 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001558 config = _PyInterpreterState_GetConfig(main_interp);
Victor Stinnerda273412017-12-15 01:46:02 +01001559 }
1560
Victor Stinnerda7933e2020-04-13 03:04:28 +02001561 status = _PyInterpreterState_SetConfig(interp, config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001562 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001563 goto error;
Victor Stinnerda273412017-12-15 01:46:02 +01001564 }
Victor Stinner252346a2020-05-01 11:33:44 +02001565 interp->config._isolated_interpreter = isolated_subinterpreter;
Eric Snow1abcf672017-05-23 21:46:51 -07001566
Victor Stinner0dd5e7a2020-05-05 20:16:37 +02001567 status = init_interp_create_gil(tstate);
1568 if (_PyStatus_EXCEPTION(status)) {
1569 goto error;
1570 }
1571
Victor Stinnerd863ade2019-12-06 03:37:07 +01001572 status = pycore_interp_init(tstate);
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001573 if (_PyStatus_EXCEPTION(status)) {
1574 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001575 }
1576
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001577 status = init_interp_main(tstate);
1578 if (_PyStatus_EXCEPTION(status)) {
1579 goto error;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001580 }
Nick Coghland6009512014-11-20 21:39:37 +10001581
Victor Stinnera7368ac2017-11-15 18:11:45 -08001582 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001583 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001584
Victor Stinner81fe5bd2019-12-06 02:43:30 +01001585error:
Victor Stinnerb0051362019-11-22 17:52:42 +01001586 *tstate_p = NULL;
1587
1588 /* Oops, it didn't work. Undo it all. */
Nick Coghland6009512014-11-20 21:39:37 +10001589 PyErr_PrintEx(0);
1590 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001591 PyThreadState_Delete(tstate);
1592 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001593 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001594
Victor Stinnerb0051362019-11-22 17:52:42 +01001595 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001596}
1597
1598PyThreadState *
Victor Stinner252346a2020-05-01 11:33:44 +02001599_Py_NewInterpreter(int isolated_subinterpreter)
Victor Stinnera7368ac2017-11-15 18:11:45 -08001600{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001601 PyThreadState *tstate = NULL;
Victor Stinner252346a2020-05-01 11:33:44 +02001602 PyStatus status = new_interpreter(&tstate, isolated_subinterpreter);
Victor Stinner331a6a52019-05-27 16:39:22 +02001603 if (_PyStatus_EXCEPTION(status)) {
1604 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001605 }
1606 return tstate;
1607
Nick Coghland6009512014-11-20 21:39:37 +10001608}
1609
Victor Stinner252346a2020-05-01 11:33:44 +02001610PyThreadState *
1611Py_NewInterpreter(void)
1612{
1613 return _Py_NewInterpreter(0);
1614}
1615
Nick Coghland6009512014-11-20 21:39:37 +10001616/* Delete an interpreter and its last thread. This requires that the
1617 given thread state is current, that the thread has no remaining
1618 frames, and that it is its interpreter's only remaining thread.
1619 It is a fatal error to violate these constraints.
1620
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001621 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001622 everything, regardless.)
1623
1624 Locking: as above.
1625
1626*/
1627
1628void
1629Py_EndInterpreter(PyThreadState *tstate)
1630{
1631 PyInterpreterState *interp = tstate->interp;
1632
Victor Stinnerb45d2592019-06-20 00:05:23 +02001633 if (tstate != _PyThreadState_GET()) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001634 Py_FatalError("thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001635 }
1636 if (tstate->frame != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001637 Py_FatalError("thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001638 }
Eric Snow5be45a62019-03-08 22:47:07 -07001639 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001640
Eric Snow842a2f02019-03-15 15:47:51 -06001641 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001642 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001643
Victor Stinnerb45d2592019-06-20 00:05:23 +02001644 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001645
Victor Stinnerb45d2592019-06-20 00:05:23 +02001646 if (tstate != interp->tstate_head || tstate->next != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001647 Py_FatalError("not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001648 }
Nick Coghland6009512014-11-20 21:39:37 +10001649
Victor Stinner987a0dc2019-06-19 10:36:10 +02001650 _PyImport_Cleanup(tstate);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001651 finalize_interp_clear(tstate);
1652 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001653}
1654
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001655/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001656
Victor Stinner331a6a52019-05-27 16:39:22 +02001657static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001658add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001659{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001660 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001661 m = PyImport_AddModule("__main__");
1662 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001663 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001664
Nick Coghland6009512014-11-20 21:39:37 +10001665 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001666 ann_dict = PyDict_New();
1667 if ((ann_dict == NULL) ||
1668 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001669 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001670 }
1671 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001672
Nick Coghland6009512014-11-20 21:39:37 +10001673 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1674 PyObject *bimod = PyImport_ImportModule("builtins");
1675 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001676 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001677 }
1678 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001679 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001680 }
1681 Py_DECREF(bimod);
1682 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001683
Nick Coghland6009512014-11-20 21:39:37 +10001684 /* Main is a little special - imp.is_builtin("__main__") will return
1685 * False, but BuiltinImporter is still the most appropriate initial
1686 * setting for its __loader__ attribute. A more suitable value will
1687 * be set if __main__ gets further initialized later in the startup
1688 * process.
1689 */
1690 loader = PyDict_GetItemString(d, "__loader__");
1691 if (loader == NULL || loader == Py_None) {
1692 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1693 "BuiltinImporter");
1694 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001695 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001696 }
1697 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001698 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001699 }
1700 Py_DECREF(loader);
1701 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001702 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001703}
1704
Nick Coghland6009512014-11-20 21:39:37 +10001705/* Import the site module (not into __main__ though) */
1706
Victor Stinner331a6a52019-05-27 16:39:22 +02001707static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001708init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10001709{
1710 PyObject *m;
1711 m = PyImport_ImportModule("site");
1712 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001713 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001714 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001715 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001716 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001717}
1718
Victor Stinner874dbe82015-09-04 17:29:57 +02001719/* Check if a file descriptor is valid or not.
1720 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1721static int
1722is_valid_fd(int fd)
1723{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001724/* dup() is faster than fstat(): fstat() can require input/output operations,
1725 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1726 startup. Problem: dup() doesn't check if the file descriptor is valid on
1727 some platforms.
1728
1729 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1730 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1731 EBADF. FreeBSD has similar issue (bpo-32849).
1732
1733 Only use dup() on platforms where dup() is enough to detect invalid FD in
1734 corner cases: on Linux and Windows (bpo-32849). */
1735#if defined(__linux__) || defined(MS_WINDOWS)
1736 if (fd < 0) {
1737 return 0;
1738 }
1739 int fd2;
1740
1741 _Py_BEGIN_SUPPRESS_IPH
1742 fd2 = dup(fd);
1743 if (fd2 >= 0) {
1744 close(fd2);
1745 }
1746 _Py_END_SUPPRESS_IPH
1747
1748 return (fd2 >= 0);
1749#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001750 struct stat st;
1751 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001752#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001753}
1754
1755/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001756static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001757create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001758 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001759 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001760{
1761 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1762 const char* mode;
1763 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001764 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001765 int buffering, isatty;
1766 _Py_IDENTIFIER(open);
1767 _Py_IDENTIFIER(isatty);
1768 _Py_IDENTIFIER(TextIOWrapper);
1769 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001770 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001771
Victor Stinner874dbe82015-09-04 17:29:57 +02001772 if (!is_valid_fd(fd))
1773 Py_RETURN_NONE;
1774
Nick Coghland6009512014-11-20 21:39:37 +10001775 /* stdin is always opened in buffered mode, first because it shouldn't
1776 make a difference in common use cases, second because TextIOWrapper
1777 depends on the presence of a read1() method which only exists on
1778 buffered streams.
1779 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001780 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001781 buffering = 0;
1782 else
1783 buffering = -1;
1784 if (write_mode)
1785 mode = "wb";
1786 else
1787 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001788 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10001789 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001790 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001791 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001792 if (buf == NULL)
1793 goto error;
1794
1795 if (buffering) {
1796 _Py_IDENTIFIER(raw);
1797 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1798 if (raw == NULL)
1799 goto error;
1800 }
1801 else {
1802 raw = buf;
1803 Py_INCREF(raw);
1804 }
1805
Steve Dower39294992016-08-30 21:22:36 -07001806#ifdef MS_WINDOWS
1807 /* Windows console IO is always UTF-8 encoded */
1808 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001809 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001810#endif
1811
Nick Coghland6009512014-11-20 21:39:37 +10001812 text = PyUnicode_FromString(name);
1813 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1814 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001815 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10001816 if (res == NULL)
1817 goto error;
1818 isatty = PyObject_IsTrue(res);
1819 Py_DECREF(res);
1820 if (isatty == -1)
1821 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001822 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001823 write_through = Py_True;
1824 else
1825 write_through = Py_False;
Jendrik Seipp5b907712020-01-01 23:21:43 +01001826 if (buffered_stdio && (isatty || fd == fileno(stderr)))
Nick Coghland6009512014-11-20 21:39:37 +10001827 line_buffering = Py_True;
1828 else
1829 line_buffering = Py_False;
1830
1831 Py_CLEAR(raw);
1832 Py_CLEAR(text);
1833
1834#ifdef MS_WINDOWS
1835 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1836 newlines to "\n".
1837 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1838 newline = NULL;
1839#else
1840 /* sys.stdin: split lines at "\n".
1841 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1842 newline = "\n";
1843#endif
1844
Victor Stinner709d23d2019-05-02 14:56:30 -04001845 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1846 if (encoding_str == NULL) {
1847 Py_CLEAR(buf);
1848 goto error;
1849 }
1850
1851 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1852 if (errors_str == NULL) {
1853 Py_CLEAR(buf);
1854 Py_CLEAR(encoding_str);
1855 goto error;
1856 }
1857
1858 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1859 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001860 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001861 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001862 Py_CLEAR(encoding_str);
1863 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001864 if (stream == NULL)
1865 goto error;
1866
1867 if (write_mode)
1868 mode = "w";
1869 else
1870 mode = "r";
1871 text = PyUnicode_FromString(mode);
1872 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1873 goto error;
1874 Py_CLEAR(text);
1875 return stream;
1876
1877error:
1878 Py_XDECREF(buf);
1879 Py_XDECREF(stream);
1880 Py_XDECREF(text);
1881 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001882
Victor Stinner874dbe82015-09-04 17:29:57 +02001883 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1884 /* Issue #24891: the file descriptor was closed after the first
1885 is_valid_fd() check was called. Ignore the OSError and set the
1886 stream to None. */
1887 PyErr_Clear();
1888 Py_RETURN_NONE;
1889 }
1890 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001891}
1892
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001893/* Set builtins.open to io.OpenWrapper */
1894static PyStatus
Andy Lester75cd5bf2020-03-12 02:49:05 -05001895init_set_builtins_open(void)
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001896{
1897 PyObject *iomod = NULL, *wrapper;
1898 PyObject *bimod = NULL;
1899 PyStatus res = _PyStatus_OK();
1900
1901 if (!(iomod = PyImport_ImportModule("io"))) {
1902 goto error;
1903 }
1904
1905 if (!(bimod = PyImport_ImportModule("builtins"))) {
1906 goto error;
1907 }
1908
1909 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1910 goto error;
1911 }
1912
1913 /* Set builtins.open */
1914 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1915 Py_DECREF(wrapper);
1916 goto error;
1917 }
1918 Py_DECREF(wrapper);
1919 goto done;
1920
1921error:
1922 res = _PyStatus_ERR("can't initialize io.open");
1923
1924done:
1925 Py_XDECREF(bimod);
1926 Py_XDECREF(iomod);
1927 return res;
1928}
1929
1930
Nick Coghland6009512014-11-20 21:39:37 +10001931/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001932static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001933init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10001934{
Victor Stinnere0c9ab82019-11-22 16:19:14 +01001935 PyObject *iomod = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001936 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001937 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001938 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001939 PyStatus res = _PyStatus_OK();
Victor Stinnerda7933e2020-04-13 03:04:28 +02001940 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001941
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001942 /* Check that stdin is not a directory
1943 Using shell redirection, you can redirect stdin to a directory,
1944 crashing the Python interpreter. Catch this common mistake here
1945 and output a useful error message. Note that under MS Windows,
1946 the shell already prevents that. */
1947#ifndef MS_WINDOWS
1948 struct _Py_stat_struct sb;
1949 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1950 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001951 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001952 }
1953#endif
1954
Nick Coghland6009512014-11-20 21:39:37 +10001955 if (!(iomod = PyImport_ImportModule("io"))) {
1956 goto error;
1957 }
Nick Coghland6009512014-11-20 21:39:37 +10001958
Nick Coghland6009512014-11-20 21:39:37 +10001959 /* Set sys.stdin */
1960 fd = fileno(stdin);
1961 /* Under some conditions stdin, stdout and stderr may not be connected
1962 * and fileno() may point to an invalid file descriptor. For example
1963 * GUI apps don't have valid standard streams by default.
1964 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001965 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001966 config->stdio_encoding,
1967 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001968 if (std == NULL)
1969 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001970 PySys_SetObject("__stdin__", std);
1971 _PySys_SetObjectId(&PyId_stdin, std);
1972 Py_DECREF(std);
1973
1974 /* Set sys.stdout */
1975 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001976 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001977 config->stdio_encoding,
1978 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001979 if (std == NULL)
1980 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001981 PySys_SetObject("__stdout__", std);
1982 _PySys_SetObjectId(&PyId_stdout, std);
1983 Py_DECREF(std);
1984
1985#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1986 /* Set sys.stderr, replaces the preliminary stderr */
1987 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001988 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001989 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001990 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001991 if (std == NULL)
1992 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001993
1994 /* Same as hack above, pre-import stderr's codec to avoid recursion
1995 when import.c tries to write to stderr in verbose mode. */
1996 encoding_attr = PyObject_GetAttrString(std, "encoding");
1997 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001998 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001999 if (std_encoding != NULL) {
2000 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
2001 Py_XDECREF(codec_info);
2002 }
2003 Py_DECREF(encoding_attr);
2004 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02002005 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10002006
2007 if (PySys_SetObject("__stderr__", std) < 0) {
2008 Py_DECREF(std);
2009 goto error;
2010 }
2011 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
2012 Py_DECREF(std);
2013 goto error;
2014 }
2015 Py_DECREF(std);
2016#endif
2017
Victor Stinnera7368ac2017-11-15 18:11:45 -08002018 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002019
Victor Stinnera7368ac2017-11-15 18:11:45 -08002020error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002021 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002022
2023done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002024 _Py_ClearStandardStreamEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10002025 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002026 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002027}
2028
2029
Victor Stinner10dc4842015-03-24 12:01:30 +01002030static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002031_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2032 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002033{
Victor Stinner10dc4842015-03-24 12:01:30 +01002034 fputc('\n', stderr);
2035 fflush(stderr);
2036
2037 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002038 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002039}
Victor Stinner791da1c2016-03-14 16:53:12 +01002040
2041/* Print the current exception (if an exception is set) with its traceback,
2042 or display the current Python stack.
2043
2044 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2045 called on catastrophic cases.
2046
2047 Return 1 if the traceback was displayed, 0 otherwise. */
2048
2049static int
Andy Lester75cd5bf2020-03-12 02:49:05 -05002050_Py_FatalError_PrintExc(PyThreadState *tstate)
Victor Stinner791da1c2016-03-14 16:53:12 +01002051{
2052 PyObject *ferr, *res;
2053 PyObject *exception, *v, *tb;
2054 int has_tb;
2055
Victor Stinnerb45d2592019-06-20 00:05:23 +02002056 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002057 if (exception == NULL) {
2058 /* No current exception */
2059 return 0;
2060 }
2061
2062 ferr = _PySys_GetObjectId(&PyId_stderr);
2063 if (ferr == NULL || ferr == Py_None) {
2064 /* sys.stderr is not set yet or set to None,
2065 no need to try to display the exception */
2066 return 0;
2067 }
2068
Victor Stinnerb45d2592019-06-20 00:05:23 +02002069 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002070 if (tb == NULL) {
2071 tb = Py_None;
2072 Py_INCREF(tb);
2073 }
2074 PyException_SetTraceback(v, tb);
2075 if (exception == NULL) {
2076 /* PyErr_NormalizeException() failed */
2077 return 0;
2078 }
2079
2080 has_tb = (tb != Py_None);
2081 PyErr_Display(exception, v, tb);
2082 Py_XDECREF(exception);
2083 Py_XDECREF(v);
2084 Py_XDECREF(tb);
2085
2086 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002087 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002088 if (res == NULL) {
2089 _PyErr_Clear(tstate);
2090 }
2091 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002092 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002093 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002094
2095 return has_tb;
2096}
2097
Nick Coghland6009512014-11-20 21:39:37 +10002098/* Print fatal error message and abort */
2099
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002100#ifdef MS_WINDOWS
2101static void
2102fatal_output_debug(const char *msg)
2103{
2104 /* buffer of 256 bytes allocated on the stack */
2105 WCHAR buffer[256 / sizeof(WCHAR)];
2106 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2107 size_t msglen;
2108
2109 OutputDebugStringW(L"Fatal Python error: ");
2110
2111 msglen = strlen(msg);
2112 while (msglen) {
2113 size_t i;
2114
2115 if (buflen > msglen) {
2116 buflen = msglen;
2117 }
2118
2119 /* Convert the message to wchar_t. This uses a simple one-to-one
2120 conversion, assuming that the this error message actually uses
2121 ASCII only. If this ceases to be true, we will have to convert. */
2122 for (i=0; i < buflen; ++i) {
2123 buffer[i] = msg[i];
2124 }
2125 buffer[i] = L'\0';
2126 OutputDebugStringW(buffer);
2127
2128 msg += buflen;
2129 msglen -= buflen;
2130 }
2131 OutputDebugStringW(L"\n");
2132}
2133#endif
2134
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002135
2136static void
2137fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2138{
2139 fprintf(stream, "Python runtime state: ");
Victor Stinner7b3c2522020-03-07 00:24:23 +01002140 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
2141 if (finalizing) {
2142 fprintf(stream, "finalizing (tstate=%p)", finalizing);
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002143 }
2144 else if (runtime->initialized) {
2145 fprintf(stream, "initialized");
2146 }
2147 else if (runtime->core_initialized) {
2148 fprintf(stream, "core initialized");
2149 }
2150 else if (runtime->preinitialized) {
2151 fprintf(stream, "preinitialized");
2152 }
2153 else if (runtime->preinitializing) {
2154 fprintf(stream, "preinitializing");
2155 }
2156 else {
2157 fprintf(stream, "unknown");
2158 }
2159 fprintf(stream, "\n");
2160 fflush(stream);
2161}
2162
2163
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002164static inline void _Py_NO_RETURN
2165fatal_error_exit(int status)
Nick Coghland6009512014-11-20 21:39:37 +10002166{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002167 if (status < 0) {
2168#if defined(MS_WINDOWS) && defined(_DEBUG)
2169 DebugBreak();
2170#endif
2171 abort();
2172 }
2173 else {
2174 exit(status);
2175 }
2176}
2177
2178
2179static void _Py_NO_RETURN
2180fatal_error(FILE *stream, int header, const char *prefix, const char *msg,
2181 int status)
2182{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002183 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002184 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002185
2186 if (reentrant) {
2187 /* Py_FatalError() caused a second fatal error.
2188 Example: flush_std_files() raises a recursion error. */
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002189 fatal_error_exit(status);
Victor Stinner53345a42015-03-25 01:55:14 +01002190 }
2191 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002192
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002193 if (header) {
2194 fprintf(stream, "Fatal Python error: ");
2195 if (prefix) {
2196 fputs(prefix, stream);
2197 fputs(": ", stream);
2198 }
2199 if (msg) {
2200 fputs(msg, stream);
2201 }
2202 else {
2203 fprintf(stream, "<message not set>");
2204 }
2205 fputs("\n", stream);
2206 fflush(stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002207 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002208
2209 _PyRuntimeState *runtime = &_PyRuntime;
2210 fatal_error_dump_runtime(stream, runtime);
2211
2212 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2213 PyInterpreterState *interp = NULL;
2214 if (tstate != NULL) {
2215 interp = tstate->interp;
2216 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002217
Victor Stinner3a228ab2018-11-01 00:26:41 +01002218 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002219 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002220
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002221 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2222 has no Python thread state.
2223
2224 tss_tstate != tstate if the current Python thread does not hold the GIL.
2225 */
2226 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2227 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002228 if (has_tstate_and_gil) {
2229 /* If an exception is set, print the exception with its traceback */
Andy Lester75cd5bf2020-03-12 02:49:05 -05002230 if (!_Py_FatalError_PrintExc(tss_tstate)) {
Victor Stinner3a228ab2018-11-01 00:26:41 +01002231 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002232 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002233 }
2234 }
2235 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002236 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002237 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002238
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002239 /* The main purpose of faulthandler is to display the traceback.
2240 This function already did its best to display a traceback.
2241 Disable faulthandler to prevent writing a second traceback
2242 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002243 _PyFaulthandler_Fini();
2244
Victor Stinner791da1c2016-03-14 16:53:12 +01002245 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002246 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002247 /* Flush sys.stdout and sys.stderr */
2248 flush_std_files();
2249 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002250
Nick Coghland6009512014-11-20 21:39:37 +10002251#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002252 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002253#endif /* MS_WINDOWS */
2254
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002255 fatal_error_exit(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002256}
2257
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002258
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002259#undef Py_FatalError
2260
Victor Stinner19760862017-12-20 01:41:59 +01002261void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002262Py_FatalError(const char *msg)
2263{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002264 fatal_error(stderr, 1, NULL, msg, -1);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002265}
2266
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002267
Victor Stinner19760862017-12-20 01:41:59 +01002268void _Py_NO_RETURN
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002269_Py_FatalErrorFunc(const char *func, const char *msg)
2270{
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002271 fatal_error(stderr, 1, func, msg, -1);
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002272}
2273
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002274
2275void _Py_NO_RETURN
2276_Py_FatalErrorFormat(const char *func, const char *format, ...)
2277{
2278 static int reentrant = 0;
2279 if (reentrant) {
2280 /* _Py_FatalErrorFormat() caused a second fatal error */
2281 fatal_error_exit(-1);
2282 }
2283 reentrant = 1;
2284
2285 FILE *stream = stderr;
2286 fprintf(stream, "Fatal Python error: ");
2287 if (func) {
2288 fputs(func, stream);
2289 fputs(": ", stream);
2290 }
2291 fflush(stream);
2292
2293 va_list vargs;
2294#ifdef HAVE_STDARG_PROTOTYPES
2295 va_start(vargs, format);
2296#else
2297 va_start(vargs);
2298#endif
2299 vfprintf(stream, format, vargs);
2300 va_end(vargs);
2301
2302 fputs("\n", stream);
2303 fflush(stream);
2304
2305 fatal_error(stream, 0, NULL, NULL, -1);
2306}
2307
2308
Victor Stinner9e5d30c2020-03-07 00:54:20 +01002309void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002310Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002311{
Victor Stinner331a6a52019-05-27 16:39:22 +02002312 if (_PyStatus_IS_EXIT(status)) {
2313 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002314 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002315 else if (_PyStatus_IS_ERROR(status)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01002316 fatal_error(stderr, 1, status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002317 }
2318 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002319 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002320 }
Nick Coghland6009512014-11-20 21:39:37 +10002321}
2322
2323/* Clean up and exit */
2324
Nick Coghland6009512014-11-20 21:39:37 +10002325/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002326void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002327{
Victor Stinner81a7be32020-04-14 15:14:01 +02002328 PyInterpreterState *is = _PyInterpreterState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01002329
Antoine Pitroufc5db952017-12-13 02:29:07 +01002330 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002331 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2332
2333 is->pyexitfunc = func;
2334 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002335}
2336
2337static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002338call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002339{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002340 PyInterpreterState *interp = tstate->interp;
2341 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002342 return;
2343
Victor Stinnerb45d2592019-06-20 00:05:23 +02002344 (*interp->pyexitfunc)(interp->pyexitmodule);
2345 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002346}
2347
2348/* Wait until threading._shutdown completes, provided
2349 the threading module was imported in the first place.
2350 The shutdown routine will wait until all non-daemon
2351 "threading" threads have completed. */
2352static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002353wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002354{
Nick Coghland6009512014-11-20 21:39:37 +10002355 _Py_IDENTIFIER(_shutdown);
2356 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002357 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002358 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002359 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002360 PyErr_WriteUnraisable(NULL);
2361 }
2362 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002363 return;
2364 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002365 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002366 if (result == NULL) {
2367 PyErr_WriteUnraisable(threading);
2368 }
2369 else {
2370 Py_DECREF(result);
2371 }
2372 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002373}
2374
2375#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002376int Py_AtExit(void (*func)(void))
2377{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002378 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002379 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002380 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002381 return 0;
2382}
2383
2384static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002385call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002386{
Victor Stinner8e91c242019-04-24 17:24:01 +02002387 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002388 /* pop last function from the list */
2389 runtime->nexitfuncs--;
2390 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2391 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2392
2393 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002394 }
Nick Coghland6009512014-11-20 21:39:37 +10002395
2396 fflush(stdout);
2397 fflush(stderr);
2398}
2399
Victor Stinnercfc88312018-08-01 16:41:25 +02002400void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002401Py_Exit(int sts)
2402{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002403 if (Py_FinalizeEx() < 0) {
2404 sts = 120;
2405 }
Nick Coghland6009512014-11-20 21:39:37 +10002406
2407 exit(sts);
2408}
2409
Victor Stinner331a6a52019-05-27 16:39:22 +02002410static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002411init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002412{
2413#ifdef SIGPIPE
2414 PyOS_setsig(SIGPIPE, SIG_IGN);
2415#endif
2416#ifdef SIGXFZ
2417 PyOS_setsig(SIGXFZ, SIG_IGN);
2418#endif
2419#ifdef SIGXFSZ
2420 PyOS_setsig(SIGXFSZ, SIG_IGN);
2421#endif
Victor Stinner400e1db2020-03-31 19:13:10 +02002422 PyOS_InitInterrupts(); /* May imply init_signals() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002423 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002424 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002425 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002426 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002427}
2428
2429
2430/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2431 *
2432 * All of the code in this function must only use async-signal-safe functions,
2433 * listed at `man 7 signal` or
2434 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
Victor Stinnerefc28bb2020-03-05 18:13:56 +01002435 *
2436 * If this function is updated, update also _posix_spawn() of subprocess.py.
Nick Coghland6009512014-11-20 21:39:37 +10002437 */
2438void
2439_Py_RestoreSignals(void)
2440{
2441#ifdef SIGPIPE
2442 PyOS_setsig(SIGPIPE, SIG_DFL);
2443#endif
2444#ifdef SIGXFZ
2445 PyOS_setsig(SIGXFZ, SIG_DFL);
2446#endif
2447#ifdef SIGXFSZ
2448 PyOS_setsig(SIGXFSZ, SIG_DFL);
2449#endif
2450}
2451
2452
2453/*
2454 * The file descriptor fd is considered ``interactive'' if either
2455 * a) isatty(fd) is TRUE, or
2456 * b) the -i flag was given, and the filename associated with
2457 * the descriptor is NULL or "<stdin>" or "???".
2458 */
2459int
2460Py_FdIsInteractive(FILE *fp, const char *filename)
2461{
2462 if (isatty((int)fileno(fp)))
2463 return 1;
2464 if (!Py_InteractiveFlag)
2465 return 0;
2466 return (filename == NULL) ||
2467 (strcmp(filename, "<stdin>") == 0) ||
2468 (strcmp(filename, "???") == 0);
2469}
2470
2471
Nick Coghland6009512014-11-20 21:39:37 +10002472/* Wrappers around sigaction() or signal(). */
2473
2474PyOS_sighandler_t
2475PyOS_getsig(int sig)
2476{
2477#ifdef HAVE_SIGACTION
2478 struct sigaction context;
2479 if (sigaction(sig, NULL, &context) == -1)
2480 return SIG_ERR;
2481 return context.sa_handler;
2482#else
2483 PyOS_sighandler_t handler;
2484/* Special signal handling for the secure CRT in Visual Studio 2005 */
2485#if defined(_MSC_VER) && _MSC_VER >= 1400
2486 switch (sig) {
2487 /* Only these signals are valid */
2488 case SIGINT:
2489 case SIGILL:
2490 case SIGFPE:
2491 case SIGSEGV:
2492 case SIGTERM:
2493 case SIGBREAK:
2494 case SIGABRT:
2495 break;
2496 /* Don't call signal() with other values or it will assert */
2497 default:
2498 return SIG_ERR;
2499 }
2500#endif /* _MSC_VER && _MSC_VER >= 1400 */
2501 handler = signal(sig, SIG_IGN);
2502 if (handler != SIG_ERR)
2503 signal(sig, handler);
2504 return handler;
2505#endif
2506}
2507
2508/*
2509 * All of the code in this function must only use async-signal-safe functions,
2510 * listed at `man 7 signal` or
2511 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2512 */
2513PyOS_sighandler_t
2514PyOS_setsig(int sig, PyOS_sighandler_t handler)
2515{
2516#ifdef HAVE_SIGACTION
2517 /* Some code in Modules/signalmodule.c depends on sigaction() being
2518 * used here if HAVE_SIGACTION is defined. Fix that if this code
2519 * changes to invalidate that assumption.
2520 */
2521 struct sigaction context, ocontext;
2522 context.sa_handler = handler;
2523 sigemptyset(&context.sa_mask);
2524 context.sa_flags = 0;
2525 if (sigaction(sig, &context, &ocontext) == -1)
2526 return SIG_ERR;
2527 return ocontext.sa_handler;
2528#else
2529 PyOS_sighandler_t oldhandler;
2530 oldhandler = signal(sig, handler);
2531#ifdef HAVE_SIGINTERRUPT
2532 siginterrupt(sig, 1);
2533#endif
2534 return oldhandler;
2535#endif
2536}
2537
2538#ifdef __cplusplus
2539}
2540#endif